using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using PlotDirector.Companion.Protocol; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; using PlotLine.Services.NativeCompanion; internal static class NativeManuscriptCaptureTests { public static async Task Run() { void Check(bool ok,string message){if(!ok)throw new Exception(message);} var source=new ManuscriptCapture{RequestId=Guid.NewGuid(),InstanceId=Guid.NewGuid(),SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Revision=1,End=30,Paragraphs=[new(){Start=0,End=10,ParagraphIndex=1,OutlineLevel=1,Text="Chapter 1\r",CompletesParagraph=true},new(){Start=10,End=30,ParagraphIndex=2,OutlineLevel=10,Text="Words remain exact.\r",CompletesParagraph=true}]}; var preview=NativeManuscriptCapture.Build(source,7,4,1,3,"Synthetic manuscript"); Check(preview.Chapters.Count==1&&preview.Chapters[0].ChapterText=="Words remain exact.\r"&&preview.Chapters[0].StartPosition==1&&preview.Chapters[0].ParagraphMap[0].WordParagraphIndex==2,"Native source uses the wizard's one-based paragraph coordinates and preserves body prose"); Check(preview.NativeParagraphPositions[2]==10,"Word character positions remain distinct from wizard paragraph ordinals"); var tagged=NativeManuscriptCapture.Build(new(){End=10,Paragraphs=[new(){Start=0,End=10,ParagraphIndex=1,OutlineLevel=10,MarkerTags=["PD-CHAPTER-10"],Text="Real prose",CompletesParagraph=true}]},7,4,1,3,"Tagged body");Check(tagged.Chapters[0].ChapterText=="Real prose"&&tagged.Chapters[0].SourceParagraphs[0].IncludeInSourceText,"A chapter marker on body text is not permission to discard manuscript prose"); var blank=NativeManuscriptCapture.Build(new(){End=0},7,4,1,3,"Blank");Check(blank.Chapters.Count==0,"Blank capture contains no invented chapter"); var bad=false;try{NativeManuscriptCapture.Build(new(){End=31,Paragraphs=source.Paragraphs},7,4,1,3,"Incomplete");}catch(ArgumentException){bad=true;}Check(bad,"Incomplete streams fail before acceptance"); var largeText=string.Concat(Enumerable.Repeat("word ",220000));var pieces=new List(); for(int offset=0;offset(repo).BuildServiceProvider(); var scans=new ManuscriptScanPreviewStore(services.GetRequiredService(),NullLogger.Instance); var store=new NativePresenceStore(TimeProvider.System);var lease=new NativePresence{BookId=3,ManuscriptId=source.ManuscriptId,Sequence=1,Revision=1,WordSaved=true,CanCapture=true,Active=true,DocumentTitle="Synthetic manuscript"}; store.Put(7,"grant",DateTimeOffset.UtcNow.AddHours(1),source.InstanceId,source.SessionId,lease); var access=NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){BookId=3,Chapters=[]})); var onboarding=NativeWorkflowTests.Proxy((_,_)=>Task.FromResult(new(){UserOnboardingStateID=4,ProjectID=1,BookID=3})); using var captureServices=new ServiceCollection().AddSingleton(access).AddSingleton(onboarding).BuildServiceProvider(); var transfer=new NativeManuscriptCapture(store,scans,TimeProvider.System,captureServices.GetRequiredService()); var state=await transfer.Start(7,4,1,3);Check(state?.ScanID!=null,"Existing wizard can request exact active native session");source.RequestId=state!.ScanID!.Value; Check(store.TakeNavigation(7,"grant",source.InstanceId,source.SessionId)?.Kind=="wizard-capture","Capture command follows existing exact-session channel"); bad=false;try{await transfer.Accept(8,"grant",source);}catch(UnauthorizedAccessException){bad=true;}Check(bad,"Other account cannot submit capture"); bad=false;try{await transfer.Accept(7,"other",source);}catch(UnauthorizedAccessException){bad=true;}Check(bad,"Different desktop grant cannot submit capture"); repo.Fail=true;bad=false;try{await transfer.Accept(7,"grant",source);}catch(IOException){bad=true;}Check(bad&&(await scans.GetStateAsync(7,4)).Status==ManuscriptScanStatuses.Running,"Durability failure never reports success");repo.Fail=false; state=await transfer.Accept(7,"grant",source);Check(state.Status==ManuscriptScanStatuses.Complete&&repo.Values.ContainsKey(source.RequestId),"Acceptance follows durable source persistence"); await transfer.Accept(7,"grant",source);Check(repo.Writes==1,"Same capture retransmission is idempotent"); var priorText=source.Paragraphs[1].Text;source.Paragraphs[1].Text="Conflicting text";bad=false;try{await transfer.Accept(7,"grant",source);}catch(ArgumentException){bad=true;}source.Paragraphs[1].Text=priorText;Check(bad&&repo.Writes==1,"Changed same-ID submission cannot overwrite accepted source"); // First-time import: no existing book association is required, but another book is never silently reassigned. var freshId=Guid.NewGuid();var freshSession=Guid.NewGuid();var freshManuscript=Guid.NewGuid(); store.Put(7,"fresh-grant",DateTimeOffset.UtcNow.AddHours(1),freshId,freshSession,new(){BookId=0,WordRunning=true,ManuscriptId=freshManuscript,Sequence=1,CanCapture=true,Active=true,DocumentTitle="First manuscript"}); store.Remove(7,"grant",source.InstanceId,source.SessionId); var otherActiveSession=Guid.NewGuid();store.Put(7,"fresh-grant",DateTimeOffset.UtcNow.AddHours(1),freshId,otherActiveSession,new(){BookId=99,ManuscriptId=Guid.NewGuid(),Sequence=1,CanCapture=true,Active=true,DocumentTitle="Different active book"}); bad=false;try{await transfer.Start(7,4,1,3);}catch(InvalidOperationException){bad=true;}Check(bad,"An inactive unassociated manuscript is never substituted for an active document belonging to another book");store.Remove(7,"fresh-grant",freshId,otherActiveSession); var firstImport=await transfer.Start(7,4,1,3);var command=store.TakeNavigation(7,"fresh-grant",freshId,freshSession); Check(firstImport?.ScanID!=null&&command?.BookId==3&&command.SessionId==freshSession,"First-time import targets the active unassociated manuscript and carries the authorised destination book"); await transfer.Fail(7,"fresh-grant",command!.Id);store.Remove(7,"fresh-grant",freshId,freshSession); store.Put(7,"fresh-grant",DateTimeOffset.UtcNow.AddHours(1),freshId,freshSession,new(){BookId=99,ManuscriptId=freshManuscript,Sequence=2,CanCapture=true,Active=true,DocumentTitle="Another book"}); Check(await transfer.Start(7,4,1,3)==null,"First-time import never silently takes a manuscript associated with a different book");store.Remove(7,"fresh-grant",freshId,freshSession); store.Remove(7,"grant",source.InstanceId,source.SessionId);Check((await scans.GetPreviewAsync(7,source.RequestId))?.Chapters[0].ChapterText=="Words remain exact.\r","Accepted manuscript survives Word/agent disconnection"); var restarted=new ManuscriptScanPreviewStore(services.GetRequiredService(),NullLogger.Instance);Check((await restarted.GetStateAsync(7,4)).PreviewID==source.RequestId&&(await restarted.GetLatestPreviewAsync(7,4))?.NativeParagraphPositions[2]==10,"Server restart reloads accepted source and coordinate provenance"); Check(await restarted.GetPreviewAsync(8,source.RequestId)==null,"Recovered source remains account scoped"); var config=new Microsoft.Extensions.Configuration.ConfigurationBuilder().AddInMemoryCollection(new Dictionary{{"Features:ParagraphManuscripts","true"}}).Build(); var automatic=new NativeManuscriptCapture(store,scans,TimeProvider.System,captureServices.GetRequiredService(),config); store.Put(7,"grant",DateTimeOffset.UtcNow.AddHours(1),source.InstanceId,source.SessionId,new(){BookId=3,ManuscriptId=source.ManuscriptId,Sequence=20,Revision=1,WordSaved=true,CanCapture=true,CanParagraphSync=true,Active=true,DocumentTitle="Version18 manuscript"}); await automatic.Start(7,4,1,3);Check(store.TakeNavigation(7,"grant",source.InstanceId,source.SessionId)?.ParagraphTracking==true,"Ordinary import automatically captures paragraph identities with Companion18; no extra opt-in/adoption step"); store.Map(7,3,source.ManuscriptId,source.SessionId,1,30,[(0,10,null),(10,10,20)]);lease.CursorStart=11; Check(store.Resolve(7,lease,source.SessionId)?.Scene==20,"Approved saved capture resolves an exact-session scene");lease.WordSaved=false;Check(store.Resolve(7,lease,source.SessionId)==null,"Dirty Word state cannot reuse positional evidence");lease.WordSaved=true;lease.Revision=2;Check(store.Resolve(7,lease,source.SessionId)==null,"Changed revision cannot reuse positional evidence"); } private sealed class Memory:IManuscriptCaptureRepository { public readonly Dictionary Values=[];public bool Fail;public int Writes; private readonly Dictionary<(int,Guid,string),string> analyses=[]; public Task GetAnalysis(int user,Guid preview,string hash)=>Task.FromResult(analyses.GetValueOrDefault((user,preview,hash))); public Task SaveAnalysis(int user,Guid preview,string hash,string result){analyses[(user,preview,hash)]=result;return Task.CompletedTask;} public Task Clear(int user,int onboarding)=>Task.CompletedTask; public Task CompleteBuild(int user,Guid preview)=>Task.CompletedTask; public Task Save(ManuscriptScanPreview preview){if(Fail)throw new IOException("Synthetic durable-store failure");if(!Values.ContainsKey(preview.PreviewID))Writes++;Values[preview.PreviewID]=preview;return Task.CompletedTask;} public Task Get(int user,Guid? preview=null,int? onboarding=null)=>Task.FromResult(Values.Values.FirstOrDefault(p=>p.UserID==user&&(!preview.HasValue||p.PreviewID==preview)&&(!onboarding.HasValue||p.OnboardingID==onboarding))); } }