From 9fed339879887964d526cff00772ffc4dc522c5d Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Mon, 9 Nov 2026 17:59:33 +0000 Subject: [PATCH] Preserve native Word picture positions and refine accepted sync progress --- ...2026-11-09-v1.0.0.28-structural-content.md | 71 ++++++++++++++ .../Agent/PipeHost.cs | 4 +- .../Agent/SessionManager.cs | 8 +- .../Agent/TrayCoordinator.Chapters.cs | 41 +++++--- .../Client/AgentLink.cs | 2 +- .../DeveloperVersion.props | 2 +- .../Protocol/Manuscript/ChapterFingerprint.cs | 32 ++++-- .../Manuscript/ChapterWordPositions.cs | 95 ++++++++++++++++++ .../Protocol/Messages.cs | 1 + .../Protocol/TrayContracts.cs | 1 + .../Tests/ChapterAgentTests.cs | 38 ++++++- .../Vsto/NativeRibbon.cs | 11 ++- .../Vsto/PlotDirector.WordAddIn.csproj | 3 +- .../Vsto/Properties/AssemblyInfo.cs | 4 +- PlotDirector.NativeCompanion/Vsto/Ribbon.xml | 7 +- .../Vsto/WordAdapter.cs | 4 +- .../Vsto/WordChapterPositions.cs | 98 +++++++++++++++++++ .../Vsto/WordChapterRead.cs | 45 ++++++--- .../WindowsValidation/Setup/Release.json | 6 +- .../Browser/chapter-sync-development.cjs | 20 ++++ .../ChapterAcceptanceDevelopmentTests.cs | 2 + .../ChapterStructuralContentTests.cs | 70 +++++++++++++ PlotLine.Tests/ChapterSyncDevelopmentTests.cs | 13 +++ PlotLine.Tests/ChapterSynchronisationTests.cs | 1 + .../Manuscript/ChapterCheckpointEngine.cs | 12 ++- .../Services/Manuscript/ChapterSyncService.cs | 5 +- 26 files changed, 531 insertions(+), 65 deletions(-) create mode 100644 Docs/WordCompanion/WindowsHandover/2026-11-09-v1.0.0.28-structural-content.md create mode 100644 PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterWordPositions.cs create mode 100644 PlotDirector.NativeCompanion/Vsto/WordChapterPositions.cs create mode 100644 PlotLine.Tests/ChapterStructuralContentTests.cs diff --git a/Docs/WordCompanion/WindowsHandover/2026-11-09-v1.0.0.28-structural-content.md b/Docs/WordCompanion/WindowsHandover/2026-11-09-v1.0.0.28-structural-content.md new file mode 100644 index 00000000..06b920f3 --- /dev/null +++ b/Docs/WordCompanion/WindowsHandover/2026-11-09-v1.0.0.28-structural-content.md @@ -0,0 +1,71 @@ +# Windows handover: 1.0.0.28 structural position correction + +Continue `codex/word-companion-native-phase1-20261104`, fetch and fast-forward only. Atlas started at pushed Windows handover `c6bde45`; that handover contained documentation only. Preserve the installed .27 package and the existing Discovery test DOCX/backup. Atlas has not operated Word, built/signed the VSTO, installed Windows software or changed the DOCX. **Final-chapter success is not yet claimed.** + +## Confirmed cause and protected state + +The .27 Windows report measures final range `[838510,845456)`: 6,946 native Word positions, 6,945 UTF-16 text units. Paragraph `[844820,844832)` has 12 positions and 11 text units. Its first one-position range returns empty text, including with hidden text/field-code retrieval enabled, and corresponds to a floating picture of native shape type 13. An inline picture is separate. The old aggregate and paragraph gates equated text length and Word span; they reject this legitimate native position before checkpoint submission. The QR/signature image identity and visual heading style are not established causes. + +Fresh Development inspection independently confirmed **47 durable checkpoints and 47 validations** for session `e3ebb78f-6dd8-422b-b4f8-7bfb0129173c`, Word revision 0; manuscript revision 2. The imported paragraph at 844820 already preserves the same 12-position/11-text-unit mismatch. The imported tail, including the letter, is mapped to the existing final scene; no independent back-matter boundary is established. Atlas preserves those mappings rather than inferring a boundary from appearance, a name or an image. Existing imported non-story assignments also remain non-story. + +## Focused implementation + +- `ChapterParagraph.Length` remains exact UTF-16 text length. Optional `WordLength` and ordered `Anchors` describe measured native Word spans; anchors contain paragraph-relative Word offset, positive native shape ID and native picture type (11/13). A separate SHA-256 `PositionHash` binds this geometry. Content/identity v1 hashes and the canonical GUID/scene model are unchanged, so the other 47 checkpoints are not rehashed or reset. +- The optional `chapter-native-positions-v1` pipe capability and `positions` metadata frames are separately negotiated. The server manifest advertises `nativePositionsSupported`; only then does the agent permit this reader path. Older clients retain their existing path. An older server cannot accept a mismatched native end as a text offset. +- Only a chapter whose native span differs from its text length enters physical-position extraction. The STA reader measures every paragraph's native start/end, ID, outline and text. For each mismatched paragraph it enumerates that paragraph's floating shapes one per scheduler turn, reads genuine anchor positions, and verifies the corresponding one-position ranges return no text even with hidden text/field codes included. Only actual picture/linked-picture anchors qualify. It then measures every intervening text segment, checking its length against its own Word span and its concatenation against the paragraph text. Paragraph concatenation must also equal the original chapter text. No padding, XML object-character projection, marker, selection, image conversion, anchor/layout/style change or document write is used. +- Server validation retains exact accepted content, native identity, paragraph count/text length/outline, mapping, grant/session/saved state and revision checks. Physical spans must be complete and account exactly for supported, ordered, unique picture anchors; the geometry digest must match. SQL positions use native spans; source prose/GUIDs/canonical positions remain unchanged. Geometry hash is additive checkpoint metadata. **No SQL migration is required.** +- Native section-break text can be certified through the same existing exact-paragraph-text mechanism; it is not guessed from XML section properties. Explicit page-break behaviour is retained. Tables, fields, text boxes, grouped shapes with unexplained positions and other unsupported content produce specific structural diagnostics. +- A bounded chapter read failure can finish that chapter under review and let other chapters finish, without rereading already accepted ranges. An unidentified finish error no longer flags the first accepted chapter for review. Neither attempted reads nor failed checks increment the accepted count. +- Ribbon: separate chapter/scene lines, larger text budgets and full tooltips; accepted-count progress (`47 of 48 chapters accepted`), complete count (`48 chapters verified`), native `WindowNew` icon for Open Companion, and Repair moved unchanged into Tools. Writing Context/Intent remain in their original group/order with identical button attributes/actions/icons. + +API references used for the native read: [Range.ShapeRange](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.range.shaperange?view=word-pia), [ShapeRange.Item](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.shaperange.item?view=word-pia). The actual zero-text anchor evidence comes from the pushed Windows qualification, not those API descriptions. + +## Automated verification + +The focused fixtures cover text-only chapters; inline and floating QR/signature representations; mixed objects; empty/image-only paragraphs; page breaks; measured native section-break text; non-Heading-1 visual headings; imported non-story back matter; unchanged content/identity digests; exact native positions after an empty anchor; tampered/incomplete/unsupported geometry refusal; negotiated transport; specific review reasons; and preservation of an already accepted chapter when another reader fails. + +Run build and suites serially: + +```powershell +dotnet build PlotLine.slnx +dotnet run --project PlotLine.Tests -- --chapter-sync +dotnet run --project PlotDirector.NativeCompanion/Tests -- --chapter-sync +dotnet run --project PlotDirector.NativeCompanion/Tests +dotnet run --project PlotLine.Tests +``` + +Atlas additionally runs guarded isolated Development fixtures for geometry persistence/fresh reads/post-anchor Context and the existing 48-chapter scale/selective edit/resume regressions. The existing authenticated HTTP browser regression accepts `--structural` to test the deployed native geometry protocol and following-chapter positions. These are synthetic native-value/XML/protocol tests, not real Word COM results. VSTO C# syntax and ribbon XML are checked on Atlas; Office/VSTO binding and visual rendering require Windows. + +## Windows build/package + +After a clean fast-forward, use the established scripts and existing signing identity; do not launch/close Word, change trust stores or install unattended: + +```powershell +.\PlotDirector.NativeCompanion\WindowsValidation\Update-WordCompanion.ps1 +# This prepares the signed developer payload; it does not install. +.\PlotDirector.NativeCompanion\WindowsValidation\Setup\Build-Setup.ps1 ` + -PackagePath '' ` + -ExpectedSourceCommit '' ` + -OutputDirectory '' ` + -CertificateThumbprint '' +``` + +Run the established developer payload, MSI/CAB and upgrade gates using the retained qualified baseline pins. Metadata selects application 1.0.0.28/MSI 1.0.28, a fresh ProductCode and the unchanged UpgradeCode. Coordinate normal Word closure/installation with the author through the established workflow. Do not substitute a loose VSTO install or force-close Word. + +## Real Word acceptance procedure + +1. Verify both installed components are .28, the existing protected approval/book association returns, and both local peers plus Development support native positions. Use the existing associated saved development test copy, never reimport/reset/clear its mappings. Record a DOCX hash before/after; it should remain unchanged by synchronisation. +2. Request explicit repair (Tools → Repair Synchronisation) and prioritise the final chapter at the author's cursor. Native IDs are still missing in that chapter, so first adoption still needs the existing explicit repair authority. Preserve the 47 durable checkpoints. +3. Inspect the measured anchor paragraph: native start/end 844820/844832, text units 11, Word span 12, one confirmed empty picture-anchor position at relative offset 0, positive native shape ID/type 13. Verify segment text, aggregate text and native paragraph IDs. **Remaining uncertainty:** actual `Range.ShapeRange` membership/anchor ranges on this Word build and bounded COM occupancy must be qualified. If Word cannot account for a position, preserve the specific refusal; do not invent/pad text or weaken checks. +4. Require the server's received → validated → persisted diagnostics for chapter **11206**, a successful accepted reply, and an independent fresh SQL read. The final live positions must end at 845456 and preserve the paragraph end at 844832/next start at 844832; verify cursor resolution both before and after the anchor and near 845455 to the existing canonical final scene **9328**. Inspect `PositionHash` and confirm unchanged GUIDs, prose, scene/evidence decisions and canonical positions. +5. Verify **48 durable checkpoints** and **48 matching live validations for the current session/revision**, then server-confirmed whole-book completion. Old session validations may coexist; do not mistake total historical rows for current-session acceptance. A newly opened Word session still requires its existing fresh position verification; durable evidence is not reset. +6. Recheck the other 47 chapters: unchanged acceptance, interrupted repair/resume, stationary cursor without rereads, Writing Context following and the existing Writing Intent flow. Use a disposable manuscript/book for changed-chapter or unsupported-object edge cases; unsupported content should finish under review while other accepted chapters remain accepted. +7. Visually verify wide/narrow Word windows: chapter/scene readability/full tooltips, native collapse behaviour, count-only progress, `Up to date`/`48 chapters verified` only after server completion, native Open Companion window icon, Repair in Tools, and unchanged Writing Context/Intent buttons. Record COM step timing and observed editing/scrolling/save responsiveness; portable timings are not Word timings. + +Record actual results before stating that the final Discovery chapter is fixed. + +## Atlas test result before deployment + +The solution build passes with zero warnings/errors (`--disable-build-servers` was used for the final build after a transient host CLR abort). Passed: chapter/structural engine 66 PASS records, focused chapter agent 143, native foundation/authentication 273, and full application harness 456. The 8,457-paragraph/48-chapter isolated Development fixture passes unchanged acceptance, selective edits/insertion/deletion, resume, incomplete completion and preservation of accepted validations on an unidentified error. A separate guarded two-chapter fixture confirms geometry-hash persistence, correct Context after the anchor and no canonical data/revision change. Fixtures contain synthetic data only. The scale project 8191 is archived. + +The current Development backup preceding these fixtures is `/var/opt/mssql/backup/pwa-desktop-20261109T175251-bb81bbf9c7344317ae7a38a80a8b7e13.bak`; the scale run also took its own copy-only checksum backup. Discovery still has 47 unexpired validations for its original session. Deployment identity, post-deployment HTTP results and final preservation comparison are recorded below when verified. diff --git a/PlotDirector.NativeCompanion/Agent/PipeHost.cs b/PlotDirector.NativeCompanion/Agent/PipeHost.cs index f264b683..2514772f 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, Action i.Documents.Count); } } - public void Attach(Guid instance, Guid lease,bool chapters=false,bool nativeChapterText=false) + public void Attach(Guid instance, Guid lease,bool chapters=false,bool nativeChapterText=false,bool nativeChapterPositions=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}; + instances[instance] = new WordInstance(lease){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.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"))))return Reject(answer,"invalid-chapter-frame"); + 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.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"))))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;public Guid Lease = lease; public long LastSequence; public Guid? ActiveSession; public Dictionary Documents = []; } + private sealed class WordInstance(Guid lease) { public bool ChapterCapable,NativeChapterTextCapable,NativeChapterPositionsCapable;public Guid Lease = lease; public long LastSequence; public Guid? ActiveSession; public Dictionary 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 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 Fragments = []; } } diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs index e847d717..037e6e49 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs @@ -32,11 +32,7 @@ public sealed partial class TrayCoordinator return new() { State = "Needs review", Total = total, Matching = accepted, Message = doc.Status }; if (work.Busy || !work.Finished && work.Attempts > 0) { - var step = work.Processing ? "Verifying chapter with PlotDirector" : "Checking Word chapter"; - var chapter = work.Manifest?.Chapters.FirstOrDefault(c => c.Start <= work.CursorWhenQueued && work.CursorWhenQueued < c.End); - if (chapter != null) step += $" {Array.IndexOf(work.Manifest!.Chapters, chapter) + 1} of {total}"; - step += $" · {accepted} accepted"; - return new() { State = "Checking", Total = total, Matching = accepted, Message = step }; + return new() { State = "Checking", Total = total, Matching = accepted, Message = $"{accepted} of {total} chapters accepted" }; } return doc.ChapterProgress; } @@ -124,27 +120,43 @@ public sealed partial class TrayCoordinator StopChapterWork(doc, work, "Chapter checks reached the retry limit. " + work.ReviewReason); return; } - var command=new AdapterCommand{Kind="chapter-check",OperationId=work.Operation,BookId=doc.Book,Chapter=new(){Start=position}}; + 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.";} } + private void ReviewChapterReadFailure(TrayDocument doc,ChapterWork work,int start,int end,string reason) + { + work.Busy=false;work.Processing=false;work.Command=Guid.Empty; + var chapter=work.Manifest?.Chapters.SingleOrDefault(c=>c.Start==start&&c.End==end); + work.Reviewed.Add(chapter?.ChapterId??-start-1);work.ReviewReason=reason;doc.Status=reason; + AdvanceChapter(doc,work); + } private void ChapterFrame(TrayDocument doc,Message message,Message answer) { if(!chapterWork.TryGetValue(doc.Session,out var work)||!CurrentChapterWork(doc,work)||work.Command!=message.SnapshotId)return; - if(message.Kind=="adapter-result"&&message.OperationMessage!="ok"){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status=message.OperationMessage;return;} + if(message.Kind=="adapter-result"&&message.OperationMessage!="ok") + { + if(work.Begun&&work.End>work.Start&&work.Manifest!=null) + { + ReviewChapterReadFailure(doc,work,work.Start,work.End,message.OperationMessage); + } + else StopChapterWork(doc,work,message.OperationMessage); + return; + } if(!message.Kind.StartsWith("chapter-",StringComparison.Ordinal))return; 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"; + var identityFrame=message.Action is "ids" or "ids-exact" or "positions"; 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?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*16):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);} + 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");} } private void AdvanceChapter(TrayDocument doc,ChapterWork work) { if(work.Manifest==null)return; + if(work.Manifest.Chapters.All(c=>work.Checked.ContainsKey(c.ChapterId)||work.Reviewed.Contains(c.ChapterId))){CompleteChapters(doc,work);return;} var next=work.End; for(int count=0;countid>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;}}} 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) + 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) { if(!await chapterProcessing.WaitAsync(0)){lock(gate)if(CurrentChapterWork(doc,work)&&work.Command==command){work.Busy=false;work.Command=Guid.Empty;work.RetryAfter=DateTime.UtcNow.AddSeconds(1);doc.Status="Waiting for bounded chapter processing; accepted checkpoints are retained.";}return;} 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(()=>ChapterFingerprint.ReadXml(xml,text,identities,nativeTextVerified));xml="";text=""; + var rows=await Task.Run(()=>physicalPositions?ChapterFingerprint.ReadXml(xml,text,null,true,ChapterWordPositions.Decode(identities??"")):ChapterFingerprint.ReadXml(xml,text,identities,nativeTextVerified));xml="";text=""; 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!)); var candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==rows[0].NativeId).ToArray(); 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),Paragraphs=rows.Select(p=>new ChapterParagraph{NativeId=p.NativeId,Length=p.Length,Outline=p.Outline}).ToArray()}; + 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()}; 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; @@ -188,7 +201,7 @@ public sealed partial class TrayCoordinator } }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||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){work.Reviewed.Add(-start-1);work.ReviewReason="Chapter content needs review: "+e.Message;doc.Status=work.ReviewReason;AdvanceChapter(doc,work);} + 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();} } diff --git a/PlotDirector.NativeCompanion/Client/AgentLink.cs b/PlotDirector.NativeCompanion/Client/AgentLink.cs index ea8d86f8..15c4ba81 100644 --- a/PlotDirector.NativeCompanion/Client/AgentLink.cs +++ b/PlotDirector.NativeCompanion/Client/AgentLink.cs @@ -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 }, 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 }, 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/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props index b265f257..3e39cd67 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.27 +1.0.0.28 diff --git a/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs index 73e555c8..bb9e2a26 100644 --- a/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs +++ b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs @@ -10,6 +10,8 @@ public sealed class ChapterParagraph { [DataMember] public string NativeId {get;set;}=""; [DataMember] public int Length {get;set;} + [DataMember(EmitDefaultValue=false)] public int WordLength {get;set;} + [DataMember] public ChapterPictureAnchor[] Anchors {get;set;}=Array.Empty(); [DataMember] public int Outline {get;set;}=10; [DataMember] public string? Text {get;set;} } @@ -29,6 +31,7 @@ public sealed class ChapterObservation [DataMember] public string Algorithm {get;set;}=ChapterFingerprint.Version; [DataMember] public string ContentHash {get;set;}=""; [DataMember] public string IdentityHash {get;set;}=""; + [DataMember] public string PositionHash {get;set;}=""; [DataMember] public string NextHeadingId {get;set;}=""; [DataMember] public bool Reconcile {get;set;} [DataMember] public ChapterParagraph[] Paragraphs {get;set;}=Array.Empty(); @@ -57,17 +60,25 @@ public static class ChapterFingerprint public static string Mapping(IEnumerable assignments)=>Content(assignments); // Parses only the main Word part. Complex constructs require the established bounded reader rather than guessed offsets. - public static ChapterParagraph[] ReadXml(string xml,string rangeText,string? liveIdentities=null,bool nativeParagraphTextVerified=false) + public static ChapterParagraph[] ReadXml(string xml,string rangeText,string? liveIdentities=null,bool nativeParagraphTextVerified=false,ChapterParagraph[]? nativePositions=null) { + if(nativePositions!=null) + { + if(liveIdentities!=null)throw new ArgumentException("Mixed native position/identity encodings are not supported."); + ChapterWordPositions.ValidateRows(nativePositions); + liveIdentities=string.Concat(nativePositions.Select(p=>p.NativeId+p.Length.ToString("X8",System.Globalization.CultureInfo.InvariantCulture))); + nativeParagraphTextVerified=true; + } if(xml.Length>8*1024*1024||rangeText.Length>MaxCharacters)throw new ArgumentException("Chapter XML exceeds the bounded reader."); using var reader=XmlReader.Create(new StringReader(xml),new XmlReaderSettings{DtdProcessing=DtdProcessing.Prohibit,XmlResolver=null,MaxCharactersInDocument=8*1024*1024}); var root=XDocument.Load(reader);XNamespace w="http://schemas.openxmlformats.org/wordprocessingml/2006/main",pkg="http://schemas.microsoft.com/office/2006/xmlPackage",w14="http://schemas.microsoft.com/office/word/2010/wordml"; var document=root.Root?.Name==w+"document"?root.Root:root.Descendants(pkg+"part").Where(p=>(string?)p.Attribute(pkg+"name")=="/word/document.xml").SelectMany(p=>p.Descendants(w+"document")).SingleOrDefault(); var body=document?.Element(w+"body")??throw new ArgumentException("Main Word document part is missing."); var unsafeNames=new HashSet(new[]{"tbl","txbxContent","fldChar","instrText","footnoteReference","endnoteReference","object","ins","del","moveFrom","moveTo","altChunk","sym"}.Select(n=>w+n)); - if(body.Descendants().Any(e=>unsafeNames.Contains(e.Name)))throw new ArgumentException("Complex chapter content needs bounded reconciliation; positions were not guessed."); - var hasDrawings=body.Descendants(w+"drawing").Any(); - if(hasDrawings&&(!nativeParagraphTextVerified||liveIdentities==null))throw new ArgumentException("Pictures require exact native paragraph text and span verification; XML projection was not guessed."); + var unsupported=body.Descendants().FirstOrDefault(e=>unsafeNames.Contains(e.Name)); + if(unsupported!=null)throw new ArgumentException("Unsupported Word structure: "+unsupported.Name.LocalName+". Review this chapter in Companion diagnostics; other accepted chapters are retained."); + var hasDrawings=body.Descendants(w+"drawing").Any()||body.Descendants(w+"pPr").Elements(w+"sectPr").Any(); + if(hasDrawings&&(!nativeParagraphTextVerified||liveIdentities==null))throw new ArgumentException("Pictures/section breaks require exact native paragraph text and span verification; XML projection was not guessed."); var styles=root.Descendants(w+"style").Where(e=>e.Attribute(w+"styleId")!=null).GroupBy(e=>(string)e.Attribute(w+"styleId")!).ToDictionary(g=>g.Key,g=>g.First()); int Outline(XElement paragraph){ var properties=paragraph.Element(w+"pPr");var seen=new HashSet(); @@ -105,7 +116,7 @@ public static class ChapterFingerprint if(!int.TryParse(liveIdentities.Substring(i*16+8,8),System.Globalization.NumberStyles.HexNumber,System.Globalization.CultureInfo.InvariantCulture,out var measured)||measured<=0||measured>rangeText.Length-offset) throw new ArgumentException("Native paragraph text spans do not cover the exact chapter range."); var nativeText=rangeText.Substring(offset,measured); - if(!paragraphs[i].Descendants(w+"drawing").Any()&&rows[i].Text!=nativeText) + if(!paragraphs[i].Descendants(w+"drawing").Any()&¶graphs[i].Element(w+"pPr")?.Element(w+"sectPr")==null&&rows[i].Text!=nativeText) throw new ArgumentException("Native paragraph text differs from XML outside picture content."); rows[i].Text=nativeText;rows[i].Length=measured;offset+=measured; } @@ -117,13 +128,22 @@ public static class ChapterFingerprint } if(nativeParagraphTextVerified&&offset!=rangeText.Length)throw new ArgumentException("Native paragraph text spans leave an incomplete chapter range."); } + if(nativePositions!=null) + { + for(var i=0;ip.Text!));return rows; } } public sealed class ChapterManifest { - public int BookId{get;set;}public Guid ManuscriptId{get;set;}public long Revision{get;set;}public string Mode{get;set;}="Manual";public ChapterManifestItem[] Chapters{get;set;}=Array.Empty(); + public bool NativePositionsSupported{get;set;}public int BookId{get;set;}public Guid ManuscriptId{get;set;}public long Revision{get;set;}public string Mode{get;set;}="Manual";public ChapterManifestItem[] Chapters{get;set;}=Array.Empty(); } public sealed class ChapterManifestItem { diff --git a/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterWordPositions.cs b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterWordPositions.cs new file mode 100644 index 00000000..760fd918 --- /dev/null +++ b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterWordPositions.cs @@ -0,0 +1,95 @@ +using System.Runtime.Serialization; +using System.Runtime.Serialization.Json; +using System.Security.Cryptography; +using System.Text; + +namespace PlotDirector.Companion.Protocol.Manuscript; + +[DataContract] +public sealed class ChapterPictureAnchor +{ + [DataMember] public int Offset { get; set; } + [DataMember] public int ShapeId { get; set; } + [DataMember] public int ShapeType { get; set; } +} + +// Word positions and UTF-16 text units are different coordinates. These are +// measured paragraph spans, with explicit one-position, zero-text picture anchors. +public static class ChapterWordPositions +{ + public const string Version = "native-picture-positions-v1"; + public const int MaxFrameCharacters = 2 * 1024 * 1024; + public static int Span(ChapterParagraph paragraph) => paragraph.WordLength == 0 ? paragraph.Length : paragraph.WordLength; + + public static void ValidateRows(ChapterParagraph[] rows) + { + if (rows.Length == 0 || rows.Length > ChapterFingerprint.MaxParagraphs || rows.Any(p => p == null || p.WordLength <= 0 || p.Length <= 0 || p.WordLength > ChapterFingerprint.MaxCharacters || WordParagraphIdentity.Normalise(p.NativeId) != p.NativeId || p.Outline < 1 || p.Outline > 10 || p.Anchors == null || p.Anchors.Length > 256 || p.WordLength - p.Length != p.Anchors.Length) || rows.Sum(p => (long)p.WordLength) > ChapterFingerprint.MaxCharacters) + throw new ArgumentException("Native Word spans require complete text lengths and explicit picture anchor evidence."); + if(rows.Sum(p=>(long)p.Anchors.Length)>4096)throw new ArgumentException("More than 4096 native picture anchors in one chapter exceeds the bounded position reader."); + var shapes = new HashSet(); + foreach (var row in rows) + { + var previous = -1; + foreach (var anchor in row.Anchors) + { + if (anchor == null || anchor.Offset <= previous || anchor.Offset >= row.WordLength || anchor.ShapeId <= 0 || !shapes.Add(anchor.ShapeId) || anchor.ShapeType is not (11 or 13)) + throw new ArgumentException("Native picture anchors must be ordered, unique, in range and supported floating pictures."); + previous = anchor.Offset; + } + } + } + + // Content/identity v1 remain unchanged. Geometry has its own digest so the + // existing text/identity checkpoints do not acquire different identities. + public static string Hash(ChapterParagraph[] rows) + { + ValidateRows(rows); + using var buffer = new MemoryStream(); + using (var writer = new BinaryWriter(buffer, Encoding.UTF8, true)) + { + writer.Write(Version); writer.Write(rows.Length); + foreach (var row in rows) + { + writer.Write(row.NativeId); writer.Write(row.Length); writer.Write(row.Outline); writer.Write(row.WordLength); writer.Write(row.Anchors.Length); + foreach (var anchor in row.Anchors) { writer.Write(anchor.Offset); writer.Write(anchor.ShapeId); writer.Write(anchor.ShapeType); } + } + } + using var sha = SHA256.Create(); + return BitConverter.ToString(sha.ComputeHash(buffer.ToArray())).Replace("-", ""); + } + + public static void Validate(ChapterParagraph[] rows, int start, int end, string? hash) + { + if (rows == null || rows.Length == 0 || rows.Any(p => p == null || p.Anchors == null) || start < 0 || end <= start) + throw new ArgumentException("Incomplete native chapter positions."); + var physical = rows.Any(p => p.WordLength != 0 || p.Anchors.Length != 0); + if (physical ? string.IsNullOrEmpty(hash) || Hash(rows) != hash : !string.IsNullOrEmpty(hash)) + throw new ArgumentException("Native Word position digest is missing or inconsistent."); + if (rows.Sum(p => (long)Span(p)) != (long)end - start) + throw new ArgumentException("Native paragraph spans do not cover the chapter's Word positions."); + } + + private static DataContractJsonSerializer Serializer() => new(typeof(ChapterParagraph[]), new DataContractJsonSerializerSettings { MaxItemsInObjectGraph = 500000 }); + public static string Encode(ChapterParagraph[] rows) + { + ValidateRows(rows); + if (rows.Any(p => p.Text != null)) throw new ArgumentException("Position frames contain metadata only."); + using var buffer = new MemoryStream(); Serializer().WriteObject(buffer, rows); + var result = Encoding.UTF8.GetString(buffer.ToArray()); + if (result.Length > MaxFrameCharacters) throw new ArgumentException("Native position evidence exceeds the bounded transport."); + return result; + } + public static ChapterParagraph[] Decode(string frames) + { + if (frames.Length > MaxFrameCharacters) throw new ArgumentException("Native position evidence exceeds the bounded transport."); + try + { + using var buffer = new MemoryStream(Encoding.UTF8.GetBytes(frames)); + var rows = (ChapterParagraph[]?)Serializer().ReadObject(buffer) ?? throw new ArgumentException("Missing native position evidence."); + ValidateRows(rows); + if (rows.Any(p => p.Text != null)) throw new ArgumentException("Position frames contain metadata only."); + return rows; + } + catch (SerializationException) { throw new ArgumentException("Malformed native position evidence."); } + } +} diff --git a/PlotDirector.NativeCompanion/Protocol/Messages.cs b/PlotDirector.NativeCompanion/Protocol/Messages.cs index a2b8fce5..1654875b 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 NativeChapterPositionsCapability="chapter-native-positions-v1"; public const string NativeChapterTextCapability="chapter-native-text-v1"; public const string ChapterSyncCapability="chapter-sync-v1"; public const string ParagraphCapability="paragraph-snapshots-v1"; diff --git a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs index ac414ef1..5f1523b5 100644 --- a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs +++ b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs @@ -4,6 +4,7 @@ namespace PlotDirector.Companion.Protocol; public sealed class AdapterCommand { [DataMember] public Guid OperationId {get;set;} + [DataMember] public bool NativeChapterPositions {get;set;} [DataMember] public bool ParagraphTracking {get;set;} [DataMember] public long BaseRevision {get;set;} [DataMember] public string BaseSnapshotHash {get;set;}=""; diff --git a/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs b/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs index 99ce1dc3..3cf2f8f0 100644 --- a/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs +++ b/PlotDirector.NativeCompanion/Tests/ChapterAgentTests.cs @@ -10,13 +10,14 @@ 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);tray.Attach(instance,lease,capture:true,paragraphs:true,chapters:true); + sessions.Attach(instance,lease,chapters:true,nativeChapterText:true,nativeChapterPositions: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); try{ AdapterCommand? command=null;for(int n=0;n<200&&command==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")command=pending;await Task.Delay(20);} Check(command?.Kind=="chapter-check","Reopened chapter-capable document requests a bounded current-chapter read, never a full snapshot"); + Check(tray.ChapterProgressForDisplay(session)?.Message=="0 of 1 chapters accepted","Checking progress reports committed acceptances, never a queued chapter number"); var text="Chapter 1\rExact prose\r";var xml="Chapter 1Exact prose"; void Frames(AdapterCommand read,bool exact=false){Send(new(){Kind="chapter-begin",SnapshotId=read.Id,BookId=3,Start=0,End=text.Length,DocumentEnd=text.Length,WordSaved=true});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="text",Start=0,OperationMessage=text});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="xml",Start=0,OperationMessage=xml});if(exact){var evidence=ChapterFingerprint.ReadXml(xml,text);Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="ids-exact",Start=0,OperationMessage=string.Concat(evidence.Select(p=>p.NativeId+p.Length.ToString("X8")))});}Send(new(){Kind="chapter-end",SnapshotId=read.Id});} Frames(command!);await Until(()=>handler.Validations>0);await Until(()=>handler.Finishes>0); @@ -39,6 +40,32 @@ internal static class ChapterAgentTests await Until(() => tray.ChapterProgressForDisplay(session)?.State == "Needs review"); Check(tray.ChapterProgressForDisplay(session)!.Message.Contains("native chapter identities"), "Unindexed legacy identity displays actionable review instead of a zero-count scan"); Check(Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command?.Kind != "chapter-check" && handler.Validations == before, "No automatic chapter read is queued when every legacy heading lacks a native ID"); + handler.LegacyManifest=false;handler.NativeGap=true; + session=Guid.NewGuid();Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Native picture span fixture.docx"}]}); + tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}); + AdapterCommand? physicalRead=null;for(int n=0;n<200&&physicalRead==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")physicalRead=pending;await Task.Delay(20);} + Check(physicalRead?.NativeChapterPositions==true,"Native geometry reading is enabled only by the server manifest's support"); + var nativeRows=new[]{new ChapterParagraph{NativeId="00000001",Length=10,WordLength=10,Outline=1},new ChapterParagraph{NativeId="00000002",Length=12,WordLength=13,Outline=10,Anchors=[new(){Offset=0,ShapeId=59,ShapeType=13}]}}; + Send(new(){Kind="chapter-begin",SnapshotId=physicalRead!.Id,BookId=3,Start=0,End=23,DocumentEnd=23,WordSaved=true}); + Send(new(){Kind="chapter-chunk",SnapshotId=physicalRead.Id,Action="text",Start=0,OperationMessage=text}); + Send(new(){Kind="chapter-chunk",SnapshotId=physicalRead.Id,Action="xml",Start=0,OperationMessage=xml.Replace("Exact prose","Exact prose")}); + Send(new(){Kind="chapter-chunk",SnapshotId=physicalRead.Id,Action="positions",Start=0,OperationMessage=ChapterWordPositions.Encode(nativeRows)}); + Send(new(){Kind="chapter-end",SnapshotId=physicalRead.Id}); + await Until(()=>tray.ChapterProgressForDisplay(session)?.State=="Synchronised"); + var physicalProof=JsonSerializer.Deserialize(handler.Bodies.Last(),new JsonSerializerOptions(JsonSerializerDefaults.Web))!; + Check(physicalProof.End==23&&physicalProof.Paragraphs.Sum(p=>p.Length)==22&&physicalProof.PositionHash==ChapterWordPositions.Hash(physicalProof.Paragraphs)&&physicalProof.Paragraphs.All(p=>p.Text==null),"Agent preserves native Word spans, exact text lengths and geometry hash without uploading unchanged prose"); + handler.NativeGap=false;handler.StructuralFailure=true; + session=Guid.NewGuid();Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="One structural chapter under review.docx"}]}); + tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=22,End=22,WordSaved=true}); + AdapterCommand? unsupportedRead=null;for(int n=0;n<200&&unsupportedRead==null;n++){var pending=Send(new(){Kind="selection",Start=22,End=22,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")unsupportedRead=pending;await Task.Delay(20);} + Check(unsupportedRead?.Chapter?.Start==22&&tray.ChapterProgressForDisplay(session)?.Matching==1,"Structural review starts with the other chapter already durably accepted"); + var beforeUnsupported=handler.Validations; + Send(new(){Kind="chapter-begin",SnapshotId=unsupportedRead!.Id,BookId=3,Start=22,End=45,DocumentEnd=45,WordSaved=true}); + Send(new(){Kind="adapter-result",SnapshotId=unsupportedRead.Id,OperationMessage="Unsupported floating shape type 6 at Word position 22."}); + await Until(()=>tray.ChapterProgressForDisplay(session)?.State=="Needs review"); + Check(tray.ChapterProgressForDisplay(session)?.Matching==1&&tray.ChapterProgressForDisplay(session)!.Message.Contains("shape type 6")&&handler.Validations==beforeUnsupported,"Unsupported final structure completes under review without rereading or revoking the accepted chapter"); + Check(Send(new(){Kind="selection",Start=22,End=22,WordSaved=true}).Command?.Kind!="chapter-check","Stationary observations do not restart an unsupported structural chapter"); + handler.StructuralFailure=false; handler.LegacyManifest = false; handler.RejectValidation = true; session = Guid.NewGuid(); Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Rejected chapter fixture.docx"}]}); @@ -54,21 +81,24 @@ internal static class ChapterAgentTests 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"); 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"}]}); + Check(Legacy(new(){Kind="chapter-chunk",SnapshotId=Guid.NewGuid(),Action="positions",OperationMessage="[]"}).Status=="invalid-chapter-frame","Native physical position evidence requires its separately negotiated capability"); }finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}} } private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);} private static async Task Until(Func condition){for(int i=0;i<300;i++){if(condition())return;await Task.Delay(30);}throw new Exception("Chapter test timed out");} private sealed class Handler:HttpMessageHandler { - public Guid Manuscript;public bool LegacyManifest,RejectValidation;public int Validations,Finishes;public List Bodies=[];public List Paths=[]; + public Guid Manuscript;public bool LegacyManifest,RejectValidation,NativeGap,StructuralFailure;public int Validations,Finishes;public List Bodies=[];public List Paths=[]; protected override async Task SendAsync(HttpRequestMessage request,CancellationToken cancel) { var path=request.RequestUri!.AbsolutePath;Paths.Add(path);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 value=await request.Content!.ReadFromJsonAsync(cancel);value!.ChapterSyncSupported=true;value.ParagraphRevision=1;return Json(value);} - if(path.EndsWith("/chapter-sync"))return Json(new ChapterManifest{BookId=3,ManuscriptId=Manuscript,Revision=1,Chapters=[new(){ChapterId=10,HeadingNativeId=LegacyManifest?"":"00000001",ContentHash=ChapterFingerprint.Content(["Chapter 1\r","Exact prose\r"]),Start=0,End=22,ParagraphCount=2}]}); + if(path.EndsWith("/chapter-sync")&&StructuralFailure)return Json(new ChapterManifest{NativePositionsSupported=true,BookId=3,ManuscriptId=Manuscript,Revision=1,Chapters=[new(){ChapterId=10,HeadingNativeId="00000001",Start=0,End=22,State="Synchronised"},new(){ChapterId=11,HeadingNativeId="00000003",Start=22,End=45}]}); + if(path.EndsWith("/chapter-sync"))return Json(new ChapterManifest{NativePositionsSupported=true,BookId=3,ManuscriptId=Manuscript,Revision=1,Chapters=[new(){ChapterId=10,HeadingNativeId=LegacyManifest?"":"00000001",ContentHash=ChapterFingerprint.Content(["Chapter 1\r","Exact prose\r"]),Start=0,End=NativeGap?23:22,ParagraphCount=2}]}); if(path.EndsWith("/validate")){var body=await request.Content!.ReadAsStringAsync(cancel);Bodies.Add(body);Validations++;if(RejectValidation)return Json(new ChapterSyncReply{State="Failed",ChapterId=10,Revision=1,Message="Synthetic storage refusal: retry the chapter."});return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",ChapterId=10,Revision=1,Message="Chapter accepted."});} - if(path.EndsWith("/finish")){Finishes++;if(RejectValidation)return Json(new ChapterSyncProgress{Total=1,Matching=0,State="Needs review",Message="No chapters accepted."});return Json(new ChapterSyncProgress{Total=1,Checked=1,Matching=1,State="Synchronised",Message="All chapters accepted."});} + if(path.EndsWith("/finish")){Finishes++;if(StructuralFailure)return Json(new ChapterSyncProgress{Total=2,Matching=1,State="Needs review",Message="One chapter accepted."});if(RejectValidation)return Json(new ChapterSyncProgress{Total=1,Matching=0,State="Needs review",Message="No chapters accepted."});return Json(new ChapterSyncProgress{Total=1,Checked=1,Matching=1,State="Synchronised",Message="All chapters accepted."});} return Json(new{}); } } diff --git a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs index 1246c4eb..d8a9ab83 100644 --- a/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs +++ b/PlotDirector.NativeCompanion/Vsto/NativeRibbon.cs @@ -35,7 +35,8 @@ namespace PlotDirector.WordAddIn { Refresh("PlotDirectorStatus", GetStatus(null)); Refresh("PlotDirectorBook", GetBookTip(null)); - Refresh("PlotDirectorLocation", GetLocationTip(null)); + Refresh("PlotDirectorChapter", GetChapterTip(null)); + Refresh("PlotDirectorScene", GetSceneTip(null)); Refresh("PlotDirectorSyncStatus", GetSyncStatus(null) + "\n" + GetSyncTip(null)); Refresh("PlotDirectorSyncProgress", GetSyncProgress(null)); var enabled = CanOpenBook(null).ToString(); @@ -58,10 +59,12 @@ namespace PlotDirector.WordAddIn text.Length <= limit ? text : text.Substring(0, limit - (char.IsHighSurrogate(text[limit - 1]) ? 1 : 0)) + "…"; public bool CanOpenBook(Office.IRibbonControl control) => adapter()?.HasRibbonBook == true; - public string GetBook(Office.IRibbonControl control) => ShortLabel(GetBookTip(control), 25); + public string GetBook(Office.IRibbonControl control) => ShortLabel(GetBookTip(control), 40); public string GetBookTip(Office.IRibbonControl control) => adapter()?.RibbonBook ?? "No linked book"; - public string GetLocation(Office.IRibbonControl control) => ShortLabel(GetLocationTip(control), 32); - public string GetLocationTip(Office.IRibbonControl control) => adapter()?.RibbonLocation ?? "Location unavailable"; + public string GetChapter(Office.IRibbonControl control) => ShortLabel(GetChapterTip(control), 64); + public string GetChapterTip(Office.IRibbonControl control) => adapter()?.RibbonChapter ?? "Chapter unverified"; + public string GetScene(Office.IRibbonControl control) => ShortLabel(GetSceneTip(control), 64); + public string GetSceneTip(Office.IRibbonControl control) => adapter()?.RibbonScene ?? "Scene unverified"; public string GetSyncStatus(Office.IRibbonControl control) => adapter()?.ChapterStatusLabel ?? "Not connected"; public string GetSyncProgress(Office.IRibbonControl control) => adapter()?.RibbonSyncProgress ?? " "; public string GetSyncTip(Office.IRibbonControl control) => adapter()?.ChapterStatusTip ?? "Open Companion to connect."; diff --git a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj index adc4b5eb..bc439f1b 100644 --- a/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj +++ b/PlotDirector.NativeCompanion/Vsto/PlotDirector.WordAddIn.csproj @@ -23,7 +23,8 @@ PlotDirector.Companion.Protocol PlotDirector.Companion.Client ThisAddIn.cs - + + ThisAddIn.cs diff --git a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs index 6ce88fb2..60c279bc 100644 --- a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs +++ b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs @@ -3,6 +3,6 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("PlotDirector Word Companion — Native development")] [assembly: AssemblyCompany("Nick Beckley")] [assembly: AssemblyProduct("PlotDirector")] -[assembly: AssemblyVersion("1.0.0.27")] -[assembly: AssemblyFileVersion("1.0.0.27")] +[assembly: AssemblyVersion("1.0.0.28")] +[assembly: AssemblyFileVersion("1.0.0.28")] [assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml index 54131c3b..d7f4eb67 100644 --- a/PlotDirector.NativeCompanion/Vsto/Ribbon.xml +++ b/PlotDirector.NativeCompanion/Vsto/Ribbon.xml @@ -4,7 +4,8 @@ - + +