using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using PlotDirector.Companion.Protocol; using PlotDirector.Companion.Protocol.Manuscript; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; using PlotLine.Services.Manuscript; using PlotLine.Services.NativeCompanion; internal static class ParagraphWorkflowTests { private sealed class Memory: IParagraphManuscriptRepository { public ParagraphManuscript State=null!;public bool Empty;public bool Paused;public int Writes; public Task Get(int user,int book)=>Task.FromResult(Empty?null:ParagraphManuscriptEngine.Clone(State)); public Task SetMode(int user,int book,long expected,string mode){if(user!=7||expected!=State.Revision)throw new InvalidOperationException();State.Mode=mode;State.Revision++;return Task.FromResult(ParagraphManuscriptEngine.Clone(State));} public Task Save(int user,ParagraphManuscript state,long expected,Guid request){if(user!=7)throw new UnauthorizedAccessException();if(expected!=(Empty?-1:State.Revision))throw new InvalidOperationException("Revision conflict");state.Revision=Empty?1:state.Revision+1;Empty=false;state.LastRequestId=request;State=ParagraphManuscriptEngine.Clone(state);Writes++;return Task.FromResult(state);} public Task Status(int user,int book)=>Task.FromResult(new(){BookId=book,CanWrite=user==7,Paused=Paused,Mode=State.Mode,SessionId=State.SessionId,WordRevision=State.WordRevision,Revision=State.Revision,ManuscriptId=State.ManuscriptId,SnapshotHash=State.SnapshotHash}); public Task> Events(int user,int book)=>Task.FromResult>([]); public Task Capture(int user,int book)=>Task.FromResult(null); public Task Position(int user,int book,Guid manuscript,Guid session,long revision,int position)=>Task.FromResult(null); } public static async Task Run() { void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);} var manuscript=Guid.NewGuid();var rows=ParagraphReconciliation.Compare([],new[]{new ParagraphOccurrence{Text="The keeper waited.\r",NativeId="00000001",Start=0,End=19}}).Current; var memory=new Memory{State=ParagraphManuscriptEngine.Bootstrap(3,1,manuscript,rows,[new(){SceneId=11,ChapterId=4,Title="Waiting",Start=1,End=1}])};memory.State.Mode="OnSave";memory.State.Revision=1; var access=NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){BookId=3})); var statistics=NativeWorkflowTests.Proxy((_,_)=>Task.CompletedTask); var configuration=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary{{"Features:ParagraphManuscripts","true"}}).Build(); using var services=new ServiceCollection().AddSingleton(memory).AddSingleton(access).AddSingleton(configuration).AddSingleton(new ParagraphManuscriptService(memory,access,null!,null!,statistics,configuration)).BuildServiceProvider(); var adoption=new Memory{State=new(){BookId=3},Empty=true}; var build=NativeWorkflowTests.Proxy((n,a)=>n=="GetByPreviewAsync"?Task.FromResult(new(){BookID=3,ProjectID=1,SceneMappings=[new(){SceneID=11},new(){SceneID=12}]}):throw new Exception(n)); int offset=0;var fragments=new[]{"Arrival\r","Opening prose.\r","Private section\r","Explicitly excluded prose.\r","Departure\r","Ending prose.\r"}.Select((text,i)=>{var f=new ParagraphFragment{ParagraphIndex=i+1,Start=offset,End=offset+text.Length,Text=text,OutlineLevel=i%2==0?1:10,CompletesParagraph=true,NativeParagraphId=(i+1).ToString("X8")};offset=f.End;return f;}).ToArray(); var preview=NativeManuscriptCapture.Build(new(){ManuscriptId=manuscript,RequestId=Guid.NewGuid(),ParagraphTracking=true,End=offset,Paragraphs=fragments},7,4,1,3,"Synthetic selective import"); var adopted=await new ParagraphManuscriptService(adoption,access,null!,build,statistics,configuration).Initialise(7,preview,[new(){SceneID=11,ChapterID=4,WordStartParagraphIndex=2},new(){SceneID=99,ChapterID=99,WordStartParagraphIndex=4},new(){SceneID=12,ChapterID=5,WordStartParagraphIndex=6}],1); Check(adopted.Scenes.Count==2&&adopted.Paragraphs.Count==6&&adopted.Paragraphs.Count(p=>p.Story)==2&&adopted.Chapters.Any(c=>c.CanonicalId==0),"Adoption uses only the completed capture's canonical scene map and retains excluded prose outside the imported book"); ParagraphManuscriptEngine.Reconcile(adopted,adopted.Paragraphs.Select(p=>p.Occurrence).ToArray());Check(!adopted.Paragraphs[3].Story,"Reconnection cannot silently restore an excluded chapter into canonical scenes"); var presence=new NativePresenceStore(TimeProvider.System);var instance=Guid.NewGuid();var session=Guid.NewGuid(); var input=new NativePresence{CanCapture=true,CanParagraphSync=true,WordSaved=true,BookId=3,ManuscriptId=manuscript,Revision=2,Sequence=1,Active=true,DocumentTitle="Synthetic novel"};presence.Put(7,"grant",DateTimeOffset.UtcNow.AddHours(1),instance,session,input); var capture=new NativeManuscriptCapture(presence,null!,TimeProvider.System,services.GetRequiredService(),configuration); memory.Paused=true;bool refused=false;try{await capture.RequestParagraphSnapshot(7,3);}catch(InvalidOperationException){refused=true;}Check(refused&&memory.Writes==0,"An unfinished import pauses snapshots without changing its accepted source or checkpoints");memory.Paused=false; await capture.ObserveParagraphSave(7,presence.Read(7,3).Single());var command=presence.TakeNavigation(7,"grant",instance,session)!;Check(command.Kind=="paragraph-snapshot"&&command.BaseRevision==1,"Explicitly opted-in save/reconnect uses existing exact-session capture channel"); var body=new ManuscriptCapture{RequestId=command.Id,InstanceId=instance,SessionId=session,ManuscriptId=manuscript,Revision=2,ParagraphTracking=true,End=19,Paragraphs=[new(){ParagraphIndex=1,Start=0,End=19,Text="The keeper smiled.\r",CompletesParagraph=true,NativeParagraphId="00000001"}]}; Check(await capture.AcceptParagraphSnapshot(7,"grant",body)&&memory.Writes==1&&memory.State.Paragraphs[0].Occurrence.Id==rows[0].Id&&memory.State.Paragraphs[0].Occurrence.Text.Contains("smiled"),"Authorised snapshot persists exact new prose and reconciles opaque paragraph identity"); await capture.AcceptParagraphSnapshot(7,"grant",body);Check(memory.Writes==1,"Lost acknowledgement retry cannot apply the snapshot twice"); Check((await capture.AcceptedParagraphState(7,body.RequestId)).Paragraphs.Single().Occurrence.Id==rows[0].Id,"Acknowledgement returns canonical occurrence ID for delta recovery"); var id=await capture.RequestParagraphSnapshot(7,3);await capture.CancelParagraphSnapshot(7,3);Check(presence.TakeNavigation(7,"grant",instance,session)?.Kind=="cancel"&&memory.Writes==1,"Cancellation retires only pending snapshot and retains already accepted revision"); bool foreign=false;try{await capture.RequestParagraphSnapshot(8,3);}catch(UnauthorizedAccessException){foreign=true;}Check(foreign&&memory.Writes==1,"Another account cannot request manuscript synchronisation"); memory.Paused=true;await services.GetRequiredService().Enable(7,3,"Off");Check(memory.State.Mode=="Off"&&memory.Writes==1,"Turning off automatic synchronisation changes only preferences even while imports or scene conflicts pause snapshots"); input.CanChapterSync=true;input.Sequence=2;presence.Put(7,"grant",DateTimeOffset.UtcNow.AddHours(1),instance,session,input);var repair=Guid.NewGuid();var currentLease=presence.Read(7,3).Single();presence.TakeNavigation(7,"grant",instance,session);Check(presence.RequestChapterRepair(7,currentLease,repair)&&capture.ParagraphTransferStatus(7,3,instance,session)?.RequestId==repair,"A new chapter repair is not hidden behind an older completed full snapshot receipt"); } }