using System.Diagnostics; using PlotDirector.Companion.Agent; using PlotDirector.Companion.Client; using PlotDirector.Companion.Protocol; internal static class AnalysisTests { public static async Task Run(Action check) { ParagraphFragment Fragment(string text,int index=1,int start=0,int outline=10,string[]? tags=null) => new(){Text=text,Start=start,End=start+text.Length,ParagraphIndex=index,OutlineLevel=outline,MarkerTags=tags??[],CompletesParagraph=true}; var blank=new DocumentAnalysis();blank.Add(Fragment("\r")); check(blank.Page(0).WordCount==0&&blank.Page(0).Total==0&&blank.Page(0).Notice.Contains("No manuscript"),"blank document has an explicit empty analysis"); var countOnly=new DocumentAnalysis(false); countOnly.Add(new(){Text="hel",Start=0,End=3,CompletesParagraph=false}); countOnly.Add(new(){Text="lo world\r",Start=3,End=12,CompletesParagraph=true}); check(countOnly.WordCount==2&&countOnly.Count==0,"normal snapshot counts across split fragments without retaining review candidates"); var ordinary=new DocumentAnalysis();var position=0;var index=0; foreach(var text in new[]{"Chapter One\r","Ordinary manuscript prose.\r","* * *\r","Another scene.\r","Chapter 2: Return\r","More prose.\r"}) {ordinary.Add(Fragment(text,++index,position));position+=text.Length;} check(ordinary.Page(0).ChapterCount==2&&ordinary.Page(0).SceneCount==1,"plain chapter labels and separators become review suggestions"); var ambiguous=new DocumentAnalysis(); ambiguous.Add(Fragment("12\r"));ambiguous.Add(Fragment("Chapter One was what she called it.\r",2,3)); ambiguous.Add(Fragment("A scene\r",3,40,2)); check(ambiguous.Page(0).Items[0].Confidence=="Uncertain"&&ambiguous.Page(0).Items[1].Confidence=="Possible"&&ambiguous.Page(0).Items[2].Reason.Contains("review"),"ambiguous text and heading levels explain uncertainty instead of approving import"); var marked=new DocumentAnalysis();marked.Add(Fragment("Tagged chapter\r",1,0,10,["PD_CHAPTER_42"]));marked.Add(Fragment("Tagged scene\r",2,15,10,["PD_SCENE_77"])); check(marked.Page(0).Items.All(i=>i.Confidence=="Strong")&&marked.Page(0).ChapterCount==1&&marked.Page(0).SceneCount==1,"analysis reuses existing PlotDirector marker interpretation"); var fragmented=new DocumentAnalysis();fragmented.Add(new(){Text="hel",Start=0,End=3,ParagraphIndex=1,OutlineLevel=10,CompletesParagraph=false}); fragmented.Add(new(){Text="lo world\r",Start=3,End=12,ParagraphIndex=1,OutlineLevel=10,CompletesParagraph=true}); check(fragmented.Page(0).WordCount==2&&fragmented.Page(0).ParagraphCount==1,"fragment splits do not inflate word or paragraph counts"); var large=new DocumentAnalysis();var clock=Stopwatch.StartNew(); for(var i=0;i<25000;i++)large.Add(Fragment("one two three four five six seven eight nine ten\r",i+1,i*48,i%1000==0?1:10)); check(large.Page(0).WordCount==250000&&large.Page(0).ParagraphCount==25000&&large.Page(0).ChapterCount==25,"250000-word many-paragraph manuscript analysed incrementally"); Console.WriteLine($"Agent synthetic 250000-word analysis: {clock.ElapsedMilliseconds}ms (not Word extraction/UI timing)."); var dense=new DocumentAnalysis();for(var i=0;i<9000;i++)dense.Add(Fragment("Heading\r",i+1,i*8,1)); check(dense.Page(0).Truncated&&dense.Page(0).Total==8192,"review suggestion storage is bounded with explicit truncation"); var page=dense.Page(40);check(page.Offset==40&&page.Items.Length==ProtocolVersion.AnalysisPageSize,"analysis results are paginated"); using(var stream=new MemoryStream()) {await FrameCodec.WriteAsync(stream,new(){Analysis=page},CancellationToken.None);check(stream.Lengthnew DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Revision=1}).ToArray(); Send(new(){Kind="reconcile",Documents=docs}); var snapshots=new List(); foreach(var doc in docs) { var snapshot=Guid.NewGuid();snapshots.Add(snapshot);var fragment=Fragment("Chapter One\r"); Send(new(){Kind="snapshot-begin",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot,End=fragment.End,RequestAnalysis=true}); var progress=Send(new(){Kind="snapshot-fragment",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot,Fragment=fragment}); var result=Send(new(){Kind="snapshot-end",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot}); check(progress.Progress==100&&result.Status=="analysis-complete"&&result.Analysis?.ChapterCount==1,"document-specific analysis returns structured results and progress"); } check(Send(new(){Kind="analysis-page",SessionId=docs[0].SessionId,Revision=1,SnapshotId=snapshots[1]}).Status=="analysis-unavailable","another document's snapshot cannot retrieve results"); var cancelled=Guid.NewGuid();Send(new(){Kind="snapshot-begin",SessionId=docs[0].SessionId,Revision=1,SnapshotId=cancelled,End=20,RequestAnalysis=true}); var partial=Send(new(){Kind="snapshot-fragment",SessionId=docs[0].SessionId,Revision=1,SnapshotId=cancelled,Fragment=Fragment("first\r")}); check(partial.Progress==30,"analysis acknowledges bounded partial progress before cancellation"); Send(new(){Kind="snapshot-cancel",SessionId=docs[0].SessionId,Revision=1,SnapshotId=cancelled}); check(Send(new(){Kind="snapshot-end",SessionId=docs[0].SessionId,Revision=1,SnapshotId=cancelled}).Status=="obsolete-snapshot","cancelled analysis cannot complete"); var review=new AnalysisReview();review.Prepare(docs[0].SessionId); check(review.Running&&review.SnapshotId==Guid.Empty,"analysis waiting for Word scheduler is cancellable");review.Stop("Cancelled before extraction");check(!review.Running,"pending analysis cancellation does not require extraction");review.Begin(docs[0].SessionId,1,snapshots[0]); check(!review.Accept(new(){SessionId=docs[1].SessionId,Revision=1,SnapshotId=snapshots[0],Status="analysis-complete",Analysis=page}),"review rejects results from a different document"); review.Stop("Cancelled");check(!review.Accept(new(){SessionId=docs[0].SessionId,Revision=1,SnapshotId=snapshots[0],Status="analysis-complete",Analysis=page}),"late results cannot replace cancellation"); review.Begin(docs[0].SessionId,2,Guid.NewGuid()); check(!review.Accept(new(){SessionId=docs[0].SessionId,Revision=1,SnapshotId=snapshots[0],Status="analysis-complete",Analysis=page}),"new analysis rejects obsolete revision and snapshot"); var complete=new Message{SessionId=review.SessionId,Revision=review.Revision,SnapshotId=review.SnapshotId,Status="analysis-complete",Analysis=ordinary.Page(0)}; check(review.Accept(complete)&&!review.Running&&review.Page?.ChapterCount==2,"review completes only matching analysis"); check(!review.Accept(new(){SessionId=review.SessionId,Revision=review.Revision,SnapshotId=review.SnapshotId,Status="ok"})&&review.Status.Contains("complete"),"selection replies cannot regress completed review progress"); review.ExpectPage(40);check(!review.Accept(complete),"late page zero cannot replace requested later page"); sessions.Detach(instance,lease);sessions.Attach(instance,Guid.NewGuid()); check(sessions.SessionCount==0,"agent restart releases document analysis state"); } }