Preserve native Word picture positions and refine accepted sync progress
This commit is contained in:
parent
c6bde4561f
commit
9fed339879
@ -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 '<verified 1.0.0.28 developer package>' `
|
||||
-ExpectedSourceCommit '<exact clean package source SHA>' `
|
||||
-OutputDirectory '<new 1.0.0.28 setup output directory>' `
|
||||
-CertificateThumbprint '<existing developer signing identity>'
|
||||
```
|
||||
|
||||
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.
|
||||
@ -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));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},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));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);
|
||||
log?.Invoke("peer-connected");
|
||||
while (!cancellation.IsCancellationRequested)
|
||||
{
|
||||
|
||||
@ -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)
|
||||
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.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"))))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.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");
|
||||
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<Guid,DocumentState> Documents = []; }
|
||||
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 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 = []; }
|
||||
}
|
||||
|
||||
@ -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;count<work.Manifest.Chapters.Length+1;count++){
|
||||
if(work.Wrapped&&next==work.FirstStart){CompleteChapters(doc,work);return;}
|
||||
@ -167,19 +179,20 @@ public sealed partial class TrayCoordinator
|
||||
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;}}}
|
||||
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();}
|
||||
}
|
||||
|
||||
@ -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");
|
||||
|
||||
@ -1 +1 @@
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.27</ApplicationVersion></PropertyGroup></Project>
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.28</ApplicationVersion></PropertyGroup></Project>
|
||||
|
||||
@ -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<ChapterPictureAnchor>();
|
||||
[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<ChapterParagraph>();
|
||||
@ -57,17 +60,25 @@ public static class ChapterFingerprint
|
||||
public static string Mapping(IEnumerable<string> 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<XName>(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<string>();
|
||||
@ -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;i<rows.Length;i++)
|
||||
{
|
||||
var native=nativePositions[i];
|
||||
if(native.Outline!=rows[i].Outline||native.Length!=rows[i].Length)throw new ArgumentException("Native paragraph outline/text evidence differs from XML.");
|
||||
rows[i].WordLength=native.WordLength;rows[i].Anchors=native.Anchors;
|
||||
}
|
||||
}
|
||||
Identity(rows);Content(rows.Select(p=>p.Text!));return rows;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ChapterManifest
|
||||
{
|
||||
public int BookId{get;set;}public Guid ManuscriptId{get;set;}public long Revision{get;set;}public string Mode{get;set;}="Manual";public ChapterManifestItem[] Chapters{get;set;}=Array.Empty<ChapterManifestItem>();
|
||||
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<ChapterManifestItem>();
|
||||
}
|
||||
public sealed class ChapterManifestItem
|
||||
{
|
||||
|
||||
@ -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<int>();
|
||||
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."); }
|
||||
}
|
||||
}
|
||||
@ -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";
|
||||
|
||||
@ -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;}="";
|
||||
|
||||
@ -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="<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);
|
||||
@ -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("<w:t>Exact prose</w:t>","<w:drawing/><w:t>Exact prose</w:t>")});
|
||||
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<ChapterObservation>(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<bool> 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<string> Bodies=[];public List<string> Paths=[];
|
||||
public Guid Manuscript;public bool LegacyManifest,RejectValidation,NativeGap,StructuralFailure;public int Validations,Finishes;public List<string> Bodies=[];public List<string> Paths=[];
|
||||
protected override async Task<HttpResponseMessage> 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<NativePresence>(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{});
|
||||
}
|
||||
}
|
||||
|
||||
@ -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.";
|
||||
|
||||
@ -23,7 +23,8 @@
|
||||
<ProjectReference Include="..\Protocol\PlotDirector.Companion.Protocol.csproj"><Name>PlotDirector.Companion.Protocol</Name></ProjectReference>
|
||||
<ProjectReference Include="..\Client\PlotDirector.Companion.Client.csproj"><Name>PlotDirector.Companion.Client</Name></ProjectReference>
|
||||
<Compile Include="ThisAddIn.cs" /><Compile Include="ThisAddIn.Designer.cs"><DependentUpon>ThisAddIn.cs</DependentUpon></Compile>
|
||||
<Compile Include="WordAdapter.cs" /><Compile Include="WordChapterRead.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="WordAdapter.cs" /><Compile Include="WordChapterRead.cs" />
|
||||
<Compile Include="WordChapterPositions.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<None Include="ThisAddIn.Designer.xml"><DependentUpon>ThisAddIn.cs</DependentUpon></None>
|
||||
<EmbeddedResource Include="Ribbon.xml" />
|
||||
</ItemGroup>
|
||||
|
||||
@ -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)]
|
||||
|
||||
@ -4,7 +4,8 @@
|
||||
<tab id="PlotDirectorTab" label="PlotDirector">
|
||||
<group id="PlotDirectorManuscript" label="Manuscript">
|
||||
<labelControl id="PlotDirectorBook" getLabel="GetBook" getSupertip="GetBookTip" />
|
||||
<labelControl id="PlotDirectorLocation" getLabel="GetLocation" getSupertip="GetLocationTip" />
|
||||
<labelControl id="PlotDirectorChapter" getLabel="GetChapter" getSupertip="GetChapterTip" />
|
||||
<labelControl id="PlotDirectorScene" getLabel="GetScene" getSupertip="GetSceneTip" />
|
||||
</group>
|
||||
<group id="PlotDirectorWriting" label="Writing">
|
||||
<button id="PlotDirectorContext" label="Writing Context" size="large" imageMso="ReadingMode" onAction="OpenContext" getEnabled="CanOpenBook" />
|
||||
@ -14,12 +15,12 @@
|
||||
<button id="PlotDirectorSyncStatus" getLabel="GetSyncStatus" getSupertip="GetSyncTip" imageMso="FileDocumentInspect" onAction="Troubleshooting" />
|
||||
<labelControl id="PlotDirectorSyncProgress" getLabel="GetSyncProgress" />
|
||||
<button id="PlotDirectorSynchronise" label="Synchronise" imageMso="RefreshAll" onAction="Synchronise" getEnabled="CanOpenBook" supertip="Check this manuscript using the existing chapter synchronisation workflow." />
|
||||
<button id="PlotDirectorRepair" label="Repair Synchronisation" onAction="Repair" getEnabled="CanOpenBook" supertip="Validate or repair the existing import while preserving existing chapters, scenes and author decisions." />
|
||||
</group>
|
||||
<group id="PlotDirectorConnection" label="Connection">
|
||||
<labelControl id="PlotDirectorStatus" getLabel="GetStatus" />
|
||||
<button id="PlotDirectorOpen" label="Open Companion" imageMso="FileOpen" onAction="OpenCompanion" />
|
||||
<button id="PlotDirectorOpen" label="Open Companion" imageMso="WindowNew" onAction="OpenCompanion" />
|
||||
<menu id="PlotDirectorTools" label="Tools">
|
||||
<button id="PlotDirectorRepair" label="Repair Synchronisation" onAction="Repair" getEnabled="CanOpenBook" supertip="Validate or repair the existing import while preserving existing chapters, scenes and author decisions." />
|
||||
<button id="PlotDirectorRemoveLegacyMarkers" label="Remove Legacy Markers" onAction="RemoveLegacyMarkers" supertip="Remove old PlotDirector chapter and scene anchors while keeping the manuscript and its identity." />
|
||||
<button id="PlotDirectorTroubleshooting" label="Troubleshooting" onAction="Troubleshooting" supertip="Inspect advanced Word connection, navigation and synchronisation diagnostics." />
|
||||
</menu>
|
||||
|
||||
@ -75,7 +75,7 @@ namespace PlotDirector.WordAddIn
|
||||
link.StateChanged += state => PostToUi(() => {
|
||||
ConnectionState = state;
|
||||
if(state!="connected")
|
||||
{traySupported=false;nativeChapterTextSupported=false;
|
||||
{traySupported=false;nativeChapterTextSupported=false;nativeChapterPositionsSupported=false;
|
||||
foreach(var doc in documents.Values){StopAi(doc,"Agent disconnected. Successful AI suggestions retained; reconnect before retrying.");}
|
||||
}
|
||||
if (state == "connected")
|
||||
@ -86,7 +86,7 @@ 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);});
|
||||
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.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;});
|
||||
|
||||
98
PlotDirector.NativeCompanion/Vsto/WordChapterPositions.cs
Normal file
98
PlotDirector.NativeCompanion/Vsto/WordChapterPositions.cs
Normal file
@ -0,0 +1,98 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
using Word = Microsoft.Office.Interop.Word;
|
||||
|
||||
namespace PlotDirector.WordAddIn
|
||||
{
|
||||
public sealed partial class WordAdapter
|
||||
{
|
||||
// All COM access stays on the Word STA. One shape or text segment is
|
||||
// measured per scheduler turn; no document, layout or selection is changed.
|
||||
private void ReadChapterPictureAnchor(LocalDocument doc, ChapterRead read)
|
||||
{
|
||||
Word.Range paragraph = null, anchor = null, unit = null;
|
||||
Word.ShapeRange shapes = null; Word.Shape shape = null; Word.TextRetrievalMode mode = null;
|
||||
try
|
||||
{
|
||||
paragraph = Com(() => doc.Document.Range(read.PendingStart, read.PendingEnd));
|
||||
shapes = Com(() => paragraph.ShapeRange, "chapter-picture-anchors");
|
||||
var count = Com(() => shapes.Count);
|
||||
if (count > 256) throw new InvalidOperationException("More than 256 floating shapes in one paragraph; review this structural range before retrying.");
|
||||
if (read.ShapeIndex > count)
|
||||
{
|
||||
if (read.PendingAnchors.Count != read.PendingPosition.WordLength - read.PendingPosition.Length)
|
||||
throw new InvalidOperationException("Unaccounted Word positions in paragraph at " + read.PendingStart + ": span " + read.PendingPosition.WordLength + ", text units " + read.PendingPosition.Length + ", verified picture anchors " + read.PendingAnchors.Count + ". Other structural content requires review.");
|
||||
read.PendingPosition.Anchors = read.PendingAnchors.OrderBy(p => p.Key).Select(p => p.Value).ToArray();
|
||||
read.SegmentPosition = read.PendingStart; read.SegmentAnchor = 0; read.SegmentText.Clear(); read.Phase = 10;
|
||||
return;
|
||||
}
|
||||
object index = read.ShapeIndex++;
|
||||
shape = Com(() => shapes.get_Item(ref index));
|
||||
anchor = Com(() => shape.Anchor);
|
||||
if (Com(() => anchor.StoryType) != Word.WdStoryType.wdMainTextStory) return;
|
||||
var at = Com(() => anchor.Start);
|
||||
if (at < read.PendingStart || at >= read.PendingEnd) return;
|
||||
unit = Com(() => doc.Document.Range(at, at + 1));
|
||||
if ((Com(() => unit.Text) ?? "").Length != 0) return;
|
||||
// Empty must not mean hidden manuscript text or hidden field codes.
|
||||
mode = Com(() => unit.TextRetrievalMode);
|
||||
Com(() => { mode.IncludeHiddenText = true; mode.IncludeFieldCodes = true; return true; });
|
||||
if ((Com(() => unit.Text) ?? "").Length != 0)
|
||||
throw new InvalidOperationException("Hidden text/field content at Word position " + at + " cannot certify an empty picture anchor.");
|
||||
var type = (int)Com(() => shape.Type);
|
||||
if (type != 11 && type != 13)
|
||||
throw new InvalidOperationException("Unsupported floating shape type " + type + " at Word position " + at + "; only measured picture anchors can account for empty positions.");
|
||||
if (!read.PendingAnchors.ContainsKey(at - read.PendingStart))
|
||||
read.PendingAnchors.Add(at - read.PendingStart, new ChapterPictureAnchor { Offset = at - read.PendingStart, ShapeId = Com(() => shape.ID), ShapeType = type });
|
||||
}
|
||||
catch (COMException error)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot measure native floating picture anchors in paragraph at " + read.PendingStart + " (COM 0x" + error.HResult.ToString("X8") + "). Existing mappings are retained.", error);
|
||||
}
|
||||
finally { Release(mode); Release(unit); Release(anchor); Release(shape); Release(shapes); Release(paragraph); }
|
||||
}
|
||||
|
||||
private void ReadChapterPositionSegment(LocalDocument doc, ChapterRead read)
|
||||
{
|
||||
var anchors = read.PendingPosition.Anchors;
|
||||
var end = read.SegmentAnchor < anchors.Length ? read.PendingStart + anchors[read.SegmentAnchor].Offset : read.PendingEnd;
|
||||
Word.Range segment = null;
|
||||
try
|
||||
{
|
||||
if (end > read.SegmentPosition)
|
||||
{
|
||||
segment = Com(() => doc.Document.Range(read.SegmentPosition, end));
|
||||
var text = Com(() => segment.Text, "chapter-position-segment") ?? "";
|
||||
if (text.Length != end - read.SegmentPosition)
|
||||
throw new InvalidOperationException("Unaccounted structural position between " + read.SegmentPosition + " and " + end + "; native picture evidence does not explain this text span.");
|
||||
read.SegmentText.Append(text); read.SegmentPosition = end;
|
||||
}
|
||||
if (read.SegmentAnchor < anchors.Length)
|
||||
{
|
||||
// Skip only the exact one-position range independently proven
|
||||
// empty and anchored to a genuine native floating picture.
|
||||
read.SegmentPosition++; read.SegmentAnchor++; return;
|
||||
}
|
||||
if (read.SegmentText.ToString() != read.PendingText)
|
||||
throw new InvalidOperationException("Measured native text segments do not equal the paragraph text; no position was inferred.");
|
||||
CompleteChapterNativeParagraph(read, read.PendingPosition, read.PendingText, read.PendingEnd);
|
||||
}
|
||||
finally { Release(segment); }
|
||||
}
|
||||
|
||||
private void CompleteChapterNativeParagraph(ChapterRead read, ChapterParagraph evidence, string text, int end)
|
||||
{
|
||||
read.NativePositions.Add(evidence); read.NativeText.Append(text);
|
||||
read.Identities.Append(evidence.NativeId).Append(evidence.Length.ToString("X8", System.Globalization.CultureInfo.InvariantCulture));
|
||||
read.IdentityPosition = end; read.Phase = 7;
|
||||
if (end != read.End) return;
|
||||
if (read.NativeText.ToString() != read.Text)
|
||||
throw new InvalidOperationException("Native paragraph text does not equal the complete chapter range; retry after saving Word.");
|
||||
var rows = read.NativePositions.ToArray();
|
||||
ChapterWordPositions.Validate(rows, read.Start, read.End, ChapterWordPositions.Hash(rows));
|
||||
read.IdentityFrames = ChapterWordPositions.Encode(rows); read.Phase = 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -11,7 +11,7 @@ namespace PlotDirector.WordAddIn
|
||||
private string serverBook = "", serverChapter = "", serverScene = "";
|
||||
private int serverBookId;
|
||||
private long serverRevision = -1;
|
||||
private bool nativeChapterTextSupported;
|
||||
private bool nativeChapterTextSupported,nativeChapterPositionsSupported;
|
||||
private ChapterSyncProgress serverChapterProgress;
|
||||
|
||||
public bool HasRibbonBook => active != null && ConnectionState == "connected" && serverBookId > 0 && serverChapterProgress?.State != "Sign-in required";
|
||||
@ -22,6 +22,9 @@ namespace PlotDirector.WordAddIn
|
||||
? (serverChapter.Length == 0 ? serverScene : serverChapter + " · " + serverScene)
|
||||
: "Location unverified";
|
||||
|
||||
public string RibbonChapter => HasCurrentRibbonState && serverChapter.Length > 0 ? serverChapter : "Chapter unverified";
|
||||
public string RibbonScene => HasCurrentRibbonState && serverScene.Length > 0 ? serverScene : "Scene unverified";
|
||||
|
||||
public string ChapterStatusLabel
|
||||
{
|
||||
get
|
||||
@ -45,9 +48,10 @@ namespace PlotDirector.WordAddIn
|
||||
}
|
||||
}
|
||||
|
||||
public string RibbonSyncProgress => ChapterStatusLabel == "Synchronising" && serverChapterProgress.Total > 0
|
||||
? serverChapterProgress.Message
|
||||
: ChapterStatusLabel == "Review needed" ? "See status tooltip" : " ";
|
||||
public string RibbonSyncProgress => HasCurrentRibbonState && serverChapterProgress?.Total > 0
|
||||
? ChapterStatusLabel == "Up to date" ? serverChapterProgress.Total + " chapters verified"
|
||||
: serverChapterProgress.Matching + " of " + serverChapterProgress.Total + " chapters accepted"
|
||||
: ChapterStatusLabel == "Review needed" ? "See Companion diagnostics" : " ";
|
||||
public string ChapterStatusTip => (HasCurrentRibbonState || serverChapterProgress?.State == "Sign-in required" ? serverChapterProgress?.Message : null)
|
||||
?? "Synchronise to verify the manuscript position.";
|
||||
|
||||
@ -101,7 +105,11 @@ 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; public readonly System.Text.StringBuilder NativeText = new System.Text.StringBuilder();
|
||||
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 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>();
|
||||
public readonly System.Text.StringBuilder SegmentText=new System.Text.StringBuilder(); public readonly System.Text.StringBuilder NativeText = new System.Text.StringBuilder();
|
||||
}
|
||||
private readonly Dictionary<Guid,ChapterRead> chapterReads=new Dictionary<Guid,ChapterRead>();
|
||||
private void CancelChapterRead(LocalDocument doc){chapterReads.Remove(doc.Session);scheduler.Cancel("chapter:"+doc.Session);}
|
||||
@ -126,7 +134,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)&&(!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)&&(!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);
|
||||
@ -152,13 +160,17 @@ namespace PlotDirector.WordAddIn
|
||||
if(read.End<=read.Start||read.End-read.Start>ChapterFingerprint.MaxCharacters)throw new InvalidOperationException("This chapter exceeds the bounded fast reader. Use bounded manuscript synchronisation; no mapping was guessed.");
|
||||
if(!read.Begun){if(!link.TryPost(new Message{Kind="chapter-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,OperationId=read.Command.OperationId,BookId=read.Command.BookId,DocumentEnd=doc.End,Start=read.Start,End=read.End,WordSaved=true,ChapterTitle=read.NextId}))return;read.Begun=true;}
|
||||
range=Com(()=>doc.Document.Range(read.Start,read.End));read.Text=Com(()=>range.Text,"chapter-range-text")??"";
|
||||
if(read.Text.Length!=read.End-read.Start)throw new InvalidOperationException("Word range length contains unsupported structural content; positions were not guessed.");read.Phase=3;
|
||||
if(read.Text.Length>read.End-read.Start)throw new InvalidOperationException("Word range text exceeds its native positions at "+read.Start+"; this structural expansion requires review.");
|
||||
read.PhysicalPositions=read.Text.Length!=read.End-read.Start;
|
||||
if(read.PhysicalPositions&&(!nativeChapterPositionsSupported||!read.Command.NativeChapterPositions))
|
||||
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")??"";
|
||||
if(read.Xml.Length>8*1024*1024)throw new InvalidOperationException("Chapter XML exceeds the bounded transport. Use existing bounded synchronisation.");
|
||||
// Only drawings need the more expensive direct paragraph text fallback.
|
||||
// Drawings, native position gaps and measured breaks need direct paragraph text.
|
||||
// A lexical false positive merely performs extra verification.
|
||||
read.NativeTextRequired=read.Xml.IndexOf(":drawing",StringComparison.Ordinal)>=0||read.Xml.IndexOf("<drawing",StringComparison.Ordinal)>=0;
|
||||
read.NativeTextRequired=read.PhysicalPositions||read.Text.IndexOf('\f')>=0||read.Xml.IndexOf(":drawing",StringComparison.Ordinal)>=0||read.Xml.IndexOf("<drawing",StringComparison.Ordinal)>=0;
|
||||
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){
|
||||
@ -168,6 +180,15 @@ namespace PlotDirector.WordAddIn
|
||||
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)
|
||||
throw new InvalidOperationException("Live Word paragraph boundaries do not match the chapter.");
|
||||
if(read.PhysicalPositions)
|
||||
{
|
||||
var nativeText=Com(()=>range.Text,"chapter-native-paragraph-text")??"";
|
||||
var evidence=new ChapterParagraph{NativeId=ReadLiveParagraphId(paragraph),Length=nativeText.Length,WordLength=end-start,Outline=(int)Com(()=>paragraph.OutlineLevel)};
|
||||
if(nativeText.Length<=0||nativeText.Length>end-start)throw new InvalidOperationException("Unsupported native paragraph text at Word position "+start+": span "+(end-start)+", text units "+nativeText.Length+".");
|
||||
if(nativeText.Length==end-start)CompleteChapterNativeParagraph(read,evidence,nativeText,end);
|
||||
else{read.PendingStart=start;read.PendingEnd=end;read.PendingText=nativeText;read.PendingPosition=evidence;read.PendingAnchors.Clear();read.ShapeIndex=1;read.Phase=9;}
|
||||
return;
|
||||
}
|
||||
if(read.NativeTextRequired)
|
||||
{
|
||||
var nativeText=Com(()=>range.Text,"chapter-native-paragraph-text")??"";
|
||||
@ -178,17 +199,19 @@ namespace PlotDirector.WordAddIn
|
||||
read.Identities.Append((end-start).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);
|
||||
}else if(read.Phase==10){ReadChapterPositionSegment(doc,read);
|
||||
}else{
|
||||
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.NativeTextRequired?"ids-exact":"ids",Start=read.Offset,OperationMessage=source.Substring(read.Offset,count)}))return;read.Offset+=count;}
|
||||
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;}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(Exception error)when(error is System.Runtime.InteropServices.COMException||error is InvalidOperationException||error is ArgumentException||error is NullReferenceException){CancelChapterRead(doc);Reply(read.Command,"Chapter validation stopped: "+error.Message);lastResult="Chapter validation stopped; existing accepted mappings are preserved.";}
|
||||
catch(Exception error)when(error is System.Runtime.InteropServices.COMException||error is InvalidOperationException||error is ArgumentException||error is NullReferenceException){CancelChapterRead(doc);Reply(read.Command,"Chapter validation stopped: "+error.Message);lastResult="Chapter validation stopped: "+error.Message;}
|
||||
finally{Release(range);Release(paragraph);Release(paragraphs);Release(heading);Release(point);Metric("chapter-ui-step",watch.Elapsed.TotalMilliseconds);if(chapterReads.ContainsKey(doc.Session)&&!scheduler.Post("chapter:"+doc.Session,()=>ReadChapterStep(doc))){CancelChapterRead(doc);Reply(read.Command,"Chapter validation stopped: Word queue is busy. Accepted checkpoints are preserved.");}}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"version": "1.0.0.27",
|
||||
"msiVersion": "1.0.27",
|
||||
"productCode": "{E804E119-8376-4439-9BAD-47F7F37C5734}",
|
||||
"version": "1.0.0.28",
|
||||
"msiVersion": "1.0.28",
|
||||
"productCode": "{DDEA70FE-62F7-4530-922F-B3C2CA1A2860}",
|
||||
"upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}",
|
||||
"atlasBaseline": "b78a88eeabf76465c5c06c0cc1d82e8952536a5a",
|
||||
"baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",
|
||||
|
||||
@ -25,6 +25,26 @@ assert.equal((await validate(changed)).allowText,true);changed.Paragraphs=rows;c
|
||||
const second={...proofs[1],RequestId:crypto.randomUUID(),WordRevision:wordRevision,BaseRevision:reconciled.revision,Start:proofs[1].Start+(changed.End-proofs[0].End),End:proofs[1].End+(changed.End-proofs[0].End)};assert.equal((await validate(second)).accepted,true);reply=await observe(second.Start+second.Paragraphs[0].Length);assert.equal(reply.sceneId,scope.Scenes[1]);assert.equal(reply.navigation,null);await validate({...changed,BaseRevision:evidence.Revision,RequestId:crypto.randomUUID()},409);
|
||||
r=await page.request.post(endpoint+'/finish',{headers,data:{instanceId:instance,sessionId:session,wordRevision,operationId:changed.OperationId}});assert.equal(r.status(),200);const progress=await r.json();assert.equal(progress.state,'Synchronised');assert.equal(progress.repaired,1);
|
||||
console.log('PASS manual-mode upload refusal, explicit existing repair command, changed-chapter-only reconciliation, stale CAS rejection and shifted later-chapter cursor mapping');
|
||||
// Optional native Word geometry regression: values model an observed zero-text floating picture anchor.
|
||||
// This exercises the deployed protocol, not real Word/COM.
|
||||
if(process.argv.includes('--structural')){
|
||||
assert.equal((await manifest()).nativePositionsSupported,true,'server explicitly advertises native geometry support');
|
||||
wordRevision=2;await observe(1000);
|
||||
const nativeRows=rows.map(({Text,...p})=>({...p,WordLength:p.Length,Anchors:[]}));
|
||||
nativeRows[1].WordLength++;nativeRows[1].Anchors=[{Offset:0,ShapeId:37,ShapeType:13}];
|
||||
const nativeString=s=>{const bytes=Buffer.from(s,'utf8');assert.ok(bytes.length<128);return Buffer.concat([Buffer.from([bytes.length]),bytes]);};
|
||||
const positionHash=crypto.createHash('sha256').update(Buffer.concat([nativeString('native-picture-positions-v1'),i32(nativeRows.length),...nativeRows.flatMap(p=>[nativeString(p.NativeId),i32(p.Length),i32(p.Outline),i32(p.WordLength),i32(p.Anchors.length),...p.Anchors.flatMap(a=>[i32(a.Offset),i32(a.ShapeId),i32(a.ShapeType)])])])).digest('hex').toUpperCase();
|
||||
const nativeProof={...changed,RequestId:crypto.randomUUID(),WordRevision:wordRevision,BaseRevision:reconciled.revision,End:changed.End+1,OperationId:'00000000-0000-0000-0000-000000000000',Reconcile:false,Paragraphs:nativeRows,PositionHash:positionHash};
|
||||
assert.equal((await validate(nativeProof)).accepted,true,'native spans and exact text lengths are distinct and both validated');
|
||||
const afterAnchor=nativeProof.Start+nativeRows[0].WordLength+nativeRows[1].WordLength;
|
||||
reply=await observe(afterAnchor);assert.equal(reply.sceneId,scope.Scenes[0],'Context after the zero-text anchor has no one-position drift');
|
||||
await validate({...nativeProof,RequestId:crypto.randomUUID(),PositionHash:'0'.repeat(64)},409);
|
||||
const secondNative={...second,RequestId:crypto.randomUUID(),WordRevision:wordRevision,Start:second.Start+1,End:second.End+1};
|
||||
assert.equal((await validate(secondNative)).accepted,true);reply=await observe(secondNative.Start+secondNative.Paragraphs[0].Length);assert.equal(reply.sceneId,scope.Scenes[1]);
|
||||
r=await page.request.post(endpoint+'/finish',{headers,data:{instanceId:instance,sessionId:session,wordRevision}});assert.equal(r.status(),200);assert.equal((await r.json()).state,'Synchronised');
|
||||
assert.equal((await manifest()).chapters.filter(c=>c.state==='Synchronised').length,2,'rejected geometry leaves accepted chapters intact');
|
||||
console.log('PASS deployed native picture geometry, unchanged text/identity evidence, post-anchor Context, shifted following chapter, bad-digest rejection and complete acceptance');
|
||||
}
|
||||
// Download and restore through the established author-facing recovery workflow.
|
||||
await page.goto(base+'/BookRecovery/Backup?projectId='+scope.Project);let token=await page.locator('form[action="/BookRecovery/ReviewBackup"] input[name=__RequestVerificationToken]').inputValue();r=await page.request.post(base+'/BookRecovery/Download',{form:{projectId:String(scope.Project),books:String(scope.Book),__RequestVerificationToken:token}});assert.equal(r.status(),200);assert.match(r.headers()['content-disposition'],/\.plotdirector/);const buffer=await r.body(),backup=JSON.parse(buffer);const source=backup.Snapshot.Recovery.ParagraphManuscripts[0];assert.equal(source.ChapterCheckpoints.length,2);assert.equal(source.Paragraphs[1].Occurrence.Text,rows[1].Text);assert.deepEqual(source.Paragraphs.map(p=>p.Occurrence.Id),evidence.Paragraphs.map(p=>p.Occurrence.Id));
|
||||
await page.goto(base+'/BookRecovery/Restore');await page.locator('input[type=file]').setInputFiles({name:'chapter-checkpoint.plotdirector',mimeType:'application/json',buffer});await page.getByRole('button',{name:'Validate backup',exact:true}).click();await page.locator('[name=name]').fill('Chapter sync restored synthetic fixture');await page.getByRole('button',{name:'Preview restore',exact:true}).click();await page.locator('#confirm').check();await page.getByRole('button',{name:'Restore books',exact:true}).click();assert.match(await page.locator('main').innerText(),/restor/i);assert.ok(!(await page.locator('main').innerText()).includes('could not be confirmed'));const link=page.locator('a[href*="/Projects/Details/"]').first();const restoredProject=Number((await link.getAttribute('href')).match(/\d+$/)[0]);assert.ok(restoredProject&&restoredProject!==scope.Project);
|
||||
|
||||
@ -136,6 +136,8 @@ internal static class ChapterAcceptanceDevelopmentTests
|
||||
Check(presence.ChapterProgress(user, book, instance, session, 0)?.Matching == 2, "Live progress counts persisted acceptances immediately");
|
||||
var partial = await service.Finish(user, grant, book, new() { InstanceId = instance, SessionId = session, WordRevision = 0 });
|
||||
Check(partial.State == "Needs review" && partial.Matching == 2 && partial.Total == 48, "Two accepted chapters cannot imply whole-manuscript completion");
|
||||
var unknownIssue=await service.Finish(user,grant,book,new(){InstanceId=instance,SessionId=session,WordRevision=0,HasIssues=true});
|
||||
Check(unknownIssue.State=="Needs review"&&unknownIssue.Matching==2&&(await checkpoints.List(user,book,session,0)).Count==2,"An unidentified structural failure does not revoke an unrelated accepted chapter");
|
||||
var unchanged = Proof(saved, 0);
|
||||
await Accept(unchanged);
|
||||
var changed = Proof(saved, 0); changed.WordRevision = 1;
|
||||
|
||||
70
PlotLine.Tests/ChapterStructuralContentTests.cs
Normal file
70
PlotLine.Tests/ChapterStructuralContentTests.cs
Normal file
@ -0,0 +1,70 @@
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services.Manuscript;
|
||||
|
||||
internal static class ChapterStructuralContentTests
|
||||
{
|
||||
public static void Run()
|
||||
{
|
||||
void Check(bool value,string label){if(!value)throw new Exception(label);Console.WriteLine("PASS "+label);}
|
||||
void Refused(Action work,string label){try{work();}catch(ArgumentException){Console.WriteLine("PASS "+label);return;}throw new Exception("Unsafe structural evidence accepted: "+label);}
|
||||
const string prefix="<w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:w14='http://schemas.microsoft.com/office/word/2010/wordml' xmlns:wp='http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'><w:body>";
|
||||
const string suffix="</w:body></w:document>";
|
||||
var xml=prefix+"<w:p w14:paraId='00000001'><w:pPr><w:outlineLvl w:val='0'/></w:pPr><w:r><w:t>Chapter</w:t></w:r></w:p><w:p w14:paraId='00000002'><w:r><w:drawing><wp:anchor/></w:drawing><w:t>Letter text</w:t></w:r></w:p><w:p w14:paraId='00000003'/>"+suffix;
|
||||
var texts=new[]{"Chapter\r","Letter text\r","\r"};
|
||||
var geometry=new[]{new ChapterParagraph{NativeId="00000001",Length=texts[0].Length,WordLength=texts[0].Length,Outline=1},new ChapterParagraph{NativeId="00000002",Length=texts[1].Length,WordLength=texts[1].Length+1,Outline=10,Anchors=[new(){Offset=0,ShapeId=17,ShapeType=13}]},new ChapterParagraph{NativeId="00000003",Length=1,WordLength=1,Outline=10}};
|
||||
var frames=ChapterWordPositions.Encode(geometry);var decoded=ChapterWordPositions.Decode(frames);
|
||||
var rows=ChapterFingerprint.ReadXml(xml,string.Concat(texts),null,true,decoded);
|
||||
Check(rows[1].Text==texts[1]&&rows[1].Length==texts[1].Length&&rows[1].WordLength==texts[1].Length+1,"Floating picture anchor retains separate native Word span without adding a text unit");
|
||||
Check(rows.Select(p=>p.NativeId).SequenceEqual(geometry.Select(p=>p.NativeId))&&rows[2].Text=="\r","Native paragraph identities and empty paragraphs survive structural framing");
|
||||
var identity=ChapterFingerprint.Identity(rows);var hash=ChapterWordPositions.Hash(rows);var wordEnd=500+rows.Sum(ChapterWordPositions.Span);
|
||||
ChapterWordPositions.Validate(rows,500,wordEnd,hash);
|
||||
Check(ChapterFingerprint.Content(rows.Select(p=>p.Text!))==ChapterFingerprint.Content(texts),"Picture position evidence leaves exact manuscript content hashes unchanged");
|
||||
var legacy=rows.Select(p=>new ChapterParagraph{NativeId=p.NativeId,Length=p.Length,Outline=p.Outline}).ToArray();
|
||||
Check(ChapterFingerprint.Identity(legacy)==identity,"Existing text/identity checkpoints retain the same v1 identity digest");
|
||||
Refused(()=>ChapterWordPositions.Validate(rows,500,wordEnd,""),"Physical Word spans cannot omit their geometry digest");
|
||||
Refused(()=>ChapterWordPositions.Validate(rows,500,wordEnd-1,hash),"Text offsets cannot be substituted for native chapter end positions");
|
||||
var tampered=ChapterWordPositions.Decode(frames);tampered[1].Anchors[0].Offset=1;
|
||||
Refused(()=>ChapterWordPositions.Validate(tampered,500,wordEnd,hash),"Changing a native anchor position invalidates the geometry digest");
|
||||
var bad=ChapterWordPositions.Decode(frames);bad[1].Anchors=[];
|
||||
Refused(()=>ChapterWordPositions.Hash(bad),"A span/text mismatch needs exact picture evidence, not padding");
|
||||
bad=ChapterWordPositions.Decode(frames);bad[1].Anchors[0].ShapeType=6;
|
||||
Refused(()=>ChapterWordPositions.Hash(bad),"Grouped objects are not silently certified as floating pictures");
|
||||
bad=ChapterWordPositions.Decode(frames);bad[1].Anchors[0].Offset=bad[1].WordLength;
|
||||
Refused(()=>ChapterWordPositions.Hash(bad),"Out-of-paragraph anchors are rejected");
|
||||
bad=ChapterWordPositions.Decode(frames);bad[1].WordLength++;bad[1].Anchors=[bad[1].Anchors[0],new(){Offset=0,ShapeId=18,ShapeType=13}];
|
||||
Refused(()=>ChapterWordPositions.Hash(bad),"Duplicate native anchor positions cannot account for extra Word positions");
|
||||
var occurrences=new List<ParagraphOccurrence>();var start=0;
|
||||
foreach(var row in rows){occurrences.Add(new(){NativeId=row.NativeId,Text=row.Text!,Outline=row.Outline,Ordinal=occurrences.Count,Start=start,End=start+row.WordLength});start+=row.WordLength;}
|
||||
var state=ParagraphManuscriptEngine.Bootstrap(12,7,Guid.NewGuid(),occurrences,[new(){ChapterId=10,SceneId=22,Start=2,End=3,Title="Imported scene"}]);state.Revision=3;
|
||||
var proof=new ChapterObservation{RequestId=Guid.NewGuid(),SessionId=Guid.NewGuid(),InstanceId=Guid.NewGuid(),ManuscriptId=state.ManuscriptId,BaseRevision=3,ChapterId=10,Start=500,End=wordEnd,ContentHash=ChapterFingerprint.Content(texts),IdentityHash=identity,PositionHash=hash,Paragraphs=rows};
|
||||
var result=ChapterCheckpointEngine.Validate(state,proof,DateTime.UtcNow);
|
||||
Check(result.Positions[1].End-result.Positions[1].Start==rows[1].WordLength&&result.Positions[2].Start==result.Positions[1].End&&result.Positions[^1].End==wordEnd,"Checkpoint positions use measured Word spans through and after a zero-text anchor");
|
||||
Check(result.Positions[1].SceneId==22&&result.Checkpoint.PositionHash==hash,"Structural acceptance preserves the imported scene identity and persists geometry evidence");
|
||||
var before=state.Paragraphs.Select(p=>(p.Occurrence.Id,p.Occurrence.Text,p.SceneId,p.ChapterId)).ToArray();
|
||||
state.Paragraphs[2].Story=false;state.Paragraphs[2].SceneId=null;
|
||||
var backMatter=ChapterCheckpointEngine.Validate(state,proof,DateTime.UtcNow);
|
||||
Check(backMatter.Positions[2].SceneId==null&&state.Paragraphs.Take(2).Select(p=>(p.Occurrence.Id,p.Occurrence.Text,p.SceneId,p.ChapterId)).SequenceEqual(before.Take(2)),"Imported non-story back matter is not silently assigned to the final scene");
|
||||
var plainXml=xml.Replace("<w:drawing><wp:anchor/></w:drawing>","");
|
||||
Check(ChapterFingerprint.ReadXml(plainXml,string.Concat(texts)).All(p=>p.WordLength==0),"Ordinary text-only chapters retain the existing identity and position path");
|
||||
var inlineXml=xml.Replace("<wp:anchor/>","<wp:inline/>");
|
||||
var inlineText="Letter \u0001text\r";
|
||||
var inlineRows=ChapterWordPositions.Decode(frames);inlineRows[1].Length=inlineRows[1].WordLength=inlineText.Length;inlineRows[1].Anchors=[];
|
||||
Check(ChapterFingerprint.ReadXml(inlineXml,texts[0]+inlineText+texts[2],null,true,inlineRows)[1].Text==inlineText,"Inline QR/signature image retains its native object character as text, not as a floating gap");
|
||||
var mixedXml=xml.Replace("<w:t>Letter text</w:t>","<w:drawing><wp:inline/></w:drawing><w:t>Letter text</w:t>");
|
||||
var mixedRows=ChapterWordPositions.Decode(frames);mixedRows[1].Length=inlineText.Length;mixedRows[1].WordLength=inlineText.Length+1;
|
||||
Check(ChapterFingerprint.ReadXml(mixedXml,texts[0]+inlineText+texts[2],null,true,mixedRows)[1].WordLength==inlineText.Length+1,"Mixed inline QR and floating signature preserve both actual text units and zero-text Word positions");
|
||||
var emptyPictureRows=ChapterWordPositions.Decode(frames);emptyPictureRows[1].Length=1;emptyPictureRows[1].WordLength=2;
|
||||
var emptyPictureXml=xml.Replace("<w:t>Letter text</w:t>","");
|
||||
Check(ChapterFingerprint.ReadXml(emptyPictureXml,texts[0]+"\r"+texts[2],null,true,emptyPictureRows)[1].Text=="\r","A picture anchored to an otherwise empty paragraph preserves the paragraph terminator and native anchor position");
|
||||
var section=prefix+"<w:p w14:paraId='00000001'><w:pPr><w:sectPr/></w:pPr><w:r><w:t>Text</w:t></w:r></w:p>"+suffix;
|
||||
var sectionText="Text\f\r";var sectionIds="00000001"+sectionText.Length.ToString("X8");
|
||||
Check(ChapterFingerprint.ReadXml(section,sectionText,sectionIds,true).Single().Text==sectionText,"Section break text comes from exact native paragraph evidence rather than XML projection");
|
||||
Refused(()=>ChapterFingerprint.ReadXml(section,sectionText,sectionIds),"Section breaks cannot bypass native text certification");
|
||||
var visualHeading=xml.Replace("<w:p w14:paraId='00000003'/>","<w:p w14:paraId='00000003'><w:pPr><w:pStyle w:val='Title'/></w:pPr><w:r><w:t>Author letter</w:t></w:r></w:p>");
|
||||
var headingText="Author letter\r";var visualRows=ChapterWordPositions.Decode(frames);visualRows[2].Length=visualRows[2].WordLength=headingText.Length;
|
||||
Check(ChapterFingerprint.ReadXml(visualHeading,texts[0]+texts[1]+headingText,null,true,visualRows)[2].Outline==10,"A visually formatted non-Heading-1 letter does not manufacture a chapter boundary");
|
||||
Refused(()=>ChapterFingerprint.ReadXml(xml.Replace("<wp:anchor/>","<wp:anchor><w:txbxContent/></wp:anchor>"),string.Concat(texts),null,true,geometry),"Text boxes remain explicitly unsupported even with native picture metadata");
|
||||
Refused(()=>ChapterFingerprint.ReadXml(xml.Replace("<w:t>Letter text</w:t>","<w:fldChar/><w:t>Letter text</w:t>"),string.Concat(texts),null,true,geometry),"Fields do not acquire picture-anchor authority");
|
||||
}
|
||||
}
|
||||
@ -33,6 +33,19 @@ internal static class ChapterSyncDevelopmentTests
|
||||
Check(accepted.SnapshotHash==ParagraphManuscriptEngine.Hash(accepted.Paragraphs.Select(p=>p.Occurrence).ToArray()),"Legacy native-ID adoption keeps the existing full-snapshot digest coherent");
|
||||
Check(accepted.ChapterCheckpoints.Count==2&&(await chapters.List(scope.User,scope.Book,session,0)).Count==2,"Independent accepted chapters survive interrupted processing and same-request retry");
|
||||
var unauthorised=false;try{await chapters.List(0,scope.Book,session,0);}catch(SqlException){unauthorised=true;}Check(unauthorised,"Unauthorised account cannot access chapter checkpoint evidence");
|
||||
var physicalSession=Guid.NewGuid();
|
||||
var firstPart=ChapterCheckpointEngine.Parts(accepted)[0];
|
||||
var nativeRows=firstPart.Rows.Select(p=>new ChapterParagraph{NativeId=p.Occurrence.NativeId,Length=p.Occurrence.Text.Length,WordLength=p.Occurrence.Text.Length,Outline=p.Occurrence.Outline}).ToArray();
|
||||
nativeRows[1].WordLength++;nativeRows[1].Anchors=[new(){Offset=0,ShapeId=17,ShapeType=13}];
|
||||
var physicalProof=new ChapterObservation{SessionId=physicalSession,InstanceId=scope.Instance,ManuscriptId=scope.Manuscript,WordRevision=1,BaseRevision=accepted.Revision,ChapterId=firstPart.Chapter.CanonicalId,Start=1000,End=1000+nativeRows.Sum(ChapterWordPositions.Span),NextHeadingId=accepted.Paragraphs[firstPart.End].Occurrence.NativeId,ContentHash=ChapterFingerprint.Content(firstPart.Rows.Select(p=>p.Occurrence.Text)),IdentityHash=ChapterFingerprint.Identity(nativeRows),PositionHash=ChapterWordPositions.Hash(nativeRows),Paragraphs=nativeRows};
|
||||
var nativeResult=ChapterCheckpointEngine.Validate(accepted,physicalProof,DateTime.UtcNow);
|
||||
await chapters.Accept(scope.User,scope.Book,physicalProof,nativeResult);
|
||||
var physicalRead=(await repository.Get(scope.User,scope.Book))!;
|
||||
Check(physicalRead.ChapterCheckpoints.Single(c=>c.ChapterId==physicalProof.ChapterId).PositionHash==physicalProof.PositionHash,"Physical Word geometry digest survives a fresh database read");
|
||||
var nextPosition=nativeResult.Positions[2];
|
||||
Check(nextPosition.Start==1000+nativeRows[0].WordLength+nativeRows[1].WordLength&&(await chapters.Position(scope.User,scope.Book,scope.Manuscript,physicalSession,1,nextPosition.Start))?.SceneID==scope.Scenes[0],"Writing Context after a zero-text native anchor uses Word positions without a one-character shift");
|
||||
var preserved=physicalRead.Paragraphs.Select(p=>(p.Occurrence.Id,p.Occurrence.Text,p.Occurrence.Start,p.Occurrence.End,p.ChapterId,p.SceneId,p.Story,p.PositionVerified));
|
||||
Check(preserved.SequenceEqual(accepted.Paragraphs.Select(p=>(p.Occurrence.Id,p.Occurrence.Text,p.Occurrence.Start,p.Occurrence.End,p.ChapterId,p.SceneId,p.Story,p.PositionVerified)))&&physicalRead.Revision==accepted.Revision,"Native structural acceptance changes no canonical paragraph positions, GUIDs, prose, scene assignments or revision");
|
||||
await File.WriteAllTextAsync(args[2]+".evidence.json",JsonSerializer.Serialize(new{scope.Book,scope.Manuscript,Revision=accepted.Revision,Proofs=proofs,Paragraphs=accepted.Paragraphs}));File.SetUnixFileMode(args[2]+".evidence.json",UnixFileMode.UserRead|UnixFileMode.UserWrite);
|
||||
// Metadata adoption is the only mutation in this fixture. Author data never participates.
|
||||
}
|
||||
|
||||
@ -7,6 +7,7 @@ internal static class ChapterSynchronisationTests
|
||||
{
|
||||
public static void Run()
|
||||
{
|
||||
ChapterStructuralContentTests.Run();
|
||||
void Check(bool condition,string message){if(!condition)throw new Exception(message);Console.WriteLine("PASS "+message);}
|
||||
void Refused(Action work,string message){try{work();throw new Exception("Unsafe chapter evidence accepted: "+message);}catch(Exception e)when(e is ArgumentException or InvalidOperationException){Console.WriteLine("PASS "+message);}}
|
||||
Check(ChapterFingerprint.Content(["a\r","b\r"])!=ChapterFingerprint.Content(["a\rb\r"]),"Fingerprint preserves paragraph splitting/merging");
|
||||
|
||||
@ -6,7 +6,7 @@ public sealed class ChapterCheckpoint
|
||||
{
|
||||
public int ChapterId {get;set;}public Guid HeadingId {get;set;}public string NativeHeadingId {get;set;}="";public string NextHeadingId {get;set;}="";
|
||||
public string Algorithm {get;set;}=ChapterFingerprint.Version;
|
||||
public string ContentHash {get;set;}="";public string IdentityHash {get;set;}="";public string MappingHash {get;set;}="";
|
||||
public string ContentHash {get;set;}="";public string IdentityHash {get;set;}="";public string MappingHash {get;set;}="";public string PositionHash {get;set;}="";
|
||||
public int ParagraphCount {get;set;}public int Order {get;set;}public long AcceptedRevision {get;set;}
|
||||
public DateTime LastSuccessfulSyncUtc {get;set;}public string Status {get;set;}="Not yet checked";public string Message {get;set;}="";
|
||||
}
|
||||
@ -37,7 +37,7 @@ public static class ChapterCheckpointEngine
|
||||
checkpoint.IdentityHash=ChapterFingerprint.Identity(Evidence(part));
|
||||
}catch(ArgumentException e){checkpoint.Status="Needs review";checkpoint.Message=e.Message;}
|
||||
var prior=state.ChapterCheckpoints.FirstOrDefault(c=>c.ChapterId==checkpoint.ChapterId&&c.ContentHash==checkpoint.ContentHash&&c.IdentityHash==checkpoint.IdentityHash&&c.MappingHash==checkpoint.MappingHash&&c.NextHeadingId==checkpoint.NextHeadingId);
|
||||
if(prior!=null){checkpoint.LastSuccessfulSyncUtc=prior.LastSuccessfulSyncUtc;checkpoint.AcceptedRevision=prior.AcceptedRevision;if(prior.Status=="Needs review"){checkpoint.Status=prior.Status;checkpoint.Message=prior.Message;}}
|
||||
if(prior!=null){checkpoint.PositionHash=prior.PositionHash;checkpoint.LastSuccessfulSyncUtc=prior.LastSuccessfulSyncUtc;checkpoint.AcceptedRevision=prior.AcceptedRevision;if(prior.Status=="Needs review"){checkpoint.Status=prior.Status;checkpoint.Message=prior.Message;}}
|
||||
return checkpoint;
|
||||
}).ToArray();
|
||||
}
|
||||
@ -48,7 +48,8 @@ public static class ChapterCheckpointEngine
|
||||
var part=Parts(state).SingleOrDefault(p=>p.Chapter.CanonicalId==proof.ChapterId)??throw new InvalidOperationException("The chapter is not in the accepted manuscript index.");
|
||||
if(part.Rows.Any(p=>p.ChapterId>0&&p.ChapterId!=proof.ChapterId))throw new InvalidOperationException("Existing chapter assignments disagree with chapter boundaries; review is required.");
|
||||
var identity=ChapterFingerprint.Identity(proof.Paragraphs);
|
||||
if(identity!=proof.IdentityHash||proof.Paragraphs.Sum(p=>(long)p.Length)!=proof.End-proof.Start)throw new ArgumentException("Chapter identity/position evidence is incomplete.");
|
||||
ChapterWordPositions.Validate(proof.Paragraphs,proof.Start,proof.End,proof.PositionHash);
|
||||
if(identity!=proof.IdentityHash)throw new ArgumentException("Chapter identity/position evidence is incomplete.");
|
||||
var all=Build(state,state.Revision);var checkpoint=all.Single(p=>p.ChapterId==proof.ChapterId);
|
||||
if(checkpoint.ContentHash!=proof.ContentHash||part.Rows.Length!=proof.Paragraphs.Length)throw new InvalidOperationException("Changed chapter; bounded chapter reconciliation is required. Accepted mappings are unchanged.");
|
||||
var nativeOwners=state.Paragraphs.Where(p=>p.Occurrence.NativeId!="").GroupBy(p=>p.Occurrence.NativeId).ToDictionary(g=>g.Key,g=>g.Select(p=>p.Occurrence.Id).ToHashSet());
|
||||
@ -65,8 +66,8 @@ public static class ChapterCheckpointEngine
|
||||
checkpoint.Status="Synchronised";checkpoint.Message=checkpoint.NextHeadingId!=proof.NextHeadingId&&(checkpoint.NextHeadingId!=""||part.End==state.Paragraphs.Count)?"Chapter text and paragraph map verified; surrounding chapter order needs review.":"Accepted chapter positions verified for this session.";
|
||||
if(checkpoint.Message.Contains("order needs review"))checkpoint.Status="Needs review";
|
||||
if(checkpoint.NextHeadingId==""&&part.End<state.Paragraphs.Count)checkpoint.NextHeadingId=proof.NextHeadingId;
|
||||
checkpoint.IdentityHash=identity;checkpoint.NativeHeadingId=proof.Paragraphs[0].NativeId;checkpoint.LastSuccessfulSyncUtc=now;
|
||||
var start=proof.Start;var positions=part.Rows.Select((row,i)=>{var end=checked(start+proof.Paragraphs[i].Length);var scene=state.Scenes.FirstOrDefault(s=>!s.Retired&&s.Id==row.SceneId&&s.ChapterId==proof.ChapterId);var value=new ChapterPosition(row.Occurrence.Id,start,end,proof.ChapterId,scene?.CanonicalId>0?scene.CanonicalId:null,row.PositionVerified&&row.ChapterId==proof.ChapterId);start=end;return value;}).ToArray();
|
||||
checkpoint.PositionHash=proof.PositionHash;checkpoint.IdentityHash=identity;checkpoint.NativeHeadingId=proof.Paragraphs[0].NativeId;checkpoint.LastSuccessfulSyncUtc=now;
|
||||
var start=proof.Start;var positions=part.Rows.Select((row,i)=>{var end=checked(start+ChapterWordPositions.Span(proof.Paragraphs[i]));var scene=state.Scenes.FirstOrDefault(s=>!s.Retired&&s.Id==row.SceneId&&s.ChapterId==proof.ChapterId);var value=new ChapterPosition(row.Occurrence.Id,start,end,proof.ChapterId,scene?.CanonicalId>0?scene.CanonicalId:null,row.PositionVerified&&row.ChapterId==proof.ChapterId);start=end;return value;}).ToArray();
|
||||
var bindingsById=bindings.ToDictionary(b=>b.ParagraphId,b=>b.NativeId);
|
||||
var adoptedHash=bindings.Count==0?null:ParagraphManuscriptEngine.Hash(state.Paragraphs.Select(p=>new ParagraphOccurrence{Id=p.Occurrence.Id,NativeId=bindingsById.GetValueOrDefault(p.Occurrence.Id,p.Occurrence.NativeId),Text=p.Occurrence.Text,Outline=p.Occurrence.Outline,Start=p.Occurrence.Start,End=p.Occurrence.End}).ToArray());
|
||||
return new(checkpoint,bindings.ToArray(),positions){AdoptedSnapshotHash=adoptedHash};
|
||||
@ -74,6 +75,7 @@ public static class ChapterCheckpointEngine
|
||||
public static ParagraphOccurrence[] MergeChapter(ParagraphManuscript state,ChapterObservation proof)
|
||||
{
|
||||
var part=Parts(state).SingleOrDefault(p=>p.Chapter.CanonicalId==proof.ChapterId)??throw new InvalidOperationException("Unknown chapter.");
|
||||
ChapterWordPositions.Validate(proof.Paragraphs,proof.Start,proof.End,proof.PositionHash);
|
||||
if(proof.BaseRevision!=state.Revision||proof.ManuscriptId!=state.ManuscriptId||!proof.Reconcile||proof.Paragraphs.Any(p=>p.Text==null||p.Text.Length!=p.Length)||ChapterFingerprint.Content(proof.Paragraphs.Select(p=>p.Text!))!=proof.ContentHash||ChapterFingerprint.Identity(proof.Paragraphs)!=proof.IdentityHash)throw new InvalidOperationException("A complete, explicitly authorised changed chapter is required.");
|
||||
if(part.Rows[0].Occurrence.NativeId==""||proof.Paragraphs[0].NativeId!=part.Rows[0].Occurrence.NativeId||proof.Paragraphs[0].Outline!=1||proof.Paragraphs.Skip(1).Any(p=>p.Outline==1))throw new InvalidOperationException("Chapter insertion, deletion or uncertain heading requires structural review; no cross-chapter grouping was proposed.");
|
||||
var outside=state.Paragraphs.Take(part.Index).Concat(state.Paragraphs.Skip(part.End)).Select(p=>p.Occurrence.NativeId).Where(id=>id!="").ToHashSet();
|
||||
|
||||
@ -12,7 +12,7 @@ public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscript
|
||||
if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException();
|
||||
var state=await manuscripts.Get(user,book)??throw new InvalidOperationException("Finish the existing manuscript import first; no saved index is available.");
|
||||
var live=await checkpoints.List(user,book,session,wordRevision);var sources=ChapterCheckpointEngine.Build(state,state.Revision);
|
||||
var manifest=new ChapterManifest(){BookId=book,ManuscriptId=state.ManuscriptId,Revision=state.Revision,Mode=state.Mode,Chapters=ChapterCheckpointEngine.Parts(state).Select(part=>{
|
||||
var manifest=new ChapterManifest(){NativePositionsSupported=true,BookId=book,ManuscriptId=state.ManuscriptId,Revision=state.Revision,Mode=state.Mode,Chapters=ChapterCheckpointEngine.Parts(state).Select(part=>{
|
||||
var source=sources.Single(c=>c.ChapterId==part.Chapter.CanonicalId);var accepted=live.FirstOrDefault(c=>c.ChapterID==source.ChapterId&&c.ContentHash==source.ContentHash&&c.IdentityHash==source.IdentityHash&&c.MappingHash==source.MappingHash);
|
||||
return new ChapterManifestItem{ChapterId=source.ChapterId,Title=part.Chapter.Title,HeadingNativeId=source.NativeHeadingId,ContentHash=source.ContentHash,IdentityHash=source.IdentityHash,Start=accepted?.StartPosition??part.Rows[0].Occurrence.Start,End=accepted?.EndPosition??part.Rows[^1].Occurrence.End,ParagraphCount=source.ParagraphCount,State=accepted!=null&&source.Status!="Needs review"?"Synchronised":source.Status};
|
||||
}).ToArray()};
|
||||
@ -27,7 +27,7 @@ public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscript
|
||||
if(completion.OperationId!=Guid.Empty&&!presence.CanRepairChapter(user,lease,completion.OperationId))throw new UnauthorizedAccessException();
|
||||
var status=await manuscripts.Status(user,book);if(status?.CanWrite!=true)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active; completion is paused and accepted checkpoints are retained.");
|
||||
var manifest=await Manifest(user,book,completion.SessionId,completion.WordRevision);
|
||||
if(completion.HasIssues&&manifest.Chapters.Length>0){var ids=(completion.ReviewChapterIds??[]).Where(id=>manifest.Chapters.Any(c=>c.ChapterId==id)).Distinct().Take(256).ToArray();if(ids.Length==0)ids=[manifest.Chapters[0].ChapterId];foreach(var id in ids)await checkpoints.FlagReview(user,book,id,manifest.Revision);manifest=await Manifest(user,book,completion.SessionId,completion.WordRevision);}
|
||||
if(completion.HasIssues&&manifest.Chapters.Length>0){var ids=(completion.ReviewChapterIds??[]).Where(id=>manifest.Chapters.Any(c=>c.ChapterId==id)).Distinct().Take(256).ToArray();foreach(var id in ids)await checkpoints.FlagReview(user,book,id,manifest.Revision);manifest=await Manifest(user,book,completion.SessionId,completion.WordRevision);}
|
||||
var accepted=manifest.Chapters.Count(c=>c.State=="Synchronised");var complete=accepted==manifest.Chapters.Length&&accepted>0&&!completion.HasIssues;
|
||||
var progress=new ChapterSyncProgress{Total=manifest.Chapters.Length,Checked=manifest.Chapters.Length,Matching=accepted,Repaired=presence.RepairedChapters(user,book,completion.InstanceId,completion.SessionId,completion.WordRevision),NeedsReview=complete?0:Math.Max(1,manifest.Chapters.Length-accepted),State=complete?"Synchronised":"Needs review",Message=complete?$"All {accepted} chapter mappings are accepted for this Word session.":$"{accepted}/{manifest.Chapters.Length} chapters accepted; remaining structure needs review. Successfully accepted repairs are retained."};
|
||||
presence.RecordChapterProgress(user,book,completion.InstanceId,completion.SessionId,completion.WordRevision,progress);
|
||||
@ -56,6 +56,7 @@ public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscript
|
||||
{
|
||||
if(proof==null||proof.Paragraphs==null||proof.Paragraphs.Length==0||proof.Paragraphs.Length>ChapterFingerprint.MaxParagraphs||proof.Paragraphs.Any(p=>p==null))throw new ArgumentException("Complete bounded chapter evidence is required.");
|
||||
RequireFeature();
|
||||
ChapterWordPositions.Validate(proof.Paragraphs,proof.Start,proof.End,proof.PositionHash);
|
||||
stage="access";
|
||||
if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException();
|
||||
var status=await manuscripts.Status(user,book)??throw new InvalidOperationException("No accepted manuscript index.");
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user