using System.Text; using PlotDirector.Companion.Protocol; using PlotDirector.Companion.Protocol.Manuscript; namespace PlotDirector.Companion.Agent; public sealed partial class TrayCoordinator { private sealed class ChapterWork { 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 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 (!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) { var step = work.Processing ? "Verifying chapter with PlotDirector" : "Checking Word chapter"; if (work.Attempts > 0 && work.Attempts <= total) step += $" {work.Attempts} of {total}"; return new() { State = "Checking", Total = total, Matching = accepted, Message = step }; } return doc.ChapterProgress; } 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.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.Finished = false; work.Manifest = null; work.RetryAfter = DateTime.UtcNow.AddSeconds(15); doc.Status = reason; } private bool ChapterCapable(Guid instance){lock(gate)return chapterInstances.Contains(instance);} private readonly HashSet ribbonRequests=[]; private async Task RequestChapterFromRibbon(TrayDocument doc,long revision) { int book;Guid context,instance,session; lock(gate){if(ribbonRequests.Count>=32||!ribbonRequests.Add(doc.Session))return;book=doc.Book;context=doc.Authentication;instance=doc.Instance;session=doc.Session;} 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);lock(gate)if(documents.GetValueOrDefault(session)==doc&&doc.Revision==revision&&doc.Authentication==context){doc.Status=reply.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}} catch(Exception e)when(NetworkFailure(e)){lock(gate)if(documents.GetValueOrDefault(session)==doc)doc.Status="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(chapterWork.TryGetValue(doc.Session,out var work)){work.Command=Guid.Empty;work.Operation=Guid.Empty;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; var work=GetChapterWork(doc);work.Completion=null;work.Operation=operation;work.FailedRevision=-1;work.Attempts=0;work.Retries=0;work.ReviewReason="";work.Manifest=null;work.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.Wrapped=false;work.FirstStart=-1;work.Finished=false;work.Command=Guid.Empty;work.Busy=false; doc.Status="Repairing existing chapter mappings; accepted scenes and author decisions are retained.";work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work); } private ChapterWork GetChapterWork(TrayDocument doc) { if(!chapterWork.TryGetValue(doc.Session,out var work)||work.Context!=doc.Authentication||work.Revision!=doc.Revision||work.Book!=doc.Book||work.Manuscript!=doc.Manuscript)chapterWork[doc.Session]=work=new(){Book=doc.Book,Manuscript=doc.Manuscript,Revision=doc.Revision,Context=doc.Authentication};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.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Completion=null;work.Manifest=null;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;} if(DateTime.UtcNowwork.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(DateTime.UtcNow-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=DateTime.UtcNow;_ = LoadChapterManifest(doc,work);return;} var here=work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor!work.Checked.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 async Task LoadChapterManifest(TrayDocument doc,ChapterWork work) { 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.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 command=new AdapterCommand{Kind="chapter-check",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();doc.Status=$"Checking chapter positions ({work.Checked.Count}/{work.Manifest!.Chapters.Length} accepted); Word prose is unchanged.";} } 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.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 value=message.Action=="text"?work.Text:message.Action=="ids"?work.Identities:work.Xml;var limit=message.Action=="text"?ChapterFingerprint.MaxCharacters:message.Action=="ids"?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);} } private void AdvanceChapter(TrayDocument doc,ChapterWork work) { if(work.Manifest==null)return; var next=work.End; for(int count=0;countp.Value.Start==next&&p.Value.End>next); if(cached.Value.End>next){next=cached.Value.End;continue;} break; } if(work.FirstStart==0&&next>=work.DocumentEnd){CompleteChapters(doc,work);return;} if(nextc.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))},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) { 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,identities));xml="";text=""; ChapterManifest manifest;lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;manifest=work.Manifest!;} 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 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; if(result.Accepted){work.Retries=0;work.Checked[chapter.ChapterId]=(start,end);manifest.Revision=result.Revision;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||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{work.FailedRevision=doc.Revision;doc.Status="Chapter needs review: "+e.Message+" Existing import is unchanged.";}}} finally{chapterProcessing.Release();} } }