using System.Net; using System.Net.Http.Json; using System.Text.Json; using PlotDirector.Companion.Agent; using PlotDirector.Companion.Protocol; using PlotDirector.Companion.Protocol.Manuscript; internal static class ChapterHandshakeTests { private static void Check(bool value,string name){if(!value)throw new Exception(name);Console.WriteLine("PASS "+name);} public static async Task Run() { await RibbonLifecycle(); foreach(var scenario in new[]{(Edited:Array.Empty(),Missing:-1,Geometry:-1),(Edited:new[]{17},Missing:-1,Geometry:-1),(Edited:new[]{7,22,47},Missing:-1,Geometry:-1),(Edited:Array.Empty(),Missing:31,Geometry:-1),(Edited:Array.Empty(),Missing:-1,Geometry:47),(Edited:Array.Empty(),Missing:-2,Geometry:-1)}) { var changed=scenario.Edited;var fallback=(scenario.Missing>=0?1:0)+(scenario.Geometry>=0?1:0);var handler=new Handler(changed,scenario.Missing,scenario.Geometry);using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://handshake.test/");await Until(()=>cloud.Status().Books.Any());await cloud.CheckConnection(); var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var tray=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid();long sequence=0;var pendingCommands=new Queue(); sessions.Attach(instance,lease,chapters:true,liveChapterText:true);tray.Attach(instance,lease,chapters:true); Message Send(Message m){m.WordInstanceId=instance;m.SessionId=session;m.Revision=1;m.Sequence=++sequence;var answer=tray.Exchange(instance,m,sessions.Apply(lease,m),lease);if(answer.Command?.Kind=="chapter-check")pendingCommands.Enqueue(answer.Command);return answer;} Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Synthetic reopen.docx"}]});tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",WordSaved=true}); using var stop=new CancellationTokenSource();var heartbeats=tray.Heartbeat(stop.Token);var watch=System.Diagnostics.Stopwatch.StartNew(); try { for(var c=0;c<48;c++) { AdapterCommand? command=null;await Until(()=>{Send(new(){Kind="selection",WordSaved=true});if(pendingCommands.Count>0)command=pendingCommands.Dequeue();return command!=null;}); var body=handler.Current[c];var start=handler.Starts[c]; Send(new(){Kind="chapter-begin",SnapshotId=command!.Id,BookId=3,Start=start,End=start+body.Length,DocumentEnd=handler.Starts[47]+handler.Current[47].Length,WordSaved=true,ChapterTitle=c==47?"":((c+1)*2+1).ToString("X8")}); void Chunks(string action,string value){for(var offset=0;offsethandler.Reused==1);await Until(()=>tray.PresentationDocuments.Single().SceneId.HasValue);Check(handler.Finishes==0,"Writing Context is available before the other 47 chapters are acknowledged");} } if(scenario.Missing==-2) { await Until(()=>handler.ReuseRequests==2);Send(new(){Kind="close"});handler.ReleaseSecond.SetResult();await Task.Delay(100); Check(tray.PresentationDocuments.All(d=>d.Session!=session),"Closing during final batch rejects the late reuse acknowledgement"); Check(handler.Finishes==0,"Interrupted reuse cannot report whole-manuscript completion after close");continue; } await Until(()=>tray.ChapterProgressForDisplay(session)?.State=="Synchronised");await Until(()=>tray.PresentationDocuments.Single().SceneId.HasValue); Check(handler.ReuseRequests==2&&handler.Reused==48-changed.Length-fallback,"Matching chapters use two bounded acknowledgements, including early current-chapter readiness"); Check(handler.AcceptRequests==changed.Length*2+fallback&&handler.Reconciled==changed.Length,"Actual request counts prove only changed chapters submit reconciliation prose"); Check(tray.ChapterProgressForDisplay(session)?.State=="Synchronised","Batch reuse reaches independently confirmed Up to date"); Check(tray.ChapterDiagnostics(session).Contains($"reused={48-changed.Length-fallback}")&&tray.ChapterDiagnostics(session).Contains($"reconciled={changed.Length}"),"Diagnostics distinguish reused, submitted and reconciled chapters"); Console.WriteLine($"MEASURE agent HTTP-contract fixture: chapters=48 changed={changed.Length} reuseRequests={handler.ReuseRequests} acceptanceRequests={handler.AcceptRequests} reconciled={handler.Reconciled} payloadBytes={handler.Bytes} totalMs={watch.Elapsed.TotalMilliseconds:F1}; HTTP in-memory, no Word/real network/SQL."); } finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}} } } private static async Task RibbonLifecycle() { var handler=new Handler([17],-1,-1); using var cloud=new CloudGateway(handler,_=>{}); cloud.Connect("https://handshake.test/"); await Until(()=>cloud.Status().Books.Any()); await cloud.CheckConnection(); var sessions=new SessionManager(); using var ai=new ChapterAiWork(cloud); var tray=new TrayCoordinator(sessions,cloud,ai); var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid();long sequence=0,revision=1; sessions.Attach(instance,lease,chapters:true,liveChapterText:true);tray.Attach(instance,lease,chapters:true); Message Send(Message m){m.WordInstanceId=instance;m.SessionId=session;m.Revision=revision;m.Sequence=++sequence;return tray.Exchange(instance,m,sessions.Apply(lease,m),lease);} Message Register()=>Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=revision,Title="Disposable edit fixture.docx"}]}); Register();tray.SelectBook(session,3,false);Send(new(){Kind="active"}); Send(new(){Kind="selection",WordSaved=false}); Check(Send(new(){Kind="tray-sync"}).ChapterProgress?.State=="Save required","Synchronise on an unsaved edit shows the save requirement"); Check(Send(new(){Kind="tray-repair"}).ChapterProgress?.Message.Contains("Repair Synchronisation")==true&&handler.RepairRequests==0,"Repair reports its saved-state refusal without submitting stale evidence"); revision++;Check(Register().Command==null,"Revision change clears old commands without emitting a stale cancel"); Send(new(){Kind="tray-sync"});Send(new(){Kind="tray-sync"}); using var stop=new CancellationTokenSource(); var heartbeats=tray.Heartbeat(stop.Token); try { Send(new(){Kind="selection",WordSaved=true}); await Until(()=>tray.ChapterDiagnostics(session).Contains("Fixture repair refused")); Check(handler.RepairRequests==1&&tray.ChapterProgressForDisplay(session)?.State=="Needs review","Repeated clicks coalesce and an HTTP repair refusal reaches the ribbon"); Send(new(){Kind="tray-repair"}); AdapterCommand? command=null; await Until(()=>{var reply=Send(new(){Kind="selection",WordSaved=true});if(reply.Command?.Kind=="chapter-check")command=reply.Command;return command!=null;}); Check(handler.RepairRequests==2&&command!.Revision==revision&&command.OperationId!=Guid.Empty,"Repair starts verification against the freshly confirmed saved revision"); Send(new(){Kind="tray-sync"}); Check(tray.ChapterDiagnostics(session).Contains("already running")&&handler.RepairRequests==2,"Synchronise joins an active explicitly authorised verification"); revision++;Register(); Check(Send(new(){Kind="chapter-end",Revision=revision,SnapshotId=command!.Id}).Command==null,"Further edits retire the old chapter command"); Check(tray.ChapterDiagnostics(session).Contains("Document revision changed"),"Interrupted verification reports the revision change"); } finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}} } private static async Task Until(Func ready){for(var n=0;n<3000;n++){if(ready())return;await Task.Delay(5);}throw new Exception("Handshake fixture timed out");} private sealed class Handler:HttpMessageHandler { public readonly Guid Manuscript=Guid.NewGuid();public readonly string[] Current;public readonly int[] Starts;private readonly string[] hashes;private readonly int missing,geometry;private long revision=1; public readonly TaskCompletionSource ReleaseSecond=new(TaskCreationOptions.RunContinuationsAsynchronously); public int ReuseRequests,Reused,AcceptRequests,Reconciled,Finishes;public long Bytes;private bool currentReady; public int RepairRequests;private AdapterCommand? repair; public Handler(int[] changed,int missing,int geometry) { this.missing=missing;this.geometry=geometry; var original=Enumerable.Range(0,48).Select(c=>$"Chapter {c}\r"+string.Join(" ",Enumerable.Repeat("synthetic",3187))+"\r").ToArray(); Current=original.Select((s,c)=>changed.Contains(c)?s.Replace("synthetic","different"):s).ToArray();Starts=new int[48];for(var c=1;c<48;c++)Starts[c]=Starts[c-1]+Current[c-1].Length; hashes=original.Select((s,c)=>ChapterFingerprint.Content([$"Chapter {c}\r",s[($"Chapter {c}\r").Length..]])).ToArray(); } protected override async Task SendAsync(HttpRequestMessage request,CancellationToken cancellation) { var path=request.RequestUri!.AbsolutePath;HttpResponseMessage Json(object value)=>new(HttpStatusCode.OK){Content=JsonContent.Create(value)}; if(path.EndsWith("/pair"))return Json(new{code="00112233445566778899AABB"});if(path.EndsWith("/token"))return Json(new{accessToken="fixture"});if(path.EndsWith("/books"))return Json(new[]{new{bookId=3,title="Synthetic book"}});if(path.EndsWith("/connection"))return Json(new{state="Connected",authentication="verified",server="online",expiresUtc=DateTime.UtcNow.AddHours(4)}); if(path.EndsWith("/presence")){var p=(await request.Content!.ReadFromJsonAsync(cancellation))!;p.ChapterSyncSupported=true;p.ParagraphRevision=revision;p.Navigation=Interlocked.Exchange(ref repair,null);if(currentReady){p.ChapterId=1;p.SceneId=10;p.ChapterTitle="Chapter 0";p.SceneTitle="Verified scene";}return Json(p);} if(path.EndsWith("/repair")) { if(++RepairRequests==1)return new(HttpStatusCode.Conflict){Content=JsonContent.Create(new{message="Fixture repair refused."})}; var target=(await request.Content!.ReadFromJsonAsync(cancellation))!; var operation=Guid.NewGuid(); repair=new(){Id=operation,Kind="chapter-repair",SessionId=target.SessionId,Revision=target.WordRevision}; return Json(new ChapterRepairRequested{OperationId=operation,Message="Fixture repair accepted."}); } if(path.EndsWith("/chapter-sync"))return Json(new ChapterManifest{CheckpointReuseSupported=true,NativePositionsSupported=true,BookId=3,Mode="OnSave",ManuscriptId=Manuscript,Revision=revision,Chapters=Enumerable.Range(0,48).Select(c=>new ChapterManifestItem{ChapterId=c+1,DurableAccepted=c!=missing,PositionHash=c==geometry?new string('A',64):"",Algorithm=ChapterFingerprint.Version,HeadingNativeId=(c*2+1).ToString("X8"),ContentHash=hashes[c],IdentityHash=ChapterFingerprint.Identity([new(){NativeId=(c*2+1).ToString("X8"),Length=($"Chapter {c}\r").Length,Outline=1},new(){NativeId=(c*2+2).ToString("X8"),Length=Current[c].Length-($"Chapter {c}\r").Length,Outline=10}]),NextHeadingId=c==47?"":((c+1)*2+1).ToString("X8"),Start=Starts[c],End=Starts[c]+Current[c].Length,ParagraphCount=2}).ToArray()}); if(path.EndsWith("/reuse")){var data=await request.Content!.ReadAsByteArrayAsync(cancellation);Bytes+=data.Length;var batch=JsonSerializer.Deserialize(data,new JsonSerializerOptions(JsonSerializerDefaults.Web))!;if(batch.Chapters.Any(p=>p.Paragraphs.Any(r=>r.Text!=null)))throw new Exception("Reuse leaked prose");ReuseRequests++;if(missing==-2&&ReuseRequests==2)await ReleaseSecond.Task.WaitAsync(cancellation);Reused+=batch.Chapters.Length;if(batch.Chapters.Any(p=>p.ChapterId==1))currentReady=true;return Json(new ChapterReuseReply{ChapterIds=batch.Chapters.Select(p=>p.ChapterId).ToArray(),Revision=revision});} if(path.EndsWith("/validate")){var data=await request.Content!.ReadAsByteArrayAsync(cancellation);Bytes+=data.Length;AcceptRequests++;var p=JsonSerializer.Deserialize(data,new JsonSerializerOptions(JsonSerializerDefaults.Web))!;if(p.ContentHash==hashes[p.ChapterId-1])return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",Revision=revision,ChapterId=p.ChapterId});if(p.Paragraphs.All(r=>r.Text==null))return Json(new ChapterSyncReply{State="Changed",AllowText=true,Revision=revision,ChapterId=p.ChapterId});Reconciled++;hashes[p.ChapterId-1]=p.ContentHash;return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",Revision=++revision,ChapterId=p.ChapterId});} if(path.EndsWith("/finish")){Finishes++;return Json(new ChapterSyncProgress{State="Synchronised",Matching=48,Total=48});} return Json(new{}); } } }