74 lines
9.9 KiB
C#

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()
{
foreach(var scenario in new[]{(Edited:Array.Empty<int>(),Missing:-1,Geometry:-1),(Edited:new[]{17},Missing:-1,Geometry:-1),(Edited:new[]{7,22,47},Missing:-1,Geometry:-1),(Edited:Array.Empty<int>(),Missing:31,Geometry:-1),(Edited:Array.Empty<int>(),Missing:-1,Geometry:47),(Edited:Array.Empty<int>(),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<AdapterCommand>();
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;offset<value.Length;offset+=2048)Send(new(){Kind="chapter-chunk",SnapshotId=command.Id,Action=action,Start=offset,OperationMessage=value.Substring(offset,Math.Min(2048,value.Length-offset))});}
Chunks("text",body);var heading=$"Chapter {c}\r";Chunks("live-text",(c*2+1).ToString("X8")+heading.Length.ToString("X8")+"00000001"+(c*2+2).ToString("X8")+(body.Length-heading.Length).ToString("X8")+"0000000A");
Send(new(){Kind="chapter-end",SnapshotId=command.Id});
if(c==0){await Until(()=>handler.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 Until(Func<bool> 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 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<HttpResponseMessage> 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<NativePresence>(cancellation))!;p.ChapterSyncSupported=true;p.ParagraphRevision=revision;if(currentReady){p.ChapterId=1;p.SceneId=10;p.ChapterTitle="Chapter 0";p.SceneTitle="Verified scene";}return Json(p);}
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<ChapterReuseRequest>(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<ChapterObservation>(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{});
}
}
}