PlotDirector/PlotLine.Tests/WritingIntegrationTests.cs

156 lines
16 KiB
C#

using Microsoft.AspNetCore.SignalR;
using PlotLine.Hubs;
using System.Diagnostics;
using System.Reflection;
using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging.Abstractions;
using PlotDirector.Companion.Protocol;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.NativeCompanion;
using PlotLine.ViewModels;
internal static class WritingIntegrationTests
{
private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);}
private static T Stub<T>(Func<string,object?[]?,object?>? handler=null) where T:class
=>NativeWorkflowTests.Proxy<T>(handler??((method,args)=>Default(typeof(T).GetMethods().First(m=>m.Name==method).ReturnType)));
private static object? Default(Type type)
{
if(type==typeof(Task))return Task.CompletedTask;
if(type.IsGenericType&&type.GetGenericTypeDefinition()==typeof(Task<>))
{
var item=type.GenericTypeArguments[0];
object? value=item.IsGenericType&&item.GetGenericTypeDefinition()==typeof(IReadOnlyList<>)?Array.CreateInstance(item.GenericTypeArguments[0],0):item.GetConstructor(Type.EmptyTypes)!=null||item.IsValueType?Activator.CreateInstance(item):null;
return typeof(Task).GetMethod(nameof(Task.FromResult))!.MakeGenericMethod(item).Invoke(null,[value]);
}
return type.IsValueType?Activator.CreateInstance(type):null;
}
public static async Task Run()
{
await ReadOnlyScene();
await ResolutionAndIntent();
await ChronologyAndReuse();
await NotificationBoundary();
}
private static async Task NotificationBoundary()
{
string? group=null,eventName=null,payload=null;var fail=false;
var client=Stub<IClientProxy>((name,args)=>{if(fail)throw new InvalidOperationException("Synthetic disconnected transport");eventName=(string)args![0]!;payload=JsonSerializer.Serialize(args[1]);return Task.CompletedTask;});
var clients=Stub<IHubClients>((name,args)=>{group=(string)args![0]!;return client;});
var hub=Stub<IHubContext<NativeCompanionPresenceHub>>((name,args)=>clients);
var notifications=new ContextWorkspaceNotifications(hub,NullLogger<ContextWorkspaceNotifications>.Instance);
await notifications.Invalidate(7,2,3,20);
Check(group==NativeCompanionPresenceHub.UserGroup(7)&&eventName=="ContextInvalidated"&&payload!.Contains("bookId"),"Accepted-data invalidations use the authenticated account's existing hub group and lightweight scope");
await notifications.Position(7);
Check(eventName=="ContextPositionChanged"&&!payload!.Contains("sceneId"),"Office notifications are hints, not invented authoritative cursor payloads");
fail=true;await notifications.Invalidate(7,2);
Check(true,"Notification transport failure cannot turn a committed manuscript save into failure");
}
private static async Task ReadOnlyScene()
{
var allowed=true;var edits=0;
var project=new Project{ProjectID=1};var book=new Book{BookID=2,ProjectID=1};var chapter=new Chapter{ChapterID=2,BookID=2};
var source=new Scene{SceneID=20,ChapterID=2,ScenePurposeNotes="Author purpose — preserve verbatim",SceneOutcomeNotes="Author outcome"};
var projects=Stub<IProjectRepository>((n,a)=>n=="GetForUserAsync"?Task.FromResult<Project?>(allowed&&Equals(a![1],7)?project:null):throw new Exception("Unscoped project access"));
var scene=new SceneService(projects,Stub<IBookRepository>((n,a)=>Task.FromResult<Book?>(book)),Stub<IChapterRepository>((n,a)=>Task.FromResult<Chapter?>(chapter)),
Stub<ISceneRepository>((n,a)=>n=="GetAsync"?Task.FromResult<Scene?>(source):throw new Exception("Unexpected scene write")),Stub<ILookupRepository>(),
Stub<IPlotRepository>(),Stub<IAssetRepository>(),Stub<ICharacterRepository>(),Stub<ILocationRepository>(),Stub<IWarningRepository>(),Stub<ISceneDependencyRepository>(),Stub<IWriterWorkspaceRepository>(),
Stub<ISubscriptionService>((n,a)=>throw new Exception("No analysis entitlement check needed for saved reads")),Stub<IProjectActivityService>((n,a)=>{edits++;throw new Exception("Read must not write activity");}),
Stub<IStorageService>((n,a)=>throw new Exception("No editor storage traversal")),Stub<IStoryStateService>((n,a)=>throw new Exception("No legacy per-entity state traversal")),
Stub<IManuscriptTextStatisticsRepository>((n,a)=>throw new Exception("No manuscript statistics recomputation")),Stub<ICurrentUserService>((n,a)=>7));
var model=await scene.GetWritingContextAsync(20);
Check(model?.ScenePurposeNotes==source.ScenePurposeNotes&&model.SceneOutcomeNotes==source.SceneOutcomeNotes&&edits==0,"Read-only scene hydration preserves author intent without editing, analysis or manuscript recomputation");
allowed=false;Check(await scene.GetWritingContextAsync(20)==null,"Read-only scene hydration rejects another user's project before loading workspace data");
}
private static (SceneEditViewModel Scene,StoryPointViewModel Narrative) Data()
{
var input=StoryPointTests.Fixture();var point=StoryPointContextService.Compose(input,20)!;
var scene=new SceneEditViewModel{SceneID=20,ChapterID=2,POVCharacterID=1,StartDateTime=point.Scene.StartDateTime,
Project=input.Timeline.Project,Book=point.Book,Chapter=point.Chapter,SceneTitle="Current saved scene",ScenePurposeNotes="My original scene purpose",SceneOutcomeNotes="My original outcome"};
return (scene,new(){Project=input.Timeline.Project!,Books=input.Timeline.Books,Chapters=input.Timeline.Chapters,Scenes=StoryStateService.OrderScenes(input.Timeline).ToArray(),Snapshot=point});
}
private static async Task ChronologyAndReuse()
{
var (scene,narrative)=Data();var reads=0;var projections=0;var legacy=0;
var scenes=Stub<ISceneService>((n,a)=>{if(n=="GetWritingContextAsync")reads++;else if(n=="GetEditAsync")legacy++;else throw new Exception(n);return Task.FromResult<SceneEditViewModel?>(scene);});
var points=Stub<IStoryPointContextService>((n,a)=>{projections++;return Task.FromResult<StoryPointViewModel?>(narrative);});
var access=Stub<IProjectAccessService>((n,a)=>Task.FromResult(true));
var service=new StoryContextService(scenes,points,access);
var first=await service.GetForSceneAsync(20,1,2,forWriting:true);await service.GetForSceneAsync(20,1,2,forWriting:true);
Check(reads==1&&projections==1&&legacy==0,"Repeated writing reads share request-scoped scene and chronological projection tasks");
Check(first!.Narrative!.Snapshot!.ViewpointKnowledge.Single().Description=="The gate code"&&first.Narrative.Snapshot.ViewpointKnowledge.Single().KnowledgeStateName=="Knows","Context retains earlier verified viewpoint knowledge and excludes future transitions");
Check(first.Narrative.Snapshot.Characters.Single(c=>c.Appearance.CharacterID==2).Knowledge.Count==0,"Another character's future secret is not exposed as current knowledge");
Check(first.Narrative.Snapshot.Relationships.Single().CurrentStateName=="Trusted"&&first.Narrative.Snapshot.Relationships.All(r=>r.History.All(e=>e.SceneID!=1)),"Relationship reference stops at the current narrative position");
Check(await service.GetForSceneAsync(20,99,2,forWriting:true)==null&&await service.GetForSceneAsync(20,1,9,forWriting:true)==null,"Context rejects mismatched project and book scopes");
await service.GetForSceneAsync(20,1,2);
Check(legacy==1,"Existing Timeline and inspector callers retain their full editing model path");
var intentOnly=new StoryContextService(scenes,Stub<IStoryPointContextService>((n,a)=>throw new Exception("Intent must not load knowledge histories")),access);
Check((await intentOnly.GetForSceneAsync(20,1,2,forWriting:true,includeNarrative:false))?.Scene?.ScenePurposeNotes==scene.ScenePurposeNotes,"Intent retrieves saved decisions without computing narrative histories");
var input=StoryPointTests.Fixture();input.Timeline.Scenes.Single(s=>s.SceneID==1).StartDateTime=scene.StartDateTime!.Value.AddHours(-1);
var snapshot=StoryPointContextService.Compose(input,20)!;
var framed=new StoryContextViewModel{Scene=scene,Position=new(1,2,2,20),Narrative=new(){Project=input.Timeline.Project!,Chapters=input.Timeline.Chapters,Scenes=StoryStateService.OrderScenes(input.Timeline).ToArray(),Snapshot=snapshot}};
Check(WritingContextRelevance.Nearby(framed).All(s=>s.SceneID!=1),"A future narrative scene cannot leak into timeline context even when its story date is earlier");
Check(WritingContextRelevance.Threads(framed).Select(t=>t.PlotThreadID).SequenceEqual([4]),"Initial thread context ranks current relevant unresolved threads rather than dumping every novel thread");
input.Timeline.Scenes.Single(s=>s.SceneID==20).POVCharacterID=null;
Check(StoryPointContextService.Compose(input,20)!.ViewpointKnowledge.Count==0,"Missing viewpoint does not invent a knowledge perspective");
var options=WritingContextRelevance.SceneOptions(narrative,2,20);
Check(options.Select(o=>o.Value).SequenceEqual(["20","1"]),"Scene navigation follows manuscript order rather than numeric IDs or other books");
var scale=new StoryPointViewModel{Project=new(){ProjectID=1},Chapters=Enumerable.Range(0,48).Select(i=>new Chapter{ChapterID=i+1,BookID=2}).ToArray(),Scenes=Enumerable.Range(0,4800).Select(i=>new Scene{SceneID=i+1,ChapterID=i/100+1}).ToArray()};
var watch=Stopwatch.StartNew();var list=WritingContextRelevance.SceneOptions(scale,2,2400);watch.Stop();
Check(list.Count==4800&&list.Count(x=>x.Selected)==1,"Large-manuscript navigation is one bounded in-memory projection with no per-scene database queries");
Console.WriteLine($"MEASURE writing navigation projection: 48 chapters/4800 scenes, {watch.Elapsed.TotalMilliseconds:F1}ms, no SQL or Word.");
}
private static async Task ResolutionAndIntent()
{
var (scene,narrative)=Data();var instance=Guid.NewGuid();var session=Guid.NewGuid();var manuscript=Guid.NewGuid();long sequence=0,revision=5;
var presence=new NativePresenceStore(TimeProvider.System);var allowed=true;var mapping=true;var reads=0;Action? onRead=null;
void Beat(int? current=20,bool saved=true,long paragraph=3)=>presence.Put(7,"fixture",DateTimeOffset.UtcNow.AddMinutes(5),instance,session,new(){BookId=2,ManuscriptId=manuscript,Revision=revision,Sequence=++sequence,ChapterId=2,SceneId=current,WordAvailable=true,WordSaved=saved,CanChapterSync=true,ChapterSyncSupported=true,CursorStart=100,ParagraphRevision=paragraph});
var structure=new WordCompanionBookStructureResponse{BookId=2,Chapters=[new(){ChapterId=2,Scenes=[new(){SceneId=99},new(){SceneId=20}]}]};
var companion=Stub<IWordCompanionRepository>((n,a)=>Task.FromResult<WordCompanionBookStructureResponse?>(allowed?structure:null));
var story=Stub<IStoryContextService>((n,a)=>{reads++;onRead?.Invoke();return Task.FromResult<StoryContextViewModel?>(new(){Position=new(1,2,2,20),Project=scene.Project,Book=scene.Book,Chapter=scene.Chapter,Scene=scene,Narrative=(bool)a![4]!?narrative:null});});
var goal=new ChapterGoal{GoalSummary="An author's objective",EmotionalGoal="Doubt → commitment",MustInclude="An unresolved promise",ReaderTakeaway="A possibility, not canon"};
var workflow=new ChapterWorkflowViewModel{Project=scene.Project!,Book=scene.Book!,Chapter=scene.Chapter!,Goal=goal};
var writer=Stub<IWriterWorkspaceService>((n,a)=>n=="GetChapterWorkflowAsync"?Task.FromResult<ChapterWorkflowViewModel?>(workflow):throw new Exception("Intent read attempted a write"));
var controller=new WritingController(story,null!,null!,NullLogger<WritingController>.Instance,companion,presence,Stub<IProjectAccessService>((n,a)=>Task.FromResult(allowed)),
Stub<IChapterSyncRepository>((n,a)=>n=="Position"?Task.FromResult<ParagraphPosition?>(mapping?new(){Revision=3,ChapterID=2,SceneID=presence.Read(7,2).Single().Position.SceneId}:null):throw new Exception("Context must not synchronise or reconcile")))
{ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}};
Beat();
var page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(page.WorkingContext?.VerifiedWord?.Selection.SceneID==20 && page.WorkingContext.Working==null,"Verified native projection leaves working focus independent");
Check(page.SceneID==20&&page.Display!.HasScene&&page.Display.FollowStatus=="Following Word","Native launch opens its exact verified scene rather than the book's first scene");
var before=JsonSerializer.Serialize(new{scene.ScenePurposeNotes,scene.SceneOutcomeNotes,goal});
var redirect=(RedirectToActionResult)controller.Intent(1,2,2,20,null,instanceId:instance,sessionId:session);
Check(redirect.ActionName=="Context" && (Guid)redirect.RouteValues!["sessionId"]! == session,"Intent compatibility preserves native session and routes only to Context");
Check(JsonSerializer.Serialize(new{scene.ScenePurposeNotes,scene.SceneOutcomeNotes,goal})==before,"Opening Context preserves all author-entered decisions verbatim");
Check(await controller.ContextCharacters(1,2,2,20,instance,session) is PartialViewResult characters && characters.ViewName=="_ContextTab","Characters has its own authorized partial endpoint");
Check(await controller.ContextCharacters(1,2,2,99,instance,session) is ConflictObjectResult,"Partial endpoint refuses a claimed scene different from the current session");
Check(await controller.ContextCharacters(1,2,2,20,instance,null) is BadRequestResult,"Partial endpoint rejects incomplete native document identity");
Beat(saved:false);var oldReads=reads;
page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(!page.Display!.HasScene&&reads==oldReads,"Unsaved native mapping waits without loading an unrelated saved scene");
Beat();mapping=false;page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(!page.Display!.HasScene&&reads==oldReads,"A stale database checkpoint cannot launch a scene merely claimed by the last heartbeat");mapping=true;
Beat(paragraph:0);page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(!page.Display!.HasScene&&reads==oldReads,"Chapter-capable sessions without accepted position evidence cannot launch claimed scene IDs");
Beat(current:null);page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(!page.Display!.HasScene,"A chapter without a mapped scene does not invent scene reference data");
Beat();onRead=()=>{revision++;Beat(current:99);};
page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(!page.Display!.HasScene,"A Word cursor/revision change during server loading cannot render the earlier cursor as current");
Beat();Check(await controller.ContextScene(1,2,2,20,instance,session) is ConflictObjectResult,"Native partial requests reject mappings that change during data loading");onRead=null;
Beat();allowed=false;
Check(await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session) is ForbidResult,"Native Context launch authorises the book before resolving or displaying its scene");allowed=true;
page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:Guid.NewGuid(),sessionId:session)).Model!;
Check(!page.Display!.HasScene,"Exact document selection cannot fall back to another connected Word instance");
Check(await controller.Context(1,2,null,null,null,instanceId:instance) is BadRequestObjectResult,"Incomplete native session identity is rejected");
}
}