diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs index 33c1cde2..341749a4 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.Chapters.cs @@ -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 Reviewed=[];public readonly HashSet Visited=[];public string Next=""; } private readonly Dictionary 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 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;iChapterFingerprint.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();} } } diff --git a/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs index d58a15a1..151c9355 100644 --- a/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs +++ b/PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs @@ -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'); diff --git a/PlotLine.Tests/ChapterSynchronisationTests.cs b/PlotLine.Tests/ChapterSynchronisationTests.cs index b3df3fa9..526de048 100644 --- a/PlotLine.Tests/ChapterSynchronisationTests.cs +++ b/PlotLine.Tests/ChapterSynchronisationTests.cs @@ -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(before)!;ParagraphManuscriptEngine.Reconcile(copy,merged);Check(copy.Scenes.Select(p=>p.Id).SequenceEqual(state.Scenes.Select(p=>p.Id))&©.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(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="Chapter oneExacttext"; 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("","").Replace("",""),"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("",""),"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"); diff --git a/PlotLine/Services/Manuscript/ChapterCheckpointEngine.cs b/PlotLine/Services/Manuscript/ChapterCheckpointEngine.cs index 4a9c0588..54b0ecbb 100644 --- a/PlotLine/Services/Manuscript/ChapterCheckpointEngine.cs +++ b/PlotLine/Services/Manuscript/ChapterCheckpointEngine.cs @@ -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{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);