diff --git a/Docs/WordCompanion/2026-11-12-vsto-range-synchronisation.md b/Docs/WordCompanion/2026-11-12-vsto-range-synchronisation.md new file mode 100644 index 00000000..5b9e3bf8 --- /dev/null +++ b/Docs/WordCompanion/2026-11-12-vsto-range-synchronisation.md @@ -0,0 +1,73 @@ +# Native VSTO chapter-range synchronisation + +This implementation stays within the existing VSTO add-in, named-pipe protocol, tray coordinator and chapter synchronisation endpoints. It introduces no Office.js integration, service, database migration or installer. The code is intended for source qualification; real Word extraction cost and responsiveness are not established by the portable tests. + +## Reading strategy + +The initial accepted-manuscript opening retains the qualified 1.0.0.32 reader. Subsequent checks prefer chapter ranges. Existing Word length/saved-state observations request a check after three seconds; periodic checks discover changes that those signals miss. Cursor position can prioritise a range, but is never evidence that other chapters are unchanged. + +Each saved plain chapter uses one `Range.Text` extraction. A changed content fingerprint proceeds to the existing detailed reader. Matching text is insufficient to certify native identity: the reader exports that chapter's XML and checks complete native paragraph IDs, outline, paragraph partition, heading identity, next heading and the accepted identity/content hashes. XML parsing runs outside Word's STA, with at most two comparisons pending. A successful comparison emits the existing compact live-text identity frames, not the XML package. It performs no native paragraph identity traversal. + +Incomplete XML IDs fall back to the existing bounded native identity batches while retaining XML structural validation. Drawings, floating anchors, native position gaps, fields, revisions, footnotes, unsupported structures and section/page breaks retain the qualified detailed paths. Ambiguous boundaries remain review cases. No missing native identity is accepted merely because text matches; a regression also closes an existing empty-ID acceptance gap in `ChapterFingerprint.Identity`. + +For a new Word revision, unchanged proofs use the existing batch reuse endpoint. Only changed chapters submit reconciliation prose. For an unchanged periodic pass within the same Word revision, matching absolute positions and fingerprint evidence retain the already accepted live checkpoints without any reuse, individual acceptance or finish requests. Position shifts update navigation hints for subsequent chapter reads; actual native ranges still require verification before acceptance. + +## Scheduling and lifecycle + +- A three-second debounce coalesces observed document revisions and saved-state transitions. Scheduler pumping from normal selection observations and the existing coordinator tick prevents the debounce from waiting for the slower presence refresh interval. +- After completion, the existing scheduler requests another bounded chapter-range pass at approximately 60 seconds. Word's author-priority scheduling, document closure/revision guards and COM busy handling remain in force. The interval is an opportunity, not a deadline that overrides a busy Word UI. +- Manual Synchronise immediately requests the same range path in OnSave mode, joins active work, and can retry a failed check. Manual authority modes retain the explicit permit path. Repair retains its explicit recovery permit and broader verification. +- Per-session processing exclusion prevents a superseding revision from starting another reconciliation while an older server operation is still finishing. New document revisions retire old commands and remain scheduled for the next pass. +- Older canonical-revision presence replies cannot clear newly accepted work, overwrite final progress or restore old Context. Current-cursor, book, manuscript, authentication and Word-revision guards remain intact. +- The ribbon retains its layout and distinguishes Checking from Synchronising, with verified/pending counts based on acknowledged live checkpoints. A completed operation remains authoritative over an older presence progress reply. + +## Unsaved in-memory edits + +Once an accepted baseline exists, read-only chapter range observations also run against unsaved text. They detect same-length changes and Undo while Word remains already dirty. They send only chapter identity, bounds and changed/matching metadata, not prose or accepted-position proposals. Heading identity is checked before attributing an observation to a chapter. + +**Native-position acceptance and prose reconciliation still wait for a save.** This is a coherence limitation of the existing bounded reader: Word can be edited between its UI-thread steps, and an already-unsaved document supplies no monotonic mutation token that detects every intervening edit. Periodic fingerprints locate changes but do not make a multi-step native-position read atomic. The saved-state fence is therefore retained and checked through transport; a document becoming dirty aborts that evidence. No save is forced. Saving automatically schedules selective reconciliation, so a manual Synchronise click is unnecessary. + +Unsaved observations do not label native positions or Context as currently verified. Accepted server checkpoints remain intact. Full unsaved reconciliation and verified current-position Context during arbitrary in-memory edits are not claimed by this implementation. + +## Measurements and interpretation + +The supplied historical Word log has 40 complete initial-pass chapter begin/end pairs: **61.2 ms minimum, 214.9 ms median, 541.1 ms maximum, 8,890.9 ms summed**. These are real full-reader protocol wall times, including identity traversal, scheduling and IPC. They do **not** isolate `Range.Text` extraction. + +The portable range fixture preallocates 48 chapter texts before timing content fingerprints. Its CPU timing excludes Word extraction, XML export, COM and UI responsiveness. The HTTP lifecycle fixture uses real coordinator scheduling with a virtual clock, synthetic Word replies and an in-memory HTTP handler. It includes a deliberately delayed presence reply to test a race; its elapsed time is not a Word performance benchmark. + +The single saved-edit lifecycle asserts: + +- Three-second debounce, with repeated edits coalesced and the cursor deliberately outside the edited chapter. +- 48 range comparisons, 47 matching chapters avoiding native paragraph traversal, and one detailed chapter read. +- Two bounded checkpoint-reuse requests for 47 unchanged chapters, two existing validation requests for the edited chapter, and exactly one prose reconciliation. +- Automatic return to 48 verified chapters without a ribbon command. +- An unchanged periodic pass retaining all 48 live checkpoints with zero chapter server requests. + +Existing production instrumentation separately records `chapter-range-text`, `chapter-probe-range-xml`, worker comparison time, full reader COM/queue/active time, native paragraph visits and fallback counts. The existing read-only [Word benchmark](../../PlotDirector.NativeCompanion/WindowsValidation/Measure-ChapterSync.ps1) separately times Range.Text, WordOpenXML and SHA-256 against a human-selected disposable chapter without saving or closing Word. It can be used with the existing installation; a new installer is not needed to measure extraction. + +Real Word must establish whether its exported ranges contain complete native IDs and whether XML extraction is cheaper than the qualified native batch reader. When IDs are absent, the safe fallback can still traverse unchanged chapters' native identities. The portable one-detailed-read result must not be presented as a universal Word performance guarantee. The unchanged-opening path is preserved, but its approximately 16-second baseline has not been remeasured here. + +## Regression scope + +Native fixtures exercise initial reopening, automatic single-chapter edits, repeated edits, two-chapter edits with length changes, periodic same-length detection, debounce and periodic intervals, Undo/Redo, unsaved observations, automatic save follow-up, manual Synchronise, Repair, stale presence replies and actual IPC encoding. Existing fixtures cover interrupted acknowledgements, closed/revised documents, failed requests, independent sessions and current-cursor Context. + +Chapter and structural regressions retain heading rename, insertion/deletion, reordering, cross-boundary changes, paragraph split/merge, canonical GUID/scene preservation, floating anchors, native position gaps, missing/stale checkpoints and structural fallback. No test edits the protected manuscript. Development SQL qualification uses only newly provisioned synthetic projects through the existing guarded regression harness. + +Windows Office/VSTO compilation and real Word execution remain distinct from the Atlas build, portable tests and VSTO syntax check. No Word UI responsiveness, new-code real extraction timing or real Word performance acceptance is claimed. No installer was prepared or installed. + +## Atlas qualification results + +- Solution build: zero warnings and errors. +- Focused native/chapter suite: 453 PASS. +- Chapter/structural engine suite: 71 PASS. +- Native foundation suite: 273 PASS. +- Full application executable: 457 PASS. +- Existing guarded real Development SQL reuse suite: 121 PASS; synthetic project 8201 archived. +- New guarded real Development SQL incremental suite (`--chapter-incremental-dev `): 13 PASS; synthetic project 8202 archived. It verifies all canonical paragraph GUIDs and scene identities, 47 retained durable checkpoints, eligibility for batch reuse after reconciliation, shifted downstream positions, final 48 accepted live checkpoints and unaffected-chapter Context. +- VSTO source syntax check: two changed files, zero syntax errors. This is not an Office type check or a Windows build. + +The final portable range-only fingerprint measurement was **30.5 ms** for 48 preallocated texts / 1,530,278 UTF-16 units. The synthetic coordinator cycle measured **1,402.9 ms** after virtual debounce, including a deliberately held presence reply. Neither measures Word extraction. + +The existing real SQL scale fixture measured **188,822.6 ms** for the 48-individual-acceptance baseline versus **2,785.7 ms** for two batch-reuse requests with zero individual acceptances or reconciliations. The new single-edit SQL fixture measured **5,245.9 ms** for reconciliation and acceptance, **7,926.1 ms** total, with one reconciled chapter, 47 retained checkpoints, one unchanged reuse batch and zero unchanged individual acceptances. All are in-process service/SQL measurements; none includes Word, HTTP or debounce. + +The shared-branch delivery commit is the source identity for this report. No package version or signed installer has been produced; the installed 1.0.0.33 binaries remain distinct from this source implementation. An eventual installer requires a new version and the existing Windows packaging and approval gates. diff --git a/Docs/WordCompanion/WindowsHandover/2026-11-12-incremental-synchronisation-investigation.md b/Docs/WordCompanion/WindowsHandover/2026-11-12-incremental-synchronisation-investigation.md index 877f1e27..94e47866 100644 --- a/Docs/WordCompanion/WindowsHandover/2026-11-12-incremental-synchronisation-investigation.md +++ b/Docs/WordCompanion/WindowsHandover/2026-11-12-incremental-synchronisation-investigation.md @@ -1,5 +1,7 @@ # Incremental synchronisation investigation +Follow-up: the [native VSTO range implementation](../2026-11-12-vsto-range-synchronisation.md) supersedes the implementation-status discussion below. This file preserves the original investigation and measured historical evidence. The follow-up introduces no Office.js integration or installer. + ## 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. diff --git a/PlotDirector.NativeCompanion/Agent/PipeHost.cs b/PlotDirector.NativeCompanion/Agent/PipeHost.cs index 6d41e35e..5c2ca543 100644 --- a/PlotDirector.NativeCompanion/Agent/PipeHost.cs +++ b/PlotDirector.NativeCompanion/Agent/PipeHost.cs @@ -56,8 +56,8 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action0||message.Start<0||message.End<=message.Start||message.End-message.Start>PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint.MaxCharacters||message.Action is not ("matching" or "changed"))return Reject(answer,"invalid-chapter-observation"); + return answer; + } if(message.Kind.StartsWith("chapter-",StringComparison.Ordinal)){ if(!word.ChapterCapable||(message.Action=="live-text"&&!word.LiveChapterTextCapable)||(message.Action=="ids-exact"&&!word.NativeChapterTextCapable)||(message.Action=="positions"&&!word.NativeChapterPositionsCapable)||message.SnapshotId==Guid.Empty||message.OperationMessage==null||message.OperationMessage.Length>2048||message.Kind is not ("chapter-begin" or "chapter-chunk" or "chapter-end")||(message.Kind=="chapter-begin"&&(message.Start<0||message.End<=message.Start||message.End-message.Start>PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint.MaxCharacters||message.DocumentEnd16000000))||(message.Kind=="chapter-chunk"&&(message.Start<0||message.Start>8*1024*1024||message.Action is not ("text" or "xml" or "ids" or "ids-exact" or "positions" or "live-text"))))return Reject(answer,"invalid-chapter-frame"); return answer; diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs index 4b55b8b9..76f50368 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs @@ -4,13 +4,15 @@ using PlotDirector.Companion.Protocol.Manuscript; namespace PlotDirector.Companion.Agent; public sealed partial class TrayCoordinator { + private DateTime ChapterNow=>(synchronisationClock??TimeProvider.System).GetUtcNow().UtcDateTime; + private readonly HashSet chapterProcessingSessions=[]; private sealed class ChapterWork { public readonly System.Diagnostics.Stopwatch Elapsed=System.Diagnostics.Stopwatch.StartNew(); public double RecognitionMs,ManifestMs,VerificationMs,ServerMs,ContextMs=-1,CompleteMs=-1;public int LiveReads,XmlReads,Submissions,Calculated,Matching,Mismatching,Missing,Incompatible,Reused,Reconciled,ReuseRequests,Requests;public long RequestBytes; public double ReuseReadMs,ReuseProcessingMs,ReuseValidationMs,ReusePersistenceMs;public bool ReuseFinishing; public readonly Dictionary PendingReuse=[]; - public int Book, Attempts, Retries; public string ReviewReason = "";public Guid Manuscript;public long Revision;public Guid Context,Operation,Command;public bool Busy,Supported,Processing,Begun;public long FailedRevision=-1;public DateTime Started,RetryAfter; + public readonly HashSet Dirty=[];public int ExpectedProbeChapter;public bool Reconciling;public string CurrentTitle="chapter";public bool PreferRangeEvidence,Polling,ObserveOnly;public int Retained;public int Book, Attempts, Retries; public string ReviewReason = "";public Guid Manuscript;public long Revision;public Guid Context,Operation,Command;public bool Busy,Supported,Processing,Begun;public long FailedRevision=-1;public DateTime Started,RetryAfter; public ChapterManifest? Manifest; public ChapterSyncProgress? Completion;public readonly Dictionary Checked=[]; public StringBuilder Text=new(),Xml=new(),Identities=new();public int Start,End,DocumentEnd,CursorWhenQueued,FirstStart=-1;public bool Finished;public bool Wrapped;public bool NativeTextVerified;public string IdentityAction="";public readonly HashSet Reviewed=[];public readonly HashSet Visited=[];public string Next=""; } @@ -40,9 +42,9 @@ 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} verified · {Math.Max(0,total-accepted)} pending. Checking chapter evidence; reconciliation counts are reported separately in diagnostics." }; + return new() { State = work.Reconciling?"Synchronising":"Checking", Total = total, Matching = accepted, Message = (work.Reconciling?$"Synchronising {work.CurrentTitle}. ":"")+$"{accepted} verified · {Math.Max(0,total-accepted)} pending. Checking chapter evidence; reconciliation counts are reported separately in diagnostics." }; } - return doc.ChapterProgress; + return work.Finished&&work.Completion!=null?work.Completion:doc.ChapterProgress; } public string ChapterDiagnostics(Guid session) @@ -53,7 +55,7 @@ public sealed partial class TrayCoordinator 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."; + 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}; retained={w.Retained}, rangeEvidence={w.PreferRangeEvidence}, polling={w.Polling}, observeOnly={w.ObserveOnly}, editedInMemory={w.Dirty.Count}, 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."; } } @@ -82,7 +84,7 @@ public sealed partial class TrayCoordinator work.PendingReuse.Clear();work.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.ReuseFinishing=false;work.Wrapped=false;work.FirstStart=-1;work.Attempts=0; work.Finished = false; work.Manifest = null; - work.RetryAfter = DateTime.UtcNow.AddSeconds(15); + work.RetryAfter = ChapterNow.AddSeconds(15); doc.Status = reason; doc.LastChapterInterruption=reason; } @@ -97,8 +99,15 @@ public sealed partial class TrayCoordinator if(doc.WordSaved==false){SetRibbonOutcome(doc,"Save required","Save the manuscript in Word, then retry "+(kind=="tray-repair"?"Repair Synchronisation.":"Synchronise."));return;} if(kind=="tray-sync"&&chapterWork.TryGetValue(doc.Session,out var work)&&CurrentChapterWork(doc,work)&&work.Busy&&work.Operation!=Guid.Empty) {SetRibbonOutcome(doc,"Checking","Synchronisation is already running.");doc.RibbonNotice=null;return;} + if(kind=="tray-sync"&&rangeInstances.Contains(doc.Instance)&&chapterWork.TryGetValue(doc.Session,out var incremental)&&CurrentChapterWork(doc,incremental)&&incremental.Manifest?.Mode=="OnSave"&&(!incremental.Finished||incremental.Completion?.State=="Synchronised")) + { + if(incremental.FailedRevision==doc.Revision){incremental.FailedRevision=-1;incremental.Retries=0;incremental.Attempts=0;incremental.Visited.Clear();incremental.Reviewed.Clear();} + doc.NextChapterCheckUtc=ChapterNow;incremental.RetryAfter=ChapterNow;doc.RequestChapterPoll=incremental.Finished; + doc.RibbonNotice=null;doc.LastRibbonOutcome=incremental.Busy?"Synchronise joined the current chapter check.":"Synchronise requested the pending chapter check."; + doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;return; + } doc.PendingRibbonCommand=kind; - doc.RibbonRequestedUtc=DateTime.UtcNow; + doc.RibbonRequestedUtc=ChapterNow; SetRibbonOutcome(doc,"Checking","Waiting for the current saved Word revision to be confirmed."); doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue; } @@ -111,7 +120,7 @@ public sealed partial class TrayCoordinator { if(doc.PendingRibbonCommand=="")return; if(!reply.ChapterSyncSupported||doc.Book<=0||doc.Capture!=null||doc.WordSaved==false|| - DateTime.UtcNow-doc.RibbonRequestedUtc>TimeSpan.FromSeconds(15)) + ChapterNow-doc.RibbonRequestedUtc>TimeSpan.FromSeconds(15)) { doc.PendingRibbonCommand=""; SetRibbonOutcome(doc,doc.WordSaved==false?"Save required":"Needs review",doc.WordSaved==false @@ -132,7 +141,7 @@ public sealed partial class TrayCoordinator if(!cloud.Allows(context,book))throw new InvalidOperationException("Connect and select an authorised book first."); var reply=await cloud.RequestChapterRepair(book,new(){InstanceId=instance,SessionId=session,WordRevision=revision},context); if(reply.OperationId==Guid.Empty)throw new InvalidOperationException(string.IsNullOrWhiteSpace(reply.Message)?"Check the saved manuscript connection and retry.":reply.Message); - lock(gate)if(Current()&&GetChapterWork(doc).Operation!=reply.OperationId){doc.RibbonPermit=reply.OperationId;doc.RibbonRequestedUtc=DateTime.UtcNow;SetRibbonOutcome(doc,"Checking",reply.Message);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;} + lock(gate)if(Current()&&GetChapterWork(doc).Operation!=reply.OperationId){doc.RibbonPermit=reply.OperationId;doc.RibbonRequestedUtc=ChapterNow;SetRibbonOutcome(doc,"Checking",reply.Message);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;} } catch(Exception e)when(NetworkFailure(e)){lock(gate)if(Current())SetRibbonOutcome(doc,"Needs review","Chapter request was not accepted: "+e.Message);} finally{lock(gate)ribbonRequests.Remove(session);} @@ -148,29 +157,56 @@ public sealed partial class TrayCoordinator Queue(doc,new(){Kind="chapter-cancel"}); chapterWork.Remove(doc.Session); var work=GetChapterWork(doc);work.Operation=operation; - doc.Status="Repairing existing chapter mappings; accepted scenes and author decisions are retained.";work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work); + doc.Status="Repairing existing chapter mappings; accepted scenes and author decisions are retained.";work.Busy=true;work.Started=ChapterNow;_ = LoadChapterManifest(doc,work); } private ChapterWork GetChapterWork(TrayDocument doc) { - if(!chapterWork.TryGetValue(doc.Session,out var work)||work.Context!=doc.Authentication||work.Revision!=doc.Revision||work.Book!=doc.Book||work.Manuscript!=doc.Manuscript)chapterWork[doc.Session]=work=new(){RecognitionMs=(DateTime.UtcNow-doc.FirstObserved).TotalMilliseconds,Book=doc.Book,Manuscript=doc.Manuscript,Revision=doc.Revision,Context=doc.Authentication};return work; + chapterWork.TryGetValue(doc.Session,out var work); + if(work==null||work.Context!=doc.Authentication||work.Revision!=doc.Revision||work.Book!=doc.Book||work.Manuscript!=doc.Manuscript) + { + var prefer=rangeInstances.Contains(doc.Instance)&&work!=null&&work.Context==doc.Authentication&&work.Book==doc.Book&&work.Manuscript==doc.Manuscript&& + (work.PreferRangeEvidence||work.Completion?.State=="Synchronised"); + var prior=work; + chapterWork[doc.Session]=work=new(){PreferRangeEvidence=prefer,RetryAfter=doc.NextChapterCheckUtc,RecognitionMs=(ChapterNow-doc.FirstObserved).TotalMilliseconds,Book=doc.Book,Manuscript=doc.Manuscript,Revision=doc.Revision,Context=doc.Authentication}; + if(prefer&&doc.WordSaved==false&&prior?.Manifest!=null){work.Manifest=prior.Manifest;work.Completion=prior.Completion;work.Polling=true;work.ObserveOnly=true;} + } + return work; } private void ObserveChapterPresence(TrayDocument doc,NativePresence reply) { if(!ChapterCapable(doc.Instance))return; lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc)return;var work=GetChapterWork(doc);work.Supported=reply.ChapterSyncSupported;if(work.ContextMs<0&&ChapterCursorEvidence.Ready(doc))work.ContextMs=work.RecognitionMs+work.Elapsed.Elapsed.TotalMilliseconds; - if(doc.RibbonPermit!=Guid.Empty&&reply.Navigation?.Id!=doc.RibbonPermit&&DateTime.UtcNow-doc.RibbonRequestedUtc>TimeSpan.FromSeconds(15)) + if(doc.RibbonPermit!=Guid.Empty&&reply.Navigation?.Id!=doc.RibbonPermit&&ChapterNow-doc.RibbonRequestedUtc>TimeSpan.FromSeconds(15)) {doc.RibbonPermit=Guid.Empty;SetRibbonOutcome(doc,"Needs review","The repair permit was not delivered. Check the connection and retry.");} DispatchChapterRibbonRequest(doc,reply); if(doc.PendingRibbonCommand!=""||doc.RibbonPermit!=Guid.Empty||ribbonRequests.Contains(doc.Session))return; - if(work.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Completion=null;work.Manifest=null;work.PendingReuse.Clear();work.ReuseFinishing=false;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;} - if(DateTime.UtcNowwork.Start&&doc.Active&&doc.Cursor!=work.CursorWhenQueued&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor=work.End)){QueueChapter(doc,work,doc.Cursor);return;}if(DateTime.UtcNow-work.Started>TimeSpan.FromMinutes(2)){StopChapterWork(doc,work,"Chapter validation timed out. Accepted checkpoints are retained. Check the connection before retrying.");}return;} - if(work.Manifest==null){work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work);return;} + if(work.Manifest!=null&&reply.ParagraphRevision>0&&reply.ParagraphRevision>work.Manifest.Revision){work.Completion=null;work.Manifest=null;work.PendingReuse.Clear();work.ReuseFinishing=false;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;} + PumpChapterWork(doc,work); + } + } + private void PumpChapterWork(TrayDocument doc,ChapterWork work) + { + if(doc.PendingRibbonCommand!=""||doc.RibbonPermit!=Guid.Empty||ribbonRequests.Contains(doc.Session))return; + if(chapterProcessingSessions.Contains(doc.Session)&&!work.Processing)return; + if(rangeInstances.Contains(doc.Instance)&&work.Finished&&!work.Busy&&work.Completion?.State=="Synchronised"&&work.Manifest?.Mode=="OnSave"&&(doc.WordSaved==true||work.ObserveOnly)&& + (doc.RequestChapterPoll||ChapterNow-doc.LastChapterPollUtc>=TimeSpan.FromSeconds(60))) + {work=BeginChapterPoll(doc,work);} + if(ChapterNowwork.Start&&doc.Active&&doc.Cursor!=work.CursorWhenQueued&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor=work.End)){QueueChapter(doc,work,doc.Cursor);return;}if(ChapterNow-work.Started>TimeSpan.FromMinutes(2)){StopChapterWork(doc,work,"Chapter validation timed out. Accepted checkpoints are retained. Check the connection before retrying.");}return;} + if(work.Manifest==null){work.Busy=true;work.Started=ChapterNow;_ = LoadChapterManifest(doc,work);return;} + if(work.Polling){var candidate=work.Manifest!.Chapters.FirstOrDefault(c=>!work.Visited.Contains(c.ChapterId));if(candidate!=null)QueueChapter(doc,work,candidate.Start);return;} var here=work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor!work.Checked.ContainsKey(c.ChapterId)&&!work.PendingReuse.ContainsKey(c.ChapterId)&&!work.Reviewed.Contains(c.ChapterId)&&(c.State!="Needs review"||work.Operation!=Guid.Empty)); if(next!=null)QueueChapter(doc,work,next.Start); - } + } + private ChapterWork BeginChapterPoll(TrayDocument doc,ChapterWork prior) + { + var work=new ChapterWork{Book=prior.Book,Manuscript=prior.Manuscript,Revision=prior.Revision,Context=prior.Context, + Manifest=prior.Manifest,Completion=prior.Completion,Supported=prior.Supported,PreferRangeEvidence=true,Polling=true,ObserveOnly=doc.WordSaved==false,RetryAfter=doc.NextChapterCheckUtc}; + foreach(var p in prior.Checked)work.Checked[p.Key]=p.Value; + chapterWork[doc.Session]=work;doc.RequestChapterPoll=false;doc.LastChapterPollUtc=ChapterNow; + return work; } private async Task LoadChapterManifest(TrayDocument doc,ChapterWork work) { @@ -193,8 +229,9 @@ public sealed partial class TrayCoordinator StopChapterWork(doc, work, "Chapter checks reached the retry limit. " + work.ReviewReason); return; } - var command=new AdapterCommand{Kind="chapter-check",NativeChapterPositions=work.Manifest?.NativePositionsSupported==true,OperationId=work.Operation,BookId=doc.Book,Chapter=new(){Start=position}}; - if(Queue(doc,command)){work.Command=command.Id;work.Attempts++;work.CursorWhenQueued=doc.Cursor;work.Busy=true;work.Processing=false;work.Begun=false;work.Start=work.End=0;work.Started=DateTime.UtcNow;work.Text.Clear();work.Xml.Clear();work.Identities.Clear();work.NativeTextVerified=false;work.IdentityAction="";doc.Status=$"Checking chapter positions ({work.Checked.Count}/{work.Manifest!.Chapters.Length} accepted); Word prose is unchanged.";} + var baseline=work.PreferRangeEvidence?work.Manifest?.Chapters.FirstOrDefault(c=>position>=c.Start&&positionwork.Start&&work.Manifest!=null) @@ -229,6 +273,16 @@ public sealed partial class TrayCoordinator private void AdvanceChapter(TrayDocument doc,ChapterWork work) { if(work.Manifest==null)return; + if(work.Polling) + { + var nextProbe=work.Manifest.Chapters.FirstOrDefault(c=>!work.Visited.Contains(c.ChapterId)); + if(nextProbe!=null){QueueChapter(doc,work,nextProbe.Start);return;} + work.Finished=true;work.Busy=false;work.Processing=false;work.Command=Guid.Empty; + work.CompleteMs=work.Elapsed.Elapsed.TotalMilliseconds;doc.LastChapterPollUtc=ChapterNow; + doc.ChapterProgress=work.Completion;doc.Status=work.ObserveOnly + ?$"{work.Dirty.Count} edited chapters detected in memory. Save when ready to validate native positions and reconcile; accepted checkpoints are retained." + :$"{work.Checked.Count} chapters verified; periodic range check retained {work.Retained} checkpoints.";return; + } if(work.Manifest.Chapters.All(c=>work.Checked.ContainsKey(c.ChapterId)||work.PendingReuse.ContainsKey(c.ChapterId)||work.Reviewed.Contains(c.ChapterId))){CompleteChapters(doc,work);return;} var next=work.End; for(int count=0;count0){if(!work.ReuseFinishing){work.ReuseFinishing=true;work.Busy=true;work.Processing=true;work.Command=Guid.Empty;_ = CompleteReuseAndChapters(doc,work);}return;} var expected=work.Manifest!.Chapters.Select(c=>c.ChapterId).Where(work.Checked.ContainsKey).ToArray();var actual=work.Checked.OrderBy(p=>p.Value.Start).Select(p=>p.Key).ToArray();for(int i=0;iid>0).ToArray(),HasIssues=work.Reviewed.Count>0||work.Manifest!.Chapters.Any(c=>!work.Checked.ContainsKey(c.ChapterId))};CountChapterRequest(work,completion); - try{var result=await cloud.FinishChapters(doc.Book,completion,work.Context);lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;work.Processing=false;work.CompleteMs=work.RecognitionMs+work.Elapsed.Elapsed.TotalMilliseconds;work.Completion=result;doc.ChapterProgress=result;doc.Status=result.Message;if(result.State=="Needs review" && work.ReviewReason.Length>0){result.Message=work.ReviewReason;}}} + try{var result=await cloud.FinishChapters(doc.Book,completion,work.Context);lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;work.Processing=false;work.CompleteMs=work.RecognitionMs+work.Elapsed.Elapsed.TotalMilliseconds;work.Completion=result;doc.LastChapterPollUtc=ChapterNow;doc.ChapterProgress=result;doc.Status=result.Message;if(result.State=="Needs review" && work.ReviewReason.Length>0){result.Message=work.ReviewReason;}}} catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){RetryChapterWork(doc,work,"Could not confirm chapter completion: "+e.Message);}} } + private static void UpdateChapterSeekHints(ChapterManifest manifest,ChapterManifestItem chapter,int start,int end,string nextHeading) + { + // These are navigation hints, not accepted positions. Every target range + // still proves its live heading, identity, content and absolute geometry. + if(start!=chapter.Start||nextHeading!=chapter.NextHeadingId)return; + var delta=end-chapter.End;if(delta==0)return; + var index=Array.IndexOf(manifest.Chapters,chapter); + for(var i=index+1;inew ChapterParagraph{NativeId=p.NativeId,Length=p.Length,Outline=p.Outline,WordLength=p.WordLength,Anchors=p.Anchors}).ToArray()}; lock(gate){if(chapter.ContentHash!=proof.ContentHash)work.Mismatching++;else if(ChapterCheckpointReuse.Matches(chapter,proof))work.Matching++;else if(!chapter.DurableAccepted)work.Missing++;else work.Incompatible++;work.VerificationMs+=verification.Elapsed.TotalMilliseconds;} + if(work.Polling) + { + lock(gate) + { + if(!CurrentChapterWork(doc,work)||work.Command!=command)return; + if(!ChapterCheckpointReuse.Matches(chapter,proof)||!work.Checked.TryGetValue(chapter.ChapterId,out var retained)||retained.Start!=start||retained.End!=end) + { + work.Checked.Remove(chapter.ChapterId);work.Command=Guid.Empty;work.Processing=false; + if(!Queue(doc,new(){Kind="chapter-recheck-revision"}))StopChapterWork(doc,work,"Word queue is busy; retry Synchronise."); + return; + } + chapter.Start=start;chapter.End=end;work.Retained++;work.Busy=false;work.Processing=false;AdvanceChapter(doc,work);return; + } + } + lock(gate){if(!CurrentChapterWork(doc,work)||work.Command!=command)return;UpdateChapterSeekHints(manifest,chapter,start,end,nextHeading);} if(manifest.CheckpointReuseSupported&&ChapterCheckpointReuse.Matches(chapter,proof)) { bool flush;lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;flush=work.PendingReuse.Values.Sum(p=>p.Paragraphs.Length)+proof.Paragraphs.Length>20000||work.PendingReuse.Count>=64;} @@ -288,18 +376,19 @@ public sealed partial class TrayCoordinator lock(gate) { if(!CurrentChapterWork(doc,work)||work.Command!=command||doc.WordSaved!=true)return; - proof.Reconcile=true;proof.Paragraphs=rows;work.Submissions++;CountChapterRequest(work,proof); + work.Reconciling=true;work.CurrentTitle=string.IsNullOrWhiteSpace(chapter.Title)?"chapter":chapter.Title;proof.Reconcile=true;proof.Paragraphs=rows;work.Submissions++;CountChapterRequest(work,proof); } result=await cloud.ValidateChapter(work.Book,proof,work.Context); } - lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.ServerMs+=validation.Elapsed.TotalMilliseconds;if(result.Accepted&&proof.Reconcile&&proof.Paragraphs.Any(p=>p.Text!=null))work.Reconciled++;work.Busy=false; - if(result.Accepted){work.Retries=0;work.Checked[chapter.ChapterId]=(start,end);manifest.Revision=result.Revision;if(result.State=="Needs review")work.Reviewed.Add(chapter.ChapterId);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status=$"{work.Checked.Count}/{manifest.Chapters.Length} chapters accepted · "+result.Message;AdvanceChapter(doc,work);} + lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.ServerMs+=validation.Elapsed.TotalMilliseconds;if(result.Accepted&&proof.Reconcile&&proof.Paragraphs.Any(p=>p.Text!=null))work.Reconciled++;work.Busy=false;work.Reconciling=false; + if(result.Accepted){work.Retries=0;work.Checked[chapter.ChapterId]=(start,end);manifest.Revision=result.Revision; + chapter.ContentHash=proof.ContentHash;chapter.IdentityHash=proof.IdentityHash;chapter.PositionHash=proof.PositionHash;chapter.NextHeadingId=proof.NextHeadingId;chapter.HeadingNativeId=proof.Paragraphs[0].NativeId;chapter.ParagraphCount=proof.Paragraphs.Length;chapter.DurableAccepted=result.State!="Needs review";chapter.Start=start;chapter.End=end;if(result.State=="Needs review")work.Reviewed.Add(chapter.ChapterId);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status=$"{work.Checked.Count}/{manifest.Chapters.Length} chapters accepted · "+result.Message;AdvanceChapter(doc,work);} else{work.Reviewed.Add(chapter.ChapterId);work.ReviewReason=result.Message;doc.Status=result.Message+" Accepted chapter repairs are retained.";AdvanceChapter(doc,work);} } }catch(Exception e)when(NetworkFailure(e)||e is ArgumentException or System.Xml.XmlException){lock(gate)if(CurrentChapterWork(doc,work)&&work.Command==command){work.Busy=false; if(e is HttpRequestException or OperationCanceledException or ChapterReuseConflictException||cloud.Status().Health?.Authentication!="verified"){work.Visited.Clear();RetryChapterWork(doc,work,"Chapter connection interrupted. Accepted checkpoints are retained.");} else if(e is ArgumentException or System.Xml.XmlException&&end>start){ReviewChapterReadFailure(doc,work,start,end,"Chapter content needs review: "+e.Message);} else{work.FailedRevision=doc.Revision;doc.Status="Chapter needs review: "+e.Message+" Existing import is unchanged.";}}} - finally{chapterProcessing.Release();} + finally{lock(gate)chapterProcessingSessions.Remove(doc.Session);chapterProcessing.Release();} } } diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs index 7d9f904f..932588f0 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs @@ -2,18 +2,18 @@ using PlotDirector.Companion.Protocol; namespace PlotDirector.Companion.Agent; // One control centre in the existing agent. Exact-session commands only; no COM or UI objects. -public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway cloud,ChapterAiWork ai) +public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway cloud,ChapterAiWork ai,TimeProvider? synchronisationClock=null) { private readonly Guid agentInstance=Guid.NewGuid(),agentSession=Guid.NewGuid();private int lastBook;private Guid lastAuthentication;private long agentSequence;private long presenceSequence=DateTime.UtcNow.Ticks;private int uploading;private DateTime lastAgentPresence;private bool agentOnlyPublished; private bool ParagraphCapable(Guid instance){lock(gate)return paragraphInstances.Contains(instance);} private readonly ParagraphSnapshotCache paragraphSnapshots=new(); - private readonly HashSet paragraphInstances=[];private readonly HashSet chapterInstances=[]; + private readonly HashSet rangeInstances=[];private readonly HashSet paragraphInstances=[];private readonly HashSet chapterInstances=[]; private readonly object gate=new();private readonly Dictionary documents=[]; private readonly Dictionary> commands=[];private readonly Dictionary leases=[];private readonly HashSet captureInstances=[];private readonly HashSet maintenanceInstances=[];private readonly Dictionary maintenance=[];private readonly Dictionary<(Guid,Guid),(Guid Manuscript,Guid Authentication,int Book,DateTime Expires)> reconnectBindings=[]; public event Action? OpenRequested; public TrayDocument[] Documents {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).ToArray();}} public TrayDocument[] PresentationDocuments {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).Select(d=>d.Snapshot()).ToArray();}} - public void Attach(Guid instance,Guid lease,bool capture=false,bool canMaintain=false,bool paragraphs=false,bool chapters=false){lock(gate){Disconnected(instance);if(chapters)chapterInstances.Add(instance);else chapterInstances.Remove(instance);if(paragraphs)paragraphInstances.Add(instance);else paragraphInstances.Remove(instance);leases[instance]=lease;if(canMaintain)maintenanceInstances.Add(instance);else maintenanceInstances.Remove(instance);if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}} + public void Attach(Guid instance,Guid lease,bool capture=false,bool canMaintain=false,bool paragraphs=false,bool chapters=false,bool rangeChecks=false){lock(gate){Disconnected(instance);if(rangeChecks)rangeInstances.Add(instance);if(chapters)chapterInstances.Add(instance);else chapterInstances.Remove(instance);if(paragraphs)paragraphInstances.Add(instance);else paragraphInstances.Remove(instance);leases[instance]=lease;if(canMaintain)maintenanceInstances.Add(instance);else maintenanceInstances.Remove(instance);if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}} public Message Exchange(Guid instance,Message request,Message answer,Guid lease=default) { lock(gate) @@ -25,8 +25,8 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway if(request.Kind=="reconcile")foreach(var prior in documents.Values.Where(d=>d.Instance==instance&&!request.Documents.Any(v=>v.SessionId==d.Session)).ToArray())Remove(prior.Session); foreach(var descriptor in request.Documents){ if(sessions.Descriptor(instance,descriptor.SessionId)==null)continue; - if(!documents.TryGetValue(descriptor.SessionId,out var d))documents[descriptor.SessionId]=d=new(){Session=descriptor.SessionId,Instance=instance}; - if(d.Revision!=descriptor.Revision){if(d.AssociationRequest!=Guid.Empty){d.AssociationRequest=Guid.Empty;d.AssociationNotice="Word changed before the association was confirmed. Check the document and retry.";}foreach(var pending in maintenance.Where(p=>p.Value.Session==d.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(pending);d.MaintenanceReport="Stopped: document revision changed; inspect before retrying cleanup.";}Cancel(d,notifyWord:false);d.LastChapterInterruption="Document revision changed; waiting for saved-state evidence.";d.WordSaved=null;d.Chapters=[];d.FailedChapters.Clear();d.Words=null;d.ChapterId=null;d.SceneId=null;d.ChapterTitle="";d.SceneTitle="";d.LastPresenceKey="";d.Status="Document changed. Detect chapters to refresh this snapshot.";} + var d=documents.GetValueOrDefault(descriptor.SessionId);var existed=d!=null;if(d==null)documents[descriptor.SessionId]=d=new(){Session=descriptor.SessionId,Instance=instance}; + if(d.Revision!=descriptor.Revision){if(d.AssociationRequest!=Guid.Empty){d.AssociationRequest=Guid.Empty;d.AssociationNotice="Word changed before the association was confirmed. Check the document and retry.";}foreach(var pending in maintenance.Where(p=>p.Value.Session==d.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(pending);d.MaintenanceReport="Stopped: document revision changed; inspect before retrying cleanup.";}Cancel(d,notifyWord:false);d.LastChapterInterruption="Document revision changed; waiting for saved-state evidence.";if(existed&&rangeInstances.Contains(instance))d.NextChapterCheckUtc=ChapterNow.AddSeconds(3);d.WordSaved=null;d.Chapters=[];d.FailedChapters.Clear();d.Words=null;d.ChapterId=null;d.SceneId=null;d.ChapterTitle="";d.SceneTitle="";d.LastPresenceKey="";d.Status="Document changed. Detect chapters to refresh this snapshot.";} if(reconnectBindings.Remove((instance,descriptor.SessionId),out var binding)&&binding.Expires>DateTime.UtcNow&&binding.Manuscript==descriptor.ManuscriptId&&binding.Authentication==cloud.Status().AuthenticationContext){d.Book=binding.Book;d.Authentication=binding.Authentication;} d.Revision=descriptor.Revision;d.Manuscript=descriptor.ManuscriptId;d.Title=descriptor.Title;d.RememberedBook=descriptor.RememberedBook;d.AssociationSite=descriptor.AssociationSite;d.Observed=DateTime.UtcNow; } @@ -36,7 +36,9 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway else{ doc.Observed=DateTime.UtcNow; if(request.Kind=="active"){foreach(var d in documents.Values)d.Active=false;doc.Active=true;} - if(request.Kind=="selection"){if(ChapterCapable(instance)&&(doc.Cursor!=request.Start||doc.WordSaved!=request.WordSaved)){ChapterCursorEvidence.Invalidate(doc);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(doc.WordSaved==true&&doc.RibbonNotice?.State=="Save required")doc.RibbonNotice=null;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}} + if(request.Kind=="selection"){if(doc.WordSaved!=request.WordSaved&&request.WordSaved==true&&doc.NextChapterCheckUtc!=default)doc.NextChapterCheckUtc=ChapterNow.AddSeconds(3);if(ChapterCapable(instance)&&(doc.Cursor!=request.Start||doc.WordSaved!=request.WordSaved)){ChapterCursorEvidence.Invalidate(doc);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(doc.WordSaved==true&&doc.RibbonNotice?.State=="Save required")doc.RibbonNotice=null;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}} + if(request.Kind=="selection"&&doc.LastPresenceKey!=""&&chapterWork.TryGetValue(doc.Session,out var localWork)&&CurrentChapterWork(doc,localWork)&&localWork.Supported) + PumpChapterWork(doc,localWork); ChapterFrame(doc,request,answer); if(request.Kind is "tray-sync" or "tray-repair")ReceiveChapterRibbonRequest(doc,request.Kind); if ((request.Kind is "tray-context" or "tray-intent") && answer.Status == "ok") @@ -69,7 +71,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway return answer; } } - public void Disconnected(Guid instance,Guid lease=default){lock(gate){if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return;leases.Remove(instance);chapterInstances.Remove(instance);paragraphInstances.Remove(instance);captureInstances.Remove(instance);maintenanceInstances.Remove(instance);foreach(var expired in reconnectBindings.Where(p=>p.Value.Expires<=DateTime.UtcNow).Select(p=>p.Key).ToArray())reconnectBindings.Remove(expired);foreach(var doc in documents.Values.Where(d=>d.Instance==instance).ToArray()){if(doc.Book>0&&reconnectBindings.Count<256)reconnectBindings[(instance,doc.Session)]=(doc.Manuscript,doc.Authentication,doc.Book,DateTime.UtcNow.AddMinutes(2));Remove(doc.Session);}commands.Remove(instance);}} + public void Disconnected(Guid instance,Guid lease=default){lock(gate){if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return;leases.Remove(instance);rangeInstances.Remove(instance);chapterInstances.Remove(instance);paragraphInstances.Remove(instance);captureInstances.Remove(instance);maintenanceInstances.Remove(instance);foreach(var expired in reconnectBindings.Where(p=>p.Value.Expires<=DateTime.UtcNow).Select(p=>p.Key).ToArray())reconnectBindings.Remove(expired);foreach(var doc in documents.Values.Where(d=>d.Instance==instance).ToArray()){if(doc.Book>0&&reconnectBindings.Count<256)reconnectBindings[(instance,doc.Session)]=(doc.Manuscript,doc.Authentication,doc.Book,DateTime.UtcNow.AddMinutes(2));Remove(doc.Session);}commands.Remove(instance);}} private void Remove(Guid session){chapterWork.Remove(session);paragraphSnapshots.Remove(session);foreach(var key in maintenance.Where(p=>p.Value.Session==session).Select(p=>p.Key).ToArray())maintenance.Remove(key);if(documents.Remove(session,out var doc)){Cancel(doc);_ = cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);}} private bool Queue(TrayDocument doc,AdapterCommand command){if(!commands.TryGetValue(doc.Instance,out var queue))commands[doc.Instance]=queue=new();if(queue.Count>=16){doc.Status="Word request queue is busy. Retry after current operation.";return false;}command.SessionId=doc.Session;command.Revision=doc.Revision;queue.Enqueue(command);return true;} public bool CanMaintain(Guid session){lock(gate)return documents.TryGetValue(session,out var d)&&maintenanceInstances.Contains(d.Instance);} @@ -115,6 +117,8 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway if(doc.Book>0&&cloudState.Health?.Authentication=="verified"&&cloudState.Health.State=="Connected"&&!cloudState.Books.Any(b=>b.BookId==doc.Book)){Cancel(doc);doc.Book=0;doc.Status="Book access is no longer verified. Reconnect and select an authorised book.";} if(doc.Book==0&&cloud.RestoreBinding(doc.Manuscript) is int localBook){doc.Book=localBook;doc.Authentication=cloudState.AuthenticationContext;lastBook=localBook;lastAuthentication=doc.Authentication;} if(doc.Book==0&&DocumentBindingRestore(doc,cloudState)) {doc.Book=doc.RememberedBook!.Value;doc.Authentication=cloudState.AuthenticationContext;lastBook=doc.Book;lastAuthentication=doc.Authentication;} + if(ChapterCapable(doc.Instance)&&doc.LastPresenceKey!=""&&chapterWork.TryGetValue(doc.Session,out var scheduled)&&CurrentChapterWork(doc,scheduled)&&scheduled.Supported) + PumpChapterWork(doc,scheduled); if(doc.Job==Guid.Empty){if(doc.Pending.Count>0&&!documents.Values.Any(other=>other.Job!=Guid.Empty))Next(doc);continue;}var result=ai.Result(doc.Session); if(result?.RequestId==doc.Job&&result.State is "complete" or "failed" or "cancelled"){ if(result.State=="complete"&&!string.IsNullOrEmpty(result.ReviewPath)){if(result.SourceRetained)doc.Retained++;if(doc.Completed.Count>=8192)doc.Completed.RemoveWhere(c=>c.Item1!=doc.Revision);doc.Completed.Add((doc.Revision,doc.Book,doc.Current!.Start));doc.FailedChapters.Remove((doc.Revision,doc.Book,doc.Current.Start));doc.ReviewPath=result.ReviewPath;} @@ -139,7 +143,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway public async Task Heartbeat(CancellationToken cancellation) { while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromMilliseconds(500),cancellation);var available=Documents.Where(d=>d.Authentication==cloud.Status().AuthenticationContext&&cloud.Status().Health?.Authentication=="verified").ToArray(); - foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc0&&reply.ParagraphRevision0&&!ChapterCapable(doc.Instance))lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext){doc.ChapterId=reply.ChapterId;doc.SceneId=reply.SceneId;} if(reply.Navigation is {Kind:"wizard-capture",BookId:>0} requested&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Book==0){await cloud.CheckConnection();lock(gate){if(doc.Book==0&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext&&cloud.Allows(doc.Authentication,requested.BookId)&&documents.GetValueOrDefault(doc.Session)==doc){doc.Book=requested.BookId;cloud.RememberBinding(doc.Manuscript,doc.Book,doc.Authentication);doc.LastPresenceKey="";}}} if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision){if((reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")&&captureInstances.Contains(doc.Instance)&&(reply.Navigation.BookId==0||reply.Navigation.BookId==doc.Book)&&cloud.Allows(doc.Authentication,doc.Book)){if(uploading!=0||documents.Values.Any(d=>d.Capture!=null)){_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);continue;}var retained=doc.RetryCapture;var reusable=retained!=null&&doc.RetryAuthentication==doc.Authentication&&doc.RetryBook==doc.Book&&retained.ManuscriptId==doc.Manuscript&&retained.Revision==doc.Revision&&retained.ParagraphTracking==reply.Navigation.ParagraphTracking; @@ -200,7 +204,7 @@ public sealed class TrayDocument internal DateTime RibbonRequestedUtc;internal Guid RibbonPermit;internal PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? RibbonNotice; public int? ContextCursor;public long ContextRevision=-1;public int ContextBook;public Guid ContextManuscript; public readonly DateTime FirstObserved=DateTime.UtcNow; - public Guid AssociationRequest;public bool AssociationNeedsSave;public string AssociationNotice="";public string MaintenanceReport="";public string WordDiagnostics="";public int Cursor;public int Retained;public int Failed;public int Book,Progress,Total,Done;public int? RememberedBook,Words,ChapterId,SceneId;public bool Active;public DateTime Observed,Started; + public DateTime NextChapterCheckUtc,LastChapterPollUtc;public bool RequestChapterPoll;public Guid AssociationRequest;public bool AssociationNeedsSave;public string AssociationNotice="";public string MaintenanceReport="";public string WordDiagnostics="";public int Cursor;public int Retained;public int Failed;public int Book,Progress,Total,Done;public int? RememberedBook,Words,ChapterId,SceneId;public bool Active;public DateTime Observed,Started; public StructureSuggestion[] Chapters=[];public StructureSuggestion? Current;public Queue Pending=[];public HashSet<(long,int,int)> Completed=[];public HashSet<(long,int,int)> FailedChapters=[];public List Errors=[]; internal TrayDocument Snapshot(){var copy=(TrayDocument)MemberwiseClone();copy.Completed=new(Completed);copy.FailedChapters=new(FailedChapters);copy.Errors=new(Errors);copy.Pending=new(Pending);return copy;} public override string ToString()=>Title+(Active?" (active in Word)":""); diff --git a/PlotDirector.NativeCompanion/Client/AgentLink.cs b/PlotDirector.NativeCompanion/Client/AgentLink.cs index 0fdbd983..a110d58f 100644 --- a/PlotDirector.NativeCompanion/Client/AgentLink.cs +++ b/PlotDirector.NativeCompanion/Client/AgentLink.cs @@ -119,7 +119,7 @@ public sealed class AgentLink : IDisposable lock (gate) activePipe = pipe; await pipe.ConnectAsync(700, stop.Token).ConfigureAwait(false); if (!verifyServer(pipe)) throw new UnauthorizedAccessException("Unexpected agent owner."); - await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability+","+ProtocolVersion.ChapterSyncCapability+","+ProtocolVersion.NativeChapterTextCapability+","+ProtocolVersion.NativeChapterPositionsCapability+","+ProtocolVersion.LiveChapterTextCapability }, stop.Token).ConfigureAwait(false); + await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability+","+ProtocolVersion.ChapterSyncCapability+","+ProtocolVersion.NativeChapterTextCapability+","+ProtocolVersion.NativeChapterPositionsCapability+","+ProtocolVersion.LiveChapterTextCapability+","+ProtocolVersion.ChapterRangeCapability }, stop.Token).ConfigureAwait(false); mailbox.Clear(); // Reconcile authoritative open documents; never replay stale extraction fragments. await ExchangeAsync(pipe, Reconcile(), stop.Token).ConfigureAwait(false); attempt = 0; StateChanged?.Invoke("connected"); diff --git a/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs index 0ac36901..4b3ac5fb 100644 --- a/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs +++ b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs @@ -54,7 +54,7 @@ public static class ChapterFingerprint } 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."); + var rows=paragraphs.ToArray();if(rows.Length==0||rows.Length>MaxParagraphs||rows.Any(p=>p.Length<=0||string.IsNullOrEmpty(p.NativeId)||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); diff --git a/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterRangeVerification.cs b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterRangeVerification.cs new file mode 100644 index 00000000..d2b4d43a --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterRangeVerification.cs @@ -0,0 +1,42 @@ +namespace PlotDirector.Companion.Protocol.Manuscript; + +// Range.Text includes Word's paragraph terminators. No paragraph COM enumeration is +// needed to calculate content, but content alone must never certify native identity. +public enum ChapterRangeResult { RequiresDetailed, Matching, Changed } + +public sealed class ChapterRangeCheck +{ + public ChapterRangeResult Result {get;set;} + public string IdentityFrames {get;set;}=""; +} + +public static class ChapterRangeVerification +{ + public static string Content(string text) + { + if(text.Length==0||text.Length>ChapterFingerprint.MaxCharacters||text[text.Length-1]!='\r') + throw new ArgumentException("A complete bounded chapter range is required."); + var rows=new List();var start=0; + for(var i=0;iCheck(text,xml,baseline,nextHeading).Result; + public static ChapterRangeCheck Check(string text,string xml,ChapterManifestItem baseline,string nextHeading) + { + try + { + if(!baseline.DurableAccepted||baseline.Algorithm!=ChapterFingerprint.Version||baseline.State=="Needs review"||baseline.PositionHash!="")return new(){Result=ChapterRangeResult.RequiresDetailed}; + if(baseline.NextHeadingId!=nextHeading||Content(text)!=baseline.ContentHash)return new(){Result=ChapterRangeResult.Changed}; + // Missing XML native IDs, pictures, fields, revisions, section breaks, + // ambiguous styles or geometry all fall back to the qualified live reader. + var rows=ChapterFingerprint.ReadXml(xml,text); + var matches=rows.Length==baseline.ParagraphCount&&rows[0].NativeId==baseline.HeadingNativeId&& + rows[0].Outline==1&&!rows.Skip(1).Any(p=>p.Outline==1)&& + ChapterFingerprint.Identity(rows)==baseline.IdentityHash&&ChapterFingerprint.Content(rows.Select(p=>p.Text!))==baseline.ContentHash; + return new(){Result=matches?ChapterRangeResult.Matching:ChapterRangeResult.Changed, + IdentityFrames=matches?string.Concat(rows.Select(p=>p.NativeId+p.Length.ToString("X8",System.Globalization.CultureInfo.InvariantCulture)+p.Outline.ToString("X8",System.Globalization.CultureInfo.InvariantCulture))):""}; + } + catch(Exception e)when(e is ArgumentException or System.Xml.XmlException){return new(){Result=ChapterRangeResult.RequiresDetailed};} + } +} diff --git a/PlotDirector.NativeCompanion/Protocol/Messages.cs b/PlotDirector.NativeCompanion/Protocol/Messages.cs index 97079529..26e62d00 100644 --- a/PlotDirector.NativeCompanion/Protocol/Messages.cs +++ b/PlotDirector.NativeCompanion/Protocol/Messages.cs @@ -5,6 +5,7 @@ namespace PlotDirector.Companion.Protocol; public static class ProtocolVersion { public const int Current = 1; + public const string ChapterRangeCapability="chapter-range-verification-v1"; public const string LiveChapterTextCapability="chapter-live-text-v1"; public const string NativeChapterPositionsCapability="chapter-native-positions-v1"; public const string NativeChapterTextCapability="chapter-native-text-v1"; diff --git a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs index 5f1523b5..bf16c495 100644 --- a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs +++ b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs @@ -3,6 +3,9 @@ namespace PlotDirector.Companion.Protocol; [DataContract] public sealed class AdapterCommand { + [DataMember] public PlotDirector.Companion.Protocol.Manuscript.ChapterManifestItem? RangeBaseline {get;set;} + [DataMember] public bool RecheckRevision {get;set;} + [DataMember] public bool ObserveOnly {get;set;} [DataMember] public Guid OperationId {get;set;} [DataMember] public bool NativeChapterPositions {get;set;} [DataMember] public bool ParagraphTracking {get;set;} diff --git a/PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs b/PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs index ba144d24..38a6dac2 100644 --- a/PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs +++ b/PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs @@ -9,6 +9,7 @@ internal static class ChapterHandshakeTests private static void Check(bool value,string name){if(!value)throw new Exception(name);Console.WriteLine("PASS "+name);} public static async Task Run() { + await AutomaticRangeLifecycle(); await RibbonLifecycle(); foreach(var scenario in new[]{(Edited:Array.Empty(),Missing:-1,Geometry:-1),(Edited:new[]{17},Missing:-1,Geometry:-1),(Edited:new[]{7,22,47},Missing:-1,Geometry:-1),(Edited:Array.Empty(),Missing:31,Geometry:-1),(Edited:Array.Empty(),Missing:-1,Geometry:47),(Edited:Array.Empty(),Missing:-2,Geometry:-1)}) { @@ -50,6 +51,145 @@ internal static class ChapterHandshakeTests finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}} } } + private sealed class SyncClock:TimeProvider + { + private DateTimeOffset value=DateTimeOffset.UtcNow; + public override DateTimeOffset GetUtcNow()=>value; + public void Advance(double seconds)=>value=value.AddSeconds(seconds); + } + private static async Task AutomaticRangeLifecycle() + { + var handler=new Handler([],-1,-1);using var cloud=new CloudGateway(handler,_=>{}); + cloud.Connect("https://handshake.test/");await Until(()=>cloud.Status().Books.Any());await cloud.CheckConnection(); + var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var clock=new SyncClock(); + var tray=new TrayCoordinator(sessions,cloud,ai,clock);var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid(); + long sequence=0,revision=1;var commands=new Queue();var detailed=0;var probes=0;var saved=true; + sessions.Attach(instance,lease,chapters:true,liveChapterText:true);tray.Attach(instance,lease,chapters:true,rangeChecks:true); + Message Send(Message message) + { + message.WordInstanceId=instance;message.SessionId=session;message.Revision=revision;message.Sequence=++sequence; + var answer=tray.Exchange(instance,message,sessions.Apply(lease,message),lease); + if(answer.Command is {Kind:"chapter-check"} command)commands.Enqueue(command); + if(answer.Command is {Kind:"chapter-recheck-revision"}){revision++;Register();} + return answer; + } + void Register()=>Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=revision,Title="Disposable periodic range fixture.docx"}]}); + void Select()=>Send(new(){Kind="selection",WordSaved=saved}); + async Task ReadNext() + { + await Until(()=>{Select();return commands.Count>0;});var command=commands.Dequeue(); + var c=Array.FindIndex(handler.Starts,p=>p==command.Chapter!.Start); + if(c<0)throw new Exception("Fixture received a non-boundary chapter request"); + var text=handler.Current[c];var xml=ChapterRangeVerificationTests.Xml(c,text);var next=c==47?"":((c+1)*2+1).ToString("X8"); + if(command.ObserveOnly) + { + Send(new(){Kind="chapter-observe",SnapshotId=command.Id,ChapterId=command.RangeBaseline!.ChapterId,Start=handler.Starts[c],End=handler.Starts[c]+text.Length, + Action=ChapterRangeVerification.Content(text)==command.RangeBaseline.ContentHash?"matching":"changed",WordSaved=false}); + return; + } + var light=command.RangeBaseline!=null&&ChapterRangeVerification.Compare(text,xml,command.RangeBaseline,next)==ChapterRangeResult.Matching; + if(command.RangeBaseline!=null)probes++; + if(!light&&command.RecheckRevision){revision++;Register();Select();return;} + if(!light)detailed++; + Send(new(){Kind="chapter-begin",SnapshotId=command.Id,Start=handler.Starts[c],End=handler.Starts[c]+text.Length,DocumentEnd=handler.Starts[47]+handler.Current[47].Length,WordSaved=true,ChapterTitle=next}); + void Chunk(string action,string value){for(var n=0;ntray.ChapterProgressForDisplay(session)?.State=="Synchronised"); + Check(detailed==48&&probes==0,"Initial reopen retains the existing qualified native identity reader"); + var baselineReused=handler.Reused;var baselineAccept=handler.AcceptRequests;var finish=handler.Finishes; + detailed=probes=0; + handler.Current[13]=handler.Current[13].Replace("synthetic","different"); + // Three edits in the same chapter coalesce. Cursor is deliberately in + // Chapter 1, so it cannot serve as evidence that Chapter 14 changed. + for(var i=0;i<3;i++){revision++;Register();Select();clock.Advance(1);} + Select();await Task.Delay(100); + Check(commands.Count==0,"Automatic chapter checking waits for three seconds of edit inactivity"); + clock.Advance(2); + var watch=System.Diagnostics.Stopwatch.StartNew(); + for(var i=0;i<48;i++) + { + await ReadNext(); + if(i==0) + { + await Until(()=>handler.Reused>baselineReused); + handler.HoldNextPresence=1;Send(new(){Kind="selection",Start=1,WordSaved=true}); + await handler.HeldPresence.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } + } + await Until(()=>handler.Finishes==finish+1&&tray.ChapterProgressForDisplay(session)?.State=="Synchronised"); + var manifests=handler.ManifestRequests;handler.ReleasePresence.TrySetResult();await Task.Delay(100);Select(); + Check(handler.ManifestRequests==manifests&&commands.Count==0,"An older in-flight presence revision cannot discard newly accepted chapter work or restart verification"); + Check(detailed==1&&probes==48,"A single saved chapter edit performs forty-seven lightweight checks and one detailed chapter read"); + Check(handler.Reused-baselineReused==47&&handler.AcceptRequests-baselineAccept==2&&handler.Reconciled==1,"Automatic lifecycle reuses forty-seven checkpoints in batches and reconciles only Chapter 14"); + Check(tray.ChapterProgressForDisplay(session) is {Matching:48,Total:48,State:"Synchronised"},"Automatic saved edit returns to forty-eight verified without a ribbon command"); + Console.WriteLine($"MEASURE incremental HTTP fixture: debounce=3s virtual, rangeChecks={probes}, detailedReads={detailed}, reused=47, reconciled=1, processingMs={watch.Elapsed.TotalMilliseconds:F1}; includes held presence reply, synthetic XML, no Word extraction or COM."); + var reuse=handler.ReuseRequests;var accept=handler.AcceptRequests;finish=handler.Finishes;detailed=probes=0; + clock.Advance(59);Select();await Task.Delay(50);Check(commands.Count==0,"Periodic verification does not run continuously after a completed cycle"); + clock.Advance(1); + for(var i=0;i<48;i++)await ReadNext(); + await Until(()=>tray.ChapterDiagnostics(session).Contains("retained=48")); + Check(detailed==0&&probes==48&&handler.ReuseRequests==reuse&&handler.AcceptRequests==accept&&handler.Finishes==finish,"Sixty-second unchanged checks retain all live checkpoints without any server reacceptance"); + // Manual Synchronise immediately enters the same periodic range path. + Send(new(){Kind="tray-sync"}); + for(var i=0;i<48;i++)await ReadNext(); + await Until(()=>tray.ChapterDiagnostics(session).Contains("retained=48")); + Check(handler.RepairRequests==0&&handler.AcceptRequests==accept,"Manual Synchronise uses the range pipeline without invoking Repair"); + // A periodic probe, without a length/saved/selection revision signal, + // discovers changed content and requests a new Word revision first. + handler.Current[22]=handler.Current[22].Replace("synthetic","different"); + var oldRevision=revision;clock.Advance(60); + while(revision==oldRevision)await ReadNext(); + Check(revision>oldRevision,"Periodic range checks discover same-length edits without relying on Word change notifications"); + clock.Advance(3);detailed=probes=0;var priorReconciled=handler.Reconciled;finish=handler.Finishes; + for(var i=0;i<48;i++)await ReadNext(); + await Until(()=>handler.Finishes==finish+1); + Check(detailed==1&&handler.Reconciled==priorReconciled+1,"A detected periodic mismatch is reconciled only under the newly registered revision"); + // Undo before synchronisation restores accepted content; no prose + // reconciliation should be necessary for that revision. + handler.Current[7]=handler.Current[7].Replace("synthetic","different"); + revision++;Register();Select(); + handler.Current[7]=handler.Current[7].Replace("different","synthetic"); + revision++;Register();Select();clock.Advance(3);detailed=0;priorReconciled=handler.Reconciled;finish=handler.Finishes; + for(var i=0;i<48;i++)await ReadNext();await Until(()=>handler.Finishes==finish+1); + Check(detailed==0&&handler.Reconciled==priorReconciled,"Undo restoring accepted chapter content reuses checkpoints without reconciliation"); + handler.Current[7]=handler.Current[7].Replace("synthetic","different"); + revision++;Register();Select();clock.Advance(3);detailed=0;finish=handler.Finishes; + for(var i=0;i<48;i++)await ReadNext();await Until(()=>handler.Finishes==finish+1); + Check(detailed==1&&handler.Reconciled==priorReconciled+1,"Redo takes the same selective automatic lifecycle"); + // Length changes require live position updates downstream, not prose + // reconciliation or native paragraph walks in unaffected chapters. + handler.Current[2]=handler.Current[2].Replace("synthetic synthetic","extra",StringComparison.Ordinal); + handler.Current[35]=handler.Current[35].TrimEnd('\r')+" Longer paragraph.\r"; + for(var i=1;i<48;i++)handler.Starts[i]=handler.Starts[i-1]+handler.Current[i-1].Length; + revision++;Register();Select();clock.Advance(3);detailed=0;priorReconciled=handler.Reconciled;finish=handler.Finishes; + for(var i=0;i<48;i++)await ReadNext();await Until(()=>handler.Finishes==finish+1); + Check(detailed==2&&handler.Reconciled==priorReconciled+2,"Edits in two chapters rebase later seek hints and reconcile only the two changed chapters"); + saved=false;handler.Current[9]=handler.Current[9].Replace("synthetic","different");revision++;Register();Select();clock.Advance(3); + accept=handler.AcceptRequests;reuse=handler.ReuseRequests;priorReconciled=handler.Reconciled; + for(var i=0;i<48;i++)await ReadNext(); + Check(tray.ChapterDiagnostics(session).Contains("editedInMemory=1")&&handler.AcceptRequests==accept&&handler.ReuseRequests==reuse,"Unsaved range observations detect edited content without submitting incoherent native positions"); + handler.Current[9]=handler.Current[9].Replace("different","synthetic"); + handler.Current[41]=handler.Current[41].Replace("synthetic","different"); + clock.Advance(60); + for(var i=0;i<48;i++)await ReadNext(); + Check(tray.ChapterDiagnostics(session).Contains("editedInMemory=1")&&handler.Reconciled==priorReconciled,"Periodic observations detect same-length changes and Undo while Word remains already unsaved"); + saved=true;revision++;Register();Select();clock.Advance(3);detailed=0;finish=handler.Finishes; + for(var i=0;i<48;i++)await ReadNext();await Until(()=>handler.Finishes==finish+1); + Check(detailed==1&&handler.Reconciled==priorReconciled+1,"Saving observed in-memory edits automatically reconciles only the remaining changed chapter"); + + + } + finally{handler.ReleasePresence.TrySetResult();stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}} + } private static async Task RibbonLifecycle() { var handler=new Handler([17],-1,-1); @@ -94,14 +234,17 @@ internal static class ChapterHandshakeTests private static async Task Until(Func ready){for(var n=0;n<3000;n++){if(ready())return;await Task.Delay(5);}throw new Exception("Handshake fixture timed out");} private sealed class Handler:HttpMessageHandler { - public readonly Guid Manuscript=Guid.NewGuid();public readonly string[] Current;public readonly int[] Starts;private readonly string[] hashes;private readonly int missing,geometry;private long revision=1; + public readonly Guid Manuscript=Guid.NewGuid();public readonly string[] Current;public readonly int[] Starts;private readonly string[] hashes;private readonly int[] acceptedLengths;private readonly int missing,geometry;private long revision=1; public readonly TaskCompletionSource ReleaseSecond=new(TaskCreationOptions.RunContinuationsAsynchronously); public int ReuseRequests,Reused,AcceptRequests,Reconciled,Finishes;public long Bytes;private bool currentReady; + public int HoldNextPresence,ManifestRequests; + public readonly TaskCompletionSource HeldPresence=new(TaskCreationOptions.RunContinuationsAsynchronously),ReleasePresence=new(TaskCreationOptions.RunContinuationsAsynchronously); public int RepairRequests;private AdapterCommand? repair; public Handler(int[] changed,int missing,int geometry) { this.missing=missing;this.geometry=geometry; var original=Enumerable.Range(0,48).Select(c=>$"Chapter {c}\r"+string.Join(" ",Enumerable.Repeat("synthetic",3187))+"\r").ToArray(); + acceptedLengths=original.Select(p=>p.Length).ToArray(); Current=original.Select((s,c)=>changed.Contains(c)?s.Replace("synthetic","different"):s).ToArray();Starts=new int[48];for(var c=1;c<48;c++)Starts[c]=Starts[c-1]+Current[c-1].Length; hashes=original.Select((s,c)=>ChapterFingerprint.Content([$"Chapter {c}\r",s[($"Chapter {c}\r").Length..]])).ToArray(); } @@ -109,7 +252,7 @@ internal static class ChapterHandshakeTests { var path=request.RequestUri!.AbsolutePath;HttpResponseMessage Json(object value)=>new(HttpStatusCode.OK){Content=JsonContent.Create(value)}; if(path.EndsWith("/pair"))return Json(new{code="00112233445566778899AABB"});if(path.EndsWith("/token"))return Json(new{accessToken="fixture"});if(path.EndsWith("/books"))return Json(new[]{new{bookId=3,title="Synthetic book"}});if(path.EndsWith("/connection"))return Json(new{state="Connected",authentication="verified",server="online",expiresUtc=DateTime.UtcNow.AddHours(4)}); - if(path.EndsWith("/presence")){var p=(await request.Content!.ReadFromJsonAsync(cancellation))!;p.ChapterSyncSupported=true;p.ParagraphRevision=revision;p.Navigation=Interlocked.Exchange(ref repair,null);if(currentReady){p.ChapterId=1;p.SceneId=10;p.ChapterTitle="Chapter 0";p.SceneTitle="Verified scene";}return Json(p);} + if(path.EndsWith("/presence")){var p=(await request.Content!.ReadFromJsonAsync(cancellation))!;p.ChapterSyncSupported=true;p.ParagraphRevision=revision;p.Navigation=Interlocked.Exchange(ref repair,null);if(currentReady){p.ChapterId=1;p.SceneId=10;p.ChapterTitle="Chapter 0";p.SceneTitle="Verified scene";}if(Interlocked.Exchange(ref HoldNextPresence,0)==1){HeldPresence.TrySetResult();await ReleasePresence.Task.WaitAsync(cancellation);}return Json(p);} if(path.EndsWith("/repair")) { if(++RepairRequests==1)return new(HttpStatusCode.Conflict){Content=JsonContent.Create(new{message="Fixture repair refused."})}; @@ -118,9 +261,9 @@ internal static class ChapterHandshakeTests repair=new(){Id=operation,Kind="chapter-repair",SessionId=target.SessionId,Revision=target.WordRevision}; return Json(new ChapterRepairRequested{OperationId=operation,Message="Fixture repair accepted."}); } - if(path.EndsWith("/chapter-sync"))return Json(new ChapterManifest{CheckpointReuseSupported=true,NativePositionsSupported=true,BookId=3,Mode="OnSave",ManuscriptId=Manuscript,Revision=revision,Chapters=Enumerable.Range(0,48).Select(c=>new ChapterManifestItem{ChapterId=c+1,DurableAccepted=c!=missing,PositionHash=c==geometry?new string('A',64):"",Algorithm=ChapterFingerprint.Version,HeadingNativeId=(c*2+1).ToString("X8"),ContentHash=hashes[c],IdentityHash=ChapterFingerprint.Identity([new(){NativeId=(c*2+1).ToString("X8"),Length=($"Chapter {c}\r").Length,Outline=1},new(){NativeId=(c*2+2).ToString("X8"),Length=Current[c].Length-($"Chapter {c}\r").Length,Outline=10}]),NextHeadingId=c==47?"":((c+1)*2+1).ToString("X8"),Start=Starts[c],End=Starts[c]+Current[c].Length,ParagraphCount=2}).ToArray()}); + if(path.EndsWith("/chapter-sync")){ManifestRequests++;return Json(new ChapterManifest{CheckpointReuseSupported=true,NativePositionsSupported=true,BookId=3,Mode="OnSave",ManuscriptId=Manuscript,Revision=revision,Chapters=Enumerable.Range(0,48).Select(c=>new ChapterManifestItem{ChapterId=c+1,DurableAccepted=c!=missing,PositionHash=c==geometry?new string('A',64):"",Algorithm=ChapterFingerprint.Version,HeadingNativeId=(c*2+1).ToString("X8"),ContentHash=hashes[c],IdentityHash=ChapterFingerprint.Identity([new(){NativeId=(c*2+1).ToString("X8"),Length=($"Chapter {c}\r").Length,Outline=1},new(){NativeId=(c*2+2).ToString("X8"),Length=acceptedLengths[c]-($"Chapter {c}\r").Length,Outline=10}]),NextHeadingId=c==47?"":((c+1)*2+1).ToString("X8"),Start=acceptedLengths.Take(c).Sum(),End=acceptedLengths.Take(c+1).Sum(),ParagraphCount=2}).ToArray()});} if(path.EndsWith("/reuse")){var data=await request.Content!.ReadAsByteArrayAsync(cancellation);Bytes+=data.Length;var batch=JsonSerializer.Deserialize(data,new JsonSerializerOptions(JsonSerializerDefaults.Web))!;if(batch.Chapters.Any(p=>p.Paragraphs.Any(r=>r.Text!=null)))throw new Exception("Reuse leaked prose");ReuseRequests++;if(missing==-2&&ReuseRequests==2)await ReleaseSecond.Task.WaitAsync(cancellation);Reused+=batch.Chapters.Length;if(batch.Chapters.Any(p=>p.ChapterId==1))currentReady=true;return Json(new ChapterReuseReply{ChapterIds=batch.Chapters.Select(p=>p.ChapterId).ToArray(),Revision=revision});} - if(path.EndsWith("/validate")){var data=await request.Content!.ReadAsByteArrayAsync(cancellation);Bytes+=data.Length;AcceptRequests++;var p=JsonSerializer.Deserialize(data,new JsonSerializerOptions(JsonSerializerDefaults.Web))!;if(p.ContentHash==hashes[p.ChapterId-1])return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",Revision=revision,ChapterId=p.ChapterId});if(p.Paragraphs.All(r=>r.Text==null))return Json(new ChapterSyncReply{State="Changed",AllowText=true,Revision=revision,ChapterId=p.ChapterId});Reconciled++;hashes[p.ChapterId-1]=p.ContentHash;return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",Revision=++revision,ChapterId=p.ChapterId});} + if(path.EndsWith("/validate")){var data=await request.Content!.ReadAsByteArrayAsync(cancellation);Bytes+=data.Length;AcceptRequests++;var p=JsonSerializer.Deserialize(data,new JsonSerializerOptions(JsonSerializerDefaults.Web))!;if(p.ContentHash==hashes[p.ChapterId-1])return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",Revision=revision,ChapterId=p.ChapterId});if(p.Paragraphs.All(r=>r.Text==null))return Json(new ChapterSyncReply{State="Changed",AllowText=true,Revision=revision,ChapterId=p.ChapterId});Reconciled++;acceptedLengths[p.ChapterId-1]=p.End-p.Start;hashes[p.ChapterId-1]=p.ContentHash;return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",Revision=++revision,ChapterId=p.ChapterId});} if(path.EndsWith("/finish")){Finishes++;return Json(new ChapterSyncProgress{State="Synchronised",Matching=48,Total=48});} return Json(new{}); } diff --git a/PlotDirector.NativeCompanion/Tests/ChapterRangeVerificationTests.cs b/PlotDirector.NativeCompanion/Tests/ChapterRangeVerificationTests.cs new file mode 100644 index 00000000..9b33f7ea --- /dev/null +++ b/PlotDirector.NativeCompanion/Tests/ChapterRangeVerificationTests.cs @@ -0,0 +1,46 @@ +using System.Diagnostics; +using PlotDirector.Companion.Protocol; +using PlotDirector.Companion.Protocol.Manuscript; + +internal static class ChapterRangeVerificationTests +{ + public static string Xml(int chapter,string text) + { + var heading=$"Chapter {chapter}\r"; + var body=System.Security.SecurityElement.Escape(text.Substring(heading.Length).TrimEnd('\r')); + return $"Chapter {chapter}{body}"; + } + public static void Run() + { + void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);} + var text="Chapter 0\rBody text\r";var xml=Xml(0,text); + var rows=ChapterFingerprint.ReadXml(xml,text); + var baseline=new ChapterManifestItem{Algorithm=ChapterFingerprint.Version,DurableAccepted=true,HeadingNativeId=rows[0].NativeId,ContentHash=ChapterFingerprint.Content(rows.Select(p=>p.Text!)),IdentityHash=ChapterFingerprint.Identity(rows),ParagraphCount=2}; + Check(ChapterRangeVerification.Content(text)==baseline.ContentHash,"Range-only fingerprint uses the accepted paragraph-delimited algorithm"); + Check(ChapterRangeVerification.Compare(text,xml,baseline,"")==ChapterRangeResult.Matching,"Complete unchanged XML identity evidence avoids the native paragraph walk"); + using(var wire=new MemoryStream()) + { + FrameCodec.WriteAsync(wire,new Message{Command=new AdapterCommand{Kind="chapter-check",RangeBaseline=baseline,ObserveOnly=true,RecheckRevision=true}},default).GetAwaiter().GetResult(); + wire.Position=0;var decoded=FrameCodec.ReadAsync(wire,default).GetAwaiter().GetResult(); + Check(decoded.Command is {ObserveOnly:true,RecheckRevision:true,RangeBaseline:not null}&&decoded.Command.RangeBaseline.IdentityHash==baseline.IdentityHash,"Range baselines and read-only flags survive the actual native IPC codec"); + } + var compact=ChapterRangeVerification.Check(text,xml,baseline,"").IdentityFrames; + Check(ChapterFingerprint.Identity(ChapterFingerprint.ReadLiveText(text,compact))==baseline.IdentityHash,"Locally verified XML emits the existing compact identity frames without transmitting XML"); + Check(ChapterRangeVerification.Compare(text.Replace("Body","Edit"),xml,baseline,"")==ChapterRangeResult.Changed,"A same-length text edit is found without length or saved-state changes"); + Check(ChapterRangeVerification.Compare(text,xml.Replace("00000002","000000FF"),baseline,"")==ChapterRangeResult.Changed,"Identical prose with replaced native identity is a changed chapter"); + Check(ChapterRangeVerification.Compare(text,xml.Replace(" w14:paraId='00000002'",""),baseline,"")==ChapterRangeResult.RequiresDetailed,"Missing exported native identities require detailed verification rather than guessed checkpoint reuse"); + Check(ChapterRangeVerification.Compare(text,xml.Replace("Body","Body"),baseline,"")==ChapterRangeResult.RequiresDetailed,"Floating drawing evidence retains the qualified native anchor reader"); + foreach(var element in new[]{"tbl","fldChar","ins","del","footnoteReference","object","altChunk"}) + Check(ChapterRangeVerification.Compare(text,xml.Replace("",$""),baseline,"")==ChapterRangeResult.RequiresDetailed,$"Structural {element} cannot take the lightweight reuse path"); + Check(ChapterRangeVerification.Compare(text,xml,baseline,"000000FF")==ChapterRangeResult.Changed,"Changed chapter order and boundaries cannot retain range evidence"); + baseline.PositionHash=new string('A',64); + Check(ChapterRangeVerification.Compare(text,xml,baseline,"")==ChapterRangeResult.RequiresDetailed,"Native geometry gaps always retain measured position validation"); + var values=Enumerable.Range(0,48).Select(i=>$"Chapter {i}\r"+string.Join(" ",Enumerable.Repeat("synthetic",3187))+"\r").ToArray(); + var expected=values.Select((value,i)=>ChapterFingerprint.Content([$"Chapter {i}\r",value[($"Chapter {i}\r").Length..]])).ToArray(); + var matches=new bool[48];var watch=Stopwatch.StartNew(); + for(var i=0;i<48;i++)matches[i]=ChapterRangeVerification.Content(values[i])==expected[i]; + watch.Stop(); + for(var i=0;i<48;i++)Check(matches[i],"Scale range fingerprint preserves exact chapter content "+i); + Console.WriteLine($"MEASURE range fingerprint CPU only: 48 chapters, {values.Sum(p=>p.Length)} UTF-16 units, {watch.Elapsed.TotalMilliseconds:F1}ms. Text was preallocated in memory. Range.Text extraction, Word XML export and Word UI responsiveness NOT measured."); + } +} diff --git a/PlotDirector.NativeCompanion/Tests/Program.cs b/PlotDirector.NativeCompanion/Tests/Program.cs index 1d55c02d..75f6ec48 100644 --- a/PlotDirector.NativeCompanion/Tests/Program.cs +++ b/PlotDirector.NativeCompanion/Tests/Program.cs @@ -3,7 +3,7 @@ using PlotDirector.Companion.Agent; using PlotDirector.Companion.Client; using PlotDirector.Companion.Protocol; -if(args.Contains("--chapter-sync")){ChapterReopenTests.Run();await ChapterAgentTests.Run();await ChapterHandshakeTests.Run();await WordReopeningWorkTests.Run();return;} +if(args.Contains("--chapter-sync")){ChapterRangeVerificationTests.Run();ChapterReopenTests.Run();await ChapterAgentTests.Run();await ChapterHandshakeTests.Run();await WordReopeningWorkTests.Run();return;} if(args.Contains("--native-capture-upload")){await NativeCaptureUploadTests.Run();return;} var passed = 0; void Check(bool value,string name) {if(!value)throw new Exception(name);passed++;Console.WriteLine("PASS "+name);} diff --git a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs index b5dbe590..3cbdd2b5 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs @@ -254,6 +254,7 @@ namespace PlotDirector.WordAddIn if(doc.Maintenance!=null){var previous=doc.Maintenance;scheduler.Cancel("maintenance:"+doc.Session);Reply(previous,"Stopped: superseded by a new document request. Inspect before retrying cleanup.");} if(command.Kind=="chapter-cancel"){CancelChapterRead(doc);Reply(command,"ok");return;} if(command.Kind=="chapter-check"){StartChapterRead(doc,command);return;} + if(command.Kind=="chapter-recheck-revision"){InvalidateChapterProbe(doc);return;} if(command.Kind.StartsWith("maintenance-",StringComparison.Ordinal)){StartMaintenance(doc,command);return;} else if((command.Kind=="wizard-capture"||command.Kind=="paragraph-snapshot")){ CancelExtraction(doc); diff --git a/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs b/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs index 3facb5cc..21afb2f5 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs @@ -40,6 +40,7 @@ namespace PlotDirector.WordAddIn switch (serverChapterProgress.State) { case "Checking": return "Checking"; + case "Synchronising": return "Synchronising"; case "Save required": return "Save to synchronise"; case "Synchronised": if (serverChapterProgress.Total > 0 && serverChapterProgress.Matching == serverChapterProgress.Total) @@ -115,7 +116,7 @@ namespace PlotDirector.WordAddIn } private sealed class ChapterRead { - public readonly Stopwatch Total=Stopwatch.StartNew();public double ActiveMs,ComMs,ReleaseMs,QueueMs,QuietMs,OtherWorkMs,TimerHostMs;public long ComCalls,ParagraphVisits,ReleaseCalls,PlainBatches;public AdapterCommand Command;public int Phase,Seek,Steps,Start,End,Offset;public string Text="",Xml="",NextId="";public bool Begun; public int IdentityPosition; public readonly System.Text.StringBuilder Identities = new System.Text.StringBuilder(); public string IdentityFrames = ""; public bool NativeTextRequired,PhysicalPositions,LiveText; + public readonly Stopwatch Total=Stopwatch.StartNew();public double ComparisonMs;public double ActiveMs,ComMs,ReleaseMs,QueueMs,QuietMs,OtherWorkMs,TimerHostMs;public long ComCalls,ParagraphVisits,ReleaseCalls,PlainBatches;public System.Threading.Tasks.Task RangeComparison;public AdapterCommand Command;public int Phase,Seek,Steps,Start,End,Offset;public string Text="",Xml="",NextId="",StartId="";public bool Begun; public int IdentityPosition; public readonly System.Text.StringBuilder Identities = new System.Text.StringBuilder(); public string IdentityFrames = ""; public bool NativeTextRequired,PhysicalPositions,LiveText,PlainIdentityBatch; public readonly List NativePositions=new List(); public int PendingStart,PendingEnd,ShapeIndex,SegmentPosition,SegmentAnchor;public string PendingText="";public ChapterParagraph PendingPosition; public readonly Dictionary PendingAnchors=new Dictionary(); @@ -170,7 +171,7 @@ namespace PlotDirector.WordAddIn { shapes=Com(()=>doc.Document.Shapes);var count=Com(()=>shapes.Count); if(count>128){read.Phase=12;return;} - if(read.ShapeIndex>count){read.LiveText=true;read.IdentityPosition=read.Start;read.Phase=7;return;} + if(read.ShapeIndex>count){read.LiveText=true;read.IdentityPosition=read.Start;read.Phase=read.Command.RangeBaseline!=null?14:7;return;} shape=Com(()=>shapes[read.ShapeIndex]);anchor=Com(()=>shape.Anchor); var start=Com(()=>anchor.Start); if(start>=read.Start&&startparagraphRange.Start);var end=Com(()=>paragraphRange.End); read.IdentityPosition=ChapterIdentityRead.Append(read.Identities,read.IdentityPosition,read.End,start,end,ReadLiveParagraphId(paragraph),(int)Com(()=>paragraph.OutlineLevel)); read.ParagraphVisits++; - if(end==read.End){read.IdentityFrames=read.Identities.ToString();read.Phase=4;break;} + if(end==read.End){ + read.IdentityFrames=read.Identities.ToString(); + if(read.PlainIdentityBatch){var ids=new System.Text.StringBuilder();for(var n=0;ndoc.Document.Saved)||Com(()=>application.BackgroundSavingStatus)!=0))throw new InvalidOperationException("Save Word and wait for background saving before validating chapters."); + if(!read.Command.ObserveOnly&&(!Com(()=>doc.Document.Saved)||Com(()=>application.BackgroundSavingStatus)!=0))throw new InvalidOperationException("Save Word and wait for background saving before validating chapters."); if(read.Phase==0){ if(++read.Steps>128)throw new InvalidOperationException("No bounded Heading 1 boundary could be verified. Use manuscript repair; existing mappings are preserved."); point=Com(()=>doc.Document.Range(read.Seek,read.Seek));paragraphs=Com(()=>point.Paragraphs);paragraph=Com(()=>paragraphs[1]);range=Com(()=>paragraph.Range); var start=Com(()=>range.Start);var outline=(int)Com(()=>paragraph.OutlineLevel); - if(outline==1){read.Start=start;read.Seek=start+1;read.Phase=1;} + if(outline==1){read.Start=start;if(read.Command.ObserveOnly)read.StartId=ReadLiveParagraphId(paragraph);read.Seek=start+1;read.Phase=1;} else{heading=Com(()=>point.GoTo(What:Word.WdGoToItem.wdGoToHeading,Which:Word.WdGoToDirection.wdGoToPrevious));var previous=Com(()=>heading.Start);if(previous>=read.Seek||previous==0&&start==0){read.Start=-1;read.Seek=0;read.Phase=1;}else read.Seek=previous;} }else if(read.Phase==1){ if(++read.Steps>256)throw new InvalidOperationException("Chapter boundary search exceeded its bound; review the document structure."); point=Com(()=>doc.Document.Range(read.Seek,read.Seek));heading=Com(()=>point.GoTo(What:Word.WdGoToItem.wdGoToHeading,Which:Word.WdGoToDirection.wdGoToNext));var next=Com(()=>heading.Start); if(next<=read.Seek||next>=doc.End){if(read.Start<0)throw new InvalidOperationException("No Heading 1 chapter is available at this Word location.");read.End=DocumentEnd(doc.Document);read.Phase=2;} else{paragraphs=Com(()=>heading.Paragraphs);paragraph=Com(()=>paragraphs[1]);var level=(int)Com(()=>paragraph.OutlineLevel); - if(level==1){if(read.Start<0){read.Start=next;read.Seek=next+1;}else{read.End=next;read.Seek=next;read.Phase=6;}} + if(level==1){if(read.Start<0){read.Start=next;if(read.Command.ObserveOnly)read.StartId=ReadLiveParagraphId(paragraph);read.Seek=next+1;}else{read.End=next;read.Seek=next;read.Phase=6;}} else read.Seek=next+1; } }else if(read.Phase==6){ @@ -243,8 +253,16 @@ namespace PlotDirector.WordAddIn read.NextId=ReadLiveParagraphId(paragraph);read.Phase=2; }else if(read.Phase==2){ if(read.End<=read.Start||read.End-read.Start>ChapterFingerprint.MaxCharacters)throw new InvalidOperationException("This chapter exceeds the bounded fast reader. Use bounded manuscript synchronisation; no mapping was guessed."); - if(!read.Begun){if(!link.TryPost(new Message{Kind="chapter-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,OperationId=read.Command.OperationId,BookId=read.Command.BookId,DocumentEnd=doc.End,Start=read.Start,End=read.End,WordSaved=true,ChapterTitle=read.NextId}))return;read.Begun=true;} + if(!read.Begun&&!read.Command.ObserveOnly){if(!link.TryPost(new Message{Kind="chapter-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,OperationId=read.Command.OperationId,BookId=read.Command.BookId,DocumentEnd=doc.End,Start=read.Start,End=read.End,WordSaved=true,ChapterTitle=read.NextId}))return;read.Begun=true;} range=Com(()=>doc.Document.Range(read.Start,read.End));read.Text=Com(()=>range.Text,"chapter-range-text")??""; + if(read.Command.ObserveOnly) + { + var baseline=read.Command.RangeBaseline; + if(baseline==null||read.StartId!=baseline.HeadingNativeId)throw new InvalidOperationException("Chapter boundaries changed; save to perform structural verification."); + var changed=baseline==null||baseline.NextHeadingId!=read.NextId||ChapterRangeVerification.Content(read.Text)!=baseline.ContentHash; + if(!link.TryPost(new Message{Kind="chapter-observe",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,ChapterId=baseline?.ChapterId,Start=read.Start,End=read.End,Action=changed?"changed":"matching",WordSaved=false}))return; + Metric("chapter-observe-range",watch.Elapsed.TotalMilliseconds);CancelChapterRead(doc);return; + } if(read.Text.Length>read.End-read.Start)throw new InvalidOperationException("Word range text exceeds its native positions at "+read.Start+"; this structural expansion requires review."); read.PhysicalPositions=read.Text.Length!=read.End-read.Start; if(read.PhysicalPositions&&(!nativeChapterPositionsSupported||!read.Command.NativeChapterPositions)) @@ -253,7 +271,7 @@ namespace PlotDirector.WordAddIn }else if(read.Phase==11){CheckChapterShape(doc,read); }else if(read.Phase==3||read.Phase==12){ range=Com(()=>doc.Document.Range(read.Start,read.End)); - if(read.Phase==3&&liveChapterTextSupported&&!read.PhysicalPositions&&IsPlainChapter(range)) + if(read.Phase==3&&liveChapterTextSupported&&!read.PhysicalPositions&&read.Text.IndexOf('\f')<0&&IsPlainChapter(range)) { read.ShapeIndex=1;read.Phase=11;return; } @@ -265,7 +283,7 @@ namespace PlotDirector.WordAddIn if(read.NativeTextRequired&&!nativeChapterTextSupported)throw new InvalidOperationException("Update the Companion agent to verify picture paragraphs. Existing mappings are retained."); read.IdentityPosition=read.Start;read.Phase=7; }else if(read.Phase==7){ - if(read.LiveText){ReadPlainChapterBatch(doc,read);return;} + if(read.LiveText||read.PlainIdentityBatch){ReadPlainChapterBatch(doc,read);return;} // Structural/native-position extraction retains its qualified one-paragraph step. point=Com(()=>doc.Document.Range(read.IdentityPosition,read.IdentityPosition)); paragraphs=Com(()=>point.Paragraphs);paragraph=Com(()=>paragraphs[1]);range=Com(()=>paragraph.Range); @@ -292,6 +310,38 @@ namespace PlotDirector.WordAddIn if(read.LiveText)read.Identities.Append(((int)Com(()=>paragraph.OutlineLevel)).ToString("X8",System.Globalization.CultureInfo.InvariantCulture)); read.IdentityPosition=end; if(end==read.End){if(read.NativeTextRequired&&read.NativeText.ToString()!=read.Text)throw new InvalidOperationException("Native paragraph text does not equal the chapter range; retry after saving Word.");read.IdentityFrames=read.Identities.ToString();read.Phase=4;} + }else if(read.Phase==14&&read.Command.RangeBaseline!=null&&ChapterRangeVerification.Content(read.Text)!=read.Command.RangeBaseline.ContentHash){ + Metric("chapter-probe-text-changed",0); + if(read.Command.RecheckRevision){InvalidateChapterProbe(doc);return;} + read.Xml="";read.Identities.Clear();read.IdentityPosition=read.Start;read.LiveText=true;read.Phase=7; + }else if(read.Phase==14){ + // Export one bounded range, never the whole document. COM stays on + // Word's STA; XML parsing/hashing runs outside its UI thread. + if(!rangeComparisonSlots.Wait(0))return; + var queued=false; + try + { + range=Com(()=>doc.Document.Range(read.Start,read.End)); + read.Xml=Com(()=>range.WordOpenXML,"chapter-probe-range-xml")??""; + if(read.Xml.Length>8*1024*1024)throw new InvalidOperationException("Chapter XML exceeds the bounded range comparison."); + var text=read.Text;var xml=read.Xml;var baseline=read.Command.RangeBaseline;var nextId=read.NextId; + read.RangeComparison=System.Threading.Tasks.Task.Run(()=>{var comparison=Stopwatch.StartNew();try{return ChapterRangeVerification.Check(text,xml,baseline,nextId);}finally{read.ComparisonMs=comparison.Elapsed.TotalMilliseconds;rangeComparisonSlots.Release();}}); + queued=true;read.Phase=13; + } + finally{if(!queued)rangeComparisonSlots.Release();} + }else if(read.Phase==13){ + if(!read.RangeComparison.IsCompleted)return; + Metric("chapter-probe-compare-worker",read.ComparisonMs); + if(read.RangeComparison.GetAwaiter().GetResult().Result==ChapterRangeResult.Matching) + {Metric("chapter-probe-match",0);read.LiveText=true;read.IdentityFrames=read.RangeComparison.GetAwaiter().GetResult().IdentityFrames;read.Xml="";read.Phase=4;} + else + { + Metric("chapter-probe-detailed-fallback",0); + if(read.Command.RecheckRevision&&read.RangeComparison.GetAwaiter().GetResult().Result==ChapterRangeResult.Changed){InvalidateChapterProbe(doc);return;} + // Preserve the XML structural checks when range evidence + // is incomplete; collect live IDs in the existing 32-item batches. + read.Identities.Clear();read.IdentityPosition=read.Start;read.LiveText=false;read.PlainIdentityBatch=true;read.Phase=7; + } }else if(read.Phase==9){ReadChapterPictureAnchor(doc,read); }else if(read.Phase==10){ReadChapterPositionSegment(doc,read); }else{ diff --git a/PlotLine.Tests/ChapterAcceptanceDevelopmentTests.cs b/PlotLine.Tests/ChapterAcceptanceDevelopmentTests.cs index 2a5e2c64..85c7f783 100644 --- a/PlotLine.Tests/ChapterAcceptanceDevelopmentTests.cs +++ b/PlotLine.Tests/ChapterAcceptanceDevelopmentTests.cs @@ -22,7 +22,8 @@ internal static class ChapterAcceptanceDevelopmentTests { if (!OperatingSystem.IsLinux() || args.Length != 2 || !int.TryParse(args[1], out var user) || user <= 0) throw new InvalidOperationException("Use --chapter-acceptance-dev "); - var reuseMode=args[0]=="--chapter-reuse-dev"; + var incrementalMode=args[0]=="--chapter-incremental-dev"; + var reuseMode=args[0]=="--chapter-reuse-dev"||incrementalMode; var start = new ProcessStartInfo("sudo") { RedirectStandardOutput = true }; foreach (var value in new[] { "-n", "cat", "/etc/plotdirector/plotdirector.env" }) start.ArgumentList.Add(value); using var process = Process.Start(start)!; @@ -117,7 +118,10 @@ internal static class ChapterAcceptanceDevelopmentTests original.ChapterCheckpoints=ChapterCheckpointEngine.Build(original,original.Revision).ToList(); foreach(var c in original.ChapterCheckpoints){c.Status="Synchronised";c.LastSuccessfulSyncUtc=DateTime.UtcNow;} original=await repository.Save(user,original,original.Revision,Guid.NewGuid()); - Observe();await ChapterReuseDevelopmentTests.Run(user,book,grant,original,service,repository,checkpoints,presence,Proof);return; + Observe(); + if(incrementalMode)await ChapterReuseDevelopmentTests.RunIncremental(user,book,grant,original,service,repository,checkpoints,presence,Proof); + else await ChapterReuseDevelopmentTests.Run(user,book,grant,original,service,repository,checkpoints,presence,Proof); + return; } Observe(); var repair = await service.Repair(user, book, instance, session); diff --git a/PlotLine.Tests/ChapterReuseDevelopmentTests.cs b/PlotLine.Tests/ChapterReuseDevelopmentTests.cs index 9ef7c22c..f6904795 100644 --- a/PlotLine.Tests/ChapterReuseDevelopmentTests.cs +++ b/PlotLine.Tests/ChapterReuseDevelopmentTests.cs @@ -8,6 +8,43 @@ using PlotLine.Services.NativeCompanion; internal static class ChapterReuseDevelopmentTests { + public static async Task RunIncremental(int user,int book,string grant,ParagraphManuscript state,ChapterSyncService service,IParagraphManuscriptRepository repository,IChapterSyncRepository positions,NativePresenceStore presence,Func proof) + { + void Check(bool value,string name){if(!value)throw new Exception(name);Console.WriteLine("PASS "+name);} + var instance=Guid.NewGuid();var session=Guid.NewGuid();const long wordRevision=1; + presence.DisconnectGrant(user,grant); // Only this fixture's in-memory synthetic leases. + Check(presence.Put(user,grant,DateTimeOffset.UtcNow.AddHours(1),instance,session,new(){BookId=book,ManuscriptId=state.ManuscriptId,Revision=wordRevision,Sequence=DateTime.UtcNow.Ticks,WordAvailable=true,WordRunning=true,WordSaved=true,CanChapterSync=true}),"Isolated saved edit session registered"); + var operation=await service.Repair(user,book,instance,session,wordRevision); + var changed=proof(state,13);changed.InstanceId=instance;changed.SessionId=session;changed.WordRevision=wordRevision;changed.OperationId=operation; + var part=ChapterCheckpointEngine.Parts(state)[13]; + var rows=part.Rows.Select(p=>new ChapterParagraph{NativeId=p.Occurrence.NativeId,Outline=p.Occurrence.Outline,Text=p.Occurrence.Text,Length=p.Occurrence.Text.Length}).ToArray(); + rows[1].Text=rows[1].Text!.TrimEnd('\r')+" additional text\r";rows[1].Length=rows[1].Text!.Length; + changed.ContentHash=ChapterFingerprint.Content(rows.Select(p=>p.Text!));changed.IdentityHash=ChapterFingerprint.Identity(rows);changed.End=changed.Start+rows.Sum(p=>p.Length); + changed.Paragraphs=rows.Select(p=>new ChapterParagraph{NativeId=p.NativeId,Outline=p.Outline,Length=p.Length}).ToArray(); + var timer=Stopwatch.StartNew(); + var detection=await service.Accept(user,grant,book,changed); + Check(!detection.Accepted&&detection.AllowText,"Only changed chapter requests reconciliation prose"); + changed.Reconcile=true;changed.Paragraphs=rows; + var accepted=await service.Accept(user,grant,book,changed);var reconciliationMs=timer.Elapsed.TotalMilliseconds; + Check(accepted.Accepted,"Single changed chapter committed through real SQL reconciliation"); + var after=(await repository.Get(user,book))!; + Check(after.Paragraphs.Select(p=>p.Occurrence.Id).SequenceEqual(state.Paragraphs.Select(p=>p.Occurrence.Id)),"Real SQL single-chapter edit preserves every canonical paragraph GUID"); + Check(after.Scenes.Select(s=>s.Id).SequenceEqual(state.Scenes.Select(s=>s.Id)),"Real SQL single-chapter edit preserves scene identities"); + Check(after.ChapterCheckpoints.Count(c=>c.Status=="Synchronised")==48,"Reconciliation preserves forty-seven unchanged durable checkpoints"); + var manifest=await service.Manifest(user,book,session,wordRevision); + Check(manifest.Chapters.Count(c=>c.DurableAccepted)==48&&manifest.Chapters.Count(c=>c.State=="Synchronised")==1,"Durable acceptance survives while new-session position acceptance remains scoped to the changed chapter"); + var unchanged=Enumerable.Range(0,48).Where(c=>c!=13).Select(c=>{var p=proof(after,c);p.InstanceId=instance;p.SessionId=session;p.WordRevision=wordRevision;return p;}).ToArray(); + Check(unchanged.All(p=>ChapterCheckpointReuse.Matches(manifest.Chapters.Single(c=>c.ChapterId==p.ChapterId),p)),"All forty-seven unchanged chapters remain directly eligible for batch reuse after reconciliation"); + var later=unchanged.First(p=>p.ChapterId==ChapterCheckpointEngine.Parts(after)[14].Chapter.CanonicalId); + Check(later.Start>proof(state,14).Start,"Downstream physical-position proposals reflect the edited chapter's length change"); + await service.Reuse(user,grant,book,new(){Chapters=unchanged}); + var finish=await service.Finish(user,grant,book,new(){InstanceId=instance,SessionId=session,WordRevision=wordRevision,OperationId=operation}); + Check(finish is {State:"Synchronised",Matching:48},"One changed acceptance and one batch reuse finish all forty-eight live checkpoints"); + var mapped=ChapterCheckpointEngine.Validate(after,unchanged[0],DateTime.UtcNow).Positions.First(p=>p.SceneId.HasValue); + Check((await positions.Position(user,book,state.ManuscriptId,session,wordRevision,mapped.Start))?.SceneID==mapped.SceneId,"Unchanged chapter Writing Context remains correct after real SQL selective reconciliation"); + Console.WriteLine($"MEASURE real Development SQL incremental: chapters=48, reconciled=1, checkpointsRetained=47, unchangedIndividualAcceptances=0, reuseRequests=1, validationRequests=2, reconciliationAndAcceptanceMs={reconciliationMs:F1}, totalMs={timer.Elapsed.TotalMilliseconds:F1}. In-process service and real SQL; excludes Word extraction, HTTP and debounce."); + } + public static async Task Run(int user,int book,string grant,ParagraphManuscript state,ChapterSyncService service,IParagraphManuscriptRepository repository,IChapterSyncRepository positions,NativePresenceStore presence,Func proof) { Console.WriteLine($"SCALE chapters=48 paragraphs={state.Paragraphs.Count} words={state.Paragraphs.Sum(p=>p.Occurrence.Text.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length)}"); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 5fac74aa..48e754bc 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -15,7 +15,7 @@ using PlotLine.Models; using PlotLine.Services; using PlotLine.ViewModels; -if((args.Contains("--chapter-acceptance-dev")||args.Contains("--chapter-reuse-dev"))){await ChapterAcceptanceDevelopmentTests.Run(args);return;} +if((args.Contains("--chapter-acceptance-dev")||args.Contains("--chapter-reuse-dev")||args.Contains("--chapter-incremental-dev"))){await ChapterAcceptanceDevelopmentTests.Run(args);return;} if(args.Contains("--chapter-sync-dev")){await ChapterSyncDevelopmentTests.Run(args);return;} if(args.Contains("--chapter-sync")){ChapterSynchronisationTests.Run();return;} #pragma warning disable CS8321