diff --git a/Docs/WordCompanion/2026-11-09-chapter-sync-contract.md b/Docs/WordCompanion/2026-11-09-chapter-sync-contract.md new file mode 100644 index 00000000..ee60f95a --- /dev/null +++ b/Docs/WordCompanion/2026-11-09-chapter-sync-contract.md @@ -0,0 +1,25 @@ +# Chapter synchronisation contract and implementation ledger + +Baseline: shared branch, Windows 1.0.0.22 commit `51316f0`. No author manuscript is a test fixture. + +## Decisions before implementation + +- The accepted `ParagraphManuscript` remains the sole canonical manuscript, paragraph GUID, scene assignment and author-decision model. Chapter checkpoints are additive metadata in that existing JSON snapshot, carried by the existing backup path. No import or scene detection is rerun. +- SHA-256 v1 fingerprints encode exact UTF-16 code units with a little-endian paragraph-count/length prefix. No Unicode, whitespace, line-ending or Word control-character normalisation. Paragraph boundaries, order, splitting and merging remain distinguishable. A separate identity digest includes ordered native IDs, lengths and outline levels; a mapping digest includes PlotDirector paragraph/scene/chapter assignments. +- A hash match is a proposal. The server accepts only complete unique native identity evidence, exact content/boundary equality, current authenticated document/session/revision and coherent accepted-snapshot lineage. Unknown/duplicated IDs or complex XML must fail safely. +- Per-session live position validations are distinct from durable source checkpoints. A new session does not erase source checkpoints, and validating one chapter never makes unchecked absolute positions in another chapter trustworthy. +- Unchanged chapter validation must not update prose, scenes, evidence, decisions, statistics or AI. Changed-chapter reconciliation must reuse the existing engine and transactional snapshot procedure, preserve unrelated identities and invalidate incompatible live positions. Ambiguity requires review. +- New native capabilities are negotiated explicitly. Installed 1.0.0.22 retains its existing endpoints and behaviour; no server silently sends an unsupported command or claims it has fast chapter validation. +- Benchmarks of COM `Range.Text`, native identity enumeration and `WordOpenXML` cannot run on Atlas. Prepare a Windows harness and record only actual portable measurements here; adoption/performance claims remain subject to Windows qualification. + +## Safety + +New migrations are forward-only and applied only after verified Development backup. No real-book backfill, automatic repair or mutation-based qualification. Native changes are source only on Atlas. Deploy only after the normal idle-work guard passes. Production untouched. + +## Delivery ledger + +Implementation, tests, measured portable timings, migration/deployment identity and remaining Windows limitations will be recorded as work completes. + +### First portable milestone + +Versioned fingerprint/XML reader, accepted-snapshot checkpoint model, read-only unchanged-chapter validation, explicit missing-native-ID adoption, conservative changed-chapter merging through the existing engine, authorised API/service, and forward migration 245 source are implemented. Migration is not yet applied and this milestone is not yet deployed. Solution build passes without warnings. Focused tests cover reordered/split paragraphs, Unicode/control characters, cross-session positions, stale lineage, duplicate IDs, preservation of unrelated GUIDs/scenes, hard boundaries and unsafe XML rejection. Portable SHA-256 measurement: 48 synthetic chapters / 8,640 paragraphs in 26.7 ms on Atlas; excludes Word/COM and is not a Windows performance claim. diff --git a/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs new file mode 100644 index 00000000..04136ff2 --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs @@ -0,0 +1,103 @@ +using System.Runtime.Serialization; +using System.Security.Cryptography; +using System.Text; +using System.Xml; +using System.Xml.Linq; +namespace PlotDirector.Companion.Protocol.Manuscript; + +[DataContract] +public sealed class ChapterParagraph +{ + [DataMember] public string NativeId {get;set;}=""; + [DataMember] public int Length {get;set;} + [DataMember] public int Outline {get;set;}=10; + [DataMember] public string? Text {get;set;} +} +[DataContract] +public sealed class ChapterObservation +{ + [DataMember] public Guid OperationId {get;set;} + [DataMember] public Guid RequestId {get;set;}=Guid.NewGuid(); + [DataMember] public Guid ManuscriptId {get;set;} + [DataMember] public Guid InstanceId {get;set;} + [DataMember] public Guid SessionId {get;set;} + [DataMember] public long WordRevision {get;set;} + [DataMember] public long BaseRevision {get;set;} + [DataMember] public int ChapterId {get;set;} + [DataMember] public int Start {get;set;} + [DataMember] public int End {get;set;} + [DataMember] public string Algorithm {get;set;}=ChapterFingerprint.Version; + [DataMember] public string ContentHash {get;set;}=""; + [DataMember] public string IdentityHash {get;set;}=""; + [DataMember] public string NextHeadingId {get;set;}=""; + [DataMember] public bool Reconcile {get;set;} + [DataMember] public ChapterParagraph[] Paragraphs {get;set;}=Array.Empty(); +} +public static class ChapterFingerprint +{ + public const string Version="sha256-utf16le-paragraphs-v1"; + public const int MaxCharacters=256*1024,MaxParagraphs=10000; + private static string Digest(Action write) + { + using var bytes=new MemoryStream();using(var writer=new BinaryWriter(bytes,Encoding.UTF8,true))write(writer); + using var sha=SHA256.Create();return BitConverter.ToString(sha.ComputeHash(bytes.ToArray())).Replace("-",""); + } + // Encoding code units explicitly preserves even isolated UTF-16 surrogates without replacement or normalisation. + private static void Text(BinaryWriter writer,string text){writer.Write(text.Length);foreach(var c in text)writer.Write((ushort)c);} + public static string Content(IEnumerable paragraphs) + { + var rows=paragraphs.ToArray();if(rows.Length>MaxParagraphs||rows.Sum(p=>(long)p.Length)>MaxCharacters)throw new ArgumentException("Chapter exceeds bounded validation size."); + return Digest(w=>{Text(w,Version);w.Write(rows.Length);foreach(var row in rows)Text(w,row);}); + } + public static string Identity(IEnumerable paragraphs) + { + var rows=paragraphs.ToArray();if(rows.Length==0||rows.Length>MaxParagraphs||rows.Any(p=>p.Length<=0||WordParagraphIdentity.Normalise(p.NativeId)!=p.NativeId||p.Outline<1||p.Outline>10)||rows.Select(p=>p.NativeId).Distinct().Count()!=rows.Length)throw new ArgumentException("Complete unique native paragraph identities are required."); + return Digest(w=>{Text(w,Version+"/identity");w.Write(rows.Length);foreach(var row in rows){Text(w,row.NativeId);w.Write(row.Length);w.Write(row.Outline);}}); + } + public static string Mapping(IEnumerable assignments)=>Content(assignments); + + // Parses only the main Word part. Complex constructs require the established bounded reader rather than guessed offsets. + public static ChapterParagraph[] ReadXml(string xml,string rangeText) + { + if(xml.Length>8*1024*1024||rangeText.Length>MaxCharacters)throw new ArgumentException("Chapter XML exceeds the bounded reader."); + using var reader=XmlReader.Create(new StringReader(xml),new XmlReaderSettings{DtdProcessing=DtdProcessing.Prohibit,XmlResolver=null,MaxCharactersInDocument=8*1024*1024}); + var root=XDocument.Load(reader);XNamespace w="http://schemas.openxmlformats.org/wordprocessingml/2006/main",pkg="http://schemas.microsoft.com/office/2006/xmlPackage",w14="http://schemas.microsoft.com/office/word/2010/wordml"; + var document=root.Root?.Name==w+"document"?root.Root:root.Descendants(pkg+"part").Where(p=>(string?)p.Attribute(pkg+"name")=="/word/document.xml").SelectMany(p=>p.Descendants(w+"document")).SingleOrDefault(); + var body=document?.Element(w+"body")??throw new ArgumentException("Main Word document part is missing."); + var unsafeNames=new HashSet(new[]{"tbl","txbxContent","fldChar","instrText","footnoteReference","endnoteReference","drawing","object","ins","del","moveFrom","moveTo","altChunk","sym"}.Select(n=>w+n)); + if(body.Descendants().Any(e=>unsafeNames.Contains(e.Name)))throw new ArgumentException("Complex chapter content needs bounded reconciliation; positions were not guessed."); + var styles=root.Descendants(w+"style").Where(e=>e.Attribute(w+"styleId")!=null).GroupBy(e=>(string)e.Attribute(w+"styleId")!).ToDictionary(g=>g.Key,g=>g.First()); + int Outline(XElement paragraph){ + var properties=paragraph.Element(w+"pPr");var seen=new HashSet(); + for(int depth=0;depth<16;depth++){ + if(int.TryParse((string?)properties?.Element(w+"outlineLvl")?.Attribute(w+"val"),out var n))return n+1; + var style=(string?)properties?.Element(w+"pStyle")?.Attribute(w+"val"); + if(style==null||!seen.Add(style)||!styles.TryGetValue(style,out var definition))return 10; + properties=definition.Element(w+"pPr"); + if(properties?.Element(w+"outlineLvl")==null&&definition.Element(w+"basedOn")?.Attribute(w+"val") is {} parent)properties=new XElement(w+"pPr",new XElement(w+"pStyle",new XAttribute(w+"val",parent.Value))); + }throw new ArgumentException("Cyclic Word style inheritance."); + } + var rows=body.Elements(w+"p").Select(p=>{ + var text=new StringBuilder();foreach(var node in p.Descendants()){ + if(node.Name==w+"t")text.Append(node.Value);else if(node.Name==w+"tab")text.Append('\t');else if(node.Name==w+"br"||node.Name==w+"cr"){if((string?)node.Attribute(w+"type") is {} type&&type!="textWrapping")throw new ArgumentException("Page/column break requires measured Word extraction.");text.Append('\v');} + }text.Append('\r'); + var outline=Outline(p); + return new ChapterParagraph{NativeId=WordParagraphIdentity.Normalise((string?)p.Attribute(w14+"paraId")),Text=text.ToString(),Length=text.Length,Outline=outline}; + }).ToArray(); + if(string.Concat(rows.Select(p=>p.Text))!=rangeText)throw new ArgumentException("XML paragraph text does not equal Word Range.Text; no positions were accepted."); + Identity(rows);Content(rows.Select(p=>p.Text!));return rows; + } +} + +public sealed class ChapterManifest +{ + public int BookId{get;set;}public Guid ManuscriptId{get;set;}public long Revision{get;set;}public string Mode{get;set;}="Manual";public ChapterManifestItem[] Chapters{get;set;}=Array.Empty(); +} +public sealed class ChapterManifestItem +{ + public int ChapterId{get;set;}public string Title{get;set;}="";public string HeadingNativeId{get;set;}="";public string ContentHash{get;set;}="";public string IdentityHash{get;set;}="";public int Start{get;set;}public int End{get;set;}public int ParagraphCount{get;set;}public string State{get;set;}="Not yet checked"; +} +public sealed class ChapterSyncReply +{ + public bool Accepted{get;set;}public string State{get;set;}="Not yet checked";public string Message{get;set;}="";public int ChapterId{get;set;}public long Revision{get;set;}public bool AllowText{get;set;} +} diff --git a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs index 8b3400ad..e91b4f7b 100644 --- a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs +++ b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs @@ -22,6 +22,8 @@ public sealed class NativePresence [DataMember] public Guid[]? CanonicalParagraphIds {get;set;} [DataMember] public long ParagraphRevision {get;set;} [DataMember] public string ParagraphSnapshotHash {get;set;}=""; + [DataMember] public bool CanChapterSync {get;set;} + [DataMember] public bool ChapterSyncSupported {get;set;} [DataMember] public bool CanParagraphSync {get;set;} [DataMember] public Guid CatalogVersion {get;set;} [DataMember] public Guid? CaptureRequestId {get;set;} diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Measure-ChapterSync.ps1 b/PlotDirector.NativeCompanion/WindowsValidation/Measure-ChapterSync.ps1 new file mode 100644 index 00000000..9d694030 --- /dev/null +++ b/PlotDirector.NativeCompanion/WindowsValidation/Measure-ChapterSync.ps1 @@ -0,0 +1,46 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$ProtocolAssembly, + [Parameter(Mandatory)][string]$OutputFile, + [ValidateRange(1,500)][int]$MaximumParagraphs=100, + [switch]$IncludeLegacyParagraphXml +) +$ErrorActionPreference='Stop' +if($env:OS -ne 'Windows_NT'){throw 'Real Word benchmarks require Windows; no Word process was started.'} +if([Threading.Thread]::CurrentThread.ApartmentState -ne 'STA'){throw 'Run in Windows PowerShell: powershell.exe -STA -File ...'} +if(Test-Path -LiteralPath $OutputFile){throw 'Choose a new output file. Existing results were preserved.'} +Add-Type -Path (Resolve-Path -LiteralPath $ProtocolAssembly) +# Attach only to Word which the human deliberately opened for the benchmark. Never launch, select, save or close it. +$word=[Runtime.InteropServices.Marshal]::GetActiveObject('Word.Application') +$selection=$null;$range=$null;$paragraphs=$null +try{ + $selection=$word.Selection;$range=$selection.Range.Duplicate + if($range.Start -eq $range.End){throw 'Select one representative chapter in Word first. The script never changes the selection.'} + if(!$range.Document.Saved -or $word.BackgroundSavingStatus -ne 0){throw 'Save Word and wait for background saving before benchmarking.'} + $times=[ordered]@{} + $watch=[Diagnostics.Stopwatch]::StartNew();$text=[string]$range.Text;$watch.Stop();$times.rangeTextMilliseconds=$watch.Elapsed.TotalMilliseconds + $paragraphs=$range.Paragraphs;$count=$paragraphs.Count + # Range.Text gives exact paragraph separators. The hash benchmark uses the production versioned encoder. + $rows=[Collections.Generic.List[string]]::new();$offset=0 + foreach($piece in $text.Split([char]13)){if($offset -ge $text.Length){break};$length=$piece.Length+1;if($offset+$length -gt $text.Length){throw 'Selection must end on a complete Word paragraph.'};$rows.Add($text.Substring($offset,$length));$offset+=$length} + $watch.Restart();$hash=[PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint]::Content($rows);$watch.Stop();$times.sha256Milliseconds=$watch.Elapsed.TotalMilliseconds + $watch.Restart();$xml=[string]$range.WordOpenXML;$watch.Stop();$times.chapterWordOpenXmlMilliseconds=$watch.Elapsed.TotalMilliseconds + $watch.Restart();$parsed=[PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint]::ReadXml($xml,$text);$watch.Stop();$times.portableXmlIdentityParseMilliseconds=$watch.Elapsed.TotalMilliseconds + $nativeCount=0 + if($IncludeLegacyParagraphXml){ + # Explicit expensive baseline, capped and cancellable with Ctrl+C; never part of unattended qualification. + $watch.Restart() + for($i=1;$i -le [Math]::Min($count,$MaximumParagraphs);$i++){ + $paragraph=$null;$one=$null + try{$paragraph=$paragraphs.Item($i);$one=$paragraph.Range;$id=[PlotDirector.Companion.Protocol.Manuscript.WordParagraphIdentity]::Read([string]$one.WordOpenXML);if($id){$nativeCount++}} + finally{if($one){[void][Runtime.InteropServices.Marshal]::ReleaseComObject($one)};if($paragraph){[void][Runtime.InteropServices.Marshal]::ReleaseComObject($paragraph)}} + } + $watch.Stop();$times.legacyParagraphXmlMilliseconds=$watch.Elapsed.TotalMilliseconds + } + # Cross-process COM call wall times include RPC/marshalling. Use in-add-in metrics for exact UI operation timings. + $report=[ordered]@{utc=[DateTime]::UtcNow.ToString('o');wordVersion=[string]$word.Version;characters=$text.Length;paragraphs=$count;nativeIds=$parsed.Length;legacyMeasuredParagraphs=$(if($IncludeLegacyParagraphXml){[Math]::Min($count,$MaximumParagraphs)}else{0});legacyNativeIds=$nativeCount;algorithm=[PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint]::Version;hash=$hash;timings=$times;measurementScope='Human-selected chapter, running Word, cross-process STA COM wall time. No UI responsiveness claim.'} + $report|ConvertTo-Json -Depth 5|Set-Content -LiteralPath $OutputFile -Encoding UTF8 + Write-Output "Recorded chapter benchmark: $OutputFile. No document was changed, saved or closed." +}finally{ + foreach($com in @($paragraphs,$range,$selection,$word)){if($com){[void][Runtime.InteropServices.Marshal]::ReleaseComObject($com)}} +} diff --git a/PlotLine.Tests/ChapterSynchronisationTests.cs b/PlotLine.Tests/ChapterSynchronisationTests.cs new file mode 100644 index 00000000..29e4a756 --- /dev/null +++ b/PlotLine.Tests/ChapterSynchronisationTests.cs @@ -0,0 +1,43 @@ +using System.Diagnostics; +using System.Text.Json; +using PlotDirector.Companion.Protocol.Manuscript; +using PlotLine.Models; +using PlotLine.Services.Manuscript; +internal static class ChapterSynchronisationTests +{ + public static void Run() + { + void Check(bool condition,string message){if(!condition)throw new Exception(message);Console.WriteLine("PASS "+message);} + void Refused(Action work,string message){try{work();throw new Exception("Unsafe chapter evidence accepted: "+message);}catch(Exception e)when(e is ArgumentException or InvalidOperationException){Console.WriteLine("PASS "+message);}} + Check(ChapterFingerprint.Content(["a\r","b\r"])!=ChapterFingerprint.Content(["a\rb\r"]),"Fingerprint preserves paragraph splitting/merging"); + Check(ChapterFingerprint.Content(["a\r","b\r"])!=ChapterFingerprint.Content(["b\r","a\r"]),"Fingerprint preserves paragraph order"); + Check(ChapterFingerprint.Content(["é\r"])!=ChapterFingerprint.Content(["e\u0301\r"]),"Fingerprint preserves Unicode composition differences"); + Check(ChapterFingerprint.Content(["a\r"])!=ChapterFingerprint.Content(["a\r\n"]),"Fingerprint preserves line endings and Word control characters"); + Check(ChapterFingerprint.Content(["\ud800\r"])!=ChapterFingerprint.Content(["\ufffd\r"]),"Fingerprint preserves isolated UTF-16 code units without replacement collisions"); + var rows=new List();var start=0; + foreach(var text in new[]{"Chapter one\r","First passage.\r","More first prose.\r","Chapter two\r","Second passage.\r","More second prose.\r"}){rows.Add(new(){Id=Guid.NewGuid(),NativeId=(rows.Count+1).ToString("X8"),Ordinal=rows.Count,Start=start,End=start+text.Length,Outline=rows.Count%3==0?1:10,Text=text});start+=text.Length;} + var state=ParagraphManuscriptEngine.Bootstrap(12,7,Guid.NewGuid(),rows.ToArray(),[new(){ChapterId=10,SceneId=22,Start=2,End=3,Title="First"},new(){ChapterId=11,SceneId=23,Start=5,End=6,Title="Second"}]);state.Revision=3;state.SessionId=Guid.NewGuid();state.WordRevision=1; + state.Chapters=[new(){CanonicalId=10,HeadingId=state.Paragraphs[0].Occurrence.Id,Title="Chapter one"},new(){CanonicalId=11,HeadingId=state.Paragraphs[3].Occurrence.Id,Title="Chapter two"}]; + foreach(var p in state.Paragraphs.Where(p=>p.Occurrence.Outline==1)){p.ChapterId=p.Occurrence.Ordinal==0?10:11;p.PositionVerified=true;} + ChapterObservation Proof(int id=10){var part=ChapterCheckpointEngine.Parts(state).Single(p=>p.Chapter.CanonicalId==id);var evidence=part.Rows.Select(p=>new ChapterParagraph{NativeId=p.Occurrence.NativeId,Text=p.Occurrence.Text,Length=p.Occurrence.Text.Length,Outline=p.Occurrence.Outline}).ToArray();return new(){ChapterId=id,RequestId=Guid.NewGuid(),InstanceId=Guid.NewGuid(),SessionId=Guid.NewGuid(),ManuscriptId=state.ManuscriptId,WordRevision=0,BaseRevision=state.Revision,Start=500,End=500+evidence.Sum(p=>p.Length),ContentHash=ChapterFingerprint.Content(evidence.Select(p=>p.Text!)),IdentityHash=ChapterFingerprint.Identity(evidence),Paragraphs=evidence,NextHeadingId=id==10?state.Paragraphs[3].Occurrence.NativeId:""};} + var before=JsonSerializer.Serialize(state);var proof=Proof();var accepted=ChapterCheckpointEngine.Validate(state,proof,DateTime.UtcNow); + Check(accepted.Positions.First().Start==500&&accepted.Positions.Where(p=>p.SceneId.HasValue).All(p=>p.SceneId==22),"Unchanged reopened chapter accepts new physical positions without changing scene identity"); + Check(JsonSerializer.Serialize(state)==before,"Validation proposals do not mutate accepted paragraphs, scenes, evidence or session identity"); + var stale=Proof();stale.BaseRevision--;Refused(()=>ChapterCheckpointEngine.Validate(state,stale,DateTime.UtcNow),"Stale accepted-snapshot lineage is refused"); + var duplicate=Proof();duplicate.Paragraphs[1].NativeId=duplicate.Paragraphs[0].NativeId;Refused(()=>ChapterCheckpointEngine.Validate(state,duplicate,DateTime.UtcNow),"Duplicate native paragraph identities cannot produce a green checkpoint"); + var changed=Proof();changed.Reconcile=true;changed.Paragraphs[1].Text="Edited first passage.\r";changed.Paragraphs[1].Length=changed.Paragraphs[1].Text!.Length;changed.ContentHash=ChapterFingerprint.Content(changed.Paragraphs.Select(p=>p.Text!));changed.IdentityHash=ChapterFingerprint.Identity(changed.Paragraphs);changed.End=changed.Start+changed.Paragraphs.Sum(p=>p.Length); + Refused(()=>ChapterCheckpointEngine.Validate(state,changed,DateTime.UtcNow),"Changed hash is not accepted as synchronised"); + var merged=ChapterCheckpointEngine.MergeChapter(state,changed);Check(merged.Skip(3).Select(p=>p.Id).SequenceEqual(state.Paragraphs.Skip(3).Select(p=>p.Occurrence.Id)),"Selective chapter merge preserves unrelated paragraph GUIDs"); + Check(merged[3].Start-state.Paragraphs[3].Occurrence.Start==changed.Paragraphs[1].Length-state.Paragraphs[1].Occurrence.Text.Length,"Logical positions in later chapters account for changed text length"); + var copy=JsonSerializer.Deserialize(before)!;ParagraphManuscriptEngine.Reconcile(copy,merged);Check(copy.Scenes.Select(p=>p.Id).SequenceEqual(state.Scenes.Select(p=>p.Id))&©.Paragraphs.Where(p=>p.ChapterId==11).All(p=>p.SceneId==null||p.SceneId==state.Scenes.Single(s=>s.ChapterId==11).Id),"Existing reconciliation preserves canonical scene GUIDs and hard chapter membership"); + var crossing=Proof();crossing.Reconcile=true;crossing.NextHeadingId="000000FF";Refused(()=>ChapterCheckpointEngine.MergeChapter(state,crossing),"Changed or moved chapter boundary requires review instead of cross-chapter reassignment"); + var legacy=JsonSerializer.Deserialize(before)!;foreach(var p in legacy.Paragraphs)p.Occurrence.NativeId="";var adoption=Proof();adoption.Reconcile=true; + var adopted=ChapterCheckpointEngine.Validate(legacy,adoption,DateTime.UtcNow);Check(adopted.Bindings.Length==3&&legacy.Paragraphs.All(p=>p.Occurrence.NativeId==""),"Explicit legacy repair proposes native bindings while preserving every original PlotDirector GUID"); + adoption.Reconcile=false;Refused(()=>ChapterCheckpointEngine.Validate(legacy,adoption,DateTime.UtcNow),"Passive hash checks cannot silently adopt missing legacy identities"); + var xml="Chapter oneExacttext"; + Check(ChapterFingerprint.ReadXml(xml,"Chapter one\rExact\ttext\r").Length==2,"Portable chapter XML identity enumeration matches exact Word range text"); + Refused(()=>ChapterFingerprint.ReadXml(xml,"Different\r"),"XML/range disagreement is refused rather than inventing paragraph offsets"); + Refused(()=>ChapterFingerprint.ReadXml(xml.Replace("",""),"Chapter one\rExact\ttext\r"),"Complex Word tables require safe bounded fallback"); + var watch=Stopwatch.StartNew();for(int i=0;i<48;i++)ChapterFingerprint.Content(Enumerable.Range(0,180).Select(n=>"Synthetic paragraph "+n+new string('x',100)+"\r"));watch.Stop();Console.WriteLine($"MEASURE portable exact SHA-256: 48 synthetic chapters / 8640 paragraphs in {watch.Elapsed.TotalMilliseconds:F1}ms. No Word COM or UI measurement."); + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 520c975a..ba39a584 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -15,6 +15,7 @@ using PlotLine.Models; using PlotLine.Services; using PlotLine.ViewModels; +if(args.Contains("--chapter-sync")){ChapterSynchronisationTests.Run();return;} #pragma warning disable CS8321 if (args.Contains("--word-marker-security")) diff --git a/PlotLine/Controllers/NativeChapterSyncController.cs b/PlotLine/Controllers/NativeChapterSyncController.cs new file mode 100644 index 00000000..e9e4d12d --- /dev/null +++ b/PlotLine/Controllers/NativeChapterSyncController.cs @@ -0,0 +1,18 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using PlotDirector.Companion.Protocol.Manuscript; +using PlotLine.Services.Manuscript; +using PlotLine.Services.NativeCompanion; +namespace PlotLine.Controllers; +[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion/books/{book:int}/chapter-sync")] +public sealed class NativeChapterSyncController(ChapterSyncService chapters):ControllerBase +{ + private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); + [HttpGet] + public async Task Manifest(int book,Guid session,long wordRevision)=>await Run(async()=>await chapters.Manifest(Author,book,session,wordRevision)); + [HttpPost("validate"),RequestSizeLimit(4*1024*1024)] + public async Task Validate(int book,ChapterObservation observation)=>await Run(async()=>await chapters.Accept(Author,User.FindFirstValue("NativeCompanion.Grant")??"",book,observation)); + private async Task Run(Func> read) + {try{return Ok(await read());}catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or InvalidOperationException){return Conflict(new ChapterSyncReply{State="Needs review",Message=e.Message});}catch(Microsoft.Data.SqlClient.SqlException){return Conflict(new ChapterSyncReply{State="Failed",Message="The accepted manuscript changed or chapter validation was refused. Existing work is preserved; refresh and retry."});}} +} diff --git a/PlotLine/Data/ChapterSyncRepository.cs b/PlotLine/Data/ChapterSyncRepository.cs new file mode 100644 index 00000000..5ab0e89d --- /dev/null +++ b/PlotLine/Data/ChapterSyncRepository.cs @@ -0,0 +1,20 @@ +using System.Data; +using System.Text.Json; +using Dapper; +using PlotLine.Models; +using PlotLine.Services.Manuscript; +using PlotDirector.Companion.Protocol.Manuscript; +namespace PlotLine.Data; +public interface IChapterSyncRepository +{ + Task Accept(int user,int book,ChapterObservation observation,ChapterValidationResult result); + Task Position(int user,int book,Guid manuscript,Guid session,long wordRevision,int position); + Task> List(int user,int book,Guid session,long wordRevision); +} +public sealed class ChapterLiveValidation{public int ChapterID{get;set;}public Guid SessionID{get;set;}public long WordRevision{get;set;}public string ContentHash{get;set;}="";public string IdentityHash{get;set;}="";public string MappingHash{get;set;}="";public long SourceRevision{get;set;}public DateTime ValidatedUtc{get;set;}} +public sealed class ChapterSyncRepository(ISqlConnectionFactory factory):IChapterSyncRepository +{ + public async Task Accept(int user,int book,ChapterObservation observation,ChapterValidationResult result){using var db=factory.CreateConnection();var json=await db.QuerySingleAsync("dbo.BookChapterSync",new{Action="accept",UserID=user,BookID=book,ChapterID=observation.ChapterId,SessionID=observation.SessionId,ManuscriptID=observation.ManuscriptId,WordRevision=observation.WordRevision,ExpectedRevision=observation.BaseRevision,RequestID=observation.RequestId,Checkpoint=JsonSerializer.Serialize(result.Checkpoint),Positions=JsonSerializer.Serialize(result.Positions),Bindings=JsonSerializer.Serialize(result.Bindings)},commandType:CommandType.StoredProcedure);return JsonSerializer.Deserialize(json)!;} + public async Task Position(int user,int book,Guid manuscript,Guid session,long wordRevision,int position){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync("dbo.BookChapterSync",new{Action="position",UserID=user,BookID=book,ManuscriptID=manuscript,SessionID=session,WordRevision=wordRevision,Position=position},commandType:CommandType.StoredProcedure);} + public async Task> List(int user,int book,Guid session,long wordRevision){using var db=factory.CreateConnection();return(await db.QueryAsync("dbo.BookChapterSync",new{Action="list",UserID=user,BookID=book,SessionID=session,WordRevision=wordRevision},commandType:CommandType.StoredProcedure)).ToArray();} +} diff --git a/PlotLine/Models/ParagraphManuscriptModels.cs b/PlotLine/Models/ParagraphManuscriptModels.cs index 7849f72f..343014d9 100644 --- a/PlotLine/Models/ParagraphManuscriptModels.cs +++ b/PlotLine/Models/ParagraphManuscriptModels.cs @@ -14,6 +14,7 @@ public sealed class ParagraphManuscript public string SnapshotHash {get;set;}=""; public string Mode {get;set;}="Manual"; public DateTime UpdatedUtc {get;set;} + public List ChapterCheckpoints {get;set;}=[]; public List Paragraphs {get;set;}=[]; public List Chapters {get;set;}=[]; public List Scenes {get;set;}=[]; diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 796027eb..e9940ee8 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -113,6 +113,8 @@ public class Program builder.Services.AddHostedService(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddAuthorization(options => diff --git a/PlotLine/Services/Manuscript/ChapterCheckpointEngine.cs b/PlotLine/Services/Manuscript/ChapterCheckpointEngine.cs new file mode 100644 index 00000000..11d2fa0a --- /dev/null +++ b/PlotLine/Services/Manuscript/ChapterCheckpointEngine.cs @@ -0,0 +1,80 @@ +using PlotDirector.Companion.Protocol.Manuscript; +using PlotLine.Models; +namespace PlotLine.Services.Manuscript; + +public sealed class ChapterCheckpoint +{ + public int ChapterId {get;set;}public Guid HeadingId {get;set;}public string NativeHeadingId {get;set;}="";public string NextHeadingId {get;set;}=""; + public string Algorithm {get;set;}=ChapterFingerprint.Version; + public string ContentHash {get;set;}="";public string IdentityHash {get;set;}="";public string MappingHash {get;set;}=""; + public int ParagraphCount {get;set;}public int Order {get;set;}public long AcceptedRevision {get;set;} + public DateTime LastSuccessfulSyncUtc {get;set;}public string Status {get;set;}="Not yet checked";public string Message {get;set;}=""; +} +public sealed record ChapterPart(ParagraphChapter Chapter,int Index,int End,StoryParagraph[] Rows); +public sealed record NativeParagraphBinding(Guid ParagraphId,string NativeId); +public sealed record ChapterValidationResult(ChapterCheckpoint Checkpoint,NativeParagraphBinding[] Bindings,ChapterPosition[] Positions); +public sealed record ChapterPosition(Guid ParagraphId,int Start,int End,int ChapterId,int? SceneId,bool Verified); + +public static class ChapterCheckpointEngine +{ + public static ChapterPart[] Parts(ParagraphManuscript state) + { + var bindings=state.Chapters.Select(c=>(Chapter:c,Index:state.Paragraphs.FindIndex(p=>p.Occurrence.Id==c.HeadingId))).OrderBy(c=>c.Index).ToArray(); + if(bindings.Any(c=>c.Index<0)||bindings.Select(c=>c.Index).Distinct().Count()!=bindings.Length||bindings.Where(c=>c.Chapter.CanonicalId>0).GroupBy(c=>c.Chapter.CanonicalId).Any(g=>g.Count()>1))throw new InvalidOperationException("Chapter boundaries need review; no checkpoint was guessed."); + return bindings.Select((c,i)=>new ChapterPart(c.Chapter,c.Index,i+1c.Chapter.CanonicalId>0).ToArray(); + } + public static ChapterCheckpoint[] Build(ParagraphManuscript state,long acceptedRevision) + { + var parts=Parts(state);var duplicateNative=state.Paragraphs.Select(p=>p.Occurrence.NativeId).Where(id=>id!="").GroupBy(id=>id).Where(g=>g.Count()>1).Select(g=>g.Key).ToHashSet(); + return parts.Select((part,i)=>{ + var checkpoint=new ChapterCheckpoint{ChapterId=part.Chapter.CanonicalId,HeadingId=part.Chapter.HeadingId,NativeHeadingId=part.Rows[0].Occurrence.NativeId,ParagraphCount=part.Rows.Length,Order=i,AcceptedRevision=acceptedRevision,NextHeadingId=part.Endp.Occurrence.Text)); + checkpoint.MappingHash=ChapterFingerprint.Mapping(part.Rows.Select(p=>$"{p.Occurrence.Id:D}:{p.ChapterId}:{p.SceneId:D}:{p.PositionVerified}:{p.Story}")); + if(part.Rows.Any(p=>duplicateNative.Contains(p.Occurrence.NativeId)))throw new ArgumentException("Native paragraph identity is duplicated elsewhere in this manuscript."); + checkpoint.IdentityHash=ChapterFingerprint.Identity(Evidence(part)); + }catch(ArgumentException e){checkpoint.Status="Needs review";checkpoint.Message=e.Message;} + var prior=state.ChapterCheckpoints.FirstOrDefault(c=>c.ChapterId==checkpoint.ChapterId&&c.ContentHash==checkpoint.ContentHash&&c.IdentityHash==checkpoint.IdentityHash&&c.MappingHash==checkpoint.MappingHash); + if(prior!=null){checkpoint.LastSuccessfulSyncUtc=prior.LastSuccessfulSyncUtc;checkpoint.AcceptedRevision=prior.AcceptedRevision;} + return checkpoint; + }).ToArray(); + } + private static ChapterParagraph[] Evidence(ChapterPart part)=>part.Rows.Select(p=>new ChapterParagraph{NativeId=p.Occurrence.NativeId,Length=p.Occurrence.Text.Length,Outline=p.Occurrence.Outline}).ToArray(); + public static ChapterValidationResult Validate(ParagraphManuscript state,ChapterObservation proof,DateTime now) + { + if(proof.Algorithm!=ChapterFingerprint.Version||proof.RequestId==Guid.Empty||proof.ManuscriptId!=state.ManuscriptId||proof.BaseRevision!=state.Revision||proof.SessionId==Guid.Empty||proof.WordRevision<0||proof.Start<0||proof.End<=proof.Start||proof.Paragraphs==null||proof.Paragraphs.Length==0)throw new InvalidOperationException("Stale or unsupported chapter evidence."); + var part=Parts(state).SingleOrDefault(p=>p.Chapter.CanonicalId==proof.ChapterId)??throw new InvalidOperationException("The chapter is not in the accepted manuscript index."); + if(part.Rows.Any(p=>p.ChapterId>0&&p.ChapterId!=proof.ChapterId))throw new InvalidOperationException("Existing chapter assignments disagree with chapter boundaries; review is required."); + var identity=ChapterFingerprint.Identity(proof.Paragraphs); + if(identity!=proof.IdentityHash||proof.Paragraphs.Sum(p=>(long)p.Length)!=proof.End-proof.Start)throw new ArgumentException("Chapter identity/position evidence is incomplete."); + var all=Build(state,state.Revision);var checkpoint=all.Single(p=>p.ChapterId==proof.ChapterId); + if(checkpoint.ContentHash!=proof.ContentHash||part.Rows.Length!=proof.Paragraphs.Length)throw new InvalidOperationException("Changed chapter; bounded chapter reconciliation is required. Accepted mappings are unchanged."); + var bindings=new List(); + for(int n=0;np.Occurrence.Id!=accepted.Id&&p.Occurrence.NativeId==observed.NativeId))throw new InvalidOperationException("Cross-chapter duplicate native identity; review is required."); + if(accepted.NativeId=="")bindings.Add(new(accepted.Id,observed.NativeId)); + } + if(bindings.Count>0&&(!proof.Reconcile||all.Count(c=>c.ContentHash==proof.ContentHash)!=1))throw new InvalidOperationException("Legacy native identities require explicit repair and unique complete chapter evidence. No reimport is required."); + // A moved chapter may be validated locally, but its canonical ordering is never silently rewritten. + checkpoint.Status="Synchronised";checkpoint.Message=checkpoint.NextHeadingId!=""&&checkpoint.NextHeadingId!=proof.NextHeadingId?"Chapter text and paragraph map verified; surrounding chapter order needs review.":"Accepted chapter positions verified for this session."; + checkpoint.IdentityHash=identity;checkpoint.NativeHeadingId=proof.Paragraphs[0].NativeId;checkpoint.LastSuccessfulSyncUtc=now; + var start=proof.Start;var positions=part.Rows.Select((row,i)=>{var end=checked(start+proof.Paragraphs[i].Length);var scene=state.Scenes.FirstOrDefault(s=>!s.Retired&&s.Id==row.SceneId&&s.ChapterId==proof.ChapterId);var value=new ChapterPosition(row.Occurrence.Id,start,end,proof.ChapterId,scene?.CanonicalId>0?scene.CanonicalId:null,row.PositionVerified&&row.ChapterId==proof.ChapterId);start=end;return value;}).ToArray(); + return new(checkpoint,bindings.ToArray(),positions); + } + public static ParagraphOccurrence[] MergeChapter(ParagraphManuscript state,ChapterObservation proof) + { + var part=Parts(state).SingleOrDefault(p=>p.Chapter.CanonicalId==proof.ChapterId)??throw new InvalidOperationException("Unknown chapter."); + if(proof.BaseRevision!=state.Revision||proof.ManuscriptId!=state.ManuscriptId||!proof.Reconcile||proof.Paragraphs.Any(p=>p.Text==null||p.Text.Length!=p.Length)||ChapterFingerprint.Content(proof.Paragraphs.Select(p=>p.Text!))!=proof.ContentHash||ChapterFingerprint.Identity(proof.Paragraphs)!=proof.IdentityHash)throw new InvalidOperationException("A complete, explicitly authorised changed chapter is required."); + if(part.Rows[0].Occurrence.NativeId==""||proof.Paragraphs[0].NativeId!=part.Rows[0].Occurrence.NativeId||proof.Paragraphs[0].Outline!=1||proof.Paragraphs.Skip(1).Any(p=>p.Outline==1))throw new InvalidOperationException("Chapter insertion, deletion or uncertain heading requires structural review; no cross-chapter grouping was proposed."); + var outside=state.Paragraphs.Take(part.Index).Concat(state.Paragraphs.Skip(part.End)).Select(p=>p.Occurrence.NativeId).Where(id=>id!="").ToHashSet(); + if(proof.Paragraphs.Any(p=>outside.Contains(p.NativeId))||proof.NextHeadingId!=(part.Endnew ParagraphOccurrence{NativeId=p.NativeId,Text=p.Text!,Outline=p.Outline}).ToArray(); + var rows=state.Paragraphs.Take(part.Index).Select(p=>p.Occurrence).Concat(inserted).Concat(state.Paragraphs.Skip(part.End).Select(p=>p.Occurrence)).Select(p=>new ParagraphOccurrence{Id=p.Id,NativeId=p.NativeId,Text=p.Text,Outline=p.Outline}).ToArray(); + int position=0;for(int n=0;n Manifest(int user,int book,Guid session,long wordRevision) + { + if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException(); + var state=await manuscripts.Get(user,book)??throw new InvalidOperationException("Finish the existing manuscript import first; no saved index is available."); + var live=await checkpoints.List(user,book,session,wordRevision);var sources=ChapterCheckpointEngine.Build(state,state.Revision); + return new(){BookId=book,ManuscriptId=state.ManuscriptId,Revision=state.Revision,Mode=state.Mode,Chapters=ChapterCheckpointEngine.Parts(state).Select(part=>{ + var source=sources.Single(c=>c.ChapterId==part.Chapter.CanonicalId);var accepted=live.Any(c=>c.ChapterID==source.ChapterId&&c.ContentHash==source.ContentHash&&c.IdentityHash==source.IdentityHash&&c.MappingHash==source.MappingHash); + return new ChapterManifestItem{ChapterId=source.ChapterId,Title=part.Chapter.Title,HeadingNativeId=source.NativeHeadingId,ContentHash=source.ContentHash,IdentityHash=source.IdentityHash,Start=part.Rows[0].Occurrence.Start,End=part.Rows[^1].Occurrence.End,ParagraphCount=source.ParagraphCount,State=accepted?"Synchronised":source.Status}; + }).ToArray()}; + } + public async Task Repair(int user,int book,Guid? instance,Guid? session) + { + var status=await manuscripts.Status(user,book)??throw new InvalidOperationException("The accepted snapshot is missing; finish the existing import, do not reimport an already indexed book."); + if(!status.CanWrite)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active. Accepted checkpoints are preserved."); + if(instance.HasValue!=session.HasValue)throw new InvalidOperationException("Choose a complete Word session."); + var live=presence.Read(user,book).Where(l=>l.Position.WordAvailable&&l.Position.CanChapterSync&&l.Position.WordSaved==true).ToArray(); + var selected=instance.HasValue?live.SingleOrDefault(l=>l.Instance==instance&&l.Session==session):live.Count(l=>l.Position.Active)==1?live.Single(l=>l.Position.Active):live.Length==1?live[0]:null; + if(selected==null)throw new InvalidOperationException("Open and save the intended manuscript with a chapter-capable Companion, then select its document connection."); + if(selected.Position.ManuscriptId!=status.ManuscriptId)throw new InvalidOperationException("This document has a different manuscript identity. No existing import was changed."); + var id=Guid.NewGuid();if(!presence.RequestChapterRepair(user,selected,id))throw new InvalidOperationException("Word is busy with another request. Accepted chapter checkpoints are preserved.");return id; + } + public async Task Accept(int user,string grant,int book,ChapterObservation proof) + { + if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException(); + var status=await manuscripts.Status(user,book)??throw new InvalidOperationException("No accepted manuscript index."); + if(!status.CanWrite)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active; chapter acceptance is paused."); + var lease=presence.Read(user,book).SingleOrDefault(l=>l.Instance==proof.InstanceId&&l.Session==proof.SessionId&&l.Grant==grant&&l.Position.CanChapterSync&&l.Position.WordAvailable&&l.Position.WordSaved==true&&l.Position.ManuscriptId==proof.ManuscriptId&&l.Position.Revision==proof.WordRevision); + if(lease==null)throw new InvalidOperationException("Word document closed, changed, became unsaved or was disconnected; no stale checkpoint was accepted."); + var permitted=status.Mode=="OnSave"||presence.CanRepairChapter(user,lease,proof.OperationId); + var state=await manuscripts.Get(user,book)??throw new InvalidOperationException("Missing accepted snapshot."); + var source=ChapterCheckpointEngine.Build(state,state.Revision).SingleOrDefault(c=>c.ChapterId==proof.ChapterId)??throw new InvalidOperationException("Unknown accepted chapter."); + if(source.ContentHash!=proof.ContentHash){ + if(!permitted||proof.Paragraphs.Any(p=>p.Text==null))return new(){State="Changed",ChapterId=proof.ChapterId,Revision=state.Revision,AllowText=permitted,Message=permitted?"Changed chapter; submit this chapter only for existing paragraph reconciliation.":"Changed chapter. Use Synchronise or Repair to authorise chapter reconciliation; no prose was uploaded."}; + state=await reconciliation.ReconcileChapter(user,book,proof);proof.BaseRevision=state.Revision; + } + // Native adoption is explicit repair only; ordinary hash checks cannot mint trust. + proof.Reconcile=presence.CanRepairChapter(user,lease,proof.OperationId); + var validated=ChapterCheckpointEngine.Validate(state,proof,clock.GetUtcNow().UtcDateTime); + await checkpoints.Accept(user,book,proof,validated); + return new(){Accepted=true,State=validated.Checkpoint.Message.Contains("order needs review")?"Needs review":"Synchronised",ChapterId=proof.ChapterId,Revision=state.Revision,Message=validated.Checkpoint.Message}; + } +} diff --git a/PlotLine/Services/Manuscript/ParagraphManuscriptService.cs b/PlotLine/Services/Manuscript/ParagraphManuscriptService.cs index f5e838a3..15f0a2f4 100644 --- a/PlotLine/Services/Manuscript/ParagraphManuscriptService.cs +++ b/PlotLine/Services/Manuscript/ParagraphManuscriptService.cs @@ -49,7 +49,7 @@ public sealed class ParagraphManuscriptService(IParagraphManuscriptRepository re if(bindings.Select(b=>b.HeadingId).Distinct().Count()!=bindings.Count)throw new InvalidOperationException("Multiple canonical chapters share one captured section. Review their association before enabling tracking; no manuscript was changed."); var state=ParagraphManuscriptEngine.Bootstrap(source.BookID,project,manuscript,paragraphs,limits);state.Chapters=bindings;foreach(var heading in state.Paragraphs.Where(p=>p.Occurrence.Outline==1)){var binding=bindings.FirstOrDefault(b=>b.HeadingId==heading.Occurrence.Id);heading.ChapterId=binding?.CanonicalId>0?binding.CanonicalId:null;heading.PositionVerified=heading.ChapterId.HasValue;} state.DocumentName=source.DocumentTitle??"Word manuscript";state.Mode=mode;state.SessionId=source.NativeSessionID??Guid.Empty;state.WordRevision=source.NativeRevision??0; - state.EventPositions=(await repository.Events(user,source.BookID)).ToList();return await repository.Save(user,state,-1,source.PreviewID); + state.EventPositions=(await repository.Events(user,source.BookID)).ToList();state.ChapterCheckpoints=ChapterCheckpointEngine.Build(state,0).ToList();return await repository.Save(user,state,-1,source.PreviewID); } public static ParagraphOccurrence[] LegacyParagraphs(ManuscriptScanPreview source) { @@ -69,6 +69,17 @@ public sealed class ParagraphManuscriptService(IParagraphManuscriptRepository re ParagraphManuscriptEngine.Reconcile(state,rows);state.ManuscriptId=capture.ManuscriptId;state.SessionId=capture.SessionId;state.WordRevision=capture.Revision; return await Save(user,state,expected,capture.RequestId); } + public async Task ReconcileChapter(int user,int book,ChapterObservation proof) + { + RequireFeature();var state=await repository.Get(user,book)??throw new InvalidOperationException("The accepted manuscript snapshot is missing."); + if(state.LastRequestId==proof.RequestId)return state; + var rows=ChapterCheckpointEngine.MergeChapter(state,proof); + state.EventPositions=(await repository.Events(user,book)).ToList(); + ParagraphManuscriptEngine.Reconcile(state,rows); + // Logical positions after a partial repair are not a claim that every physical Word offset was validated. + state.SessionId=Guid.Empty;state.WordRevision=-1; + return await Save(user,state,proof.BaseRevision,proof.RequestId); + } public async Task Change(int user,int book,long expected,string action,Guid target=default,Guid other=default,string? text=null,string? kind=null,int eventId=0,bool primary=true,int from=0,int to=0,int? startOffset=null,int? endOffset=null) { RequireFeature();var state=await repository.Get(user,book)??throw new ArgumentException("Enable paragraph tracking first.");if(state.Revision!=expected)throw new InvalidOperationException("The manuscript changed. Refresh before making this change."); @@ -95,7 +106,7 @@ public sealed class ParagraphManuscriptService(IParagraphManuscriptRepository re } private async Task Save(int user,ParagraphManuscript state,long expected,Guid request) { - ParagraphManuscriptEngine.Validate(state);var result=await repository.Save(user,state,expected,request); + ParagraphManuscriptEngine.Validate(state);if(state.Chapters.Count>0)state.ChapterCheckpoints=ChapterCheckpointEngine.Build(state,expected+1).ToList();var result=await repository.Save(user,state,expected,request); // Reuse deterministic continuity/statistics; never schedule whole-book AI. try{await statistics.RecalculateBookAsync(state.BookId);}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or InvalidOperationException){logger?.LogWarning("Manuscript revision {Revision} committed; derived statistics require refresh ({FailureKind}).",result.Revision,e.GetType().Name);} return result; diff --git a/PlotLine/Services/NativeCompanion/NativePresenceStore.cs b/PlotLine/Services/NativeCompanion/NativePresenceStore.cs index dec7a854..aa79a4f4 100644 --- a/PlotLine/Services/NativeCompanion/NativePresenceStore.cs +++ b/PlotLine/Services/NativeCompanion/NativePresenceStore.cs @@ -19,12 +19,16 @@ public sealed class NativePresenceStore(TimeProvider clock) lock(gate){Prune();var key=(user,instance,session);if(instance==Guid.Empty||session==Guid.Empty||(value.WordAvailable&&value.ManuscriptId==Guid.Empty)||value.Revision<0||value.Sequence<=0||value.BookId<0||value.DocumentTitle==null||value.DocumentTitle.Length>260||value.DocumentTitle.IndexOfAny(['\\','/'])>=0||expires<=clock.GetUtcNow()||revoked.ContainsKey(grant))return false; if(leases.TryGetValue(key,out var prior)){if(prior.Grant!=grant||value.Sequence<=prior.Position.Sequence||value.Revision=4096||leases.Values.Count(p=>p.User==user)>=64)return false; - leases[key]=new(user,grant,expires,instance,session,new NativePresence{CaptureRequestId=value.CaptureRequestId,CaptureProgress=value.CaptureProgress,ParagraphRevision=value.ParagraphRevision,CanCapture=value.CanCapture,CanParagraphSync=value.CanParagraphSync,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordRunning=value.WordRunning,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;} + leases[key]=new(user,grant,expires,instance,session,new NativePresence{CanChapterSync=value.CanChapterSync,CaptureRequestId=value.CaptureRequestId,CaptureProgress=value.CaptureProgress,ParagraphRevision=value.ParagraphRevision,CanCapture=value.CanCapture,CanParagraphSync=value.CanParagraphSync,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordRunning=value.WordRunning,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;} } public NativeLease[] Read(int user,int book){lock(gate){Prune();return leases.Values.Where(p=>p.User==user&&(book==0||p.Position.BookId==book)).OrderByDescending(p=>p.Updated).ToArray();}} public bool Navigate(int user,int book,Guid instance,Guid session,Guid manuscript,long revision,int start,bool requireSaved=false,Guid? navigationId=null) {lock(gate){Prune();var key=(user,instance,session);if(!leases.TryGetValue(key,out var lease)||!lease.Position.WordAvailable||lease.Position.BookId!=book||lease.Position.ManuscriptId!=manuscript||lease.Position.Revision!=revision||(requireSaved&&lease.Position.WordSaved!=true)||start<0||(navigation.TryGetValue(key,out var queued)&&queued.Kind!="navigate"))return false;var id=navigationId??Guid.NewGuid();if(id==Guid.Empty)return false;var receipt=(user,instance,session,id);if(navigationReceipts.TryGetValue(receipt,out var prior))return prior.Revision==revision&&prior.Start==start;if(navigationReceipts.Count>=8192)return false;navigationReceipts[receipt]=(clock.GetUtcNow().AddMinutes(15),revision,start);navigation[key]=new(){Id=id,Kind="navigate",SessionId=session,Revision=revision,Chapter=new(){Start=start}};return true;}} public void RequestCancellation(int user,NativeLease selected){lock(gate){var key=(user,selected.Instance,selected.Session);if(leases.TryGetValue(key,out var current)&¤t.Grant==selected.Grant&¤t.Position.Revision==selected.Position.Revision)navigation[key]=new(){Kind="cancel",SessionId=selected.Session,Revision=selected.Position.Revision};}} + private readonly Dictionary chapterRepairs=[]; + public bool RequestChapterRepair(int user,NativeLease selected,Guid id) + {lock(gate){Prune();foreach(var old in chapterRepairs.Where(p=>p.Value.Expires<=clock.GetUtcNow()).Select(p=>p.Key).ToArray())chapterRepairs.Remove(old);var key=(user,selected.Instance,selected.Session);if(chapterRepairs.Count>=128||!leases.TryGetValue(key,out var current)||current.Grant!=selected.Grant||!current.Position.CanChapterSync||current.Position.WordSaved!=true||current.Position.Revision!=selected.Position.Revision||navigation.ContainsKey(key))return false;chapterRepairs[id]=(user,selected.Position.BookId,selected.Instance,selected.Session,selected.Position.Revision,clock.GetUtcNow().AddMinutes(30));navigation[key]=new(){Id=id,Kind="chapter-repair",BookId=selected.Position.BookId,SessionId=selected.Session,Revision=selected.Position.Revision};return true;}} + public bool CanRepairChapter(int user,NativeLease lease,Guid id){lock(gate)return chapterRepairs.TryGetValue(id,out var repair)&&repair.User==user&&repair.Book==lease.Position.BookId&&repair.Instance==lease.Instance&&repair.Session==lease.Session&&repair.Revision==lease.Position.Revision&&repair.Expires>clock.GetUtcNow();} public bool RequestCapture(int user,NativeLease selected,Guid request,int book=0,bool paragraphs=false,bool synchronise=false,long baseRevision=0,string baseHash="") {lock(gate){Prune();var key=(user,selected.Instance,selected.Session);if(!leases.TryGetValue(key,out var lease)||lease.Grant!=selected.Grant||lease.Position.Revision!=selected.Position.Revision||lease.Position.ManuscriptId!=selected.Position.ManuscriptId||(book>0&&lease.Position.BookId!=0&&lease.Position.BookId!=book)||!lease.Position.CanCapture||navigation.ContainsKey(key))return false;navigation[key]=new(){Id=request,BaseRevision=baseRevision,BaseSnapshotHash=baseHash,BookId=book,ParagraphTracking=paragraphs,Kind=synchronise?"paragraph-snapshot":"wizard-capture",SessionId=lease.Session,Revision=lease.Position.Revision};return true;}} public AdapterCommand? TakeNavigation(int user,string grant,Guid instance,Guid session) diff --git a/PlotLine/Sql/245_ChapterSynchronisation.sql b/PlotLine/Sql/245_ChapterSynchronisation.sql new file mode 100644 index 00000000..60076d12 --- /dev/null +++ b/PlotLine/Sql/245_ChapterSynchronisation.sql @@ -0,0 +1,73 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +IF OBJECT_ID('dbo.BookChapterValidations','U') IS NULL + CREATE TABLE dbo.BookChapterValidations( + BookID int NOT NULL,ChapterID int NOT NULL,UserID int NOT NULL,SessionID uniqueidentifier NOT NULL,ManuscriptID uniqueidentifier NOT NULL,WordRevision bigint NOT NULL, + RequestID uniqueidentifier NOT NULL,ContentHash char(64) NOT NULL,IdentityHash char(64) NOT NULL,MappingHash char(64) NOT NULL,Positions nvarchar(max) NOT NULL, + SourceRevision bigint NOT NULL,ValidatedUtc datetime2 NOT NULL,ExpiresUtc datetime2 NOT NULL, + CONSTRAINT PK_BookChapterValidations PRIMARY KEY(BookID,ChapterID,UserID,SessionID), + CONSTRAINT FK_BookChapterValidations_Book FOREIGN KEY(BookID) REFERENCES dbo.Books(BookID) ON DELETE CASCADE, + CONSTRAINT CK_BookChapterValidations_Json CHECK(ISJSON(Positions)=1)); +GO +CREATE OR ALTER PROCEDURE dbo.BookChapterSync + @Action varchar(16),@UserID int,@BookID int,@ChapterID int=NULL,@SessionID uniqueidentifier=NULL,@ManuscriptID uniqueidentifier=NULL,@WordRevision bigint=NULL, + @ExpectedRevision bigint=NULL,@RequestID uniqueidentifier=NULL,@Checkpoint nvarchar(max)=NULL,@Positions nvarchar(max)=NULL,@Bindings nvarchar(max)=NULL,@Position int=NULL +AS +BEGIN + SET NOCOUNT ON;SET XACT_ABORT ON; + DECLARE @ProjectID int; + SELECT @ProjectID=b.ProjectID FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID; + IF @ProjectID IS NULL THROW 51000,'Book access denied',1; + IF @Action='list' BEGIN SELECT ChapterID,SessionID,WordRevision,ContentHash,IdentityHash,MappingHash,SourceRevision,ValidatedUtc FROM dbo.BookChapterValidations WHERE BookID=@BookID AND UserID=@UserID AND SessionID=@SessionID AND WordRevision=@WordRevision AND ExpiresUtc>SYSUTCDATETIME();RETURN;END; + IF @Action='position' + BEGIN + SELECT CAST(1 AS bit) HasSnapshot,m.Revision,p.ChapterID,p.SceneID + FROM dbo.BookParagraphManuscripts m + OUTER APPLY(SELECT TOP(1) pos.ChapterID,CASE WHEN s.ChapterID=pos.ChapterID AND s.IsArchived=0 THEN pos.SceneID END SceneID + FROM dbo.BookChapterValidations v + CROSS APPLY OPENJSON(m.Payload,'$.ChapterCheckpoints') WITH(ChapterID int '$.ChapterId',ContentHash char(64),IdentityHash char(64),MappingHash char(64)) c + CROSS APPLY OPENJSON(v.Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End',ChapterID int '$.ChapterId',SceneID int '$.SceneId',Verified bit) pos + JOIN dbo.Chapters ch ON ch.ChapterID=pos.ChapterID AND ch.BookID=m.BookID AND ch.IsArchived=0 + LEFT JOIN dbo.Scenes s ON s.SceneID=pos.SceneID + WHERE v.BookID=m.BookID AND v.ChapterID=c.ChapterID AND pos.ChapterID=c.ChapterID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.ManuscriptID=@ManuscriptID AND v.WordRevision=@WordRevision + AND v.ExpiresUtc>SYSUTCDATETIME() AND v.ContentHash=c.ContentHash AND v.IdentityHash=c.IdentityHash AND v.MappingHash=c.MappingHash + AND pos.Verified=1 AND pos.StartPosition<=@Position AND pos.EndPosition>@Position) p WHERE m.BookID=@BookID;RETURN; + END; + IF @Action<>'accept' THROW 51000,'Unknown chapter operation',1; + IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND AccessRole=N'Owner' AND IsActive=1) THROW 51000,'Project owner authority required',1; + IF ISJSON(@Checkpoint)<>1 OR ISJSON(@Positions)<>1 OR ISJSON(@Bindings)<>1 OR DATALENGTH(@Positions)>4*1024*1024 OR DATALENGTH(@Checkpoint)>16384 OR @SessionID IS NULL OR @RequestID IS NULL OR @WordRevision<0 THROW 51000,'Invalid chapter validation',1; + IF EXISTS(SELECT 1 FROM dbo.UserOnboardingState WHERE BookID=@BookID AND OnboardingCompletedUtc IS NULL) OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs WHERE BookID=@BookID AND Status IN ('Pending','Queued','Running','Processing','Preparing','ReadingScenes','AnalysingCharacters','AnalysingRelationships','AnalysingLocations','AnalysingAssets','AnalysingTimeline','Finalising')) THROW 51000,'Active import or analysis protected',1; + BEGIN TRANSACTION; + DECLARE @Payload nvarchar(max),@Revision bigint; + SELECT @Payload=Payload,@Revision=Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID; + IF @Revision IS NULL OR @Revision<>@ExpectedRevision OR TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId'))<>@ManuscriptID THROW 51000,'Accepted manuscript changed; chapter validation refused',1; + IF NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChapterID AND BookID=@BookID AND IsArchived=0) OR TRY_CONVERT(int,JSON_VALUE(@Checkpoint,'$.ChapterId'))<>@ChapterID THROW 51000,'Cross-book chapter rejected',1; + DECLARE @Native nvarchar(8),@Paragraph uniqueidentifier,@Index int,@Existing nvarchar(16); + DECLARE bind CURSOR LOCAL FAST_FORWARD FOR SELECT ParagraphId,NativeId FROM OPENJSON(@Bindings) WITH(ParagraphId uniqueidentifier,NativeId nvarchar(8)); + OPEN bind;FETCH NEXT FROM bind INTO @Paragraph,@Native; + WHILE @@FETCH_STATUS=0 + BEGIN + SET @Index=NULL;SET @Existing=NULL; + SELECT @Index=CONVERT(int,j.[key]),@Existing=JSON_VALUE(j.value,'$.Occurrence.NativeId') FROM OPENJSON(@Payload,'$.Paragraphs') j WHERE TRY_CONVERT(uniqueidentifier,JSON_VALUE(j.value,'$.Occurrence.Id'))=@Paragraph; + IF @Index IS NULL OR COALESCE(@Existing,'') NOT IN ('',@Native) OR LEN(@Native)<>8 OR @Native LIKE '%[^0-9A-F]%' THROW 51000,'Native identity adoption conflicts with existing evidence',1; + SET @Payload=JSON_MODIFY(@Payload,CONCAT('$.Paragraphs[',@Index,'].Occurrence.NativeId'),@Native); + FETCH NEXT FROM bind INTO @Paragraph,@Native; + END; + CLOSE bind;DEALLOCATE bind; + IF EXISTS(SELECT 1 FROM OPENJSON(@Positions) WITH(ParagraphId uniqueidentifier,ChapterId int) p WHERE p.ChapterId<>@ChapterID OR NOT EXISTS(SELECT 1 FROM OPENJSON(@Payload,'$.Paragraphs') a WHERE TRY_CONVERT(uniqueidentifier,JSON_VALUE(a.value,'$.Occurrence.Id'))=p.ParagraphId)) THROW 51000,'Chapter position refers to an unknown paragraph',1; + IF EXISTS(SELECT 1 FROM dbo.BookChapterValidations WHERE UserID=@UserID AND BookID=@BookID AND RequestID=@RequestID AND (ChapterID<>@ChapterID OR SessionID<>@SessionID OR WordRevision<>@WordRevision OR Positions<>@Positions)) THROW 51000,'Request identity was reused for different chapter evidence',1; + IF JSON_QUERY(@Payload,'$.ChapterCheckpoints') IS NULL SET @Payload=JSON_MODIFY(@Payload,'$.ChapterCheckpoints',JSON_QUERY('[]')); + SET @Index=NULL;SELECT @Index=CONVERT(int,j.[key]) FROM OPENJSON(@Payload,'$.ChapterCheckpoints') j WHERE TRY_CONVERT(int,JSON_VALUE(j.value,'$.ChapterId'))=@ChapterID; + IF @Index IS NULL SET @Payload=JSON_MODIFY(@Payload,'append $.ChapterCheckpoints',JSON_QUERY(@Checkpoint)); + ELSE SET @Payload=JSON_MODIFY(@Payload,CONCAT('$.ChapterCheckpoints[',@Index,']'),JSON_QUERY(@Checkpoint)); + IF EXISTS(SELECT 1 FROM dbo.BookChapterValidations WHERE BookID=@BookID AND ChapterID=@ChapterID AND UserID=@UserID AND SessionID=@SessionID AND WordRevision=@WordRevision AND (Positions<>@Positions OR ContentHash<>JSON_VALUE(@Checkpoint,'$.ContentHash') OR IdentityHash<>JSON_VALUE(@Checkpoint,'$.IdentityHash'))) THROW 51000,'Conflicting evidence for the same live Word revision',1; + -- Metadata-only adoption: canonical prose, GUIDs, scene assignments and author decisions are not rewritten. + UPDATE dbo.BookParagraphManuscripts SET Payload=@Payload WHERE BookID=@BookID; + DELETE dbo.BookChapterValidations WHERE BookID=@BookID AND ExpiresUtc