Verify chapter order and wrapped content controls with bounded agent processing

This commit is contained in:
Nick Beckley 2026-11-09 12:32:39 +00:00
parent 59e17df43f
commit f171d8b196
4 changed files with 9 additions and 2 deletions

View File

@ -11,6 +11,7 @@ public sealed partial class TrayCoordinator
public StringBuilder Text=new(),Xml=new();public int Start,End,DocumentEnd,FirstStart=-1;public bool Finished;public bool Wrapped;public readonly HashSet<int> Reviewed=[];public readonly HashSet<int> Visited=[];public string Next="";
}
private readonly Dictionary<Guid,ChapterWork> chapterWork=[];
private readonly SemaphoreSlim chapterProcessing=new(2,2);
private string ChapterIssue(TrayDocument doc){lock(gate)return chapterWork.TryGetValue(doc.Session,out var work)&&work.FailedRevision==doc.Revision?"needs_review":"";}
private bool ChapterCapable(Guid instance){lock(gate)return chapterInstances.Contains(instance);}
private readonly HashSet<Guid> ribbonRequests=[];
@ -96,6 +97,7 @@ public sealed partial class TrayCoordinator
}
private void CompleteChapters(TrayDocument doc,ChapterWork work)
{
var expected=work.Manifest!.Chapters.Select(c=>c.ChapterId).Where(work.Checked.ContainsKey).ToArray();var actual=work.Checked.OrderBy(p=>p.Value.Start).Select(p=>p.Key).ToArray();for(int i=0;i<Math.Min(expected.Length,actual.Length);i++)if(expected[i]!=actual[i]){work.Reviewed.Add(expected[i]);work.Reviewed.Add(actual[i]);}
work.Busy=true;work.Finished=true;work.Started=DateTime.UtcNow;_ = CompleteChapterOperation(doc,work);
}
private async Task CompleteChapterOperation(TrayDocument doc,ChapterWork work)
@ -105,6 +107,7 @@ public sealed partial class TrayCoordinator
}
private async Task ProcessChapter(TrayDocument doc,ChapterWork work,string text,string xml,Guid command,int start,int end,string nextHeading,Guid operation)
{
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 rows=await Task.Run(()=>ChapterFingerprint.ReadXml(xml,text));xml="";text="";
@ -124,5 +127,6 @@ public sealed partial class TrayCoordinator
if(e is HttpRequestException or OperationCanceledException||cloud.Status().Health?.Authentication!="verified"){work.Manifest=null;work.Command=Guid.Empty;work.Visited.Clear();work.RetryAfter=DateTime.UtcNow.AddSeconds(15);doc.Status="Chapter connection interrupted; accepted checkpoints are retained and validation will resume after reconnect.";}
else if(e is ArgumentException or System.Xml.XmlException&&end>start){work.Reviewed.Add(-start-1);doc.Status="Chapter content needs review: "+e.Message+" Other chapters can continue.";AdvanceChapter(doc,work);}
else{work.FailedRevision=doc.Revision;doc.Status="Chapter needs review: "+e.Message+" Existing import is unchanged.";}}}
finally{chapterProcessing.Release();}
}
}

View File

@ -77,7 +77,7 @@ public static class ChapterFingerprint
if(properties?.Element(w+"outlineLvl")==null&&definition.Element(w+"basedOn")?.Attribute(w+"val") is {} parent)properties=new XElement(w+"pPr",new XElement(w+"pStyle",new XAttribute(w+"val",parent.Value)));
}throw new ArgumentException("Cyclic Word style inheritance.");
}
var rows=body.Elements(w+"p").Select(p=>{
var rows=body.Descendants(w+"p").Where(p=>!p.Ancestors(w+"p").Any()).Select(p=>{
var text=new StringBuilder();foreach(var node in p.Descendants()){
if(node.Name==w+"t")text.Append(node.Value);else if(node.Name==w+"tab")text.Append('\t');else if(node.Name==w+"br"||node.Name==w+"cr"){if((string?)node.Attribute(w+"type") is {} type&&type!="textWrapping")throw new ArgumentException("Page/column break requires measured Word extraction.");text.Append('\v');}
}text.Append('\r');

View File

@ -31,6 +31,7 @@ internal static class ChapterSynchronisationTests
Check(merged[3].Start-state.Paragraphs[3].Occurrence.Start==changed.Paragraphs[1].Length-state.Paragraphs[1].Occurrence.Text.Length,"Logical positions in later chapters account for changed text length");
var copy=JsonSerializer.Deserialize<ParagraphManuscript>(before)!;ParagraphManuscriptEngine.Reconcile(copy,merged);Check(copy.Scenes.Select(p=>p.Id).SequenceEqual(state.Scenes.Select(p=>p.Id))&&copy.Paragraphs.Where(p=>p.ChapterId==11).All(p=>p.SceneId==null||p.SceneId==state.Scenes.Single(s=>s.ChapterId==11).Id),"Existing reconciliation preserves canonical scene GUIDs and hard chapter membership");
var crossing=Proof();crossing.Reconcile=true;crossing.NextHeadingId="000000FF";Refused(()=>ChapterCheckpointEngine.MergeChapter(state,crossing),"Changed or moved chapter boundary requires review instead of cross-chapter reassignment");
var movedLast=Proof(11);movedLast.NextHeadingId="00000001";Check(ChapterCheckpointEngine.Validate(state,movedLast,DateTime.UtcNow).Checkpoint.Status=="Needs review","A formerly last chapter moved before another heading cannot report unchanged global structure");
var legacy=JsonSerializer.Deserialize<ParagraphManuscript>(before)!;foreach(var p in legacy.Paragraphs)p.Occurrence.NativeId="";var adoption=Proof();adoption.Reconcile=true;
var adopted=ChapterCheckpointEngine.Validate(legacy,adoption,DateTime.UtcNow);Check(adopted.Bindings.Length==3&&legacy.Paragraphs.All(p=>p.Occurrence.NativeId==""),"Explicit legacy repair proposes native bindings while preserving every original PlotDirector GUID");
adoption.Reconcile=false;Refused(()=>ChapterCheckpointEngine.Validate(legacy,adoption,DateTime.UtcNow),"Passive hash checks cannot silently adopt missing legacy identities");
@ -54,6 +55,7 @@ internal static class ChapterSynchronisationTests
Check(restored.ChapterCheckpoints[0].ChapterId==110&&restored.ChapterCheckpoints[0].HeadingId==state.Chapters[0].HeadingId&&restored.ChapterCheckpoints[0].ContentHash==state.ChapterCheckpoints[0].ContentHash&&restored.ChapterCheckpoints[0].Status=="Not yet checked"&&restored.SessionId==Guid.Empty,"Backup remaps canonical checkpoint IDs, preserves content/GUID evidence and detaches live trust");
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 one</w:t></w:r></w:p><w:p w14:paraId='00000002'><w:r><w:t>Exact</w:t><w:tab/><w:t>text</w:t></w:r></w:p></w:body></w:document>";
Check(ChapterFingerprint.ReadXml(xml,"Chapter one\rExact\ttext\r").Length==2,"Portable chapter XML identity enumeration matches exact Word range text");
Check(ChapterFingerprint.ReadXml(xml.Replace("<w:body>","<w:body><w:sdt><w:sdtContent>").Replace("</w:body>","</w:sdtContent></w:sdt></w:body>"),"Chapter one\rExact\ttext\r").Length==2,"Existing block content-control markers preserve exact paragraph order without Word edits");
Refused(()=>ChapterFingerprint.ReadXml(xml,"Different\r"),"XML/range disagreement is refused rather than inventing paragraph offsets");
Refused(()=>ChapterFingerprint.ReadXml(xml.Replace("<w:body>","<w:body><w:tbl/>"),"Chapter one\rExact\ttext\r"),"Complex Word tables require safe bounded fallback");
var presence=new PlotLine.Services.NativeCompanion.NativePresenceStore(TimeProvider.System);var instance=Guid.NewGuid();var session=Guid.NewGuid();presence.Put(7,"grant",DateTimeOffset.UtcNow.AddHours(1),instance,session,new(){BookId=12,ManuscriptId=state.ManuscriptId,CanChapterSync=true,CanCapture=true,CanParagraphSync=true,WordAvailable=true,WordSaved=true,Sequence=1,Revision=1});var lease=presence.Read(7,12).Single();presence.RecordChapterProgress(7,12,instance,session,1,new(){State="Synchronised",Total=2,Matching=2});var operation=Guid.NewGuid();Check(presence.RequestChapterRepair(7,lease,operation)&&presence.ChapterTransfer(7,12,instance,session)?.State=="pending","A repeated repair cannot inherit a previous green completion before fresh acceptance");

View File

@ -61,8 +61,9 @@ public static class ChapterCheckpointEngine
}
if(bindings.Count>0&&(!proof.Reconcile||all.Count(c=>c.ContentHash==proof.ContentHash)!=1))throw new InvalidOperationException("Legacy native identities require explicit repair and unique complete chapter evidence. No reimport is required.");
// A moved chapter may be validated locally, but its canonical ordering is never silently rewritten.
checkpoint.Status="Synchronised";checkpoint.Message=checkpoint.NextHeadingId!=""&&checkpoint.NextHeadingId!=proof.NextHeadingId?"Chapter text and paragraph map verified; surrounding chapter order needs review.":"Accepted chapter positions verified for this session.";
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();
var bindingsById=bindings.ToDictionary(b=>b.ParagraphId,b=>b.NativeId);