using System.Diagnostics; using System.IO.Pipes; using System.Text; using PlotDirector.Companion.Agent; using PlotDirector.Companion.Client; using PlotDirector.Companion.Protocol; using PlotDirector.Companion.Protocol.Manuscript; internal static class WordReopeningWorkTests { private static void Check(bool value,string text){if(!value)throw new Exception(text);Console.WriteLine("PASS "+text);} private static void Reject(Action action,string text){try{action();}catch(InvalidOperationException){Check(true,text);return;}throw new Exception(text);} public static async Task Run() { double time=0;var scheduler=new WordAccessScheduler(()=>time);WordQueueWait? wait=null; scheduler.Waited+=(key,delay)=>{if(key=="chapter:proof")wait=delay;}; scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(10));scheduler.Post("chapter:proof",()=>time+=2); time=5;Check(!scheduler.HasRunnableChapterWork,"Author quiet periods suppress accelerated chapter scheduling");Check(!scheduler.Pump(),"Chapter work respects an outstanding author quiet period");time=25;Check(scheduler.HasRunnableChapterWork,"Only runnable chapter work requests the shorter timer cadence");scheduler.Pump(); Check(wait is {TotalMs:25,AuthorQuietMs:10,OtherWorkMs:0,TimerHostIdleMs:15},"Monotonic queue timings separate author delay and eligible timer/host idle"); time=0;scheduler=new WordAccessScheduler(()=>time);wait=null;scheduler.Waited+=(key,delay)=>{if(key=="chapter:proof")wait=delay;}; scheduler.Post("selection",()=>time+=4);scheduler.Post("chapter:proof",()=>{});scheduler.Pump();time=10;scheduler.Pump(); Check(wait is {TotalMs:10,OtherWorkMs:4,TimerHostIdleMs:6},"Queue timing separates earlier scheduled active work from idle waiting"); Check(ChapterIdentityRead.CanContinue(0,100)&&!ChapterIdentityRead.CanContinue(1,8)&&!ChapterIdentityRead.CanContinue(32,0),"Paragraph batches always make bounded progress and stop on either time or count limit"); var paragraphCount=0;var batches=0;var words=0;var watch=Stopwatch.StartNew(); for(var chapter=0;chapter<48;chapter++) { var count=chapter==47?8457-47*176:176;var paragraphs=Enumerable.Range(0,count).Select(n=>n==0?$"Chapter {chapter}\r":string.Join(" ",Enumerable.Repeat("synthetic",18+(n%5==0?1:0)))+"\r").ToArray(); var text=string.Concat(paragraphs);var frames=new StringBuilder();var position=0; for(var offset=0;offsetp.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length); Check(ChapterFingerprint.Content(decoded.Select(p=>p.Text!))==ChapterFingerprint.Content(paragraphs),"Bounded native identity batches preserve exact accepted paragraph partition and content hash"); var changed=frames.ToString();var changedId="7FFFFFFF"+changed[8..]; Check(ChapterFingerprint.Identity(ChapterFingerprint.ReadLiveText(text,changedId))!=ChapterFingerprint.Identity(decoded),"Changed native identity with unchanged prose cannot reuse the checkpoint"); } Check(paragraphCount==8457&&batches==288,"Scale fixture visits every required native identity once with 288 collection acquisitions instead of 8457"); Console.WriteLine($"PORTABLE read fixture: 48 chapters / {paragraphCount} paragraphs / {words} words, {watch.Elapsed.TotalMilliseconds:F1}ms. Point/collection setups 8457 -> {batches}; saved-state calls for the paragraph walk 16914 -> {batches*4}. No Word/COM timing."); Reject(()=>ChapterIdentityRead.Append(new(),0,10,1,10,"00000001",10),"Inserted/deleted/moved native paragraph gaps cannot be accepted as contiguous evidence"); Reject(()=>ChapterIdentityRead.Append(new(),0,10,0,11,"00000001",10),"A paragraph extending across the live chapter boundary is refused"); var repeated=new[]{"Heading\r","Repeated\r","Repeated\r"};var stableFrames=new StringBuilder();var cursor=0; for(var i=0;i<3;i++){var end=cursor+repeated[i].Length;cursor=ChapterIdentityRead.Append(stableFrames,cursor,repeated.Sum(t=>t.Length),cursor,end,(i+1).ToString("X8"),i==0?1:10);} var stable=ChapterFingerprint.ReadLiveText(string.Concat(repeated),stableFrames.ToString()); var moved=stableFrames.ToString()[..24]+stableFrames.ToString().Substring(48,24)+stableFrames.ToString().Substring(24,24); var movedRows=ChapterFingerprint.ReadLiveText(string.Concat(repeated),moved); Check(ChapterFingerprint.Content(movedRows.Select(p=>p.Text!))==ChapterFingerprint.Content(repeated)&&ChapterFingerprint.Identity(movedRows)!=ChapterFingerprint.Identity(stable),"Moving identical prose paragraphs changes identity evidence even when the chapter text fingerprint matches"); var doc=new TrayDocument{Book=1,Manuscript=Guid.NewGuid(),Cursor=100,Revision=2,WordSaved=true}; NativePresence Proof(int cursor,int? scene)=>new(){BookId=doc.Book,ManuscriptId=doc.Manuscript,CursorStart=cursor,Revision=2,WordSaved=true,ParagraphRevision=3,ChapterId=4,SceneId=scene,SceneTitle=scene.HasValue?"Verified scene":""}; Check(ChapterCursorEvidence.Apply(doc,Proof(100,5))&&ChapterCursorEvidence.Ready(doc),"Writing Context becomes ready from verified current-cursor scene evidence before book completion"); doc.Cursor=200;ChapterCursorEvidence.Invalidate(doc); Check(!ChapterCursorEvidence.Apply(doc,Proof(100,5))&&!ChapterCursorEvidence.Ready(doc),"A late presence reply cannot restore the scene at a previous cursor"); Check(ChapterCursorEvidence.Apply(doc,Proof(200,null))&&!ChapterCursorEvidence.Ready(doc)&&ChapterCursorEvidence.State(doc).StartsWith("Verified chapter; no scene"),"A verified chapter without a mapped scene never acquires a first-scene fallback"); var unmapped=Proof(200,null);unmapped.ChapterId=null;ChapterCursorEvidence.Apply(doc,unmapped); Check(ChapterCursorEvidence.State(doc).Contains("not yet verified")&&ChapterCursorEvidence.State(doc,true,false).Contains("outside mapped chapters"),"Only whole-manuscript verification can distinguish an outside-chapter cursor from pending verification"); time=0;scheduler=new WordAccessScheduler(()=>time);scheduler.Post("chapter:outer",()=>Check(!scheduler.Pump(),"A reentrant timer cannot nest Word COM work inside an active callback"));scheduler.Pump(); var stale=Proof(200,5);stale.Revision--;Check(!ChapterCursorEvidence.Apply(doc,stale),"Stale Word revision cannot make Context ready"); doc.WordSaved=false;Check(!ChapterCursorEvidence.Apply(doc,Proof(200,5)),"Unsaved Word state cannot claim a verified Context scene"); await PipeHandoff(); } private static async Task PipeHandoff() { var name="pd-reopen-"+Guid.NewGuid().ToString("N");var session=Guid.NewGuid();var instance=Guid.NewGuid(); using var stop=new CancellationTokenSource(TimeSpan.FromSeconds(10));using var server=new NamedPipeServerStream(name,PipeDirection.InOut,1,PipeTransmissionMode.Byte,PipeOptions.Asynchronous|PipeOptions.CurrentUserOnly); var received=0;var polls=0;var expired=0;var ends=0;var ready=DateTime.MaxValue; var host=Task.Run(async()=>{await server.WaitForConnectionAsync(stop.Token);while(!stop.IsCancellationRequested){var request=await FrameCodec.ReadAsync(server,stop.Token);var answer=new Message{CorrelationId=request.CorrelationId,Status=request.Kind=="hello"?"ready":"ok",Capabilities=ProtocolVersion.Capabilities};if(request.Kind=="chapter-end")ready=++ends==1?DateTime.UtcNow.AddMilliseconds(40):DateTime.MaxValue;if(request.Kind=="ping"){polls++;if(DateTime.UtcNow>=ready){ready=DateTime.MaxValue;answer.Command=new(){Kind="chapter-check",SessionId=session,Revision=1};}}await FrameCodec.WriteAsync(server,answer,stop.Token);}}); using var link=new AgentLink(name,instance,_=>true);var measured=0;var connected=false; link.ChapterHandoff+=m=>{if(m.Reason=="window-ended")Interlocked.Increment(ref expired);if(m.Reason=="next-command"){Interlocked.Increment(ref measured);Check(m.Polls>0&&m.ExchangeMs>=0&&m.IdleMs>=0,"Chapter handoff exposes actual pipe and worker-idle timing");}}; link.StateChanged+=state=>connected=state=="connected"; link.Received+=reply=>{if(reply.Command?.Kind=="chapter-check")Interlocked.Increment(ref received);};link.Start();while(!connected)await Task.Delay(5,stop.Token); link.TryPost(new(){Kind="chapter-end",SessionId=session,Revision=1,SnapshotId=Guid.NewGuid()}); var watch=Stopwatch.StartNew();while(received==0){await Task.Delay(5,stop.Token);} Check(measured==1&&polls>0,"Next asynchronous chapter command arrives without another selection or metrics frame"); Console.WriteLine($"PORTABLE real pipe handoff (Linux sockets): {watch.Elapsed.TotalMilliseconds:F1}ms, {polls} polls; not Windows IPC/Word performance."); link.TryPost(new(){Kind="chapter-end",SessionId=session,Revision=1,SnapshotId=Guid.NewGuid()}); while(expired==0)await Task.Delay(5,stop.Token);var stoppedAt=polls;await Task.Delay(250,stop.Token); Check(stoppedAt>0&&polls-stoppedAt<=3,"Fast chapter polling expires and returns to bounded 100ms idle pickup"); link.Dispose();await link.Completion.WaitAsync(TimeSpan.FromSeconds(5));stop.Cancel();try{await host;}catch(Exception e)when(e is OperationCanceledException or IOException or ObjectDisposedException){} } }