Speed up Word reopening with bounded live chapter verification

This commit is contained in:
Nick Beckley 2026-11-11 20:09:48 +00:00
parent 09449a9aab
commit 1cc8c0e10a
18 changed files with 289 additions and 42 deletions

View File

@ -0,0 +1,64 @@
# Fast reopening correction — candidate 1.0.0.30
Continue `codex/word-companion-native-phase1-20261104`; fetch and fast-forward only. No new branch/worktree. Preserve the installed .29 package and existing author DOCX. This is source-only on Atlas: no deployment, SQL, author-data changes, Windows installation or real Word execution.
## Confirmed cause and lifecycle
The .28/.29 Windows handovers independently establish that all 48 durable checkpoints survived, including the floating-picture chapter, and that reopening restored authentication/book association but started committing new-session validations. They do not contain a controlled before/after reopening benchmark.
Source tracing confirms:
1. `ChapterSyncService.Accept` verifies exact accepted content, native identities, geometry, grant, saved live session and Word/snapshot revisions. `ChapterSyncRepository.Accept` calls the existing `BookChapterSync` stored procedure to persist source checkpoint metadata and separate current-session physical positions. An unchanged acceptance does not reconcile prose or increment the manuscript revision.
2. Word save retains the document association properties. `WordAdapter.BeforeSave` never blocks saving; a changed document invalidates pending extraction and increments the local revision. `BeforeClose` cancels readers and retires the live session, without deleting durable server checkpoints.
3. `WordAdapter.Open` reads the saved document/manuscript GUID, book and server association. `LocalDocument` has a new session and initial local revision; revision zero is a new session's counter, not proof of unchanged content.
4. Authenticated presence causes `TrayCoordinator.LoadChapterManifest` to retrieve the accepted chapter fingerprints and current-session validations. Durable checkpoints do not certify old absolute positions in a new Word session. Only already validated ranges in the exact current session/revision populate `work.Checked`.
5. Previously every unchecked chapter unconditionally performed aggregate `Range.Text`, a complete `Range.WordOpenXML`, and a live paragraph-ID/span walk. Drawing/native-position chapters additionally measured paragraph text/anchors. The agent could only compare its stored fingerprints **after** this work. It was not merely misleading progress, checkpoint loss, changed document identity or automatic full-snapshot import.
6. `WordAccessScheduler.Pump` executed one action per 25 ms timer tick. Chapter identity walking posted one paragraph per action. For 8,457 paragraphs this alone implies 8,457 ticks / 211.425 seconds of nominal timer spacing, before chapter boundary reads, XML transport, server acceptance or author-priority pauses. Actual Windows timer delivery and COM costs can increase this. The Windows report's longer scan cannot be apportioned precisely without new measurements.
7. The current chapter is already prioritised; after its fresh acceptance, presence can resolve its existing scene before whole-book completion. Stationary cursor events reuse accepted current-session evidence. No change to this scheduling/Context authority contract was necessary.
## Focused changes
- Negotiate optional local capability `chapter-live-text-v1` separately from existing chapter/native-text/native-position capabilities. Mixed versions retain the qualified XML path. The HTTP proof and fingerprint algorithm remain unchanged.
- For a saved chapter with exact aggregate text/native-span equality, first exclude tables, fields, revisions, footnotes, endnotes, inline pictures and floating shapes anchored in that chapter. Floating-shape anchors are enumerated one per bounded step from [`Document.Shapes`](https://learn.microsoft.com/en-us/office/vba/api/word.document.shapes), the documented main-story collection; more than 128 shapes conservatively retains XML. No empty `Range.ShapeRange` exception is interpreted as proof of absence. Collection-access failure cannot establish a fast proof.
- Plain chapters use one aggregate `Range.Text` plus measured live paragraph start/end, `ParaID` and `OutlineLevel`. Complete contiguous native spans partition the exact aggregate text. They do **not** request chapter XML or individual paragraph text/XML. Each paragraph must remain inside the measured chapter, within existing size bounds. The bounded agent decoder rejects missing/duplicate/malformed IDs, invalid outlines, incomplete frames and incomplete text coverage.
- Reuse the existing `sha256-utf16le-paragraphs-v1` content and identity hashes and unchanged server validator. No saved filename/timestamp/file-hash cache or parallel fingerprint system is introduced. Word's saved/background-save gates and session/revision checks remain in place throughout reading. Document copies, external saved edits, heading/paragraph/scene changes and shifted chapter positions must supply fresh live evidence.
- A matching proof sends metadata only through the existing acceptance endpoint. Only an authorised changed chapter sends prose to the existing reconciliation engine. Required fresh-session position submissions remain; they are not unnecessary reconciliation. No checkpoint reset/backfill or canonical GUID/scene change was introduced. Existing acceptance may refresh its source metadata/timestamp, as before.
- Picture/structural/native-position chapters retain the .28 reader, exact native text checks and independently measured floating-anchor geometry. An unchanged picture chapter can still require XML/native text; this candidate does not claim to eliminate those mandatory reads. Unsupported structures remain review/fallback cases. The final floating-picture chapter is not special-cased by name or identity.
- The existing scheduler permits up to 16 chapter continuation steps per tick, stopping after 15 ms of elapsed batch time, a selection event, author-priority quiet period, nonchapter work or empty queue. Each step releases its COM objects. Other operations retain one-action semantics. A single COM call remains unpreemptible; Windows must measure occupancy.
- Add bounded diagnostics: process-level completed live/XML read counters and up to 32 chapter metric aggregates (count/total/max); per-document recognition, manifest, fingerprint/agent processing, server validation, first resolved Context and completion times plus submission counts. Context timing means the first server-resolved scene, not measured browser paint. The Word `chapter-document-recognition` metric covers discovery scheduling and saved-property recognition; the agent recognition interval starts at document registration. Neither starts at Word process launch. Negative values mean unobserved. Existing `chapter-range-text`, `chapter-range-xml`, `chapter-native-paragraph-text`, `chapter-paragraph-id`, `chapter-ui-step` and `chapter-ui-batch` timings remain available. Totals represent accumulated work and may overlap wall-clock stages.
- Candidate metadata is application 1.0.0.30/MSI 1.0.30 with a fresh ProductCode; existing upgrade family/baseline pins and .29 ribbon presentation are retained.
## Atlas measurements and verification
The isolated portable fixture has 48 chapters, 8,457 paragraphs and 153,139 words. It uses no author manuscript/data or database.
| Stage | Previous path | Corrected path / limitation |
| --- | --- | --- |
| Document recognition | Real Word not measured | Instrumented from agent registration; Windows pending |
| Manifest retrieval | Network/server not measured | Instrumented; Windows pending |
| Portable parsing/fingerprints | 125.0 ms XML fixture parse/hashes | 84.9 ms live fixture verification/hashes; excludes COM/network/UI |
| Word COM extraction | Not available on Atlas | Plain path contains no WordOpenXML/paragraph-text read; actual occupancy pending |
| Server validation | Existing Windows reports show commits, without controlled aggregate timings | Accumulated round-trip timer; Windows pending |
| Context usable | Not measured | First resolved scene timer; user-visible usability pending |
| Up to date | Not measured end to end | Completion timer; Windows pending |
| Scheduler spacing model, paragraph walk only | 8,457 ticks, nominal lower bound 211.425 s | 529 ticks, nominal lower bound 13.225 s at cap; excludes COM and every other stage |
Portable timings are one run, with synthetic ordinary paragraphs; neither the parsing comparison nor the tick model proves real Word performance. In particular 529 ticks assumes all 16 steps fit each 15 ms batch. The target of seconds must be qualified, not inferred from this table. The existing server's fresh validation/persistence latency remains part of the end-to-end path.
Tests cover unchanged live frames without XML, single/several edited chapters, incomplete evidence, native identity/outline failures, scheduler bounds/selection/author interruption and compatibility refusal. The existing chapter engine/structural regressions exercise new-session metadata-only acceptance and changed live evidence through the unchanged validator/reconciler, stale revisions, paragraph insert/delete/split/merge, changed/moved chapter boundaries, canonical scene/GUID preservation, inline/floating pictures, anchor geometry and backup-detached session trust. Existing agent tests retain cancellation, closing/late frames, independent sessions, current-session reuse and accepted work surviving another chapter's failure. Real Word unsaved edits, Save As, document copies and COM projection/collection behaviour remain Windows acceptance work; portable tests do not substitute for these.
Final serial gates: solution build passed with zero warnings/errors (7.71 s on the final build); focused chapter engine/structural suite **66 PASS**, focused native/reopening suite **211 PASS**, full native foundation **273 PASS**, full application harness **457 PASS**. Commands used the normal solution/executable harnesses; `--no-restore --disable-build-servers -m:1 /p:UseSharedCompilation=false` bounded the build and `--no-build` reused its outputs for serial test execution. No Windows/Office binding result is implied. Roslyn syntax inspection of all seven VSTO source files passed with zero syntax errors; actual Office/VSTO binding still requires Windows. The focused native and full native suites were repeated after adding the final batch-timing instrumentation and retained the same counts.
## Focused Windows qualification
Use the existing signed developer build/installer workflow; do not launch/close Word, install software, change trust stores or automate author selection unattended. Prepare .30 with `WindowsValidation/Update-WordCompanion.ps1`, then the established `Setup/Build-Setup.ps1` and payload/MSI/upgrade gates. Use the exact clean pushed source SHA for package provenance and retain the .29 installer. No server feature change or migration is needed. Coordinate normal installation with the author separately.
After both .30 components are installed, the author acceptance requires only:
1. Open a previously synchronised saved development document. Confirm the existing association returns and Writing Context becomes usable promptly. Record recognition, manifest, fingerprint, COM, server, first resolved scene and completion timings from Troubleshooting, and actual elapsed user-visible Context/Up-to-date times. Do not request Repair merely because Word reopened.
2. Confirm plain chapters increment live reads without `chapter-range-xml` or `chapter-native-paragraph-text` calls. A picture/structural chapter is allowed the retained qualified reader. Verify final-chapter Context before/after its floating anchor without changing its mappings. Record max/batch COM occupancy and observed responsiveness.
3. In an authorised disposable test copy, make one small chapter edit, save and reopen.
4. Confirm only the edited chapter requires reconciliation; unchanged chapters send only metadata, retain their GUIDs/scenes and regain fresh positions. In Manual mode the edit must wait for the existing explicit Synchronise authority; OnSave follows its existing preference. Check Writing Context in the edited and a later shifted chapter.
5. Record exact source/package identities and measured outcomes. If refusal or slow operation occurs, retain stage timings and live/XML/submission counts; do not reset/reimport Discovery or repeat a full author-manuscript qualification cycle. Further mutation edge cases belong in isolated documents/books, not author data.
Do not claim Windows performance/compatibility until these results are recorded. Production is outside this task.

View File

@ -56,8 +56,8 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action<st
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="unsupported-version"},cancellation); return;
}
var trayAdapter=(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.TrayCapability);
instance = hello.WordInstanceId; sessions.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterSyncCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.NativeChapterTextCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.NativeChapterPositionsCapability));if(trayAdapter)control?.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.CaptureCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.MaintenanceCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ParagraphCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterSyncCapability));
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability+","+ProtocolVersion.ChapterSyncCapability+","+ProtocolVersion.NativeChapterTextCapability+","+ProtocolVersion.NativeChapterPositionsCapability},cancellation);
instance = hello.WordInstanceId; sessions.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterSyncCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.NativeChapterTextCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.NativeChapterPositionsCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.LiveChapterTextCapability));if(trayAdapter)control?.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.CaptureCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.MaintenanceCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ParagraphCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterSyncCapability));
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,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},cancellation);
log?.Invoke("peer-connected");
while (!cancellation.IsCancellationRequested)
{

View File

@ -17,13 +17,13 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
private int totalBoundaries;
private int totalSuggestions;
public int SessionCount { get { lock (gate) return instances.Values.Sum(i => i.Documents.Count); } }
public void Attach(Guid instance, Guid lease,bool chapters=false,bool nativeChapterText=false,bool nativeChapterPositions=false)
public void Attach(Guid instance, Guid lease,bool chapters=false,bool nativeChapterText=false,bool nativeChapterPositions=false,bool liveChapterText=false)
{
lock (gate)
{
if (instance == Guid.Empty || (!instances.ContainsKey(instance) && instances.Count >= 8)) throw new InvalidDataException("Word instance capacity/identity invalid.");
DetachCore(instance);
instances[instance] = new WordInstance(lease){ChapterCapable=chapters,NativeChapterTextCapable=chapters&&nativeChapterText,NativeChapterPositionsCapable=chapters&&nativeChapterText&&nativeChapterPositions};
instances[instance] = new WordInstance(lease){LiveChapterTextCapable=chapters&&liveChapterText,ChapterCapable=chapters,NativeChapterTextCapable=chapters&&nativeChapterText,NativeChapterPositionsCapable=chapters&&nativeChapterText&&nativeChapterPositions};
}
}
public void Detach(Guid instance, Guid lease) { lock (gate) { if (instances.TryGetValue(instance, out var state) && state.Lease == lease) DetachCore(instance); } }
@ -98,7 +98,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
if(message.Kind is "workspace-select" or "workspace-refresh"){var position=new Message();Resolve(document,position);message.ChapterId=position.ChapterId;message.SceneId=position.SceneId;}
answer.Kind="workspace-response";return workspace?.Handle(document.Descriptor,message,answer)??Reject(answer,"workspace-unavailable");}
if(message.Kind.StartsWith("chapter-",StringComparison.Ordinal)){
if(!word.ChapterCapable||(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.DocumentEnd<message.End||message.DocumentEnd>16000000))||(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"))))return Reject(answer,"invalid-chapter-frame");
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.DocumentEnd<message.End||message.DocumentEnd>16000000))||(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;
}
if(message.Kind.StartsWith("ai-",StringComparison.Ordinal))return ai?.Handle(document.Descriptor,message,answer)??Reject(answer,"ai-unavailable");
@ -180,7 +180,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
}
public Guid? ActiveSession(Guid instance) { lock(gate) return instances.GetValueOrDefault(instance)?.ActiveSession; }
public bool HasSession(Guid instance, Guid session) { lock(gate) return instances.TryGetValue(instance,out var word) && word.Documents.ContainsKey(session); }
private sealed class WordInstance(Guid lease) { public bool ChapterCapable,NativeChapterTextCapable,NativeChapterPositionsCapable;public Guid Lease = lease; public long LastSequence; public Guid? ActiveSession; public Dictionary<Guid,DocumentState> Documents = []; }
private sealed class WordInstance(Guid lease) { public bool LiveChapterTextCapable,ChapterCapable,NativeChapterTextCapable,NativeChapterPositionsCapable;public Guid Lease = lease; public long LastSequence; public Guid? ActiveSession; public Dictionary<Guid,DocumentState> Documents = []; }
private sealed class DocumentState(DocumentDescriptor descriptor) { public DocumentDescriptor Descriptor = descriptor; public int Cursor;public int StructureEnd; public int? WordCount; public Snapshot? Pending; public Guid SnapshotId; public string ContentFingerprint=""; public List<StructuralBoundary> Boundaries = []; public DocumentAnalysis? Analysis; }
private sealed class Snapshot(Guid id,int expectedEnd,bool analyze) { public readonly DocumentAnalysis Counter=new(analyze); public DocumentAnalysis? Analysis=>analyze?Counter:null; public Guid Id = id; public int ExpectedEnd=expectedEnd; public bool LastComplete; public int End; public int NextParagraph=1; public int Characters; public List<ParagraphFragment> Fragments = []; }
}

View File

@ -131,7 +131,7 @@ internal sealed class CompanionWindow:Form
SetText(guidance,doc==null?"Open a manuscript in Microsoft Word. Your words stay in Word until you request an import in PlotDirector.":doc.Book==0?"Choose the PlotDirector book for this manuscript.":control.ChapterProgressForDisplay(doc.Session) is {} chapters?(chapters.State=="Synchronised"?"Up to date":chapters.Message):"Import, Context and Intent are available in PlotDirector.");
SetText(bookTitle,book==null?"No book associated":string.IsNullOrEmpty(book.BookTitle)?book.Title:book.BookTitle);SetText(projectTitle,book?.ProjectTitle??"Choose a book to connect your writing workspace.");
var noticeText=error!=""?error:doc?.AssociationNotice??"";SetText(notice,noticeText);if(settingsNotice is {IsDisposed:false}){SetText(settingsNotice,error);settingsNotice.Visible=error!="";}notice.Visible=noticeText!="";tips.SetToolTip(serverStatus,state.Health?.Explanation??"Connect in Settings.");
var text=$"Server: {state.ServerUrl}\r\nAccount: {state.Health?.AccountName}\r\n{state.Health?.Explanation}\r\n"+string.Join("\r\n",displayed.Select(d=>$"{d.Title} · session {d.Session} · book {d.Book}"))+"\r\n"+doc?.WordDiagnostics+"\r\n"+doc?.Status+"\r\n"+doc?.MaintenanceReport;
var text=$"Server: {state.ServerUrl}\r\nAccount: {state.Health?.AccountName}\r\n{state.Health?.Explanation}\r\n"+string.Join("\r\n",displayed.Select(d=>$"{d.Title} · session {d.Session} · book {d.Book}"))+"\r\n"+doc?.WordDiagnostics+"\r\n"+doc?.Status+"\r\n"+doc?.MaintenanceReport+"\r\n"+(doc==null?"":control.ChapterDiagnostics(doc.Session));
if(diagnostics is {IsDisposed:false}&&diagnostics.Text!=text)diagnostics.Text=text;
if(books.Parent!=null&&!books.IsDisposed){var signature=state.AuthenticationContext+":"+string.Join("|",state.Books.Select(b=>b.BookId+":"+b.Title));if(books.Tag as string!=signature){var chosen=(books.SelectedItem as Protocol.CompanionBook)?.BookId;books.Tag=signature;books.DataSource=state.Books;books.SelectedItem=state.Books.FirstOrDefault(b=>b.BookId==chosen);}}
var next=state.AuthenticationContext+":"+(book?.BookId??0);if(next!=coverKey){coverKey=next;coverRetry=DateTime.MinValue;coverStop?.Cancel();cover.SetImage(null);cover.Caption=bookTitle.Text;cover.Invalidate();coverLoading=false;}

View File

@ -6,6 +6,8 @@ public sealed partial class TrayCoordinator
{
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;
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<int,(int Start,int End)> 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<int> Reviewed=[];public readonly HashSet<int> Visited=[];public string Next="";
@ -37,6 +39,15 @@ public sealed partial class TrayCoordinator
return doc.ChapterProgress;
}
public string ChapterDiagnostics(Guid session)
{
lock(gate)
{
if(!chapterWork.TryGetValue(session,out var w))return "Chapter timings: awaiting recognised saved document.";
return $"Chapter timings since document registration (ms): recognition={w.RecognitionMs:F1}, manifest={w.ManifestMs:F1}, fingerprints={w.VerificationMs:F1}, server={w.ServerMs:F1}, Context={w.ContextMs:F1}, complete={w.CompleteMs:F1}. Reads live/XML={w.LiveReads}/{w.XmlReads}, submissions={w.Submissions}. Negative timing means not observed.";
}
}
private void StopChapterWork(TrayDocument doc, ChapterWork work, string reason)
{
work.Busy = false;
@ -84,12 +95,12 @@ public sealed partial class TrayCoordinator
}
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(){Book=doc.Book,Manuscript=doc.Manuscript,Revision=doc.Revision,Context=doc.Authentication};return work;
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;
}
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;
lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc)return;var work=GetChapterWork(doc);work.Supported=reply.ChapterSyncSupported;if(work.ContextMs<0&&!string.IsNullOrEmpty(reply.SceneTitle))work.ContextMs=work.RecognitionMs+work.Elapsed.Elapsed.TotalMilliseconds;
if(work.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Completion=null;work.Manifest=null;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.UtcNow<work.RetryAfter||work.Finished||!work.Supported||doc.WordSaved!=true||doc.Book<=0||work.FailedRevision==doc.Revision||doc.Capture!=null)return;
if(work.Busy){if(!work.Processing&&work.Command!=Guid.Empty&&work.End>work.Start&&doc.Active&&doc.Cursor!=work.CursorWhenQueued&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End)&&(doc.Cursor<work.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;}
@ -102,8 +113,9 @@ public sealed partial class TrayCoordinator
}
private async Task LoadChapterManifest(TrayDocument doc,ChapterWork work)
{
var timing=System.Diagnostics.Stopwatch.StartNew();
try{var manifest=await cloud.ChapterManifest(doc.Book,doc.Session,doc.Revision,doc.Authentication);
lock(gate){if(!CurrentChapterWork(doc,work))return;if(manifest.ManuscriptId!=doc.Manuscript)throw new InvalidOperationException("Saved manuscript identity does not match this Word document.");work.Manifest=manifest;work.Busy=false;if(manifest.Chapters.Length==0){StopChapterWork(doc,work,"No accepted chapter boundaries are available. Review the existing manuscript structure.");return;}if(work.Operation==Guid.Empty&&manifest.Chapters.All(c=>string.IsNullOrEmpty(c.HeadingNativeId))){StopChapterWork(doc,work,"This existing import has no native chapter identities. Use Repair Synchronisation to verify and adopt identities without reimporting.");return;}if(manifest.Mode=="Off"&&work.Operation==Guid.Empty){work.Finished=true;doc.Status="Automatic synchronisation is off. Use Synchronise or Repair for an explicit chapter check.";return;}foreach(var chapter in manifest.Chapters.Where(c=>c.State=="Synchronised"))work.Checked[chapter.ChapterId]=(chapter.Start,chapter.End);doc.Status=$"Chapter index ready: {work.Checked.Count}/{manifest.Chapters.Length} accepted for this Word session.";if(manifest.Chapters.Length>0&&work.Checked.Count==manifest.Chapters.Length){CompleteChapters(doc,work);}else if(manifest.Chapters.Length>0&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End))QueueChapter(doc,work,doc.Cursor);else{var next=manifest.Chapters.FirstOrDefault(c=>!work.Checked.ContainsKey(c.ChapterId));if(next!=null)QueueChapter(doc,work,next.Start);}}
lock(gate){if(!CurrentChapterWork(doc,work))return;if(manifest.ManuscriptId!=doc.Manuscript)throw new InvalidOperationException("Saved manuscript identity does not match this Word document.");work.ManifestMs+=timing.Elapsed.TotalMilliseconds;work.Manifest=manifest;work.Busy=false;if(manifest.Chapters.Length==0){StopChapterWork(doc,work,"No accepted chapter boundaries are available. Review the existing manuscript structure.");return;}if(work.Operation==Guid.Empty&&manifest.Chapters.All(c=>string.IsNullOrEmpty(c.HeadingNativeId))){StopChapterWork(doc,work,"This existing import has no native chapter identities. Use Repair Synchronisation to verify and adopt identities without reimporting.");return;}if(manifest.Mode=="Off"&&work.Operation==Guid.Empty){work.Finished=true;doc.Status="Automatic synchronisation is off. Use Synchronise or Repair for an explicit chapter check.";return;}foreach(var chapter in manifest.Chapters.Where(c=>c.State=="Synchronised"))work.Checked[chapter.ChapterId]=(chapter.Start,chapter.End);doc.Status=$"Chapter index ready: {work.Checked.Count}/{manifest.Chapters.Length} accepted for this Word session.";if(manifest.Chapters.Length>0&&work.Checked.Count==manifest.Chapters.Length){CompleteChapters(doc,work);}else if(manifest.Chapters.Length>0&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End))QueueChapter(doc,work,doc.Cursor);else{var next=manifest.Chapters.FirstOrDefault(c=>!work.Checked.ContainsKey(c.ChapterId));if(next!=null)QueueChapter(doc,work,next.Start);}}
}catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){RetryChapterWork(doc,work,"Chapter index unavailable: "+e.Message);}}
}
private bool CurrentChapterWork(TrayDocument doc,ChapterWork work)=>documents.GetValueOrDefault(doc.Session)==doc&&chapterWork.GetValueOrDefault(doc.Session)==work&&doc.Revision==work.Revision&&doc.Authentication==work.Context&&doc.Book==work.Book&&doc.Manuscript==work.Manuscript;
@ -146,9 +158,9 @@ public sealed partial class TrayCoordinator
if(answer.Status!="ok"){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Chapter reading was rejected; accepted checkpoints are unchanged.";return;}
if(message.Kind=="chapter-begin"){if(work.Begun)return;work.Begun=true;work.Start=message.Start;if(work.FirstStart<0)work.FirstStart=message.Start;work.End=message.End;work.DocumentEnd=message.DocumentEnd;work.Next=message.ChapterTitle;work.Text.Clear();work.Xml.Clear();work.Identities.Clear();return;}
if(message.Kind=="chapter-chunk"){if(!work.Begun||work.Processing)return;
var identityFrame=message.Action is "ids" or "ids-exact" or "positions";
var identityFrame=message.Action is "ids" or "ids-exact" or "positions" or "live-text";
if(identityFrame){if(work.IdentityAction!=""&&work.IdentityAction!=message.Action){StopChapterWork(doc,work,"Mixed native paragraph evidence was rejected.");return;}work.IdentityAction=message.Action;work.NativeTextVerified=message.Action=="ids-exact";}
var value=message.Action=="text"?work.Text:identityFrame?work.Identities:work.Xml;var limit=message.Action=="text"?ChapterFingerprint.MaxCharacters:identityFrame?(message.Action=="positions"?ChapterWordPositions.MaxFrameCharacters:ChapterFingerprint.MaxParagraphs*16):8*1024*1024;
var value=message.Action=="text"?work.Text:identityFrame?work.Identities:work.Xml;var limit=message.Action=="text"?ChapterFingerprint.MaxCharacters:identityFrame?(message.Action=="positions"?ChapterWordPositions.MaxFrameCharacters:ChapterFingerprint.MaxParagraphs*24):8*1024*1024;
if(message.Start!=value.Length||value.Length+message.OperationMessage.Length>limit){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Incomplete or oversized chapter frames; no checkpoint accepted.";return;}value.Append(message.OperationMessage);return;
}
if(message.Kind=="chapter-end"){if(!work.Begun||work.Processing)return;work.Processing=true;var text=work.Text.ToString();var xml=work.Xml.ToString();var identities=work.Identities.Length==0?null:work.Identities.ToString();work.Text=new();work.Xml=new();work.Identities=new();_ = ProcessChapter(doc,work,text,xml,identities,work.Command,work.Start,work.End,work.Next,work.Operation,work.IdentityAction=="positions");}
@ -176,7 +188,7 @@ public sealed partial class TrayCoordinator
}
private async Task CompleteChapterOperation(TrayDocument doc,ChapterWork work)
{
try{var result=await cloud.FinishChapters(doc.Book,new(){InstanceId=doc.Instance,SessionId=doc.Session,WordRevision=work.Revision,OperationId=work.Operation,ReviewChapterIds=work.Reviewed.Where(id=>id>0).ToArray(),HasIssues=work.Reviewed.Count>0||work.Manifest!.Chapters.Any(c=>!work.Checked.ContainsKey(c.ChapterId))},work.Context);lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;work.Processing=false;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,new(){InstanceId=doc.Instance,SessionId=doc.Session,WordRevision=work.Revision,OperationId=work.Operation,ReviewChapterIds=work.Reviewed.Where(id=>id>0).ToArray(),HasIssues=work.Reviewed.Count>0||work.Manifest!.Chapters.Any(c=>!work.Checked.ContainsKey(c.ChapterId))},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;}}}
catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){RetryChapterWork(doc,work,"Could not confirm chapter completion: "+e.Message);}}
}
private async Task ProcessChapter(TrayDocument doc,ChapterWork work,string text,string xml,string? identities,Guid command,int start,int end,string nextHeading,Guid operation,bool physicalPositions)
@ -185,7 +197,9 @@ public sealed partial class TrayCoordinator
try{
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(work.Wrapped&&start==work.FirstStart){CompleteChapters(doc,work);return;}}
var nativeTextVerified=work.NativeTextVerified;
var rows=await Task.Run(()=>physicalPositions?ChapterFingerprint.ReadXml(xml,text,null,true,ChapterWordPositions.Decode(identities??"")):ChapterFingerprint.ReadXml(xml,text,identities,nativeTextVerified));xml="";text="";
var verification=System.Diagnostics.Stopwatch.StartNew();
var rows=await Task.Run(()=>work.IdentityAction=="live-text"?ChapterFingerprint.ReadLiveText(text,identities??""):physicalPositions?ChapterFingerprint.ReadXml(xml,text,null,true,ChapterWordPositions.Decode(identities??"")):ChapterFingerprint.ReadXml(xml,text,identities,nativeTextVerified));xml="";text="";
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(work.IdentityAction=="live-text")work.LiveReads++;else work.XmlReads++;}
ChapterManifest manifest;lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;manifest=work.Manifest!;}
if(physicalPositions&&!manifest.NativePositionsSupported)throw new ArgumentException("Update the Development server to validate native picture positions. Existing checkpoints are retained.");
var hash=ChapterFingerprint.Content(rows.Select(p=>p.Text!));
@ -193,9 +207,11 @@ public sealed partial class TrayCoordinator
if(candidates.Length==0&&work.Operation!=Guid.Empty)candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==""&&c.ContentHash==hash&&c.ParagraphCount==rows.Length).ToArray();
if(candidates.Length!=1){lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;work.Reviewed.Add(-work.Start-1);work.ReviewReason="A chapter identity is unrecognised or ambiguous. Review its Word heading and saved mapping.";doc.Status=work.ReviewReason;AdvanceChapter(doc,work);}return;}
var chapter=candidates[0];lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(!work.Visited.Add(chapter.ChapterId)){work.Busy=false;if(!work.Checked.TryGetValue(chapter.ChapterId,out var earlier)||earlier.Start!=start||earlier.End!=end){work.Reviewed.Add(chapter.ChapterId);work.Checked.Remove(chapter.ChapterId);doc.Status="Duplicate chapter identity at another position; existing canonical structure is retained for review.";}AdvanceChapter(doc,work);return;}}var proof=new ChapterObservation{RequestId=command,OperationId=operation,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,WordRevision=doc.Revision,BaseRevision=manifest.Revision,ChapterId=chapter.ChapterId,Start=start,End=end,NextHeadingId=nextHeading,ContentHash=hash,IdentityHash=ChapterFingerprint.Identity(rows),PositionHash=physicalPositions?ChapterWordPositions.Hash(rows):"",Paragraphs=rows.Select(p=>new ChapterParagraph{NativeId=p.NativeId,Length=p.Length,Outline=p.Outline,WordLength=p.WordLength,Anchors=p.Anchors}).ToArray()};
lock(gate){work.VerificationMs+=verification.Elapsed.TotalMilliseconds;}
var validation=System.Diagnostics.Stopwatch.StartNew();work.Submissions++;
var result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);
if(!result.Accepted&&result.State=="Changed"&&result.AllowText){proof.Reconcile=true;proof.Paragraphs=rows;result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);}
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;
if(!result.Accepted&&result.State=="Changed"&&result.AllowText){proof.Reconcile=true;proof.Paragraphs=rows;work.Submissions++;result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);}
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.ServerMs+=validation.Elapsed.TotalMilliseconds;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);}
else{work.Reviewed.Add(chapter.ChapterId);work.ReviewReason=result.Message;doc.Status=result.Message+" Accepted chapter repairs are retained.";AdvanceChapter(doc,work);}
}

View File

@ -196,6 +196,7 @@ public sealed class TrayDocument
public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Link this manuscript to a book, then use Import manuscript in PlotDirector.",ReviewPath="";
internal ManuscriptCapture? RetryCapture;internal Guid RetryAuthentication;internal int RetryBook;
public long CaptureBaseRevision;public string CaptureBaseHash="";public ManuscriptCapture? Capture;public List<ParagraphFragment> CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision;
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 StructureSuggestion[] Chapters=[];public StructureSuggestion? Current;public Queue<StructureSuggestion> Pending=[];public HashSet<(long,int,int)> Completed=[];public HashSet<(long,int,int)> FailedChapters=[];public List<string> 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;}

View File

@ -97,7 +97,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 }, 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 }, 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");

View File

@ -30,11 +30,22 @@ public sealed class WordAccessScheduler
{
AssertOwner();
if (DateTime.UtcNow < quietUntil || work.Count == 0) return false;
var key = work.ContainsKey("selection") ? "selection" : order.Peek();
var action = work[key]; Cancel(key);
var watch = Stopwatch.StartNew();
try { action(); } catch (Exception ex) { Failed?.Invoke(ex); }
finally { Measured?.Invoke(key.Split(':')[0], watch.Elapsed.TotalMilliseconds); }
var batch = Stopwatch.StartNew();var chapterBatch=false;
// Only chapter continuations may share a tick. Other operations retain one-action
// semantics, and selection/author quiet periods are reconsidered after every step.
for(var steps=0;steps<16;steps++)
{
var key = work.ContainsKey("selection") ? "selection" : order.Peek();
var chapter=key.StartsWith("chapter:",StringComparison.Ordinal);
if(steps>0&&!chapter)break;
if(chapter)chapterBatch=true;
var action = work[key]; Cancel(key);
var watch = Stopwatch.StartNew();
try { action(); } catch (Exception ex) { Failed?.Invoke(ex); }
finally { Measured?.Invoke(key.Split(':')[0], watch.Elapsed.TotalMilliseconds); }
if(!chapter||batch.ElapsedMilliseconds>=15||DateTime.UtcNow<quietUntil||work.Count==0||work.ContainsKey("selection"))break;
}
if(chapterBatch)Measured?.Invoke("chapter-batch",batch.Elapsed.TotalMilliseconds);
return true;
}
}

View File

@ -1 +1 @@
<Project><PropertyGroup><ApplicationVersion>1.0.0.29</ApplicationVersion></PropertyGroup></Project>
<Project><PropertyGroup><ApplicationVersion>1.0.0.30</ApplicationVersion></PropertyGroup></Project>

View File

@ -59,6 +59,25 @@ public static class ChapterFingerprint
}
public static string Mapping(IEnumerable<string> assignments)=>Content(assignments);
// Exact native paragraph text/geometry, measured on the owning Word thread.
// This uses the existing v1 hashes and server validation; it is not a saved-file cache.
public static ChapterParagraph[] ReadLiveText(string text,string frames)
{
if(text.Length>MaxCharacters||frames.Length==0||frames.Length%24!=0||frames.Length/24>MaxParagraphs)
throw new ArgumentException("Incomplete or oversized live chapter evidence.");
var rows=new List<ChapterParagraph>();var offset=0;
for(var i=0;i<frames.Length;i+=24)
{
int Number(int at) => int.TryParse(frames.Substring(at,8),System.Globalization.NumberStyles.HexNumber,System.Globalization.CultureInfo.InvariantCulture,out var n)?n:-1;
var length=Number(i+8);var outline=Number(i+16);
if(length<=0||length>text.Length-offset)throw new ArgumentException("Live paragraph spans do not cover chapter text.");
rows.Add(new ChapterParagraph{NativeId=frames.Substring(i,8),Length=length,Outline=outline,Text=text.Substring(offset,length)});
offset+=length;
}
if(offset!=text.Length)throw new ArgumentException("Live paragraph spans leave incomplete chapter text.");
Identity(rows);return rows.ToArray();
}
// Parses only the main Word part. Complex constructs require the established bounded reader rather than guessed offsets.
public static ChapterParagraph[] ReadXml(string xml,string rangeText,string? liveIdentities=null,bool nativeParagraphTextVerified=false,ChapterParagraph[]? nativePositions=null)
{

View File

@ -5,6 +5,7 @@ namespace PlotDirector.Companion.Protocol;
public static class ProtocolVersion
{
public const int Current = 1;
public const string LiveChapterTextCapability="chapter-live-text-v1";
public const string NativeChapterPositionsCapability="chapter-native-positions-v1";
public const string NativeChapterTextCapability="chapter-native-text-v1";
public const string ChapterSyncCapability="chapter-sync-v1";

View File

@ -10,7 +10,7 @@ internal static class ChapterAgentTests
{
var handler=new Handler();using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://chapters.test/");await Until(()=>cloud.Status().Books.Any());await cloud.CheckConnection();
var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var tray=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid();handler.Manuscript=Guid.NewGuid();long sequence=0;
sessions.Attach(instance,lease,chapters:true,nativeChapterText:true,nativeChapterPositions:true);tray.Attach(instance,lease,capture:true,paragraphs:true,chapters:true);
sessions.Attach(instance,lease,chapters:true,nativeChapterText:true,nativeChapterPositions:true,liveChapterText:true);tray.Attach(instance,lease,capture:true,paragraphs:true,chapters:true);
Message Send(Message message){message.WordInstanceId=instance;message.SessionId=session;message.Revision=1;message.Sequence=++sequence;return tray.Exchange(instance,message,sessions.Apply(lease,message),lease);}
Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Synthetic chapter manuscript.docx"}]});tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=0,End=0,WordSaved=true});
using var stop=new CancellationTokenSource();var heartbeats=tray.Heartbeat(stop.Token);
@ -20,8 +20,13 @@ internal static class ChapterAgentTests
Check(tray.ChapterProgressForDisplay(session)?.Message=="0 of 1 chapters accepted","Checking progress reports committed acceptances, never a queued chapter number");
var text="Chapter 1\rExact prose\r";var xml="<w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:w14='http://schemas.microsoft.com/office/word/2010/wordml'><w:body><w:p w14:paraId='00000001'><w:pPr><w:outlineLvl w:val='0'/></w:pPr><w:r><w:t>Chapter 1</w:t></w:r></w:p><w:p w14:paraId='00000002'><w:r><w:t>Exact prose</w:t></w:r></w:p></w:body></w:document>";
void Frames(AdapterCommand read,bool exact=false){Send(new(){Kind="chapter-begin",SnapshotId=read.Id,BookId=3,Start=0,End=text.Length,DocumentEnd=text.Length,WordSaved=true});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="text",Start=0,OperationMessage=text});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="xml",Start=0,OperationMessage=xml});if(exact){var evidence=ChapterFingerprint.ReadXml(xml,text);Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="ids-exact",Start=0,OperationMessage=string.Concat(evidence.Select(p=>p.NativeId+p.Length.ToString("X8")))});}Send(new(){Kind="chapter-end",SnapshotId=read.Id});}
Frames(command!);await Until(()=>handler.Validations>0);await Until(()=>handler.Finishes>0);
Send(new(){Kind="chapter-begin",SnapshotId=command!.Id,BookId=3,Start=0,End=text.Length,DocumentEnd=text.Length,WordSaved=true});
Send(new(){Kind="chapter-chunk",SnapshotId=command.Id,Action="text",OperationMessage=text});
Send(new(){Kind="chapter-chunk",SnapshotId=command.Id,Action="live-text",OperationMessage="000000010000000A00000001000000020000000C0000000A"});
Send(new(){Kind="chapter-end",SnapshotId=command.Id});
await Until(()=>handler.Validations>0);await Until(()=>handler.Finishes>0);
Check(handler.Bodies.All(b=>JsonSerializer.Deserialize<ChapterObservation>(b,new JsonSerializerOptions(JsonSerializerDefaults.Web))!.Paragraphs.All(p=>p.Text==null)),"Unchanged chapter uploads hashes and native identity evidence, not manuscript prose");
Check(tray.ChapterDiagnostics(session).Contains("Reads live/XML=1/0"),"Reopened unchanged chapter validates without any XML frame");
Check(!handler.Paths.Any(p=>p.Contains("manuscript-capture")),"Chapter lifecycle does not invoke the full manuscript capture endpoint");
var before=handler.Validations;for(int n=0;n<100;n++){var response=Send(new(){Kind="selection",Start=12,End=12,WordSaved=true});Check(response.Command?.Kind!="navigate","Passive selection never returns a navigation command");}await Task.Delay(650);Check(handler.Validations==before,"Repeated cursor events reuse accepted current-session chapter validation");
Check(tray.Documents.Single().Status.Contains("accepted"),"Chapter completion is reported only after server acceptance");
@ -79,6 +84,7 @@ internal static class ChapterAgentTests
await Task.Delay(650);Check(handler.Validations==rejectedCount,"Rejected chapter waits for an explicit retry rather than reading Word repeatedly");
session = oldSession;
var wrong=new Message{Kind="chapter-chunk",SnapshotId=command!.Id,Action="xml",Start=0,OperationMessage="wrong"};var legacySessions=new SessionManager();legacySessions.Attach(instance,lease);long legacySequence=0;Message Legacy(Message m){m.WordInstanceId=instance;m.SessionId=session;m.Sequence=++legacySequence;m.Revision=1;return legacySessions.Apply(lease,m);}Legacy(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Legacy"}]});Check(Legacy(wrong).Status=="invalid-chapter-frame","Chapter frames require negotiated native capability; legacy clients remain isolated");
Check(Legacy(new(){Kind="chapter-chunk",SnapshotId=Guid.NewGuid(),Action="live-text",OperationMessage="000000010000000A00000001"}).Status=="invalid-chapter-frame","Live chapter evidence requires separate capability negotiation");
legacySessions.Attach(instance,lease,chapters:true);Legacy(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Legacy native IDs"}]});
Check(Legacy(new(){Kind="chapter-chunk",SnapshotId=Guid.NewGuid(),Action="ids-exact",OperationMessage="000000010000000A"}).Status=="invalid-chapter-frame","Native text certification requires its separately negotiated capability");
legacySessions.Attach(instance,lease,chapters:true,nativeChapterText:true);Legacy(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Legacy text certification"}]});

View File

@ -0,0 +1,73 @@
using System.Diagnostics;
using PlotDirector.Companion.Client;
using PlotDirector.Companion.Protocol.Manuscript;
internal static class ChapterReopenTests
{
private static void Check(bool value,string name){if(!value)throw new Exception(name);Console.WriteLine("PASS "+name);}
private static string Frames(IEnumerable<ChapterParagraph> rows)=>string.Concat(rows.Select(p=>p.NativeId+p.Length.ToString("X8")+p.Outline.ToString("X8")));
private static void Reject(Action action,string name){try{action();}catch(ArgumentException){Check(true,name);return;}throw new Exception(name);}
public static void Run()
{
var chapters=new List<ChapterParagraph[]>();var id=1;var words=0;
for(var chapter=0;chapter<48;chapter++)
{
var count=chapter==47?8457-47*176:176;
chapters.Add(Enumerable.Range(0,count).Select(i=>{
var text=i==0?$"Chapter {chapter+1}\r":string.Join(" ",Enumerable.Repeat("synthetic",18+(i%5==0?1:0)))+"\r";
words+=text.Split(' ').Length;
return new ChapterParagraph{NativeId=(id++).ToString("X8"),Text=text,Length=text.Length,Outline=i==0?1:10};
}).ToArray());
}
var watch=Stopwatch.StartNew();
foreach(var rows in chapters)
{
var restored=ChapterFingerprint.ReadLiveText(string.Concat(rows.Select(p=>p.Text)),Frames(rows));
Check(ChapterFingerprint.Content(restored.Select(p=>p.Text!))==ChapterFingerprint.Content(rows.Select(p=>p.Text!))&&ChapterFingerprint.Identity(restored)==ChapterFingerprint.Identity(rows),"New-session live evidence retains existing v1 content and identities");
}
Console.WriteLine($"PORTABLE live verification: 48 chapters, 8457 paragraphs, {words} words, {watch.Elapsed.TotalMilliseconds:F1} ms; excludes COM, network and UI.");
var xmls=chapters.Select(rows=>"<w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:w14='http://schemas.microsoft.com/office/word/2010/wordml'><w:body>"+string.Concat(rows.Select(p=>$"<w:p w14:paraId='{p.NativeId}'>{(p.Outline==1?"<w:pPr><w:outlineLvl w:val='0'/></w:pPr>":"")}<w:r><w:t>{p.Text![..^1]}</w:t></w:r></w:p>"))+"</w:body></w:document>").ToArray();
watch.Restart();for(var i=0;i<48;i++){var rows=ChapterFingerprint.ReadXml(xmls[i],string.Concat(chapters[i].Select(p=>p.Text)));ChapterFingerprint.Content(rows.Select(p=>p.Text!));ChapterFingerprint.Identity(rows);}
Console.WriteLine($"PORTABLE previous XML parse and fingerprints: {watch.Elapsed.TotalMilliseconds:F1} ms; excludes Word XML extraction and native identity enumeration.");
var sample=chapters[0];var original=ChapterFingerprint.Content(sample.Select(p=>p.Text!));
foreach(var index in new[]{1,17,80})
{
var edited=sample.Select(p=>p.Text!).ToArray();edited[index]="edited paragraph\r";
Check(ChapterFingerprint.Content(edited)!=original,"Saved/offline/unsaved text edits cannot produce unchanged content evidence");
}
Check(ChapterFingerprint.Content(sample.Skip(1).Select(p=>p.Text!))!=original,"Deleted paragraph changes content evidence");
Check(ChapterFingerprint.Content(sample.Select(p=>p.Text!).Append("new scene\r"))!=original,"Inserted scene changes content evidence");
Check(ChapterFingerprint.Content(chapters[1].Select(p=>p.Text!))!=original,"Chapter rename/reorder is not filename-based identity");
var text=string.Concat(sample.Select(p=>p.Text));var frames=Frames(sample);
Reject(()=>ChapterFingerprint.ReadLiveText(text,frames[..^1]),"Interrupted identity frames are refused");
Reject(()=>ChapterFingerprint.ReadLiveText(text,frames[..24]),"Missing paragraph evidence is refused");
Reject(()=>ChapterFingerprint.ReadLiveText(text,frames[..24]+frames[..24]+frames[48..]),"Duplicate native identities are refused");
Reject(()=>ChapterFingerprint.ReadLiveText(text,frames[..16]+"00000000"+frames[24..]),"Invalid native outline is refused");
Reject(()=>ChapterFingerprint.ReadLiveText(text+"x",frames),"Unaccounted native text is refused");
foreach(var editedChapters in new[]{new[]{7},new[]{0,19,47}})
{
var changed=new List<int>();
for(var c=0;c<48;c++)
{
var body=string.Concat(chapters[c].Select(p=>p.Text));
if(editedChapters.Contains(c))body=body.Replace("synthetic","different"); // equal UTF-16 lengths
var evidence=ChapterFingerprint.ReadLiveText(body,Frames(chapters[c]));
if(ChapterFingerprint.Content(evidence.Select(p=>p.Text!))!=ChapterFingerprint.Content(chapters[c].Select(p=>p.Text!)))changed.Add(c);
}
Check(changed.SequenceEqual(editedChapters),"Only genuinely edited chapters fail saved content fingerprints");
}
var scheduler=new WordAccessScheduler();var steps=0;var pumps=0;
Action? next=null;next=()=>{if(++steps<8457)scheduler.Post("chapter:fixture",next!);};scheduler.Post("chapter:fixture",next);
watch.Restart();while(scheduler.Pump())pumps++;
Check(steps==8457&&pumps==529,"Bounded chapter batching removes one timer tick per paragraph");
Console.WriteLine($"SCHEDULER MODEL: old 8457 ticks / 211425 ms minimum, new {pumps} ticks / {pumps*25} ms minimum; portable execution {watch.Elapsed.TotalMilliseconds:F1} ms. No COM latency simulated.");
var selection=false;var continuation=false;
scheduler.Post("chapter:first",()=>{scheduler.Post("selection",()=>selection=true);scheduler.Post("chapter:next",()=>continuation=true);});
scheduler.Pump();Check(!selection&&!continuation,"Chapter batching yields immediately to pending selection");
scheduler.Pump();Check(selection&&!continuation,"Selection executes before further chapter reads");scheduler.Clear();
scheduler.Post("chapter:first",()=>{scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1));scheduler.Post("chapter:next",()=>continuation=true);});
scheduler.Pump();Check(!scheduler.Pump()&&!continuation,"Author activity interrupts a chapter batch");scheduler.Clear();
var capped=new WordAccessScheduler();var reads=0;Action? repeat=null;repeat=()=>{reads++;capped.Post("chapter:bounded",repeat!);};capped.Post("chapter:bounded",repeat);
capped.Pump();Check(reads<=16,"A timer tick cannot execute unbounded chapter continuations");capped.Clear();
}
}

View File

@ -3,7 +3,7 @@ using PlotDirector.Companion.Agent;
using PlotDirector.Companion.Client;
using PlotDirector.Companion.Protocol;
if(args.Contains("--chapter-sync")){await ChapterAgentTests.Run();return;}
if(args.Contains("--chapter-sync")){ChapterReopenTests.Run();await ChapterAgentTests.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);}

View File

@ -32,8 +32,14 @@ namespace PlotDirector.WordAddIn
private readonly Stopwatch tickClock = Stopwatch.StartNew();
private readonly Stopwatch metricClock = Stopwatch.StartNew();
private readonly Stopwatch selectionClock = Stopwatch.StartNew();
private readonly Dictionary<string,double[]> chapterMetrics=new Dictionary<string,double[]>();
private void Metric(string name,double milliseconds)
{
if(name.StartsWith("chapter-",StringComparison.Ordinal))
{
double[] totals;if(!chapterMetrics.TryGetValue(name,out totals)&&chapterMetrics.Count<32)chapterMetrics[name]=totals=new double[3];
if(totals!=null){totals[0]++;totals[1]+=milliseconds;totals[2]=Math.Max(totals[2],milliseconds);}
}
if(pendingMetrics.Count==256)pendingMetrics.Dequeue();
pendingMetrics.Enqueue(new UiMetric{Operation=name,Milliseconds=milliseconds});
}
@ -63,6 +69,8 @@ namespace PlotDirector.WordAddIn
+ "\nAgent startup: " + AgentProcess.LaunchStatus
+ "\nMain document words: " + WordCountSummary
+ "\nLast UI batch ms: " + lastBatchMs.ToString("F2") + "\nMax recorded COM call ms: " + (operationTimes.Count == 0 ? 0 : operationTimes.Max()).ToString("F2")
+ "\nChapter reads live / XML (process): " + chapterLiveReads + " / " + chapterXmlReads
+ "\n" + string.Join("\n",chapterMetrics.Select(p=>p.Key+": count="+p.Value[0]+", total ms="+p.Value[1].ToString("F1")+", max ms="+p.Value[2].ToString("F1")))
+ "\nCOM busy/errors: " + busyFailures + (lastWordError == null ? "" : " (last: " + lastWordError + ")") + "\n" + lastResult;
public WordAdapter(Word.Application application, Action invalidateRibbon)
@ -86,13 +94,13 @@ namespace PlotDirector.WordAddIn
invalidateRibbon();
});
link.Received += message => {
if(message.Status=="ready")PostToUi(()=>{var capabilities=(message.Capabilities??"").Split(',');traySupported=capabilities.Contains(ProtocolVersion.TrayCapability);nativeChapterTextSupported=capabilities.Contains(ProtocolVersion.NativeChapterTextCapability);nativeChapterPositionsSupported=capabilities.Contains(ProtocolVersion.NativeChapterPositionsCapability);});
if(message.Status=="ready")PostToUi(()=>{var capabilities=(message.Capabilities??"").Split(',');traySupported=capabilities.Contains(ProtocolVersion.TrayCapability);liveChapterTextSupported=capabilities.Contains(ProtocolVersion.LiveChapterTextCapability);nativeChapterTextSupported=capabilities.Contains(ProtocolVersion.NativeChapterTextCapability);nativeChapterPositionsSupported=capabilities.Contains(ProtocolVersion.NativeChapterPositionsCapability);});
if(message.ChapterStatusProvided&&message.SessionId!=Guid.Empty)PostToUi(()=>ReceiveChapterStatus(message));
if(message.Command!=null)PostToUi(()=>HandleCommand(message.Command));
if(message.WordCount.HasValue)PostToUi(()=>{var doc=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);if(doc!=null)doc.WordCount=message.WordCount;});
if(message.Status!="ok"&&message.Status!="ready")lastResult=message.Status;
};
scheduler.Measured += (_, elapsed) => lastBatchMs = elapsed;
scheduler.Measured += (operation, elapsed) => {lastBatchMs=elapsed;if(operation=="chapter-batch")Metric("chapter-ui-batch",elapsed);};
scheduler.Failed += error => {
busyFailures++;
var frame=new StackTrace(error,true).GetFrames()?.FirstOrDefault(f=>f.GetMethod()?.DeclaringType?.FullName?.Contains("WordAdapter")==true);
@ -149,6 +157,7 @@ namespace PlotDirector.WordAddIn
if(document==null)return;
if (documents.ContainsKey(document) || documents.Count >= ProtocolVersion.MaxDocuments || !pendingOpen.Add(document)) return;
documentCollectionGeneration++;
var recognition=Stopwatch.StartNew();
if (!scheduler.Post("open:" + Guid.NewGuid().ToString("N"), () => {
pendingOpen.Remove(document);
if (documents.ContainsKey(document) || documents.Count >= ProtocolVersion.MaxDocuments) return;
@ -163,6 +172,7 @@ namespace PlotDirector.WordAddIn
{state.Identity=identity;state.IdentityPersisted=true;state.ProjectId=null;state.BookId=rememberedBook;state.AssociationSite=rememberedSite;}
state.End = DocumentEnd(document); state.WasSaved = Com(() => document.Saved);
documents.Add(document,state); RegisterState(state);
Metric("chapter-document-recognition",recognition.Elapsed.TotalMilliseconds);
ScheduleSelection();
})) pendingOpen.Remove(document);
}

View File

@ -11,7 +11,8 @@ namespace PlotDirector.WordAddIn
private string serverBook = "", serverChapter = "", serverScene = "";
private int serverBookId;
private long serverRevision = -1;
private bool nativeChapterTextSupported,nativeChapterPositionsSupported;
private long chapterLiveReads,chapterXmlReads;
private bool nativeChapterTextSupported,nativeChapterPositionsSupported,liveChapterTextSupported;
private ChapterSyncProgress serverChapterProgress;
public bool HasRibbonBook => active != null && ConnectionState == "connected" && serverBookId > 0 && serverChapterProgress?.State != "Sign-in required";
@ -105,7 +106,7 @@ namespace PlotDirector.WordAddIn
}
private sealed class ChapterRead
{
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;
public readonly Stopwatch Total=Stopwatch.StartNew();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 List<ChapterParagraph> NativePositions=new List<ChapterParagraph>();
public int PendingStart,PendingEnd,ShapeIndex,SegmentPosition,SegmentAnchor;public string PendingText="";public ChapterParagraph PendingPosition;
public readonly Dictionary<int,ChapterPictureAnchor> PendingAnchors=new Dictionary<int,ChapterPictureAnchor>();
@ -127,6 +128,40 @@ namespace PlotDirector.WordAddIn
if (id.Length == 0) throw new InvalidOperationException("Word did not provide a native paragraph ID. Review this chapter or use the explicit fallback.");
return id;
}
// Conservative accelerator: structural/picture chapters retain the qualified XML/position reader.
// Collection RCWs are released before returning to the scheduler.
private bool IsPlainChapter(Word.Range range)
{
Word.Tables tables=null;Word.Fields fields=null;Word.Revisions revisions=null;
Word.Footnotes footnotes=null;Word.Endnotes endnotes=null;Word.InlineShapes inline=null;
try
{
tables=Com(()=>range.Tables);if(Com(()=>tables.Count)!=0)return false;
fields=Com(()=>range.Fields);if(Com(()=>fields.Count)!=0)return false;
revisions=Com(()=>range.Revisions);if(Com(()=>revisions.Count)!=0)return false;
footnotes=Com(()=>range.Footnotes);if(Com(()=>footnotes.Count)!=0)return false;
endnotes=Com(()=>range.Endnotes);if(Com(()=>endnotes.Count)!=0)return false;
inline=Com(()=>range.InlineShapes);if(Com(()=>inline.Count)!=0)return false;
return true;
}
catch(System.Runtime.InteropServices.COMException){return false;}
finally{Release(inline);Release(endnotes);Release(footnotes);Release(revisions);Release(fields);Release(tables);}
}
private void CheckChapterShape(LocalDocument doc,ChapterRead read)
{
Word.Shapes shapes=null;Word.Shape shape=null;Word.Range anchor=null;
try
{
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;}
shape=Com(()=>shapes[read.ShapeIndex]);anchor=Com(()=>shape.Anchor);
var start=Com(()=>anchor.Start);
if(start>=read.Start&&start<read.End){read.Phase=12;return;}
read.ShapeIndex++;
}
finally{Release(anchor);Release(shape);Release(shapes);}
}
private void ReadChapterStep(LocalDocument doc)
{
ChapterRead read;if(!chapterReads.TryGetValue(doc.Session,out read))return;
@ -134,7 +169,7 @@ namespace PlotDirector.WordAddIn
var watch=Stopwatch.StartNew();Word.Range point=null,heading=null,range=null;Word.Paragraphs paragraphs=null;Word.Paragraph paragraph=null;
try
{
if((read.Phase<4||read.Phase==6||read.Phase==7||read.Phase==9||read.Phase==10)&&(!Com(()=>doc.Document.Saved)||Com(()=>application.BackgroundSavingStatus)!=0))throw new InvalidOperationException("Save Word and wait for background saving before validating chapters.");
if((read.Phase<4||read.Phase==6||read.Phase==7||read.Phase==9||read.Phase==10||read.Phase==11||read.Phase==12)&&(!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);
@ -165,8 +200,14 @@ namespace PlotDirector.WordAddIn
if(read.PhysicalPositions&&(!nativeChapterPositionsSupported||!read.Command.NativeChapterPositions))
throw new InvalidOperationException("This chapter has native Word positions without text. Update Companion and the Development server for measured picture-anchor support; existing mappings are retained.");
read.Phase=3;
}else if(read.Phase==3){
range=Com(()=>doc.Document.Range(read.Start,read.End));read.Xml=Com(()=>range.WordOpenXML,"chapter-range-xml")??"";
}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))
{
read.ShapeIndex=1;read.Phase=11;return;
}
read.Xml=Com(()=>range.WordOpenXML,"chapter-range-xml")??"";
if(read.Xml.Length>8*1024*1024)throw new InvalidOperationException("Chapter XML exceeds the bounded transport. Use existing bounded synchronisation.");
// Drawings, native position gaps and measured breaks need direct paragraph text.
// A lexical false positive merely performs extra verification.
@ -174,11 +215,11 @@ 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){
// One paragraph per scheduler turn. Word COM objects never leave the STA.
// One paragraph per bounded step; the scheduler may batch short steps. COM stays on the STA.
point=Com(()=>doc.Document.Range(read.IdentityPosition,read.IdentityPosition));
paragraphs=Com(()=>point.Paragraphs);paragraph=Com(()=>paragraphs[1]);range=Com(()=>paragraph.Range);
var start=Com(()=>range.Start);var end=Com(()=>range.End);
if(start!=read.IdentityPosition||end<=start||end>read.End||read.Identities.Length/16>=ChapterFingerprint.MaxParagraphs)
if(start!=read.IdentityPosition||end<=start||end>read.End||read.Identities.Length/(read.LiveText?24:16)>=ChapterFingerprint.MaxParagraphs)
throw new InvalidOperationException("Live Word paragraph boundaries do not match the chapter.");
if(read.PhysicalPositions)
{
@ -197,6 +238,7 @@ namespace PlotDirector.WordAddIn
}
read.Identities.Append(ReadLiveParagraphId(paragraph));
read.Identities.Append((end-start).ToString("X8",System.Globalization.CultureInfo.InvariantCulture));
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==9){ReadChapterPictureAnchor(doc,read);
@ -205,9 +247,9 @@ namespace PlotDirector.WordAddIn
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;}
for(int n=0;n<4&&watch.ElapsedMilliseconds<20;n++){
var source=read.Phase==4?read.Text:read.Phase==5?read.Xml:read.IdentityFrames;
if(read.Offset<source.Length){var count=Math.Min(2048,source.Length-read.Offset);if(!link.TryPost(new Message{Kind="chapter-chunk",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,Action=read.Phase==4?"text":read.Phase==5?"xml":read.PhysicalPositions?"positions":read.NativeTextRequired?"ids-exact":"ids",Start=read.Offset,OperationMessage=source.Substring(read.Offset,count)}))return;read.Offset+=count;}
else if(read.Phase<8){read.Phase=read.Phase==4?5:8;read.Offset=0;}
else{if(!link.TryPost(new Message{Kind="chapter-end",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id}))return;CancelChapterRead(doc);return;}
if(read.Offset<source.Length){var count=Math.Min(2048,source.Length-read.Offset);if(!link.TryPost(new Message{Kind="chapter-chunk",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,Action=read.Phase==4?"text":read.Phase==5?"xml":read.LiveText?"live-text":read.PhysicalPositions?"positions":read.NativeTextRequired?"ids-exact":"ids",Start=read.Offset,OperationMessage=source.Substring(read.Offset,count)}))return;read.Offset+=count;}
else if(read.Phase<8){read.Phase=read.Phase==4&&!read.LiveText?5:8;read.Offset=0;}
else{if(!link.TryPost(new Message{Kind="chapter-end",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id}))return;Metric(read.LiveText?"chapter-live-text-complete":"chapter-xml-complete",read.Total.Elapsed.TotalMilliseconds);if(read.LiveText)chapterLiveReads++;else chapterXmlReads++;CancelChapterRead(doc);return;}
}
}
}

View File

@ -1,7 +1,7 @@
{
"version": "1.0.0.29",
"msiVersion": "1.0.29",
"productCode": "{CE0CA0FF-BB63-43C3-82A0-B32640956FEF}",
"version": "1.0.0.30",
"msiVersion": "1.0.30",
"productCode": "{4E2DA176-5A36-4C05-89A7-5BAB66700FB2}",
"upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}",
"atlasBaseline": "9fed339879887964d526cff00772ffc4dc522c5d",
"baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",

View File

@ -21,12 +21,16 @@ internal static class ChapterSynchronisationTests
state.Chapters=[new(){CanonicalId=10,HeadingId=state.Paragraphs[0].Occurrence.Id,Title="Chapter one"},new(){CanonicalId=11,HeadingId=state.Paragraphs[3].Occurrence.Id,Title="Chapter two"}];
foreach(var p in state.Paragraphs.Where(p=>p.Occurrence.Outline==1)){p.ChapterId=p.Occurrence.Ordinal==0?10:11;p.PositionVerified=true;}
ChapterObservation Proof(int id=10){var part=ChapterCheckpointEngine.Parts(state).Single(p=>p.Chapter.CanonicalId==id);var evidence=part.Rows.Select(p=>new ChapterParagraph{NativeId=p.Occurrence.NativeId,Text=p.Occurrence.Text,Length=p.Occurrence.Text.Length,Outline=p.Occurrence.Outline}).ToArray();return new(){ChapterId=id,RequestId=Guid.NewGuid(),InstanceId=Guid.NewGuid(),SessionId=Guid.NewGuid(),ManuscriptId=state.ManuscriptId,WordRevision=0,BaseRevision=state.Revision,Start=500,End=500+evidence.Sum(p=>p.Length),ContentHash=ChapterFingerprint.Content(evidence.Select(p=>p.Text!)),IdentityHash=ChapterFingerprint.Identity(evidence),Paragraphs=evidence,NextHeadingId=id==10?state.Paragraphs[3].Occurrence.NativeId:""};}
var before=JsonSerializer.Serialize(state);var proof=Proof();var accepted=ChapterCheckpointEngine.Validate(state,proof,DateTime.UtcNow);
var before=JsonSerializer.Serialize(state);var proof=Proof();
ChapterParagraph[] Live(ChapterParagraph[] evidence)=>ChapterFingerprint.ReadLiveText(string.Concat(evidence.Select(p=>p.Text)),string.Concat(evidence.Select(p=>p.NativeId+p.Length.ToString("X8")+p.Outline.ToString("X8"))));
proof.Paragraphs=Live(proof.Paragraphs);foreach(var p in proof.Paragraphs)p.Text=null;
var accepted=ChapterCheckpointEngine.Validate(state,proof,DateTime.UtcNow);
Check(accepted.Positions.First().Start==500&&accepted.Positions.Where(p=>p.SceneId.HasValue).All(p=>p.SceneId==22),"Unchanged reopened chapter accepts new physical positions without changing scene identity");
Check(JsonSerializer.Serialize(state)==before,"Validation proposals do not mutate accepted paragraphs, scenes, evidence or session identity");
var stale=Proof();stale.BaseRevision--;Refused(()=>ChapterCheckpointEngine.Validate(state,stale,DateTime.UtcNow),"Stale accepted-snapshot lineage is refused");
var duplicate=Proof();duplicate.Paragraphs[1].NativeId=duplicate.Paragraphs[0].NativeId;Refused(()=>ChapterCheckpointEngine.Validate(state,duplicate,DateTime.UtcNow),"Duplicate native paragraph identities cannot produce a green checkpoint");
var changed=Proof();changed.Reconcile=true;changed.Paragraphs[1].Text="Edited first passage.\r";changed.Paragraphs[1].Length=changed.Paragraphs[1].Text!.Length;changed.ContentHash=ChapterFingerprint.Content(changed.Paragraphs.Select(p=>p.Text!));changed.IdentityHash=ChapterFingerprint.Identity(changed.Paragraphs);changed.End=changed.Start+changed.Paragraphs.Sum(p=>p.Length);
changed.Paragraphs=Live(changed.Paragraphs);
Refused(()=>ChapterCheckpointEngine.Validate(state,changed,DateTime.UtcNow),"Changed hash is not accepted as synchronised");
var merged=ChapterCheckpointEngine.MergeChapter(state,changed);Check(merged.Skip(3).Select(p=>p.Id).SequenceEqual(state.Paragraphs.Skip(3).Select(p=>p.Occurrence.Id)),"Selective chapter merge preserves unrelated paragraph GUIDs");
Check(merged[3].Start-state.Paragraphs[3].Occurrence.Start==changed.Paragraphs[1].Length-state.Paragraphs[1].Occurrence.Text.Length,"Logical positions in later chapters account for changed text length");