diff --git a/Docs/WordCompanion/WindowsHandover/2026-11-12-incremental-synchronisation-investigation.md b/Docs/WordCompanion/WindowsHandover/2026-11-12-incremental-synchronisation-investigation.md new file mode 100644 index 00000000..877f1e27 --- /dev/null +++ b/Docs/WordCompanion/WindowsHandover/2026-11-12-incremental-synchronisation-investigation.md @@ -0,0 +1,75 @@ +# Incremental synchronisation investigation + +## Delivery status + +**The incremental-edit acceptance criteria have not passed. This is a checkpoint-retention and progress-label correction, not a qualified incremental synchronisation release.** Do not install an upgrade or close Word on the basis of this report. No version bump, installer, server deployment, database change or manuscript mutation is included. The server checkpoint-retention correction requires Development deployment and Windows qualification before its live result can be claimed. + +The existing shared branch was clean and fast-forwarded to `b464e19`, including the 1.0.0.33 Windows qualification. The protected manuscript and accepted data have not been accessed by these tests. + +## Established cause + +The current implementation performs selective reconciliation after document-wide verification. These are different operations: + +1. `Vsto/WordAdapter.cs`, `CaptureSelection`, detects changed document length or the transition from saved to unsaved. It increments the document revision and registers the new descriptor. `BeforeSave` can also increment the revision. The periodic selection probe uses the same evidence. +2. `Agent/TrayCoordinator.cs`, `Exchange`, calls `Cancel` on the revision transition. `CancelChapterWork` invalidates Context and retires the old work. `GetChapterWork` creates a fresh work item when its revision differs from the document revision. +3. `LoadChapterManifest` requests session acceptance for the new Word revision. Durable accepted checkpoints survive, but they are distinct from live position acceptance for that session/revision. The server manifest looks up live checkpoints by session and Word revision. +4. `QueueChapter` and `AdvanceChapter` traverse the manuscript. `ProcessChapter` reads and fingerprints each chapter. Matching evidence takes the bounded checkpoint reuse path; changed content takes the existing chapter reconciliation path. + +Thus changing the progress label or retaining the old `Checked` dictionary cannot safely implement incremental synchronisation. Absolute positions downstream of an edit may have shifted, and old session evidence cannot simply be relabelled as evidence for the new revision. The current path has no affected-range journal or trustworthy proof that the other chapters remain unchanged. + +The prior handover records an earlier recovered Word pass with **48 calculated fingerprints, 48 matches, 48 reuses, two reuse requests, zero individual submissions and zero reconciliations**, completed in **19.615 seconds** from the new recognition measurement. Those counters are not the latest 1.0.0.33 saved-edit counters. The handover explicitly leaves live 1.0.0.33 qualification pending. Subsequently supplied agent logs and Development service logs establish the saved-edit counts below. + +## Change evidence and unsaved edits + +The existing detector is not a complete edit journal: a same-length replacement while already unsaved need not change either observed value. Cursor movement cannot close this gap. Paste, multi-chapter replacement, heading changes, floating-anchor changes and Undo/Redo require evidence beyond a selected range. + +Microsoft documents [WindowSelectionChange](https://learn.microsoft.com/en-us/office/vba/api/word.application.windowselectionchange) as a selection event. The [Revisions collection](https://learn.microsoft.com/en-us/office/vba/api/word.revisions) only records edits when change tracking is enabled. Enabling Track Changes would alter the author's editing workflow; it is not a transparent replacement for the missing journal. These API contracts do not establish a complete nonintrusive native change-range mechanism. + +Unsaved acceptance is currently prohibited at multiple layers: the Word chapter reader and native identity validation, agent presence scheduling and reconciliation, server checkpoint reuse, chapter validation, finish and explicit repair leases. A client-only quiet timer would neither make unsaved acceptance safe nor satisfy the server contract. No guards were removed. + +Before retaining unaffected checkpoints, the implementation needs a qualified source of complete change evidence and a safe position-rebasing contract. Saved-package comparison is a possible source after save, but cannot establish unsaved in-memory state, and must account for heading/style dependencies, native IDs, structural content and floating anchors. Comparing only text or only document length would be insufficient. No unqualified comparison mechanism is shipped here. + +## Progress correction + +The ribbon now labels the existing verification phase **Checking**, and shows **N verified · M pending**. Counts continue to come from server-acknowledged chapter acceptance. Pending fingerprint reuse is not counted as verified. The agent's progress explanation explicitly distinguishes checking evidence from reconciliation counts in diagnostics. + +The agent change does not retain unaffected live chapter acceptance across Word revisions or implement the three-second/60-second scheduler. Durable server acceptance is retained only when all required checkpoint evidence still matches. Manual Synchronise and Repair retain their existing saved-revision lifecycle. Context retains its existing cursor/revision guards and its current unsaved limitation. The task remains unfinished in these areas. + +## Windows evidence required + +Use an authorised disposable document and Development book. Preserve the protected baseline. Do not close Word or install anything without explicit approval. + +1. Establish an unchanged-open baseline, recording live/XML chapter reads, calculated fingerprints, matches/mismatches, reused checkpoints, submissions, reconciliations, requests and completion timing. +2. Edit one paragraph, observe unsaved behaviour, then save. Capture the same counters for the new revision separately from the baseline. Record last keystroke, verification start, first Context and completion times. The present implementation is expected to verify broadly; this is not an incremental acceptance pass. +3. Exercise manual Synchronise and Repair separately, then edit/save while work is active. Verify old revision replies cannot restore old Context or complete a retired operation. +4. Include same-length edits while already dirty, Undo/Redo, multi-chapter replacement, heading/boundary changes and floating-anchor movement when qualifying any future change-evidence mechanism. + +Only a later implementation demonstrating one affected chapter, 47 retained trusted checkpoints, selective live reads and reconciliation, automatic scheduling and responsive typing can satisfy the requested definition of done. Fixture timings are not Word performance measurements. + +## Portable validation + +- `dotnet build PlotLine.slnx`: passed, zero warnings/errors. This Linux build does not build the Office/VSTO add-in; Windows compilation and UI qualification are still required. +- Native foundation executable: 273 checks passed. +- Native `--chapter-sync` executable: 371 checks passed, including the added acknowledgement/progress assertions. +- Application `--chapter-sync` executable: 71 checks passed. +- Full application executable: 457 checks passed on the final implementation. +- The isolated 48-chapter HTTP fixture with one changed chapter measured 1,328.4 ms, two reuse requests, two individual acceptance requests and one reconciliation. It still verified all 48 chapters. HTTP was in memory; there was no Word, real network or database. This result proves existing selective reconciliation, not selective verification or author responsiveness. + +## Supplied Windows log and matching Development evidence + +The supplied `agent.jsonl.previous` contains 7,680 records from 19:53:06 to 19:58:23 UTC on 12 November, for session `4218b4b6-f1ac-43cf-9857-c43096b3904f`. It begins partway through an earlier read cycle. There are no server reconciliation counters in the IPC file itself; its `status=ok` values acknowledge protocol handling. + +Read-only Development service journal correlation establishes: + +- Initial completion: 19:53:21.514 UTC, Word revision 0, all 48 accepted; one reuse batch containing 48 chapters. +- Manual Synchronise: 19:54:02.727 UTC in the supplied agent log. +- Final document registration: 19:54:09.179 UTC; 94 chapter begin/end pairs subsequently occur from 19:54:10.881 to 19:58:15.357 UTC (244.476 seconds of read-cycle span, not active COM time). +- Exactly one server reconciliation persisted, for chapter 11172, at 19:54:15.622 UTC. Its reconciliation timing was 4,315 ms, and checkpoint persistence completed with a cumulative 5,535 ms timing. +- The edited cycle made 49 individual observation requests and persisted 48 chapter checkpoints. There was no successful batch-reuse event after its reconciliation. +- Final completion: 19:58:28.623 UTC, Word revision 20, all 48 accepted. This final server event is after the supplied IPC file ends. Final registration to completion was approximately 259.444 seconds. + +This proves one changed-chapter reconciliation plus broad verification and individual checkpoint acceptance, not 48 prose reconciliations. The failed batch/retry cause must be distinguished from the separate absence of selective Word change evidence. + +`ChapterCheckpointEngine.Build` previously copied a matching prior checkpoint's position hash, time and accepted revision, but copied its status only for Needs review. After reconciliation rebuilt the durable checkpoint list, unchanged Synchronised checkpoints became Not yet checked. This invalidates their eligibility for reuse and explains a route to the broad retry. The correction preserves matching Synchronised status and message, requires matching algorithm and chapter order, and never overrides a newly detected Needs review result. The manifest separately derives live session state so a retained durable Synchronised checkpoint without current-session acceptance remains Not yet checked. Live acceptance for a new Word revision still requires current position evidence. + +The user's later troubleshooting capture is a different session (`20ca6e05-6507-4509-a278-01c13b2f881c`) with agent book 0 and zero reads/requests. It cannot supply the earlier cycle's counters. Diagnostics now explicitly identify a missing book association and show the Word revision and saved-state observation. diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs index 7597d8a7..4b55b8b9 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs @@ -40,7 +40,7 @@ public sealed partial class TrayCoordinator return new() { State = "Needs review", Total = total, Matching = accepted, Message = doc.Status }; if (work.Busy || !work.Finished && work.Attempts > 0) { - return new() { State = "Checking", Total = total, Matching = accepted, Message = $"{accepted} of {total} chapters accepted" }; + return new() { State = "Checking", Total = total, Matching = accepted, Message = $"{accepted} verified · {Math.Max(0,total-accepted)} pending. Checking chapter evidence; reconciliation counts are reported separately in diagnostics." }; } return doc.ChapterProgress; } @@ -50,7 +50,8 @@ public sealed partial class TrayCoordinator lock(gate) { if(!documents.TryGetValue(session,out var doc))return "Chapter timings: awaiting recognised saved document."; - var lifecycle=$"Last ribbon command: {doc.LastRibbonCommand} · outcome: {doc.LastRibbonOutcome} · pending restart: {doc.PendingRibbonCommand} · permit pending: {doc.RibbonPermit!=Guid.Empty}. Last interruption: {doc.LastChapterInterruption}."; + var association=doc.Book>0?$"Book association: {doc.Book}.":"Book association missing: select the existing authorised book in Companion; no reimport is required."; + var lifecycle=$"{association} Word revision: {doc.Revision}; saved state: {(doc.WordSaved.HasValue?doc.WordSaved.Value.ToString():"unknown")}. Last ribbon command: {doc.LastRibbonCommand} · outcome: {doc.LastRibbonOutcome} · pending restart: {doc.PendingRibbonCommand} · permit pending: {doc.RibbonPermit!=Guid.Empty}. Last interruption: {doc.LastChapterInterruption}."; if(!chapterWork.TryGetValue(session,out var w))return lifecycle+" Chapter timings: awaiting recognised saved document."; return lifecycle+$" Verification: {(w.Busy?"running":w.Finished?"finished":"idle")}, Word read pending: {w.Command!=Guid.Empty}. Current Context: {ChapterCursorEvidence.State(documents[session],w.Completion?.State=="Synchronised"&&w.Checked.Count==w.Manifest?.Chapters.Length,w.Checked.Values.Any(p=>documents[session].Cursor>=p.Start&&documents[session].Cursorc.DurableAccepted)??0}; calculated/match/mismatch/missing/incompatible={w.Calculated}/{w.Matching}/{w.Mismatching}/{w.Missing}/{w.Incompatible}; reused={w.Reused}, pending={w.PendingReuse.Count}, reconciled={w.Reconciled}, reuseRequests={w.ReuseRequests}, requests={w.Requests}, bytes={w.RequestBytes}, reuse server read/process/validation/persistence ms={w.ReuseReadMs:F1}/{w.ReuseProcessingMs:F1}/{w.ReuseValidationMs:F1}/{w.ReusePersistenceMs:F1}. Negative timing means not observed."; } diff --git a/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs b/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs index ef255e48..bf6f05f2 100644 --- a/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs +++ b/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs @@ -17,7 +17,7 @@ internal static class ChapterAgentTests try{ AdapterCommand? command=null;for(int n=0;n<200&&command==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")command=pending;await Task.Delay(20);} Check(command?.Kind=="chapter-check","Reopened chapter-capable document requests a bounded current-chapter read, never a full snapshot"); - Check(tray.ChapterProgressForDisplay(session)?.Message=="0 of 1 chapters accepted","Checking progress reports committed acceptances, never a queued chapter number"); + Check(tray.ChapterProgressForDisplay(session) is {Matching:0,Total:1} progress&&progress.Message.StartsWith("0 verified · 1 pending"),"Checking progress reports committed acceptances, never a queued chapter number"); var text="Chapter 1\rExact prose\r";var xml="Chapter 1Exact prose"; void Frames(AdapterCommand read,bool exact=false){Send(new(){Kind="chapter-begin",SnapshotId=read.Id,BookId=3,Start=0,End=text.Length,DocumentEnd=text.Length,WordSaved=true});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="text",Start=0,OperationMessage=text});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="xml",Start=0,OperationMessage=xml});if(exact){var evidence=ChapterFingerprint.ReadXml(xml,text);Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="ids-exact",Start=0,OperationMessage=string.Concat(evidence.Select(p=>p.NativeId+p.Length.ToString("X8")))});}Send(new(){Kind="chapter-end",SnapshotId=read.Id});} Send(new(){Kind="chapter-begin",SnapshotId=command!.Id,BookId=3,Start=0,End=text.Length,DocumentEnd=text.Length,WordSaved=true}); diff --git a/PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs b/PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs index 475a6b1c..ba144d24 100644 --- a/PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs +++ b/PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs @@ -28,11 +28,15 @@ internal static class ChapterHandshakeTests void Chunks(string action,string value){for(var offset=0;offsethandler.Reused==1);await Until(()=>tray.PresentationDocuments.Single().SceneId.HasValue);Check(handler.Finishes==0,"Writing Context is available before the other 47 chapters are acknowledged");} + if(c==0){await Until(()=>handler.Reused==1);await Until(()=>tray.PresentationDocuments.Single().SceneId.HasValue);Check(handler.Finishes==0,"Writing Context is available before the other 47 chapters are acknowledged"); + var progress=tray.ChapterProgressForDisplay(session); + Check(progress?.Matching==1&&progress.Total==48&&progress.Message.Contains("1 verified · 47 pending"),"Progress counts acknowledged checkpoints rather than completed Word reads");} } if(scenario.Missing==-2) { - await Until(()=>handler.ReuseRequests==2);Send(new(){Kind="close"});handler.ReleaseSecond.SetResult();await Task.Delay(100); + await Until(()=>handler.ReuseRequests==2); + Check(tray.ChapterProgressForDisplay(session)?.Matching==1,"Forty-seven calculated fingerprints remain pending until the server acknowledges their checkpoints"); + Send(new(){Kind="close"});handler.ReleaseSecond.SetResult();await Task.Delay(100); Check(tray.PresentationDocuments.All(d=>d.Session!=session),"Closing during final batch rejects the late reuse acknowledgement"); Check(handler.Finishes==0,"Interrupted reuse cannot report whole-manuscript completion after close");continue; } @@ -60,7 +64,9 @@ internal static class ChapterHandshakeTests sessions.Attach(instance,lease,chapters:true,liveChapterText:true);tray.Attach(instance,lease,chapters:true); Message Send(Message m){m.WordInstanceId=instance;m.SessionId=session;m.Revision=revision;m.Sequence=++sequence;return tray.Exchange(instance,m,sessions.Apply(lease,m),lease);} Message Register()=>Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=revision,Title="Disposable edit fixture.docx"}]}); - Register();tray.SelectBook(session,3,false);Send(new(){Kind="active"}); + Register(); + Check(tray.ChapterDiagnostics(session).Contains("Book association missing"),"An unassociated session diagnoses the missing book instead of implying verification is underway"); + tray.SelectBook(session,3,false);Send(new(){Kind="active"}); Send(new(){Kind="selection",WordSaved=false}); Check(Send(new(){Kind="tray-sync"}).ChapterProgress?.State=="Save required","Synchronise on an unsaved edit shows the save requirement"); Check(Send(new(){Kind="tray-repair"}).ChapterProgress?.Message.Contains("Repair Synchronisation")==true&&handler.RepairRequests==0,"Repair reports its saved-state refusal without submitting stale evidence"); diff --git a/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs b/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs index cd2292a6..3facb5cc 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs @@ -39,7 +39,7 @@ namespace PlotDirector.WordAddIn if (serverChapterProgress == null) return "Not yet checked"; switch (serverChapterProgress.State) { - case "Checking": return "Synchronising"; + case "Checking": return "Checking"; case "Save required": return "Save to synchronise"; case "Synchronised": if (serverChapterProgress.Total > 0 && serverChapterProgress.Matching == serverChapterProgress.Total) @@ -54,7 +54,7 @@ namespace PlotDirector.WordAddIn public string RibbonSyncProgress => HasCurrentRibbonState && serverChapterProgress?.Total > 0 ? ChapterStatusLabel == "Up to date" ? serverChapterProgress.Total + " chapters verified" - : serverChapterProgress.Matching + " of " + serverChapterProgress.Total + " chapters accepted" + : serverChapterProgress.Matching + " verified · " + Math.Max(0,serverChapterProgress.Total-serverChapterProgress.Matching) + " pending" : ChapterStatusLabel == "Review needed" ? "See Companion diagnostics" : " "; public string ChapterStatusTip => (HasCurrentRibbonState || serverChapterProgress?.State == "Sign-in required" ? serverChapterProgress?.Message : null) ?? "Synchronise to verify the manuscript position."; diff --git a/PlotLine.Tests/ChapterSynchronisationTests.cs b/PlotLine.Tests/ChapterSynchronisationTests.cs index 104ea0f0..10c00e48 100644 --- a/PlotLine.Tests/ChapterSynchronisationTests.cs +++ b/PlotLine.Tests/ChapterSynchronisationTests.cs @@ -35,6 +35,25 @@ internal static class ChapterSynchronisationTests 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 retained=JsonSerializer.Deserialize(before)!; + retained.ChapterCheckpoints=[accepted.Checkpoint,ChapterCheckpointEngine.Validate(state,Proof(11),DateTime.UtcNow).Checkpoint]; + ParagraphManuscriptEngine.Reconcile(retained,merged); + var rebuilt=ChapterCheckpointEngine.Build(retained,state.Revision+1); + Check(rebuilt.Single(c=>c.ChapterId==11).Status=="Synchronised"&&rebuilt.Single(c=>c.ChapterId==10).Status!="Synchronised","Chapter reconciliation retains unaffected durable acceptance while invalidating edited chapter evidence"); + retained.ChapterCheckpoints.Single(c=>c.ChapterId==11).Algorithm="obsolete"; + Check(ChapterCheckpointEngine.Build(retained,state.Revision+1).Single(c=>c.ChapterId==11).Status!="Synchronised","Unsupported prior fingerprint algorithms cannot retain durable acceptance"); + var scaleRows=Enumerable.Range(0,96).Select(i=>new ParagraphOccurrence{Id=Guid.NewGuid(),NativeId=(i+1).ToString("X8"),Ordinal=i,Start=i*10,End=(i+1)*10,Text=i%2==0?"Heading x\r":"Paragraph\r",Outline=i%2==0?1:10}).ToArray(); + var scale=ParagraphManuscriptEngine.Bootstrap(12,7,Guid.NewGuid(),scaleRows,[]); + scale.Chapters=Enumerable.Range(0,48).Select(i=>new ParagraphChapter{CanonicalId=i+1,HeadingId=scale.Paragraphs[i*2].Occurrence.Id,Title=$"Chapter {i+1}"}).ToList(); + foreach(var p in scale.Paragraphs){p.ChapterId=p.Occurrence.Ordinal/2+1;p.PositionVerified=true;} + scale.ChapterCheckpoints=ChapterCheckpointEngine.Build(scale,1).ToList(); + foreach(var c in scale.ChapterCheckpoints){c.Status="Synchronised";c.LastSuccessfulSyncUtc=DateTime.UtcNow;} + scale.Paragraphs[27].Occurrence.Text="An edited paragraph\r"; + var scaleRebuilt=ChapterCheckpointEngine.Build(scale,2); + Check(scaleRebuilt.Count(c=>c.Status=="Synchronised")==47&&scaleRebuilt.Single(c=>c.ChapterId==14).Status!="Synchronised","One changed chapter retains forty-seven unaffected durable checkpoints"); + Check(ChapterCheckpointEngine.SessionState(scaleRebuilt[0],false)=="Not yet checked"&&ChapterCheckpointEngine.SessionState(scaleRebuilt[0],true)=="Synchronised","Retained durable acceptance cannot verify another Word revision without live checkpoint acknowledgement"); + scaleRebuilt[0].Status="Needs review"; + Check(ChapterCheckpointEngine.SessionState(scaleRebuilt[0],true)=="Needs review","Live acceptance cannot override a structural review requirement"); 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 movedLast=Proof(11);movedLast.NextHeadingId="00000001";Check(ChapterCheckpointEngine.Validate(state,movedLast,DateTime.UtcNow).Checkpoint.Status=="Needs review","A formerly last chapter moved before another heading cannot report unchanged global structure"); var legacy=JsonSerializer.Deserialize(before)!;foreach(var p in legacy.Paragraphs)p.Occurrence.NativeId="";var adoption=Proof();adoption.Reconcile=true; diff --git a/PlotLine/Services/Manuscript/ChapterCheckpointEngine.cs b/PlotLine/Services/Manuscript/ChapterCheckpointEngine.cs index 85cd55ed..3329a63b 100644 --- a/PlotLine/Services/Manuscript/ChapterCheckpointEngine.cs +++ b/PlotLine/Services/Manuscript/ChapterCheckpointEngine.cs @@ -17,6 +17,8 @@ public sealed record ChapterPosition(Guid ParagraphId,int Start,int End,int Chap public static class ChapterCheckpointEngine { + // Durable evidence permits reuse, but only current-session acceptance verifies live Word positions. + public static string SessionState(ChapterCheckpoint checkpoint,bool accepted)=>checkpoint.Status=="Needs review"?"Needs review":accepted?"Synchronised":"Not yet checked"; 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(); @@ -36,8 +38,8 @@ public static class ChapterCheckpointEngine 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&&c.NextHeadingId==checkpoint.NextHeadingId); - if(prior!=null){checkpoint.PositionHash=prior.PositionHash;checkpoint.LastSuccessfulSyncUtc=prior.LastSuccessfulSyncUtc;checkpoint.AcceptedRevision=prior.AcceptedRevision;if(prior.Status=="Needs review"){checkpoint.Status=prior.Status;checkpoint.Message=prior.Message;}} + var prior=state.ChapterCheckpoints.FirstOrDefault(c=>c.ChapterId==checkpoint.ChapterId&&c.Algorithm==checkpoint.Algorithm&&c.Order==checkpoint.Order&&c.ContentHash==checkpoint.ContentHash&&c.IdentityHash==checkpoint.IdentityHash&&c.MappingHash==checkpoint.MappingHash&&c.NextHeadingId==checkpoint.NextHeadingId); + if(prior!=null){checkpoint.PositionHash=prior.PositionHash;checkpoint.LastSuccessfulSyncUtc=prior.LastSuccessfulSyncUtc;checkpoint.AcceptedRevision=prior.AcceptedRevision;if(checkpoint.Status!="Needs review"&&prior.Status is "Synchronised" or "Needs review"){checkpoint.Status=prior.Status;checkpoint.Message=prior.Message;}} return checkpoint; }).ToArray(); } diff --git a/PlotLine/Services/Manuscript/ChapterSyncService.cs b/PlotLine/Services/Manuscript/ChapterSyncService.cs index db51017f..72bca455 100644 --- a/PlotLine/Services/Manuscript/ChapterSyncService.cs +++ b/PlotLine/Services/Manuscript/ChapterSyncService.cs @@ -15,7 +15,7 @@ public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscript var manifest=new ChapterManifest(){CheckpointReuseSupported=true,NativePositionsSupported=true,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.FirstOrDefault(c=>c.ChapterID==source.ChapterId&&c.ContentHash==source.ContentHash&&c.IdentityHash==source.IdentityHash&&c.MappingHash==source.MappingHash); var durable=state.ChapterCheckpoints.FirstOrDefault(c=>c.ChapterId==source.ChapterId&&c.Status=="Synchronised"&&c.ContentHash==source.ContentHash&&c.IdentityHash==source.IdentityHash&&c.MappingHash==source.MappingHash&&c.NextHeadingId==source.NextHeadingId&&c.Algorithm==ChapterFingerprint.Version); - return new ChapterManifestItem{DurableAccepted=durable!=null&&source.Status!="Needs review",Algorithm=source.Algorithm,AcceptedRevision=source.AcceptedRevision,Order=source.Order,MappingHash=source.MappingHash,PositionHash=source.PositionHash,NextHeadingId=source.NextHeadingId,ChapterId=source.ChapterId,Title=part.Chapter.Title,HeadingNativeId=source.NativeHeadingId,ContentHash=source.ContentHash,IdentityHash=source.IdentityHash,Start=accepted?.StartPosition??part.Rows[0].Occurrence.Start,End=accepted?.EndPosition??part.Rows[^1].Occurrence.End,ParagraphCount=source.ParagraphCount,State=accepted!=null&&source.Status!="Needs review"?"Synchronised":source.Status}; + return new ChapterManifestItem{DurableAccepted=durable!=null&&source.Status!="Needs review",Algorithm=source.Algorithm,AcceptedRevision=source.AcceptedRevision,Order=source.Order,MappingHash=source.MappingHash,PositionHash=source.PositionHash,NextHeadingId=source.NextHeadingId,ChapterId=source.ChapterId,Title=part.Chapter.Title,HeadingNativeId=source.NativeHeadingId,ContentHash=source.ContentHash,IdentityHash=source.IdentityHash,Start=accepted?.StartPosition??part.Rows[0].Occurrence.Start,End=accepted?.EndPosition??part.Rows[^1].Occurrence.End,ParagraphCount=source.ParagraphCount,State=ChapterCheckpointEngine.SessionState(source,accepted!=null)}; }).ToArray()}; var lease=presence.Read(user,book).SingleOrDefault(l=>l.Session==session&&l.Position.Revision==wordRevision&&l.Position.CanChapterSync); if(lease!=null){var count=manifest.Chapters.Count(c=>c.State=="Synchronised");presence.RecordChapterProgress(user,book,lease.Instance,session,wordRevision,new(){Total=manifest.Chapters.Length,Checked=count,Matching=count,Repaired=presence.RepairedChapters(user,book,lease.Instance,session,wordRevision),State="Checking",Message=$"{count}/{manifest.Chapters.Length} chapter mappings accepted for this session."});}