using System.IO.Pipes; using PlotDirector.Companion.Agent; using PlotDirector.Companion.Client; using PlotDirector.Companion.Protocol; if(args.Contains("--chapter-sync")){ChapterRangeVerificationTests.Run();ChapterReopenTests.Run();await ChapterAgentTests.Run();await ChapterHandshakeTests.Run();await WordReopeningWorkTests.Run();return;} if(args.Contains("--native-capture-upload")){await NativeCaptureUploadTests.Run();return;} var passed = 0; void Check(bool value,string name) {if(!value)throw new Exception(name);passed++;Console.WriteLine("PASS "+name);} Check(AudioSourceSelection.Key(null,null,["narration"])=="narration","One controllable audio source is selected automatically"); Check(AudioSourceSelection.Key(null,null,["narration","music"])==null,"Ambiguous media sources require selection"); Check(AudioSourceSelection.Key(null,"narration",["narration","music"])=="narration","Explicit source selection resolves ambiguity"); Check(AudioSourceSelection.Key("narration",null,[])=="narration"&& AudioSourceSelection.Key("narration",null,["narration"])=="narration","Missing telemetry retains the binding and the same paused source can recover"); Check(AudioSourceSelection.Key("narration",null,["music"])=="narration"&& AudioSourceSelection.Key("narration","music",["music"])==null,"An existing review cannot switch to a different native media key"); async Task Until(Func condition,string name) {using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(12));while(!condition()){await Task.Delay(20,timeout.Token);}Check(true,name);} void SchedulerChecks() { var scheduler=new WordAccessScheduler();var value=0;var measured=0; scheduler.Measured+=(_,ms)=>{Check(ms>=0,"Word operation timing recorded");measured++;}; for(var i=0;i<1000;i++){var latest=i;scheduler.Post("selection",()=>value=latest);} Check(scheduler.Depth==1&&scheduler.Superseded==999,"selection scheduler coalesces bursts");scheduler.Pump();Check(value==999&&measured==1,"only latest selection executes on owner"); scheduler.Post("obsolete",()=>throw new Exception("Should be cancelled"));scheduler.Cancel("obsolete");Check(!scheduler.Pump(),"obsolete Word work cancelled"); for(var i=0;i{}),"bounded Word queue accepts capacity slot "+i); Check(!scheduler.Post("overflow",()=>{}),"Word queue rejects overflow without waiting");scheduler.Clear(); var rejected=false;var thread=new Thread(()=>{try{scheduler.Pump();}catch(InvalidOperationException){rejected=true;}});thread.Start();thread.Join();Check(rejected,"Word scheduler rejects wrong thread"); scheduler.PrioritizeAuthor(TimeSpan.FromMinutes(1));scheduler.Post("low",()=>value=0);Check(!scheduler.Pump()&&value==999,"author activity suspends low priority work"); } SchedulerChecks(); var mailbox=new BoundedMailbox();var id=Guid.NewGuid(); for(var i=0;i<10000;i++)mailbox.TryPost(new Message{Kind="selection",SessionId=id,Start=i}); Check(mailbox.Depth==1&&mailbox.Coalesced==9999,"IPC coalesces selection storm to latest value");mailbox.TryTake(out var latestMessage);Check(latestMessage!.Start==9999,"coalesced position is latest"); for(var i=0;inew DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),ProjectId=10+i,BookId=20+i,Revision=1}).ToArray(); Check(Apply(new Message{Kind="reconcile",Documents=descriptors}).Status=="ok"&&sessions.SessionCount==3,"three books have independent live sessions"); for(var book=0;bookTask.Run(()=>new PipeHost(pipeName,serverSessions).RunAsync(token)); var host=StartHost(stopHost.Token); using(var bad=new NamedPipeClientStream(".",pipeName,PipeDirection.InOut,PipeOptions.Asynchronous)) { await bad.ConnectAsync(3000);var hello=new Message{Kind="hello",Version=99,WordInstanceId=Guid.NewGuid()};await FrameCodec.WriteAsync(bad,hello,CancellationToken.None); Check((await FrameCodec.ReadAsync(bad,CancellationToken.None)).Status=="unsupported-version","real pipe rejects incompatible handshake"); } using(var compatible=new NamedPipeClientStream(".",pipeName,PipeDirection.InOut,PipeOptions.Asynchronous)) { await compatible.ConnectAsync(3000);var hello=new Message{Kind="hello",WordInstanceId=Guid.NewGuid(),Capabilities=ProtocolVersion.Capabilities+",future-optional"}; await FrameCodec.WriteAsync(compatible,hello,CancellationToken.None); var ready=await FrameCodec.ReadAsync(compatible,CancellationToken.None); Check(ready.Status=="ready","same-version optional capabilities remain compatible"); Check(ready.Capabilities.Split(',').Contains(ProtocolVersion.AnalysisCapability),"agent advertises optional structural review capability"); } var connected=0;var replies=0;var offline=0; var analysisReplies=new System.Collections.Concurrent.ConcurrentQueue(); using(var link=new AgentLink(pipeName,Guid.NewGuid(),_=>true)) // Windows SID peer validation is exercised by the desktop procedure, not faked as proved here. { link.StateChanged+=state=>{if(state=="connected")Interlocked.Increment(ref connected);else if(state=="offline")Interlocked.Increment(ref offline);}; link.Received+=message=>{Interlocked.Increment(ref replies);if(message.Analysis!=null)analysisReplies.Enqueue(message);}; foreach(var descriptor in descriptors)link.Register(descriptor); link.Start();await Until(()=>Volatile.Read(ref connected)==1&&serverSessions.SessionCount==3,"real named-pipe handshake reconciles three documents"); link.TryPost(new Message{Kind="active",SessionId=descriptors[1].SessionId,Revision=1}); link.TryPost(new Message{Kind="selection",SessionId=descriptors[1].SessionId,Revision=1,Start=30,End=30}); await Until(()=>Volatile.Read(ref replies)>=4,"agent receives actual asynchronous positional/lifecycle traffic"); var analysisSnapshot=Guid.NewGuid(); link.TryPost(new Message{Kind="snapshot-begin",SessionId=descriptors[0].SessionId,Revision=1,SnapshotId=analysisSnapshot,End=12,RequestAnalysis=true}); link.TryPost(new Message{Kind="snapshot-fragment",SessionId=descriptors[0].SessionId,Revision=1,SnapshotId=analysisSnapshot,Fragment=new(){ParagraphIndex=1,Start=0,End=12,Text="Chapter One\r",OutlineLevel=10,CompletesParagraph=true}}); link.TryPost(new Message{Kind="snapshot-end",SessionId=descriptors[0].SessionId,Revision=1,SnapshotId=analysisSnapshot}); await Until(()=>analysisReplies.Any(m=>m.SnapshotId==analysisSnapshot&&m.Analysis?.ChapterCount==1),"real pipe returns document analysis results"); stopHost.Cancel();await host;await Until(()=>serverSessions.SessionCount==0,"agent shutdown retires peer sessions"); await Until(()=>Volatile.Read(ref offline)>0,"idle keepalive detects agent loss without a Word event"); stopHost.Dispose();stopHost=new CancellationTokenSource();host=StartHost(stopHost.Token); await Until(()=>Volatile.Read(ref connected)>=2&&serverSessions.SessionCount==3,"agent restart reconnects and reconciles without UI waits"); var recoveredSnapshot=Guid.NewGuid(); link.TryPost(new Message{Kind="snapshot-begin",SessionId=descriptors[1].SessionId,Revision=1,SnapshotId=recoveredSnapshot,End=0,RequestAnalysis=true}); link.TryPost(new Message{Kind="snapshot-end",SessionId=descriptors[1].SessionId,Revision=1,SnapshotId=recoveredSnapshot}); await Until(()=>analysisReplies.Any(m=>m.SnapshotId==recoveredSnapshot&&m.Analysis?.WordCount==0),"analysis can be repeated after actual pipe host restart"); link.Retire(descriptors[2].SessionId);await Until(()=>serverSessions.SessionCount==2,"real pipe document close is isolated"); link.Dispose();await link.Completion.WaitAsync(TimeSpan.FromSeconds(5)); Check(true,"link shutdown cancels background worker promptly"); } var deniedOwner=false; using(var untrusted=new AgentLink(pipeName,Guid.NewGuid(),_=>false)) { untrusted.StateChanged+=state=>{if(state=="offline")deniedOwner=true;};untrusted.Start(); await Until(()=>deniedOwner,"untrusted agent owner callback rejects connection before handshake"); untrusted.Dispose();await untrusted.Completion.WaitAsync(TimeSpan.FromSeconds(5)); } stopHost.Cancel();await host;stopHost.Dispose(); var stalledName="pd-phase1-stalled-"+Guid.NewGuid().ToString("N"); using(var stalled=new NamedPipeServerStream(stalledName,PipeDirection.InOut,1,PipeTransmissionMode.Byte,PipeOptions.Asynchronous|PipeOptions.CurrentUserOnly)) using(var stalledClient=new AgentLink(stalledName,Guid.NewGuid(),_=>true)) { var timedOut=false;stalledClient.StateChanged+=state=>{if(state=="offline")timedOut=true;}; stalledClient.Start();await stalled.WaitForConnectionAsync(); await FrameCodec.ReadAsync(stalled,CancellationToken.None); // Deliberately never acknowledge hello. await Until(()=>timedOut,"unresponsive agent handshake times out off producer thread"); stalledClient.Dispose();await stalledClient.Completion.WaitAsync(TimeSpan.FromSeconds(5)); } Check(!CompanionPresentation.Dark(null)&&!CompanionPresentation.Dark(false)&&CompanionPresentation.Dark(true),"theme policy follows Windows with accessible light fallback"); Check(CompanionPresentation.Connection(new(){Server="online",Authentication="verified",VerifiedUtc=DateTime.UtcNow},DateTime.UtcNow)=="Connected to PlotDirector","connection requires verified fresh health"); Check(CompanionPresentation.Connection(new(){Server="online",Authentication="verified",VerifiedUtc=DateTime.UtcNow.AddMinutes(-3)},DateTime.UtcNow)=="Connection needs checking","cached server success never produces stale green state"); Check(CompanionPresentation.Connection(new(){Authentication="expired"},DateTime.UtcNow)=="Sign in again","expired sign-in has actionable explanation"); Check(CompanionPresentation.Next(false,false,0,false).Contains("browser"),"first run remains useful without Word"); Check(CompanionPresentation.Next(true,false,0,false).Contains("Choose"),"book association precedes analysis"); Check(CompanionPresentation.Chapter(false,true).Contains("review")&&!CompanionPresentation.Chapter(false,true).Contains("imported"),"analysis completion never claims import completion"); Check(!CompanionPresentation.NeedsAuthorisation(new(){State="Action required",Authentication="pending"})&&CompanionPresentation.Connection(new(){Authentication="pending"},DateTime.UtcNow).Contains("Waiting"),"pending browser approval has no duplicate sign-in action"); Check(CompanionPresentation.Connection(new(){State="Connected",Server="online",Authentication="verified",VerifiedUtc=DateTime.UtcNow.AddMinutes(-5)},DateTime.UtcNow)=="Reconnecting","explicit connected state still requires current verification"); Check(!new CompanionPreferences().AdvancedMode,"Advanced mode is off for new installations"); Check(!CompanionPresentation.NeedsAuthorisation(new(){State="Reconnecting",Authentication="expired"}),"trusted access renewal does not offer repeated browser sign-in"); Check(CompanionPresentation.NeedsAuthorisation(new(){State="Action required"}),"invalid installation offers the existing browser sign-in action"); Check(CompanionPresentation.WordStatus(false,3,DateTime.UtcNow,"ok",DateTime.UtcNow).Contains("not connected"),"server success never implies Word is connected"); Check(CompanionPresentation.WordStatus(true,3,DateTime.UtcNow.AddMinutes(-2),"ok",DateTime.UtcNow).Contains("pending"),"stale Word registration cannot be displayed as connected to book"); Check(DocumentMaintenancePolicy.IsLegacyControl("PD-CHAPTER-12")&&DocumentMaintenancePolicy.IsLegacyControl("PD-SCENE-42")&&DocumentMaintenancePolicy.IsLegacyBookmark("_PD_CHAPTER_12")&&DocumentMaintenancePolicy.IsLegacyBookmark("_PD_SCENE_42")&&!DocumentMaintenancePolicy.IsLegacyControl("PD-SCENE-notes")&&!DocumentMaintenancePolicy.IsLegacyBookmark("_PD_SCENE_42_notes")&&!DocumentMaintenancePolicy.IsLegacyBookmark("AuthorBookmark"),"ribbon cleanup matches exact legacy marker identifiers only"); Check(DocumentMaintenancePolicy.OwnsControl(" pd-scene-12 ")&&DocumentMaintenancePolicy.OwnsBookmark("_PD_CHAPTER_9"),"maintenance recognises established PlotDirector marker ownership"); Check(!DocumentMaintenancePolicy.OwnsControl("Author chapter")&&!DocumentMaintenancePolicy.OwnsControl("OTHER-PD-SCENE-1")&&!DocumentMaintenancePolicy.OwnsBookmark("AuthorBookmark"),"maintenance leaves unrelated controls and bookmarks alone"); Check(DocumentMaintenancePolicy.Properties.Length==5&&!DocumentMaintenancePolicy.Properties.Contains("Author"),"document-property deletion uses an explicit owned allowlist"); await AnalysisTests.Run(Check); await ChapterAiTests.Run(Check); await WorkflowTests.Run(Check); ParagraphSnapshotTests.Run(Check); await TrayTests.Run(Check); await NativeConnectionRefreshTests.Run(Check); await PersistentConnectionTests.Run(Check); Console.WriteLine($"Native foundation: {passed} checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified.");