using System.Text; using PlotDirector.Companion.Protocol; using PlotDirector.Companion.Protocol.Manuscript; namespace PlotDirector.Companion.Agent; public sealed partial class TrayCoordinator { private DateTime ChapterNow=>(synchronisationClock??TimeProvider.System).GetUtcNow().UtcDateTime; private readonly HashSet chapterProcessingSessions=[]; private sealed class ChapterWork { public readonly System.Diagnostics.Stopwatch Elapsed=System.Diagnostics.Stopwatch.StartNew(); public double RecognitionMs,ManifestMs,VerificationMs,ServerMs,ContextMs=-1,CompleteMs=-1;public int LiveReads,XmlReads,Submissions,Calculated,Matching,Mismatching,Missing,Incompatible,Reused,Reconciled,ReuseRequests,Requests;public long RequestBytes; public double ReuseReadMs,ReuseProcessingMs,ReuseValidationMs,ReusePersistenceMs;public bool ReuseFinishing; public readonly Dictionary PendingReuse=[]; public readonly HashSet Dirty=[];public int ExpectedProbeChapter;public bool Reconciling;public string CurrentTitle="chapter";public bool PreferRangeEvidence,Polling,ObserveOnly;public int Retained;public int Book, Attempts, Retries; public string ReviewReason = "";public Guid Manuscript;public long Revision;public Guid Context,Operation,Command;public bool Busy,Supported,Processing,Begun;public long FailedRevision=-1;public DateTime Started,RetryAfter; public ChapterManifest? Manifest; public ChapterSyncProgress? Completion;public readonly Dictionary Checked=[]; public StringBuilder Text=new(),Xml=new(),Identities=new();public int Start,End,DocumentEnd,CursorWhenQueued,FirstStart=-1;public bool Finished;public bool Wrapped;public bool NativeTextVerified;public string IdentityAction="";public readonly HashSet 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":"";} public ChapterSyncProgress? ChapterProgressForDisplay(Guid session) { lock (gate) return documents.TryGetValue(session, out var doc) ? VisibleChapterProgress(doc) : null; } private ChapterSyncProgress? VisibleChapterProgress(TrayDocument doc) { if (cloud.Status().Health?.Authentication != "verified") return new() { State = "Sign-in required", Message = "Sign in to resume synchronisation. The manuscript's saved book association is retained." }; if (doc.RibbonNotice != null) return doc.RibbonNotice; if (doc.Book>0 && doc.WordSaved != true && ChapterCapable(doc.Instance)) return new() { State = "Save required", Message = "Save the manuscript in Word to verify the edited chapters." }; if (!chapterWork.TryGetValue(doc.Session, out var work) || !CurrentChapterWork(doc, work)) return doc.ChapterProgress; var total = work.Manifest?.Chapters.Length ?? doc.ChapterProgress?.Total ?? 0; var accepted = work.Checked.Count; if (work.FailedRevision == doc.Revision) return new() { State = "Needs review", Total = total, Matching = accepted, Message = doc.Status }; if (work.Busy || !work.Finished && work.Attempts > 0) { return new() { State = work.Reconciling?"Synchronising":"Checking", Total = total, Matching = accepted, Message = (work.Reconciling?$"Synchronising {work.CurrentTitle}. ":"")+$"{accepted} verified · {Math.Max(0,total-accepted)} pending. Checking chapter evidence; reconciliation counts are reported separately in diagnostics." }; } return work.Finished&&work.Completion!=null?work.Completion:doc.ChapterProgress; } public string ChapterDiagnostics(Guid session) { lock(gate) { if(!documents.TryGetValue(session,out var doc))return "Chapter timings: awaiting recognised saved document."; var association=doc.Book>0?$"Book association: {doc.Book}.":"Book association missing: select the existing authorised book in Companion; no reimport is required."; var lifecycle=$"{association} Word revision: {doc.Revision}; saved state: {(doc.WordSaved.HasValue?doc.WordSaved.Value.ToString():"unknown")}. Last ribbon command: {doc.LastRibbonCommand} · outcome: {doc.LastRibbonOutcome} · pending restart: {doc.PendingRibbonCommand} · permit pending: {doc.RibbonPermit!=Guid.Empty}. Last interruption: {doc.LastChapterInterruption}."; if(!chapterWork.TryGetValue(session,out var w))return lifecycle+" Chapter timings: awaiting recognised saved document."; return lifecycle+$" Verification: {(w.Busy?"running":w.Finished?"finished":"idle")}, Word read pending: {w.Command!=Guid.Empty}. Current Context: {ChapterCursorEvidence.State(documents[session],w.Completion?.State=="Synchronised"&&w.Checked.Count==w.Manifest?.Chapters.Length,w.Checked.Values.Any(p=>documents[session].Cursor>=p.Start&&documents[session].Cursorc.DurableAccepted)??0}; calculated/match/mismatch/missing/incompatible={w.Calculated}/{w.Matching}/{w.Mismatching}/{w.Missing}/{w.Incompatible}; retained={w.Retained}, rangeEvidence={w.PreferRangeEvidence}, polling={w.Polling}, observeOnly={w.ObserveOnly}, editedInMemory={w.Dirty.Count}, reused={w.Reused}, pending={w.PendingReuse.Count}, reconciled={w.Reconciled}, reuseRequests={w.ReuseRequests}, requests={w.Requests}, bytes={w.RequestBytes}, reuse server read/process/validation/persistence ms={w.ReuseReadMs:F1}/{w.ReuseProcessingMs:F1}/{w.ReuseValidationMs:F1}/{w.ReusePersistenceMs:F1}. Negative timing means not observed."; } } private void StopChapterWork(TrayDocument doc, ChapterWork work, string reason) { work.Busy = false; work.Processing = false; work.Command = Guid.Empty; work.FailedRevision = doc.Revision; doc.Status = reason; doc.LastChapterInterruption=reason; doc.LastPresenceKey = ""; Queue(doc, new() { Kind = "chapter-cancel" }); } private void RetryChapterWork(TrayDocument doc, ChapterWork work, string reason) { if (++work.Retries > 2) { StopChapterWork(doc, work, reason); return; } work.Busy = false; work.Processing = false; work.Command = Guid.Empty; work.PendingReuse.Clear();work.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.ReuseFinishing=false;work.Wrapped=false;work.FirstStart=-1;work.Attempts=0; work.Finished = false; work.Manifest = null; work.RetryAfter = ChapterNow.AddSeconds(15); doc.Status = reason; doc.LastChapterInterruption=reason; } private bool ChapterCapable(Guid instance){lock(gate)return chapterInstances.Contains(instance);} private readonly HashSet ribbonRequests=[]; private void ReceiveChapterRibbonRequest(TrayDocument doc,string kind) { doc.LastRibbonCommand=kind; if(doc.PendingRibbonCommand!=""||ribbonRequests.Contains(doc.Session)||doc.RibbonPermit!=Guid.Empty){doc.LastRibbonOutcome="Already awaiting the current verification request.";return;} if(doc.Capture!=null){SetRibbonOutcome(doc,"Needs review","Wait for the current manuscript transfer to finish, then retry.");return;} if(doc.WordSaved==false){SetRibbonOutcome(doc,"Save required","Save the manuscript in Word, then retry "+(kind=="tray-repair"?"Repair Synchronisation.":"Synchronise."));return;} if(kind=="tray-sync"&&chapterWork.TryGetValue(doc.Session,out var work)&&CurrentChapterWork(doc,work)&&work.Busy&&work.Operation!=Guid.Empty) {SetRibbonOutcome(doc,"Checking","Synchronisation is already running.");doc.RibbonNotice=null;return;} if(kind=="tray-sync"&&rangeInstances.Contains(doc.Instance)&&chapterWork.TryGetValue(doc.Session,out var incremental)&&CurrentChapterWork(doc,incremental)&&incremental.Manifest?.Mode=="OnSave"&&(!incremental.Finished||incremental.Completion?.State=="Synchronised")) { if(incremental.FailedRevision==doc.Revision){incremental.FailedRevision=-1;incremental.Retries=0;incremental.Attempts=0;incremental.Visited.Clear();incremental.Reviewed.Clear();} doc.NextChapterCheckUtc=ChapterNow;incremental.RetryAfter=ChapterNow;doc.RequestChapterPoll=incremental.Finished; doc.RibbonNotice=null;doc.LastRibbonOutcome=incremental.Busy?"Synchronise joined the current chapter check.":"Synchronise requested the pending chapter check."; doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;return; } doc.PendingRibbonCommand=kind; doc.RibbonRequestedUtc=ChapterNow; SetRibbonOutcome(doc,"Checking","Waiting for the current saved Word revision to be confirmed."); doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue; } private static void SetRibbonOutcome(TrayDocument doc,string state,string message) { doc.LastRibbonOutcome=message; doc.RibbonNotice=new(){State=state,Message=message}; } private void DispatchChapterRibbonRequest(TrayDocument doc,NativePresence reply) { if(doc.PendingRibbonCommand=="")return; if(!reply.ChapterSyncSupported||doc.Book<=0||doc.Capture!=null||doc.WordSaved==false|| ChapterNow-doc.RibbonRequestedUtc>TimeSpan.FromSeconds(15)) { doc.PendingRibbonCommand=""; SetRibbonOutcome(doc,doc.WordSaved==false?"Save required":"Needs review",doc.WordSaved==false ?"Save the manuscript in Word, then retry.":"The saved document connection is not ready. Check Companion and retry."); return; } if(doc.WordSaved!=true||reply.WordSaved!=true||reply.Revision!=doc.Revision)return; if(ribbonRequests.Count>=32||!ribbonRequests.Add(doc.Session))return; doc.PendingRibbonCommand=""; _=RequestChapterFromRibbon(doc,doc.Revision); } private async Task RequestChapterFromRibbon(TrayDocument doc,long revision) { var book=doc.Book;var context=doc.Authentication;var instance=doc.Instance;var session=doc.Session;var requested=doc.RibbonRequestedUtc; bool Current()=>documents.GetValueOrDefault(session)==doc&&doc.Revision==revision&&doc.Book==book&&doc.Authentication==context&&doc.RibbonRequestedUtc==requested; try { if(!cloud.Allows(context,book))throw new InvalidOperationException("Connect and select an authorised book first."); var reply=await cloud.RequestChapterRepair(book,new(){InstanceId=instance,SessionId=session,WordRevision=revision},context); if(reply.OperationId==Guid.Empty)throw new InvalidOperationException(string.IsNullOrWhiteSpace(reply.Message)?"Check the saved manuscript connection and retry.":reply.Message); lock(gate)if(Current()&&GetChapterWork(doc).Operation!=reply.OperationId){doc.RibbonPermit=reply.OperationId;doc.RibbonRequestedUtc=ChapterNow;SetRibbonOutcome(doc,"Checking",reply.Message);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;} } catch(Exception e)when(NetworkFailure(e)){lock(gate)if(Current())SetRibbonOutcome(doc,"Needs review","Chapter request was not accepted: "+e.Message);} finally{lock(gate)ribbonRequests.Remove(session);} } private bool IsChapterCommand(TrayDocument doc,Guid id)=>chapterWork.TryGetValue(doc.Session,out var work)&&id!=Guid.Empty&&work.Command==id; private void CancelChapterWork(TrayDocument doc){if(ChapterCapable(doc.Instance))ChapterCursorEvidence.Invalidate(doc);if(chapterWork.TryGetValue(doc.Session,out var work)){work.Command=Guid.Empty;work.Operation=Guid.Empty;work.PendingReuse.Clear();work.ReuseFinishing=false;work.Text=new();work.Xml=new();work.Identities=new();doc.ChapterProgress=null;work.Busy=false;work.FailedRevision=doc.Revision;}} private void BeginChapterRepair(TrayDocument doc,Guid operation) { if(!ChapterCapable(doc.Instance))return; doc.RibbonPermit=Guid.Empty;doc.RibbonNotice=null; doc.LastRibbonOutcome="Accepted: verification restarted with an explicit repair permit."; if(commands.TryGetValue(doc.Instance,out var queue))commands[doc.Instance]=new(queue.Where(c=>c.SessionId!=doc.Session||c.Kind!="chapter-check")); Queue(doc,new(){Kind="chapter-cancel"}); chapterWork.Remove(doc.Session); var work=GetChapterWork(doc);work.Operation=operation; doc.Status="Repairing existing chapter mappings; accepted scenes and author decisions are retained.";work.Busy=true;work.Started=ChapterNow;_ = LoadChapterManifest(doc,work); } private ChapterWork GetChapterWork(TrayDocument doc) { chapterWork.TryGetValue(doc.Session,out var work); if(work==null||work.Context!=doc.Authentication||work.Revision!=doc.Revision||work.Book!=doc.Book||work.Manuscript!=doc.Manuscript) { var prefer=rangeInstances.Contains(doc.Instance)&&work!=null&&work.Context==doc.Authentication&&work.Book==doc.Book&&work.Manuscript==doc.Manuscript&& (work.PreferRangeEvidence||work.Completion?.State=="Synchronised"); var prior=work; chapterWork[doc.Session]=work=new(){PreferRangeEvidence=prefer,RetryAfter=doc.NextChapterCheckUtc,RecognitionMs=(ChapterNow-doc.FirstObserved).TotalMilliseconds,Book=doc.Book,Manuscript=doc.Manuscript,Revision=doc.Revision,Context=doc.Authentication}; if(prefer&&doc.WordSaved==false&&prior?.Manifest!=null){work.Manifest=prior.Manifest;work.Completion=prior.Completion;work.Polling=true;work.ObserveOnly=true;} } return work; } private void ObserveChapterPresence(TrayDocument doc,NativePresence reply) { if(!ChapterCapable(doc.Instance))return; lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc)return;var work=GetChapterWork(doc);work.Supported=reply.ChapterSyncSupported;if(work.ContextMs<0&&ChapterCursorEvidence.Ready(doc))work.ContextMs=work.RecognitionMs+work.Elapsed.Elapsed.TotalMilliseconds; if(doc.RibbonPermit!=Guid.Empty&&reply.Navigation?.Id!=doc.RibbonPermit&&ChapterNow-doc.RibbonRequestedUtc>TimeSpan.FromSeconds(15)) {doc.RibbonPermit=Guid.Empty;SetRibbonOutcome(doc,"Needs review","The repair permit was not delivered. Check the connection and retry.");} DispatchChapterRibbonRequest(doc,reply); if(doc.PendingRibbonCommand!=""||doc.RibbonPermit!=Guid.Empty||ribbonRequests.Contains(doc.Session))return; if(work.Manifest!=null&&reply.ParagraphRevision>0&&reply.ParagraphRevision>work.Manifest.Revision){work.Completion=null;work.Manifest=null;work.PendingReuse.Clear();work.ReuseFinishing=false;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;} PumpChapterWork(doc,work); } } private void PumpChapterWork(TrayDocument doc,ChapterWork work) { if(doc.PendingRibbonCommand!=""||doc.RibbonPermit!=Guid.Empty||ribbonRequests.Contains(doc.Session))return; if(chapterProcessingSessions.Contains(doc.Session)&&!work.Processing)return; if(rangeInstances.Contains(doc.Instance)&&work.Finished&&!work.Busy&&work.Completion?.State=="Synchronised"&&work.Manifest?.Mode=="OnSave"&&(doc.WordSaved==true||work.ObserveOnly)&& (doc.RequestChapterPoll||ChapterNow-doc.LastChapterPollUtc>=TimeSpan.FromSeconds(60))) {work=BeginChapterPoll(doc,work);} if(ChapterNowwork.Start&&doc.Active&&doc.Cursor!=work.CursorWhenQueued&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor=work.End)){QueueChapter(doc,work,doc.Cursor);return;}if(ChapterNow-work.Started>TimeSpan.FromMinutes(2)){StopChapterWork(doc,work,"Chapter validation timed out. Accepted checkpoints are retained. Check the connection before retrying.");}return;} if(work.Manifest==null){work.Busy=true;work.Started=ChapterNow;_ = LoadChapterManifest(doc,work);return;} if(work.Polling){var candidate=work.Manifest!.Chapters.FirstOrDefault(c=>!work.Visited.Contains(c.ChapterId));if(candidate!=null)QueueChapter(doc,work,candidate.Start);return;} var here=work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor!work.Checked.ContainsKey(c.ChapterId)&&!work.PendingReuse.ContainsKey(c.ChapterId)&&!work.Reviewed.Contains(c.ChapterId)&&(c.State!="Needs review"||work.Operation!=Guid.Empty)); if(next!=null)QueueChapter(doc,work,next.Start); } private ChapterWork BeginChapterPoll(TrayDocument doc,ChapterWork prior) { var work=new ChapterWork{Book=prior.Book,Manuscript=prior.Manuscript,Revision=prior.Revision,Context=prior.Context, Manifest=prior.Manifest,Completion=prior.Completion,Supported=prior.Supported,PreferRangeEvidence=true,Polling=true,ObserveOnly=doc.WordSaved==false,RetryAfter=doc.NextChapterCheckUtc}; foreach(var p in prior.Checked)work.Checked[p.Key]=p.Value; chapterWork[doc.Session]=work;doc.RequestChapterPoll=false;doc.LastChapterPollUtc=ChapterNow; return work; } private async Task LoadChapterManifest(TrayDocument doc,ChapterWork work) { var timing=System.Diagnostics.Stopwatch.StartNew();work.Requests++; try{var manifest=await cloud.ChapterManifest(doc.Book,doc.Session,doc.Revision,doc.Authentication); lock(gate){if(!CurrentChapterWork(doc,work))return;if(manifest.ManuscriptId!=doc.Manuscript)throw new InvalidOperationException("Saved manuscript identity does not match this Word document.");work.ManifestMs+=timing.Elapsed.TotalMilliseconds;work.Manifest=manifest;work.Busy=false;if(manifest.Chapters.Length==0){StopChapterWork(doc,work,"No accepted chapter boundaries are available. Review the existing manuscript structure.");return;}if(work.Operation==Guid.Empty&&manifest.Chapters.All(c=>string.IsNullOrEmpty(c.HeadingNativeId))){StopChapterWork(doc,work,"This existing import has no native chapter identities. Use Repair Synchronisation to verify and adopt identities without reimporting.");return;}if(manifest.Mode=="Off"&&work.Operation==Guid.Empty){work.Finished=true;doc.Status="Automatic synchronisation is off. Use Synchronise or Repair for an explicit chapter check.";return;}foreach(var chapter in manifest.Chapters.Where(c=>c.State=="Synchronised"))work.Checked[chapter.ChapterId]=(chapter.Start,chapter.End);doc.Status=$"Chapter index ready: {work.Checked.Count}/{manifest.Chapters.Length} accepted for this Word session.";if(manifest.Chapters.Length>0&&work.Checked.Count==manifest.Chapters.Length){CompleteChapters(doc,work);}else if(manifest.Chapters.Length>0&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor!work.Checked.ContainsKey(c.ChapterId));if(next!=null)QueueChapter(doc,work,next.Start);}} }catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){RetryChapterWork(doc,work,"Chapter index unavailable: "+e.Message);}} } private bool CurrentChapterWork(TrayDocument doc,ChapterWork work)=>documents.GetValueOrDefault(doc.Session)==doc&&chapterWork.GetValueOrDefault(doc.Session)==work&&doc.Revision==work.Revision&&doc.Authentication==work.Context&&doc.Book==work.Book&&doc.Manuscript==work.Manuscript; private void QueueChapter(TrayDocument doc,ChapterWork work,int position) { if(chapterWork.Values.Count(w=>w!=work&&w.Busy&&w.Command!=Guid.Empty)>=2){ if(!doc.Active)return; var background=chapterWork.FirstOrDefault(p=>p.Value!=work&&p.Value.Busy&&p.Value.Command!=Guid.Empty&&documents.TryGetValue(p.Key,out var candidate)&&!candidate.Active); if(background.Value==null||!documents.TryGetValue(background.Key,out var backgroundDoc))return; Queue(backgroundDoc,new(){Kind="chapter-cancel"});background.Value.Command=Guid.Empty;background.Value.Busy=false;background.Value.Text=new();background.Value.Xml=new(); } if (work.Attempts >= (work.Manifest?.Chapters.Length ?? 0) * 2 + 2) { StopChapterWork(doc, work, "Chapter checks reached the retry limit. " + work.ReviewReason); return; } var baseline=work.PreferRangeEvidence?work.Manifest?.Chapters.FirstOrDefault(c=>position>=c.Start&&positionc.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=="chapter-observe") { if(!work.ObserveOnly||message.ChapterId!=work.ExpectedProbeChapter||message.ChapterId==null||work.Manifest==null)return; if(message.Action=="changed"){if(work.Dirty.Add(message.ChapterId.Value)){doc.AudioTextChanges++;_ = cloud.QueueWritingObservation(doc.Book,doc.Manuscript,message.ChapterId.Value,doc.Session,doc.Revision,doc.Authentication);}}else work.Dirty.Remove(message.ChapterId.Value); work.Visited.Add(message.ChapterId.Value);work.Calculated++;work.Busy=false;work.Processing=false;work.Command=Guid.Empty; AdvanceChapter(doc,work);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" or "positions" or "live-text"; if(identityFrame){if(work.IdentityAction!=""&&work.IdentityAction!=message.Action){StopChapterWork(doc,work,"Mixed native paragraph evidence was rejected.");return;}work.IdentityAction=message.Action;work.NativeTextVerified=message.Action=="ids-exact";} var value=message.Action=="text"?work.Text:identityFrame?work.Identities:work.Xml;var limit=message.Action=="text"?ChapterFingerprint.MaxCharacters:identityFrame?(message.Action=="positions"?ChapterWordPositions.MaxFrameCharacters:ChapterFingerprint.MaxParagraphs*24):8*1024*1024; if(message.Start!=value.Length||value.Length+message.OperationMessage.Length>limit){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Incomplete or oversized chapter frames; no checkpoint accepted.";return;}value.Append(message.OperationMessage);return; } if(message.Kind=="chapter-end"){if(!work.Begun||work.Processing)return;work.Processing=true;var text=work.Text.ToString();var xml=work.Xml.ToString();var identities=work.Identities.Length==0?null:work.Identities.ToString();work.Text=new();work.Xml=new();work.Identities=new();_ = ProcessChapter(doc,work,text,xml,identities,work.Command,work.Start,work.End,work.Next,work.Operation,work.IdentityAction=="positions");} } private void AdvanceChapter(TrayDocument doc,ChapterWork work) { if(work.Manifest==null)return; if(work.Polling) { var nextProbe=work.Manifest.Chapters.FirstOrDefault(c=>!work.Visited.Contains(c.ChapterId)); if(nextProbe!=null){QueueChapter(doc,work,nextProbe.Start);return;} work.Finished=true;work.Busy=false;work.Processing=false;work.Command=Guid.Empty; work.CompleteMs=work.Elapsed.Elapsed.TotalMilliseconds;doc.LastChapterPollUtc=ChapterNow; doc.ChapterProgress=work.Completion;doc.Status=work.ObserveOnly ?$"{work.Dirty.Count} edited chapters detected in memory. Save when ready to validate native positions and reconcile; accepted checkpoints are retained." :$"{work.Checked.Count} chapters verified; periodic range check retained {work.Retained} checkpoints.";return; } if(work.Manifest.Chapters.All(c=>work.Checked.ContainsKey(c.ChapterId)||work.PendingReuse.ContainsKey(c.ChapterId)||work.Reviewed.Contains(c.ChapterId))){CompleteChapters(doc,work);return;} var next=work.End; for(int count=0;countp.Value.Start==next&&p.Value.End>next); if(cached.Value.End<=next){var pending=work.PendingReuse.Values.FirstOrDefault(p=>p.Start==next&&p.End>next);if(pending!=null){next=pending.End;continue;}} if(cached.Value.End>next){next=cached.Value.End;continue;} break; } if(work.FirstStart==0&&next>=work.DocumentEnd){CompleteChapters(doc,work);return;} if(next0){if(!work.ReuseFinishing){work.ReuseFinishing=true;work.Busy=true;work.Processing=true;work.Command=Guid.Empty;_ = CompleteReuseAndChapters(doc,work);}return;} 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;iid>0).ToArray(),HasIssues=work.Reviewed.Count>0||work.Manifest!.Chapters.Any(c=>!work.Checked.ContainsKey(c.ChapterId))};CountChapterRequest(work,completion); try{var result=await cloud.FinishChapters(doc.Book,completion,work.Context);lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;work.Processing=false;work.CompleteMs=work.RecognitionMs+work.Elapsed.Elapsed.TotalMilliseconds;work.Completion=result;doc.LastChapterPollUtc=ChapterNow;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 static void UpdateChapterSeekHints(ChapterManifest manifest,ChapterManifestItem chapter,int start,int end,string nextHeading) { // These are navigation hints, not accepted positions. Every target range // still proves its live heading, identity, content and absolute geometry. if(start!=chapter.Start||nextHeading!=chapter.NextHeadingId)return; var delta=end-chapter.End;if(delta==0)return; var index=Array.IndexOf(manifest.Chapters,chapter); for(var i=index+1;iwork.IdentityAction=="live-text"?ChapterFingerprint.ReadLiveText(text,identities??""):physicalPositions?ChapterFingerprint.ReadXml(xml,text,null,true,ChapterWordPositions.Decode(identities??"")):ChapterFingerprint.ReadXml(xml,text,identities,nativeTextVerified));xml="";text=""; lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(work.IdentityAction=="live-text")work.LiveReads++;else work.XmlReads++;} ChapterManifest manifest;lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;manifest=work.Manifest!;} if(physicalPositions&&!manifest.NativePositionsSupported)throw new ArgumentException("Update the Development server to validate native picture positions. Existing checkpoints are retained."); var hash=ChapterFingerprint.Content(rows.Select(p=>p.Text!));lock(gate){work.Calculated++;} 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.Incompatible++;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.PendingReuse.TryGetValue(chapter.ChapterId,out var pending)||pending.Start!=start||pending.End!=end)){work.Reviewed.Add(chapter.ChapterId);work.Checked.Remove(chapter.ChapterId);work.PendingReuse.Remove(chapter.ChapterId);doc.Status="Duplicate chapter identity at another position; existing canonical structure is retained for review.";}AdvanceChapter(doc,work);return;}}var proof=new ChapterObservation{RequestId=command,OperationId=operation,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,WordRevision=doc.Revision,BaseRevision=manifest.Revision,ChapterId=chapter.ChapterId,Start=start,End=end,NextHeadingId=nextHeading,ContentHash=hash,IdentityHash=ChapterFingerprint.Identity(rows),PositionHash=physicalPositions?ChapterWordPositions.Hash(rows):"",Paragraphs=rows.Select(p=>new ChapterParagraph{NativeId=p.NativeId,Length=p.Length,Outline=p.Outline,WordLength=p.WordLength,Anchors=p.Anchors}).ToArray()}; lock(gate){if(chapter.ContentHash!=proof.ContentHash)work.Mismatching++;else if(ChapterCheckpointReuse.Matches(chapter,proof))work.Matching++;else if(!chapter.DurableAccepted)work.Missing++;else work.Incompatible++;work.VerificationMs+=verification.Elapsed.TotalMilliseconds;} if(work.Polling) { lock(gate) { if(!CurrentChapterWork(doc,work)||work.Command!=command)return; if(!ChapterCheckpointReuse.Matches(chapter,proof)||!work.Checked.TryGetValue(chapter.ChapterId,out var retained)||retained.Start!=start||retained.End!=end) { work.Checked.Remove(chapter.ChapterId);work.Command=Guid.Empty;work.Processing=false; if(!Queue(doc,new(){Kind="chapter-recheck-revision"}))StopChapterWork(doc,work,"Word queue is busy; retry Synchronise."); return; } chapter.Start=start;chapter.End=end;work.Retained++;work.Busy=false;work.Processing=false;AdvanceChapter(doc,work);return; } } lock(gate){if(!CurrentChapterWork(doc,work)||work.Command!=command)return;UpdateChapterSeekHints(manifest,chapter,start,end,nextHeading);} if(manifest.CheckpointReuseSupported&&ChapterCheckpointReuse.Matches(chapter,proof)) { bool flush;lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;flush=work.PendingReuse.Values.Sum(p=>p.Paragraphs.Length)+proof.Paragraphs.Length>20000||work.PendingReuse.Count>=64;} if(flush)await FlushReuse(doc,work); lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.PendingReuse[chapter.ChapterId]=proof;} if(work.Checked.Count==0&&doc.Cursor>=start&&doc.Cursorp.Text!=null))work.Reconciled++;work.Busy=false;work.Reconciling=false; if(result.Accepted){work.Retries=0;work.Checked[chapter.ChapterId]=(start,end);manifest.Revision=result.Revision; chapter.ContentHash=proof.ContentHash;chapter.IdentityHash=proof.IdentityHash;chapter.PositionHash=proof.PositionHash;chapter.NextHeadingId=proof.NextHeadingId;chapter.HeadingNativeId=proof.Paragraphs[0].NativeId;chapter.ParagraphCount=proof.Paragraphs.Length;chapter.DurableAccepted=result.State!="Needs review";chapter.Start=start;chapter.End=end;if(result.State=="Needs review")work.Reviewed.Add(chapter.ChapterId);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status=$"{work.Checked.Count}/{manifest.Chapters.Length} chapters accepted · "+result.Message;AdvanceChapter(doc,work);} else{work.Reviewed.Add(chapter.ChapterId);work.ReviewReason=result.Message;doc.Status=result.Message+" Accepted chapter repairs are retained.";AdvanceChapter(doc,work);} } }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 or ChapterReuseConflictException||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){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{lock(gate)chapterProcessingSessions.Remove(doc.Session);chapterProcessing.Release();} } }