175 lines
17 KiB
C#
175 lines
17 KiB
C#
using System.IO.Pipes;
|
|
using PlotDirector.Companion.Agent;
|
|
using PlotDirector.Companion.Client;
|
|
using PlotDirector.Companion.Protocol;
|
|
|
|
var passed = 0;
|
|
void Check(bool value,string name) {if(!value)throw new Exception(name);passed++;Console.WriteLine("PASS "+name);}
|
|
async Task Until(Func<bool> 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<WordAccessScheduler.Capacity;i++)Check(scheduler.Post("work"+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;i<BoundedMailbox.Capacity;i++)mailbox.TryPost(new Message{Kind="snapshot-fragment"});
|
|
Check(!mailbox.TryPost(new Message{Kind="snapshot-fragment"})&&mailbox.Depth==64,"IPC snapshot queue backpressure bounded");mailbox.Clear();
|
|
for(var i=0;i<ProtocolVersion.MaxDocuments;i++)mailbox.TryPost(new Message{Kind="selection",SessionId=Guid.NewGuid()});
|
|
Check(!mailbox.TryPost(new Message{Kind="selection",SessionId=Guid.NewGuid()}),"IPC selection session slots bounded");
|
|
|
|
Check(!ProtocolVersion.SupportsRequiredCapabilities("sessions-v1"),"missing required protocol capabilities refused");
|
|
var sessions=new SessionManager();var instance=Guid.NewGuid();var lease=Guid.NewGuid();sessions.Attach(instance,lease);long seq=0;
|
|
Message Apply(Message m) {m.WordInstanceId=instance;m.Sequence=++seq;return sessions.Apply(lease,m);}
|
|
var books=new[]{"Discovery","Reckoning","Redemption"}; // Synthetic fixture labels only; never production recognition.
|
|
var descriptors=books.Select((_,i)=>new 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;book<descriptors.Length;book++)
|
|
{
|
|
var doc=descriptors[book];var snapshot=Guid.NewGuid();
|
|
Apply(new Message{Kind="snapshot-begin",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot,End=40});
|
|
Apply(new Message{Kind="snapshot-fragment",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot,Fragment=new(){ParagraphIndex=1,Start=0,End=20,OutlineLevel=1,Text=books[book],MarkerTags=["PD-CHAPTER-"+(100+book)],CompletesParagraph=true}});
|
|
Apply(new Message{Kind="snapshot-fragment",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot,Fragment=new(){ParagraphIndex=2,Start=20,End=40,OutlineLevel=2,Text="Repeated paragraph text",MarkerTags=["_PD_SCENE_"+(200+book)],CompletesParagraph=true}});
|
|
Check(Apply(new Message{Kind="snapshot-end",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot}).Status=="ok","commit structural snapshot "+books[book]);
|
|
var answer=Apply(new Message{Kind="selection",SessionId=doc.SessionId,Revision=1,Start=30,End=30});
|
|
Check(answer.ChapterId==100+book&&answer.SceneId==200+book,"positional scene resolution independent of repeated text "+books[book]);
|
|
}
|
|
for(var pass=0;pass<50;pass++)foreach(var doc in descriptors){Apply(new Message{Kind="active",SessionId=doc.SessionId,Revision=1});if(sessions.ActiveSession(instance)!=doc.SessionId)throw new Exception("Wrong active document");}
|
|
Check(true,"rapid three-document switching preserves active identity");
|
|
var pendingId=Guid.NewGuid();var first=descriptors[0];Apply(new Message{Kind="snapshot-begin",SessionId=first.SessionId,Revision=1,SnapshotId=pendingId});
|
|
Apply(new Message{Kind="snapshot-cancel",SessionId=first.SessionId,Revision=1,SnapshotId=pendingId});
|
|
Check(Apply(new Message{Kind="snapshot-end",SessionId=first.SessionId,Revision=1,SnapshotId=pendingId}).Status=="obsolete-snapshot","cancelled snapshot cannot commit");
|
|
var incomplete=Guid.NewGuid();Apply(new Message{Kind="snapshot-begin",SessionId=first.SessionId,Revision=1,SnapshotId=incomplete,End=40});
|
|
Check(Apply(new Message{Kind="snapshot-end",SessionId=first.SessionId,Revision=1,SnapshotId=incomplete}).Status=="incomplete-snapshot","partial snapshot cannot masquerade as complete");
|
|
Check(Apply(new Message{Kind="snapshot-fragment",SessionId=first.SessionId,Revision=1,SnapshotId=incomplete,Fragment=new(){ParagraphIndex=1,Start=0,End=2049,Text=new string('x',2049),OutlineLevel=10}}).Status=="invalid-fragment","oversized extraction fragment refused");
|
|
Check(Apply(new Message{Kind="selection",SessionId=first.SessionId,Revision=0}).Status=="stale-revision","stale revision refused");
|
|
var foreign=Guid.NewGuid();Check(sessions.Apply(foreign,new Message{WordInstanceId=instance,Sequence=++seq}).Status=="wrong-instance","peer cannot address another instance lease");
|
|
Check(sessions.Apply(lease,new Message{WordInstanceId=instance,Sequence=seq-1}).Status=="stale-sequence","duplicate/out-of-order sequence refused");
|
|
Apply(new Message{Kind="close",SessionId=first.SessionId});Check(!sessions.HasSession(instance,first.SessionId)&&sessions.SessionCount==2,"closing one document retires only its state");
|
|
var newLease=Guid.NewGuid();sessions.Attach(instance,newLease);sessions.Detach(instance,lease);Check(sessions.Apply(newLease,new Message{Kind="reconcile",WordInstanceId=instance,Sequence=1,Documents=descriptors}).Status=="ok","old disconnect cannot retire replacement lease");
|
|
sessions.Detach(instance,newLease);Check(sessions.SessionCount==0,"disconnect releases all owned sessions and snapshots");
|
|
|
|
var multiple=new SessionManager();var wordA=Guid.NewGuid();var wordB=Guid.NewGuid();var peerA=Guid.NewGuid();var peerB=Guid.NewGuid();
|
|
multiple.Attach(wordA,peerA);multiple.Attach(wordB,peerB);
|
|
multiple.Apply(peerA,new Message{Kind="reconcile",WordInstanceId=wordA,Sequence=1,Documents=[descriptors[0]]});
|
|
multiple.Apply(peerB,new Message{Kind="reconcile",WordInstanceId=wordB,Sequence=1,Documents=[descriptors[1]]});
|
|
Check(multiple.Apply(peerA,new Message{Kind="selection",WordInstanceId=wordA,SessionId=descriptors[1].SessionId,Sequence=2,Revision=1}).Status=="unknown-session","one Word process cannot route into another process document");
|
|
multiple.Detach(wordA,peerA);Check(multiple.SessionCount==1&&multiple.HasSession(wordB,descriptors[1].SessionId),"terminating one Word process preserves another instance");
|
|
var revisionSession=descriptors[1];var oldSnapshot=Guid.NewGuid();
|
|
multiple.Apply(peerB,new Message{Kind="snapshot-begin",WordInstanceId=wordB,SessionId=revisionSession.SessionId,Sequence=2,Revision=1,SnapshotId=oldSnapshot,End=40});
|
|
multiple.Apply(peerB,new Message{Kind="document",WordInstanceId=wordB,Sequence=3,Documents=[new(){SessionId=revisionSession.SessionId,ManuscriptId=revisionSession.ManuscriptId,Revision=2,ProjectId=revisionSession.ProjectId,BookId=revisionSession.BookId}]});
|
|
Check(multiple.Apply(peerB,new Message{Kind="snapshot-end",WordInstanceId=wordB,SessionId=revisionSession.SessionId,Sequence=4,Revision=1,SnapshotId=oldSnapshot}).Status=="stale-revision","new observation revision invalidates in-flight old extraction");
|
|
|
|
Check(multiple.Apply(peerB,new Message{Kind="document",WordInstanceId=wordB,Sequence=5,Documents=[null!]}).Status=="invalid-documents","malformed null document cannot crash agent session processing");
|
|
|
|
using(var malformed=new MemoryStream(new byte[]{255,255,255,127}))
|
|
{
|
|
try{await FrameCodec.ReadAsync(malformed,CancellationToken.None);throw new Exception("Accepted oversized prefix");}catch(InvalidDataException){Check(true,"oversized frame rejected before allocation");}
|
|
}
|
|
using(var frame=new MemoryStream())
|
|
{
|
|
var original=new Message{Kind="selection",WordInstanceId=Guid.NewGuid(),SessionId=Guid.NewGuid(),Start=99};await FrameCodec.WriteAsync(frame,original,CancellationToken.None);frame.Position=0;
|
|
var copy=await FrameCodec.ReadAsync(frame,CancellationToken.None);Check(copy.CorrelationId==original.CorrelationId&©.Start==99,"versioned frame round-trip retains identity");
|
|
}
|
|
|
|
var queueDirectory=Path.Combine(Path.GetTempPath(),"pd-phase1-outbox-"+Guid.NewGuid().ToString("N"));
|
|
try
|
|
{
|
|
var queue=new DeferredWorkQueue(queueDirectory);var manuscript=Guid.NewGuid();
|
|
var item=new DeferredWork(manuscript,1,1,Guid.NewGuid(),ProseSynchronizationMode.OnSave,"revision-1",DateTime.UtcNow);
|
|
Check(queue.TryEnqueue(item),"offline work persisted without manuscript prose");
|
|
Check(queue.Ready(ProseSynchronizationMode.Automatic,DateTime.UtcNow).Length==0,"On Save mode cannot be triggered by automatic quiet period");
|
|
Check(new DeferredWorkQueue(queueDirectory).Ready(ProseSynchronizationMode.OnSave,DateTime.UtcNow).Length==1,"offline work survives agent restart");
|
|
Check(queue.TryEnqueue(item with {Revision=2,IdempotencyKey="revision-2"})&&queue.Count==1,"new scene revision supersedes queued older work");
|
|
Check(!queue.TryEnqueue(item),"stale offline revision cannot replace newer work");
|
|
queue.Acknowledge("revision-1");Check(queue.Count==1,"old acknowledgement cannot remove newer work");
|
|
queue.Acknowledge("revision-2");Check(queue.Count==0,"matching idempotency acknowledgement retires work");
|
|
for(var n=1;n<=DeferredWorkQueue.Capacity;n++)queue.TryEnqueue(item with{SceneId=n,IdempotencyKey="scene-"+n});
|
|
Check(!queue.TryEnqueue(item with{SceneId=999}),"durable queue rejects capacity overflow");
|
|
}
|
|
finally{Directory.Delete(queueDirectory,true);}
|
|
|
|
var pipeName="pd-phase1-test-"+Guid.NewGuid().ToString("N");var serverSessions=new SessionManager();var stopHost=new CancellationTokenSource();
|
|
Task StartHost(CancellationToken token)=>Task.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<Message>();
|
|
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");
|
|
await AnalysisTests.Run(Check);
|
|
await ChapterAiTests.Run(Check);
|
|
await WorkflowTests.Run(Check);
|
|
await TrayTests.Run(Check);
|
|
Console.WriteLine($"Native foundation: {passed} checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified.");
|