Integrate scene-aware Writing Context and saved Intent with native sessions

This commit is contained in:
Nick Beckley 2026-11-12 22:24:22 +00:00
parent 5fb5cc9e7e
commit 1ad8e12ca8
22 changed files with 440 additions and 60 deletions

View File

@ -0,0 +1,33 @@
# Writing Context and Intent integration — 12 November 2026
The existing VSTO → Windows agent → native workspace redirect → Writing Context/Intent browser contract is retained. No native source, Companion version, installer, synchronisation algorithm, schema or manuscript data changes are included.
## Findings and implementation
Context already had scene cards, people, relationships, maps, metrics and plot exploration. Intent already displayed saved scene purpose/outcome, chapter objectives, emotional direction, reader takeaway, continuity requirements, notes, checklist and explicitly requested assessment. Existing Story Point services already provided batched, chronological, verified knowledge and relationship histories.
Native launch previously fell back to the first scene when the request provided only a book and exact document session. Both Writing pages now resolve that exact user/book/instance/session. Chapter-capable sessions require accepted chapter-position evidence from the existing position stored procedure. Missing, unsaved, stale or disconnected mappings wait instead of choosing another scene. Native fragment requests carry the exact session and recheck acceptance after loading; concurrent changes return 409. The browser cancels older native requests on pending/disconnected mappings and retains the saved fragment with an explicit status.
Writing uses a read-only scene hydration path rather than loading the full editing form, manuscript statistics, storage quotas, suggestions or per-entity legacy state. Existing Timeline/editor callers retain their original model. Intent avoids chronological history queries entirely. Request-scoped tasks share repeated scene/projection reads; unchanged native observations do not fetch another fragment.
Context reuses Story Point's canonical narrative ordering and verified knowledge transitions, including earlier scenes and books. It prioritises the recorded viewpoint, limits initial knowledge and thread lists, ranks unresolved threads by current developments, character knowledge and chapter, and shows at most five established nearby scenes in the current book. A later narrative scene is excluded even if its story date is earlier. Historical relationships and other characters' knowledge are labelled author reference rather than viewpoint awareness. Reader knowledge is explicitly not independently recorded; missing viewpoint/knowledge is not inferred. Source links remain available. The full exploratory plot chart is identified as author planning, including future material.
Intent displays saved purpose types and clearly identifies the author plan and scene reference. Opening either page does not save, analyse, accept suggestions or rewrite author decisions. Project membership and existing authentication/subscription boundaries remain in place; new writing hydration authorises the owning project before scene workspace queries.
## Validation
- `dotnet build PlotLine.slnx`: passed, zero warnings/errors. This normal solution gate compiles its existing agent projects; no Windows VSTO package/version/installer was produced.
- Full executable regression harness: passed (484 PASS lines, including nested checks).
- Focused `--writing-integration`: 26 checks passed; exact scene/session resolution, saved Intent preservation, unauthorised scope, stale/unsaved/claimed mappings, concurrent revision changes, chronological knowledge/relationships, relevant threads, missing viewpoint, repeated task reuse and canonical scene order.
- Focused `--writing-context-navigation`: 30 checks passed, including exact-session commands, access, maps/metrics and no passive navigation feedback.
- Chromium follow/recovery: passed native/legacy races, pending response cancellation, server 409 recovery, unverified mapping refusal, unchanged-scene deduplication and no passive Word commands/focus.
- Compiled Razor browser suites: Context shell/PWA and embedded layouts; navigation at three widths/four themes; people/plots/maps/metrics; Context/Intent saved plans and missing metadata; 400-scene chart fixture. The scale fixture retained one chart read across four scene changes (282 ms initial chart / 195 ms changes on this run).
- In-memory navigation projection: 48 chapters / 4,800 scenes in 3.0 ms, no SQL or Word. This is a projection measurement, not a live Discovery database or Word latency claim. The protected Discovery manuscript and accepted chapters were not modified.
## Development delivery
Deployment verification is recorded below after installation. No database migration is required. Development activity is checked before stopping the service; deployed settings, uploads, keys and logs are preserved.
## Remaining Windows check
Use the already qualified Companion to open Context and Intent at two accepted scenes, including a cross-chapter move. Confirm the current scene and saved objectives, then edit/save and confirm pending-to-verified following. Atlas tests exercise the server/browser contracts and compiled pages; they do not automate real Word. No Companion upgrade is required for this integration.

View File

@ -4,15 +4,16 @@ const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:
const page=await browser.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));
const html=`<button id="native-companion-status"><span id="native-companion-status-text">Checking Word…</span></button><main data-writing-context data-scope-book-id="12" data-scope-project-id="7" data-context-url="/Writing/Context/Scene"><span data-writing-context-status-text></span><input name="__RequestVerificationToken" value="fixture"><section data-writing-context-content></section></main>`;
const fragment=(scene)=>`<article data-writing-context-fragment data-project-id="7" data-book-id="12" data-chapter-id="${scene===22?10:11}" data-scene-id="${scene}"><nav><button data-writing-context-tab="overview">Overview</button><button data-writing-context-tab="people">People</button></nav><select data-writing-context-scene-select><option value="22" ${scene===22?'selected':''}>First</option><option value="23" ${scene===23?'selected':''}>Second</option></select><button data-writing-scene-step="${scene===22?23:22}">Next</button><div data-writing-context-panel="overview">Overview saved data</div><div data-writing-context-panel="people">People saved data</div></article>`;
let current=22,failStatus=false,holdStatus=false,release,reads=0,commands=0,fragmentFailure=false,holdFragment=false,releaseFragment;
let current=22,wordSaved=true,verified=true,fragmentReads=0,failStatus=false,holdStatus=false,release,reads=0,commands=0,fragmentFailure=false,fragmentConflict=false,holdFragment=false,releaseFragment;
await page.route('https://context.test/**',async r=>{const u=new URL(r.request().url());
if(u.pathname==='/')return r.fulfill({contentType:'text/html',body:html});
if(u.pathname==='/native-companion/status'){
reads++;const snapshot=current;if(holdStatus){holdStatus=false;await new Promise(resolve=>release=resolve);}
return r.fulfill(failStatus?{status:503}:{json:[{instanceId:'instance',sessionId:'session',bookId:12,chapterId:snapshot===22?10:11,sceneId:snapshot,wordAvailable:true,wordSaved:true,active:true,documentTitle:'Synthetic',expires:new Date(Date.now()+45000).toISOString()}]});}
return r.fulfill(failStatus?{status:503}:{json:[{instanceId:'instance',sessionId:'session',bookId:12,chapterId:snapshot===22?10:11,sceneId:snapshot,wordAvailable:true,wordSaved,positionVerified:verified,active:true,documentTitle:'Synthetic',expires:new Date(Date.now()+45000).toISOString()}]});}
if(u.pathname==='/Writing/Context/Scene'){
fragmentReads++;assert.equal(u.searchParams.get('instanceId')||'instance','instance');assert.equal(u.searchParams.get('sessionId')||'session','session');
if(holdFragment){holdFragment=false;await new Promise(resolve=>releaseFragment=resolve);}
return r.fulfill(fragmentFailure?{status:503}:{contentType:'text/html',body:fragment(Number(u.searchParams.get('sceneId')))});}
return r.fulfill(fragmentConflict?{status:409}:fragmentFailure?{status:503}:{contentType:'text/html',body:fragment(Number(u.searchParams.get('sceneId')))});}
if(u.pathname==='/Writing/Context/Navigate'){commands++;assert.ok(new URLSearchParams(r.request().postData()).get('navigationId'));return r.fulfill({json:{message:'Navigation requested in Word.'}});}
return r.fulfill({json:{known:false}});
});
@ -30,7 +31,8 @@ const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:
// A delayed legacy broadcast must not override a live native cursor scene.
await page.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:story-position-changed',{detail:{projectId:7,bookId:12,chapterId:10,sceneId:22,source:'WordCompanion'}})));
await page.waitForTimeout(120);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'23','stale legacy position cannot replace live native scene');
for(let i=0;i<8;i++)await pulse();await page.waitForTimeout(60);assert.equal(commands,0);assert.equal(await page.evaluate(()=>focusCalls),0);
const repeated=fragmentReads;
for(let i=0;i<8;i++)await pulse();await page.waitForTimeout(60);assert.equal(commands,0);assert.equal(await page.evaluate(()=>focusCalls),0);assert.equal(fragmentReads,repeated,'unchanged native scenes do not recompute context fragments');
// Status failure must dispatch disconnection, not throw ReferenceError for an out-of-scope leases variable.
failStatus=true;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('disconnected'));
failStatus=false;current=22;await pulse();await scene(22);assert.deepEqual(errors,[]);
@ -44,6 +46,13 @@ const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:
// Genuine keyboard action requests exactly one command; its acknowledgement is passive.
await page.locator('[data-writing-context-scene-select]').press('Home');await scene(22);await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Navigation requested'));assert.equal(commands,1);
current=22;for(let i=0;i<4;i++)await pulse();await page.waitForTimeout(60);assert.equal(commands,1);assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.deepEqual(errors,[]);
// A pending/unsaved mapping must invalidate an older in-flight scene response.
holdFragment=true;current=23;await pulse();while(!releaseFragment)await page.waitForTimeout(10);
wordSaved=false;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Save Word'));
releaseFragment();await page.waitForTimeout(150);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22','late fragment cannot restore an earlier cursor after native mapping becomes pending');
wordSaved=true;verified=false;await pulse();await page.waitForTimeout(60);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22','unverified claimed native scene cannot replace saved context');
verified=true;fragmentConflict=true;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('awaiting verification'));assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22');fragmentConflict=false;await pulse();await scene(23);assert.equal(commands,1);
console.log('PASS pending native response cancellation, unverified mapping refusal, exact-session query parameters and no recomputation for repeated unchanged scenes');
console.log('PASS native/legacy race, cross-chapter cursor following, repeated presence without commands/focus, status failure recovery, in-flight invalidation, unchanged-scene fragment retry, trusted explicit navigation and acknowledgement without feedback; simulated Chromium protocol, not Word');
// Native safety source guard: ordinary polling must never invalidate the ribbon or select a range.
const adapter=fs.readFileSync(path.resolve(__dirname,'../../PlotDirector.NativeCompanion/Vsto/WordAdapter.cs'),'utf8');const observation=adapter.split('private void CaptureSelection()')[1].split('private int DocumentEnd')[0];assert.doesNotMatch(observation,/invalidateRibbon\(|\.Select\(/);assert.match(adapter,/command.Kind=="navigate"/);console.log('PASS native source invariant: selection observation contains no ribbon invalidation or range selection (not runtime Word proof)');

View File

@ -141,6 +141,7 @@ if(args.Contains("--native-import-corrections")){await NativeImportCorrectionTes
if(args.Contains("--native-captured-evidence")){await NativeImportCorrectionTests.CapturedEvidence(args[1],args[2]);return;}
if(args.Contains("--writing-context-dev-seed")){await WritingContextDevelopmentFixture.Run(args);return;}
if(args.Contains("--writing-context-navigation")){await WritingContextNavigationTests.Run();return;}
if(args.Contains("--writing-integration")){await WritingIntegrationTests.Run();return;}
if(args.Contains("--native-capture-lifetime")){await NativeCaptureLifetimeTests.Run();return;}
if(args.Contains("--native-tray")){await NativeTrayIntegrationTests.Run();await NativeManuscriptCaptureTests.Run();Console.WriteLine("PASS native tray presence, expiry, scope and persistent PWA review decisions");return;}
if(args.Contains("--native-workflow")){await NativeWorkflowTests.Run();Console.WriteLine("PASS native saved workspace and safe import preview validation");return;}
@ -501,6 +502,7 @@ var tests = new (string Name, Action Test)[]
("Toolbar preferences, authorisation and contextual routes", ToolbarTests.PreferencesAndRoutes),
("Application navigation resolves authorised project and book context", ApplicationNavigationTests.ContextAndPermissions),
("Writing pair shares canonical follow infrastructure", WritingPairSharesCanonicalFollowInfrastructure),
("Writing Context and Intent resolve native sessions, preserve decisions and reuse bounded chronological data", () => WritingIntegrationTests.Run().GetAwaiter().GetResult()),
("Writing Context Plot Lines preserves canonical associations, developments and book access", () => WritingContextPlotLinesTests.Run().GetAwaiter().GetResult()),
("Writing workspace presence scopes browser windows", WritingWorkspacePresenceScopesBrowserWindows),
("Writing workspace client uses session window identity and stable names", WritingWorkspaceClientUsesSessionIdentityAndStableNames),

View File

@ -120,7 +120,7 @@ internal static class StoryPointTests
private static T Proxy<T>(Func<string, object?[]?, object?> invoke) where T : class
{ var proxy = DispatchProxy.Create<T, StoryPointProxy>(); ((StoryPointProxy)(object)proxy).Handler = invoke; return proxy; }
private static StoryPointInputs Fixture() => new()
internal static StoryPointInputs Fixture() => new()
{
Timeline = new TimelineData { Project = new Project { ProjectID = 1 },
Books = [new Book { BookID = 2, BookNumber = 2, SortOrder = 2, BookTitle = "Voyage" }, new Book { BookID = 9, BookNumber = 1, SortOrder = 1, BookTitle = "Departure" }],

View File

@ -0,0 +1,133 @@
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();
}
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!,writer,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.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 intent=(WritingIntentPageViewModel)((ViewResult)await controller.Intent(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(intent.SceneID==20&&intent.Display!.ChapterWorkflow!.Goal==goal&&intent.Display.Context!.Scene!.ScenePurposeNotes==scene.ScenePurposeNotes,"Native Intent retrieves the selected scene's existing purpose and chapter objectives");
Check(JsonSerializer.Serialize(new{scene.ScenePurposeNotes,scene.SceneOutcomeNotes,goal})==before,"Opening Context and Intent preserves all author-entered decisions verbatim");
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);intent=(WritingIntentPageViewModel)((ViewResult)await controller.Intent(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(intent.Display!.IsChapterOnly&&intent.Display.ChapterWorkflow!.Goal==goal,"A verified chapter with no mapped scene can show its own saved chapter intent");
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;
Check(await controller.Intent(1,2,null,null,null,instanceId:Guid.NewGuid(),sessionId:session) is ViewResult missing&&((WritingIntentPageViewModel)missing.Model!).Display!.HasScene==false,"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");
}
}

View File

@ -27,7 +27,7 @@ public sealed class NativeCompanionWorkflowController(IWordCompanionRepository a
var book=await books.GetAsync(bookId);if(book==null)return NotFound();
var parent=sceneId.HasValue?structure.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==sceneId)):chapterId.HasValue?structure.Chapters.FirstOrDefault(c=>c.ChapterId==chapterId):null;
if((sceneId.HasValue||chapterId.HasValue)&&(parent==null||(chapterId.HasValue&&parent.ChapterId!=chapterId)))return NotFound();
var saved=sceneId.HasValue?await context.GetForSceneAsync(sceneId.Value,book.ProjectID,bookId):null;
var saved=sceneId.HasValue?await context.GetForSceneAsync(sceneId.Value,book.ProjectID,bookId,forWriting:true,includeNarrative:false):null;
if(sceneId.HasValue&&saved?.Scene==null)return NotFound();
var workflow=parent!=null?await writer.GetChapterWorkflowAsync(parent.ChapterId):null;
if(workflow!=null&&(workflow.Book.BookID!=bookId||workflow.Project.ProjectID!=book.ProjectID))return Forbid();

View File

@ -37,11 +37,12 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB
foreach(var book in leases.Select(l=>l.Position.BookId).Where(b=>b>0).Distinct())if(await access.GetBookStructureAsync(book,Author)!=null)allowed.Add(book);
var snapshots=new Dictionary<int,ParagraphSyncStatus?>();
if(paragraphs!=null)foreach(var book in leases.Where(l=>l.Position.WordAvailable&&allowed.Contains(l.Position.BookId)&&l.Position.BookId>0).Select(l=>l.Position.BookId).Distinct())snapshots[book]=await paragraphs.Status(Author,book);
return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,l.Position.ChapterIssue,l.Position.CanChapterSync,chapterProgress=presence.ChapterProgress(Author,l.Position.BookId,l.Instance,l.Session,l.Position.Revision),l.Position.CanParagraphSync,l.Position.CaptureRequestId,l.Position.CaptureProgress,
return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.Revision,l.Position.ManuscriptId,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,l.Position.ChapterIssue,l.Position.CanChapterSync,chapterProgress=presence.ChapterProgress(Author,l.Position.BookId,l.Instance,l.Session,l.Position.Revision),l.Position.CanParagraphSync,l.Position.CaptureRequestId,l.Position.CaptureProgress,
paragraphTransfer=capture?.ParagraphTransferStatus(Author,l.Position.BookId,l.Instance,l.Session),
positionVerified=l.Position.WordSaved==true&&(!(l.Position.CanChapterSync||l.Position.CanParagraphSync)||l.Position.ParagraphRevision>0)&&l.Position.ChapterId.HasValue,
snapshotRevision=snapshots.GetValueOrDefault(l.Position.BookId)?.Revision,
mappingCurrent=snapshots.GetValueOrDefault(l.Position.BookId) is {} saved&&saved.ManuscriptId==l.Position.ManuscriptId&&saved.SessionId==l.Session&&saved.WordRevision==l.Position.Revision,
positionMessage=l.Position.WordSaved==false?"Save Word, then synchronise to refresh its scene mapping":l.Position.SceneId.HasValue?null:l.Position.CanChapterSync?(l.Position.ChapterIssue=="needs_review"?"Chapter reading needs review or retry; accepted mappings are preserved":l.Position.ChapterId.HasValue?"Current paragraph is checked but has no scene assignment; move into scene prose":"Checking the current chapter for this Word session; saved scenes remain available"):snapshots.GetValueOrDefault(l.Position.BookId) is {} snapshot?(snapshot.ManuscriptId!=l.Position.ManuscriptId?"This Word document does not match the book's saved manuscript identity":snapshot.SessionId!=l.Session||snapshot.WordRevision!=l.Position.Revision?"Word reopened or changed; synchronise from Word to verify this session's paragraph positions":snapshot.Paused?"Scene mapping is unresolved; synchronisation is paused while existing book processing finishes":"Current paragraph has no verified scene assignment") : "Synchronise from Word to establish a verified paragraph mapping",
positionMessage=l.Position.WordSaved==false?"Save Word before verifying its scene mapping":l.Position.SceneId.HasValue?null:l.Position.CanChapterSync?(l.Position.ChapterIssue=="needs_review"?"Chapter reading needs review or retry; accepted mappings are preserved":l.Position.ChapterId.HasValue?"Current paragraph is checked but has no scene assignment; move into scene prose":"Checking the current chapter for this Word session; saved scenes remain available"):snapshots.GetValueOrDefault(l.Position.BookId) is {} snapshot?(snapshot.ManuscriptId!=l.Position.ManuscriptId?"This Word document does not match the book's saved manuscript identity":snapshot.SessionId!=l.Session||snapshot.WordRevision!=l.Position.Revision?"Word reopened or changed; synchronise from Word to verify this session's paragraph positions":snapshot.Paused?"Scene mapping is unresolved; synchronisation is paused while existing book processing finishes":"Current paragraph has no verified scene assignment") : "Synchronise from Word to establish a verified paragraph mapping",
updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
}
[HttpGet("reviews/{id:guid}")]

View File

@ -18,7 +18,7 @@ public sealed class WritingController(
IRelationshipMapService relationshipMap,
IFloorPlanService floorPlans,
IWriterWorkspaceService writerWorkspace,
ILogger<WritingController> logger,IStoryCalendarService? calendar=null,IWordCompanionRepository? companion=null) : Controller
ILogger<WritingController> logger,IWordCompanionRepository? companion=null,NativePresenceStore? nativePresence=null,IProjectAccessService? projectAccess=null,IChapterSyncRepository? chapterPositions=null) : Controller
{
[HttpGet("Context")]
public async Task<IActionResult> Context(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false,bool embedded=false,Guid? instanceId=null,Guid? sessionId=null)
@ -32,7 +32,21 @@ public sealed class WritingController(
sceneId,
documentGuid.HasValue);
if(!sceneId.HasValue&&bookId.HasValue&&companion!=null) {
if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest("Choose one complete Word document session.");
var nativeLaunch=!pinned&&(instanceId.HasValue||sessionId.HasValue);
NativeWritingTarget? target=null;
if(nativeLaunch)
{
if(!bookId.HasValue||companion==null)return BadRequest("A linked book is required.");
var structure=await companion.GetBookStructureAsync(bookId.Value,WritingUser);
if(structure==null)return Forbid();
target=await NativeTarget(bookId,instanceId,sessionId);
var chapter=structure.Chapters.FirstOrDefault(c=>c.ChapterId==target?.ChapterId);
if(target?.SceneId is int current&&chapter?.Scenes.Any(x=>x.SceneId==current)!=true)target=null;
if(target?.ChapterId!=null&&chapter==null)target=null;
chapterId=target?.ChapterId;sceneId=target?.SceneId;
}
if(!nativeLaunch&&!sceneId.HasValue&&bookId.HasValue&&companion!=null) {
var structure=await companion.GetBookStructureAsync(bookId.Value,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!));
sceneId=structure?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault()?.SceneId;
}
@ -40,11 +54,17 @@ public sealed class WritingController(
? await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual context")
: WaitingContextDisplay(projectId, bookId, documentGuid);
if(nativeLaunch&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId)))
{
sceneId=null;chapterId=null;
display=WaitingContextDisplay(projectId,bookId,documentGuid);
}
if(nativeLaunch&&display!=null)display.FollowStatus=target!=null&&sceneId.HasValue?"Following Word":"Word mapping pending · choose a saved scene to browse manually";
if(pinned&&display!=null){display.FollowStatus="Saved PlotDirector snapshot";if(!sceneId.HasValue){display.EmptyTitle="No saved scene selected";display.EmptyMessage="This is a scoped saved-data view, not live Word following. Select a saved scene in PlotDirector; local markers or AI suggestions do not create saved context.";}}
var model = new WritingContextPageViewModel
{
ProjectID = projectId,
BookID = bookId,
ProjectID = display?.Context?.Position.ProjectId ?? projectId,
BookID = display?.Context?.Position.BookId ?? bookId,
ChapterID = chapterId,
SceneID = sceneId,
DocumentGuid = documentGuid,
@ -66,7 +86,21 @@ public sealed class WritingController(
sceneId,
documentGuid.HasValue);
if(!sceneId.HasValue&&!chapterId.HasValue&&bookId.HasValue&&companion!=null) {
if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest("Choose one complete Word document session.");
var nativeLaunch=!pinned&&(instanceId.HasValue||sessionId.HasValue);
NativeWritingTarget? target=null;
if(nativeLaunch)
{
if(!bookId.HasValue||companion==null)return BadRequest("A linked book is required.");
var structure=await companion.GetBookStructureAsync(bookId.Value,WritingUser);
if(structure==null)return Forbid();
target=await NativeTarget(bookId,instanceId,sessionId);
var chapter=structure.Chapters.FirstOrDefault(c=>c.ChapterId==target?.ChapterId);
if(target?.SceneId is int current&&chapter?.Scenes.Any(x=>x.SceneId==current)!=true)target=null;
if(target?.ChapterId!=null&&chapter==null)target=null;
chapterId=target?.ChapterId;sceneId=target?.SceneId;
}
if(!nativeLaunch&&!sceneId.HasValue&&!chapterId.HasValue&&bookId.HasValue&&companion!=null) {
var structure=await companion.GetBookStructureAsync(bookId.Value,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!));
var first=structure?.Chapters.FirstOrDefault(c=>c.Scenes.Count>0)??structure?.Chapters.FirstOrDefault();
chapterId=first?.ChapterId;sceneId=first?.Scenes.FirstOrDefault()?.SceneId;
@ -75,11 +109,17 @@ public sealed class WritingController(
? await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual intent")
: WaitingIntentDisplay(projectId, bookId, documentGuid);
if(nativeLaunch&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId)))
{
sceneId=null;chapterId=null;
display=WaitingIntentDisplay(projectId,bookId,documentGuid);
}
if(nativeLaunch&&display!=null)display.FollowStatus=target!=null&&(sceneId.HasValue||chapterId.HasValue)?"Following Word":"Word mapping pending · choose a saved scene to browse manually";
if(pinned&&display!=null){display.FollowStatus="Saved PlotDirector snapshot";if(!sceneId.HasValue&&!chapterId.HasValue){display.EmptyTitle="No saved writing objective selected";display.EmptyMessage="Choose a saved chapter or scene in PlotDirector. Set its goal/purpose explicitly; this view does not invent or automatically save intent.";}}
var model = new WritingIntentPageViewModel
{
ProjectID = projectId,
BookID = bookId,
ProjectID = display?.Context?.Position.ProjectId ?? display?.ChapterWorkflow?.Project.ProjectID ?? projectId,
BookID = display?.Context?.Position.BookId ?? display?.ChapterWorkflow?.Book.BookID ?? bookId,
ChapterID = chapterId,
SceneID = sceneId,
DocumentGuid = documentGuid,
@ -90,8 +130,12 @@ public sealed class WritingController(
}
[HttpGet("Context/Scene")]
public async Task<IActionResult> ContextScene(int? projectId, int? bookId, int? chapterId, int? sceneId)
public async Task<IActionResult> ContextScene(int? projectId, int? bookId, int? chapterId, int? sceneId,Guid? instanceId=null,Guid? sessionId=null)
{
if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest();
var nativeRequest=instanceId.HasValue||sessionId.HasValue;
var target=nativeRequest?await NativeTarget(bookId,instanceId,sessionId):null;
if(nativeRequest&&(target==null||target.SceneId!=sceneId||(chapterId.HasValue&&target.ChapterId!=chapterId)))return Conflict(new{message="Word position changed or is awaiting verification."});
if (!sceneId.HasValue)
{
logger.LogWarning("Writing Context partial requested without SceneID. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID}", projectId, bookId, chapterId);
@ -99,6 +143,7 @@ public sealed class WritingController(
}
var model = await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene");
if(nativeRequest&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId)))return Conflict(new{message="Word position changed while context was loading."});
if (model?.HasScene == true)
{
return PartialView("~/Views/Writing/_WritingContextContent.cshtml", model);
@ -109,8 +154,12 @@ public sealed class WritingController(
}
[HttpGet("Intent/Scene")]
public async Task<IActionResult> IntentScene(int? projectId, int? bookId, int? chapterId, int? sceneId)
public async Task<IActionResult> IntentScene(int? projectId, int? bookId, int? chapterId, int? sceneId,Guid? instanceId=null,Guid? sessionId=null)
{
if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest();
var nativeRequest=instanceId.HasValue||sessionId.HasValue;
var target=nativeRequest?await NativeTarget(bookId,instanceId,sessionId):null;
if(nativeRequest&&(target==null||target.SceneId!=sceneId||(chapterId.HasValue&&target.ChapterId!=chapterId)))return Conflict(new{message="Word position changed or is awaiting verification."});
if (!sceneId.HasValue && !chapterId.HasValue)
{
logger.LogWarning("Writing Intent partial requested without ChapterID or SceneID. ProjectID={ProjectID} BookID={BookID}", projectId, bookId);
@ -118,6 +167,7 @@ public sealed class WritingController(
}
var model = await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene");
if(nativeRequest&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId)))return Conflict(new{message="Word position changed while context was loading."});
if (model is not null && (model.HasScene || model.HasChapter))
{
return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", model);
@ -127,6 +177,26 @@ public sealed class WritingController(
return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", MissingIntentDisplay(projectId, bookId, chapterId, sceneId));
}
private int WritingUser=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
private sealed record NativeWritingTarget(Guid Instance,Guid Session,Guid Manuscript,long Revision,int? ChapterId,int? SceneId,long AcceptedRevision);
private static bool InvalidNativeSelection(Guid? instance,Guid? session)=>instance.HasValue!=session.HasValue||instance==Guid.Empty||session==Guid.Empty;
private async Task<NativeWritingTarget?> NativeTarget(int? book,Guid? instance,Guid? session)
{
if(!book.HasValue||!instance.HasValue||!session.HasValue||nativePresence==null)return null;
var lease=nativePresence.Read(WritingUser,book.Value).SingleOrDefault(l=>l.Instance==instance&&l.Session==session&&l.Position.WordAvailable&&l.Position.WordSaved==true&&(!(l.Position.CanChapterSync||l.Position.CanParagraphSync)||l.Position.ParagraphRevision>0));
if(lease==null)return null;
var acceptedRevision=lease.Position.ParagraphRevision;
if(lease.Position.CanChapterSync)
{
if(chapterPositions==null||lease.Position.CursorStart is not int cursor)return null;
var accepted=await chapterPositions.Position(WritingUser,book.Value,lease.Position.ManuscriptId,lease.Session,lease.Position.Revision,cursor);
if(accepted?.ChapterID!=lease.Position.ChapterId||accepted?.SceneID!=lease.Position.SceneId||accepted==null||accepted.Revision<=0)return null;
acceptedRevision=accepted.Revision;
}
return new(lease.Instance,lease.Session,lease.Position.ManuscriptId,lease.Position.Revision,lease.Position.ChapterId,lease.Position.SceneId,acceptedRevision);
}
private static bool SameNativeTarget(NativeWritingTarget? before,NativeWritingTarget? after)=>before!=null&&before==after;
private async Task<WritingContextDisplayViewModel?> BuildDisplayAsync(int? projectId, int? bookId, int? chapterId, int? sceneId, string followStatus)
{
if (!sceneId.HasValue)
@ -134,21 +204,26 @@ public sealed class WritingController(
return new WritingContextDisplayViewModel { FollowStatus = followStatus };
}
var context = await storyContext.GetForSceneAsync(sceneId.Value, projectId, bookId);
if (context?.Scene is null)
var context = await storyContext.GetForSceneAsync(sceneId.Value, projectId, bookId,forWriting:true);
if (context?.Scene is null||chapterId.HasValue&&context.Position.ChapterId!=chapterId)
{
return null;
}
var position = context.Position;
var relationships = await relationshipMap.GetAsync(position, null, true);
var point=context.Narrative?.Snapshot;
var relationships=point!=null?new RelationshipMapViewModel{Relationships=point.Relationships}:await relationshipMap.GetAsync(position,null,true);
if(point!=null)
{
if(context.Scene.POVCharacterID is int pov)context.Scene.CharacterOptions=[new SelectListItem(point.PovName??"Unknown POV",pov.ToString())];
if(point.Location is {} place)context.Scene.LocationOptions=[new SelectListItem(place.LocationPath.Length>0?place.LocationPath:place.LocationName,place.LocationID.ToString())];
}
var floorPlan = context.Scene.FloorPlanID.HasValue
? await floorPlans.GetEditorAsync(context.Scene.FloorPlanID.Value)
: null;
var nearby = calendar is not null && context.Scene.StartDateTime.HasValue
? (await calendar.GetAsync(position.ProjectId,position.BookId,null,DateOnly.FromDateTime(context.Scene.StartDateTime.Value)))?.DatedScenes.Where(x=>x.SceneID!=sceneId && x.StartDateTime.HasValue && Math.Abs((x.StartDateTime.Value-context.Scene.StartDateTime.Value).TotalDays)<=3).OrderBy(x=>x.StartDateTime).Take(5).ToArray() ?? []
: [];
if(floorPlan!=null&&floorPlan.FloorPlan.ProjectID!=position.ProjectId)floorPlan=null;
var nearby=WritingContextRelevance.Nearby(context);
return new WritingContextDisplayViewModel
{
NearbyScenes = nearby,
@ -156,7 +231,7 @@ public sealed class WritingController(
RelationshipMap = relationships,
FloorPlan = floorPlan,
FollowStatus = followStatus,
SceneOptions = await ContextSceneOptions(context.Scene)
SceneOptions = await ContextSceneOptions(context.Scene,context.Narrative)
};
}
@ -165,8 +240,8 @@ public sealed class WritingController(
StoryContextViewModel? context = null;
if (sceneId.HasValue)
{
context = await storyContext.GetForSceneAsync(sceneId.Value, projectId, bookId);
if (context?.Scene is null)
context = await storyContext.GetForSceneAsync(sceneId.Value, projectId, bookId,forWriting:true,includeNarrative:false);
if (context?.Scene is null||chapterId.HasValue&&context.Position.ChapterId!=chapterId)
{
return null;
}
@ -179,6 +254,7 @@ public sealed class WritingController(
if (chapterWorkflow is not null)
{
if(projectAccess==null||!await projectAccess.CanAccessProjectAsync(chapterWorkflow.Project.ProjectID))return null;
if (projectId.HasValue && chapterWorkflow.Project.ProjectID != projectId.Value)
{
return null;
@ -241,8 +317,9 @@ public sealed class WritingController(
return data.Project==null?NotFound():PartialView("_WritingContextMetrics",WritingContextMetrics.Build(data,recorded));
}
private async Task<IReadOnlyList<SelectListItem>> ContextSceneOptions(SceneEditViewModel scene)
private async Task<IReadOnlyList<SelectListItem>> ContextSceneOptions(SceneEditViewModel scene,StoryPointViewModel? narrative=null)
{
if(narrative!=null)return WritingContextRelevance.SceneOptions(narrative,scene.Book!.BookID,scene.SceneID);
if(companion==null)return BuildSceneOptions(scene);
var structure=await companion.GetBookStructureAsync(scene.Book!.BookID,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!));
return structure?.Chapters.SelectMany(c=>c.Scenes.Select(s=>new SelectListItem($"{c.Title} · {s.Title}",s.SceneId.ToString(),s.SceneId==scene.SceneID))).ToList()??[];

View File

@ -126,6 +126,7 @@ public interface ISceneService
{
Task<SceneEditViewModel?> GetCreateAsync(int chapterId);
Task<SceneEditViewModel?> GetEditAsync(int sceneId);
Task<SceneEditViewModel?> GetWritingContextAsync(int sceneId);
Task<int> SaveAsync(SceneEditViewModel model);
Task UpdatePovCharacterAsync(int sceneId, int? povCharacterId, string source = "Author", decimal? confidence = null, string? evidence = null, string? suggestedName = null, bool overwriteAuthor = false);
Task ArchiveAsync(int sceneId);
@ -155,11 +156,12 @@ public interface IStoryStateService
public interface IStoryContextService
{
Task<StoryContextViewModel?> GetAsync(StoryPosition position);
Task<StoryContextViewModel?> GetForSceneAsync(int sceneId, int? projectId = null, int? bookId = null);
Task<StoryContextViewModel?> GetForSceneAsync(int sceneId, int? projectId = null, int? bookId = null, bool forWriting = false, bool includeNarrative = true);
}
public sealed class StoryContextViewModel
{
public StoryPointViewModel? Narrative {get;init;}
public StoryPosition Position { get; init; } = new(0);
public Project? Project { get; init; }
public Book? Book { get; init; }
@ -1952,7 +1954,9 @@ public sealed class SceneService(
}, lookupData));
}
public async Task<SceneEditViewModel?> GetEditAsync(int sceneId)
public Task<SceneEditViewModel?> GetEditAsync(int sceneId)=>LoadSceneAsync(sceneId,false);
public Task<SceneEditViewModel?> GetWritingContextAsync(int sceneId)=>LoadSceneAsync(sceneId,true);
private async Task<SceneEditViewModel?> LoadSceneAsync(int sceneId,bool writing)
{
var scene = await scenes.GetAsync(sceneId);
if (scene is null)
@ -1960,15 +1964,15 @@ public sealed class SceneService(
return null;
}
var context = await GetContextAsync(scene.ChapterID);
var context = await GetContextAsync(scene.ChapterID,writing);
if (context is null)
{
return null;
}
var lookupData = await lookups.GetAllAsync();
var textStatistics = await manuscriptTextStatistics.GetBySceneAsync(sceneId);
return await PopulateWorkspaceDataAsync(PopulateLists(new SceneEditViewModel
var textStatistics = writing?null:await manuscriptTextStatistics.GetBySceneAsync(sceneId);
var model=PopulateLists(new SceneEditViewModel
{
SceneID = scene.SceneID,
ChapterID = scene.ChapterID,
@ -2006,7 +2010,8 @@ public sealed class SceneService(
Chapter = context.Value.Chapter,
Book = context.Value.Book,
Project = context.Value.Project
}, lookupData));
}, lookupData);
return writing?await PopulateWritingDataAsync(model):await PopulateWorkspaceDataAsync(model);
}
public async Task<int> SaveAsync(SceneEditViewModel model)
@ -2091,11 +2096,13 @@ public sealed class SceneService(
public Task MoveRelativeAsync(int sceneId, int anchorSceneId, string position) =>
scenes.MoveRelativeAsync(sceneId, anchorSceneId, position);
private async Task<(Project Project, Book Book, Chapter Chapter)?> GetContextAsync(int chapterId)
private async Task<(Project Project, Book Book, Chapter Chapter)?> GetContextAsync(int chapterId,bool writing=false)
{
var chapter = await chapters.GetAsync(chapterId);
var book = chapter is null ? null : await books.GetAsync(chapter.BookID);
var project = book is null ? null : await projects.GetAsync(book.ProjectID);
var project = book is null ? null : writing
? currentUser.UserId is int user?await projects.GetForUserAsync(book.ProjectID,user):null
: await projects.GetAsync(book.ProjectID);
return chapter is null || book is null || project is null ? null : (project, book, chapter);
}
@ -2109,6 +2116,32 @@ public sealed class SceneService(
return model;
}
private async Task<SceneEditViewModel> PopulateWritingDataAsync(SceneEditViewModel model)
{
// Read only existing scene records. Do not load editing choices, suggestions,
// storage quotas, or the legacy per-entity whole-project state traversal.
var threads=plots.ListThreadEventsBySceneAsync(model.SceneID);
var events=assets.ListEventsBySceneAsync(model.SceneID);
var custody=assets.ListCustodyBySceneAsync(model.SceneID);
var places=locations.ListSceneAssetLocationsAsync(model.SceneID);
var people=characters.ListSceneCharactersAsync(model.SceneID);
var attributes=characters.ListAttributeEventsBySceneAsync(model.SceneID);
var continuity=warnings.ListBySceneAsync(model.SceneID);
var dependencies=sceneDependencies.ListBySceneAsync(model.SceneID);
var relationships=characters.ListRelationshipEventsBySceneAsync(model.SceneID);
var workflow=writerWorkspace.GetWorkflowAsync(model.SceneID);
var notes=writerWorkspace.ListNotesAsync(model.SceneID);
var checklist=writerWorkspace.ListChecklistItemsAsync(model.SceneID);
await Task.WhenAll(threads,events,custody,places,people,attributes,continuity,dependencies,relationships,workflow,notes,checklist);
model.ThreadEvents=threads.Result;model.AssetEvents=events.Result;model.AssetCustodyEvents=custody.Result;
model.SceneAssetLocations=places.Result;model.SceneCharacters=people.Result;model.CharacterAttributeEvents=attributes.Result;
model.Warnings=continuity.Result;model.RelationshipEvents=relationships.Result.Where(x=>x.EvidenceState=="Verified").ToList();
model.DependenciesThisSceneNeeds=dependencies.Result.Where(x=>x.TargetSceneID==model.SceneID).ToList();
model.DependenciesNeedingThisScene=dependencies.Result.Where(x=>x.SourceSceneID==model.SceneID).ToList();
model.Workflow=workflow.Result;model.Notes=notes.Result;model.ChecklistItems=checklist.Result;
return model;
}
private async Task<SceneEditViewModel> PopulateWorkspaceDataAsync(SceneEditViewModel model)
{
if (model.Project is null)
@ -2462,8 +2495,11 @@ public sealed class SceneService(
}
}
public sealed class StoryContextService(ISceneService scenes) : IStoryContextService
public sealed class StoryContextService(ISceneService scenes,IStoryPointContextService points,IProjectAccessService access) : IStoryContextService
{
// Request-scoped memoisation only: no stale cross-request cache of author decisions.
private readonly Dictionary<(int Scene,bool Writing),Task<SceneEditViewModel?>> sceneReads=[];
private readonly Dictionary<int,Task<StoryPointViewModel?>> pointReads=[];
public async Task<StoryContextViewModel?> GetAsync(StoryPosition position)
{
if (!position.IsValid)
@ -2482,16 +2518,18 @@ public sealed class StoryContextService(ISceneService scenes) : IStoryContextSer
};
}
public async Task<StoryContextViewModel?> GetForSceneAsync(int sceneId, int? projectId = null, int? bookId = null)
public async Task<StoryContextViewModel?> GetForSceneAsync(int sceneId, int? projectId = null, int? bookId = null,bool forWriting=false,bool includeNarrative=true)
{
if (sceneId <= 0)
{
return null;
}
var scene = await scenes.GetEditAsync(sceneId);
var key=(sceneId,forWriting);
if(!sceneReads.TryGetValue(key,out var read))sceneReads[key]=read=forWriting?scenes.GetWritingContextAsync(sceneId):scenes.GetEditAsync(sceneId);
var scene=await read;
var position = StoryPosition.FromScene(scene);
if (position is null)
if (position is null || scene is null)
{
return null;
}
@ -2506,8 +2544,17 @@ public sealed class StoryContextService(ISceneService scenes) : IStoryContextSer
return null;
}
if(!forWriting&&!await access.CanAccessProjectAsync(position.ProjectId))return null;
StoryPointViewModel? narrative=null;
if(forWriting&&includeNarrative)
{
if(!pointReads.TryGetValue(sceneId,out var pointRead))pointReads[sceneId]=pointRead=points.GetAsync(position.ProjectId,sceneId);
narrative=await pointRead;
if(narrative?.Snapshot is not {} snapshot||snapshot.ProjectID!=position.ProjectId||snapshot.Book.BookID!=position.BookId||snapshot.Scene.SceneID!=sceneId||snapshot.Chapter.ChapterID!=position.ChapterId||snapshot.Scene.POVCharacterID!=scene.POVCharacterID)return null;
}
return new StoryContextViewModel
{
Narrative=narrative,
Position = position,
Project = scene!.Project,
Book = scene.Book,

View File

@ -18,7 +18,7 @@ public sealed class IntentAssessmentService(IStoryContextService context,IWriter
public static string Fingerprint(string prose,IEnumerable<IntentObjective> plan)=>Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes("intent-evidence-v1\n"+JsonSerializer.Serialize(plan)+"\n"+prose)));
public async Task<IntentAssessmentFrame> Read(int user,int scene)
{
var story=await context.GetForSceneAsync(scene,null,null)??throw new UnauthorizedAccessException();var s=story.Scene??throw new UnauthorizedAccessException();
var story=await context.GetForSceneAsync(scene,null,null,forWriting:true,includeNarrative:false)??throw new UnauthorizedAccessException();var s=story.Scene??throw new UnauthorizedAccessException();
var chapter=await writer.GetChapterWorkflowAsync(story.Position.ChapterId!.Value);
var plan=new List<IntentObjective>();void Add(string key,string? text){if(!string.IsNullOrWhiteSpace(text))plan.Add(new(key,text.Trim()));}
Add("purpose",s.ScenePurposeNotes);Add("outcome",s.SceneOutcomeNotes);Add("chapter-goal",chapter?.Goal?.GoalSummary);Add("emotional-goal",chapter?.Goal?.EmotionalGoal);Add("must-include",chapter?.Goal?.MustInclude);Add("reader-takeaway",chapter?.Goal?.ReaderTakeaway);

View File

@ -103,6 +103,7 @@ public sealed class StoryPointContextService(IProjectAccessService access, ITime
{
ProjectID = input.Timeline.Project.ProjectID, Book = book, Chapter = chapter, Scene = scene, Characters = people,
PovName = scene.POVCharacterID.HasValue ? characterModels.GetValueOrDefault(scene.POVCharacterID.Value)?.CharacterName ?? scene.POVCharacterName : scene.POVCharacterName,
ViewpointKnowledge = scene.POVCharacterID is int pov && characterModels.ContainsKey(pov) ? knowledge[pov].ToList() : [],
Relationships = RelationshipMapService.BuildAtScene(input.Relationships, indexes, sceneId)
.Where(x => presentIds.Contains(x.CharacterAID) || presentIds.Contains(x.CharacterBID)).ToList(),
Assets = pointAssets, Location = location, PreviousLocationUse = lastLocationScene is null ? null : sources[lastLocationScene.SceneID],

View File

@ -0,0 +1,38 @@
using Microsoft.AspNetCore.Mvc.Rendering;
using PlotLine.ViewModels;
namespace PlotLine.Services;
// Presentation of the existing chronological Story Point projection, not another
// knowledge store. Selection never changes author records or generates facts.
public static class WritingContextRelevance
{
public static IReadOnlyList<SelectListItem> SceneOptions(StoryPointViewModel narrative,int book,int current)
{
var chapters=narrative.Chapters.Where(c=>c.BookID==book).ToDictionary(c=>c.ChapterID);
return narrative.Scenes.Where(s=>chapters.ContainsKey(s.ChapterID)).Select(s=>new SelectListItem(
$"Chapter {chapters[s.ChapterID].ChapterNumber:0.##} · {s.SceneTitle}",s.SceneID.ToString(),s.SceneID==current)).ToArray();
}
public static IReadOnlyList<StoryCalendarSceneViewModel> Nearby(StoryContextViewModel context)
{
if(context.Narrative?.Snapshot is not {} point||context.Scene?.StartDateTime is not {} date)return [];
var chapters=context.Narrative.Chapters.Where(c=>c.BookID==point.Book.BookID).ToDictionary(c=>c.ChapterID);
return context.Narrative.Scenes.Where(s=>s.SceneID!=point.Scene.SceneID&&point.Sources.ContainsKey(s.SceneID)&&chapters.ContainsKey(s.ChapterID)&&
s.StartDateTime.HasValue&&Math.Abs((s.StartDateTime.Value-date).TotalDays)<=3)
.OrderBy(s=>Math.Abs((s.StartDateTime!.Value-date).TotalSeconds)).Take(5)
.Select(s=>new StoryCalendarSceneViewModel{SceneID=s.SceneID,BookID=point.Book.BookID,ChapterID=s.ChapterID,ChapterNumber=chapters[s.ChapterID].ChapterNumber,
SceneNumber=s.SceneNumber,Title=s.SceneTitle,StartDateTime=s.StartDateTime}).ToArray();
}
public static IReadOnlyList<StoryPointThread> Threads(StoryContextViewModel context)
{
if(context.Narrative?.Snapshot is not {} point)return [];
var current=context.Scene?.ThreadEvents.Select(e=>e.PlotThreadID).ToHashSet()??[];
var viewpoint=point.ViewpointKnowledge.Where(k=>k.PlotThreadID.HasValue).Select(k=>k.PlotThreadID!.Value).ToHashSet();
var people=point.Characters.SelectMany(c=>c.Knowledge).Where(k=>k.PlotThreadID.HasValue).Select(k=>k.PlotThreadID!.Value).ToHashSet();
var chapterScenes=context.Narrative.Scenes.Where(s=>s.ChapterID==point.Chapter.ChapterID).Select(s=>s.SceneID).ToHashSet();
int Score(StoryPointThread t)=>current.Contains(t.PlotThreadID)?4:viewpoint.Contains(t.PlotThreadID)?3:people.Contains(t.PlotThreadID)?2:t.Source!=null&&chapterScenes.Contains(t.Source.SceneID)?1:0;
return point.Threads.Where(t=>Score(t)>0).OrderByDescending(Score).ThenBy(t=>t.Title).Take(6).ToArray();
}
}

View File

@ -477,6 +477,8 @@ public sealed class WritingContextPageViewModel
public sealed class WritingContextDisplayViewModel
{
public StoryPointSnapshot? AtPoint => Context?.Narrative?.Snapshot;
public IReadOnlyList<StoryPointThread> RelevantThreads => Context==null?[]:WritingContextRelevance.Threads(Context);
public IReadOnlyList<StoryCalendarSceneViewModel> NearbyScenes {get;set;}=[];
public StoryContextViewModel? Context { get; set; }
public RelationshipMapViewModel? RelationshipMap { get; set; }

View File

@ -19,6 +19,7 @@ public sealed class StoryPointSnapshot
public Chapter Chapter { get; init; } = new();
public Scene Scene { get; init; } = new();
public string? PovName { get; init; }
public IReadOnlyList<CharacterKnowledgeItem> ViewpointKnowledge { get; init; } = [];
public IReadOnlyList<StoryPointCharacter> Characters { get; init; } = [];
public IReadOnlyList<RelationshipMapRelationshipViewModel> Relationships { get; init; } = [];
public IReadOnlyList<AssetStoryStateViewModel> Assets { get; init; } = [];

View File

@ -33,6 +33,7 @@
Chapter @(scene.Chapter?.ChapterNumber.ToString("0.##"))
<span aria-hidden="true">/</span>
Scene @(scene.SceneNumber.ToString("0.##"))
@if(current>=0){<span>· Manuscript scene @(current+1) of @sequence.Count</span>}
</p>
</div>
<div class="writing-context-scene-actions">

View File

@ -1,7 +1,7 @@
@model WritingContextDisplayViewModel
@{
var scene = Model.Context!.Scene!;
var pov = scene.CharacterOptions.FirstOrDefault(x => x.Value == scene.POVCharacterID?.ToString())?.Text
var pov = (scene.POVCharacterID.HasValue ? Model.AtPoint?.PovName : null) ?? scene.CharacterOptions.FirstOrDefault(x => x.Value == scene.POVCharacterID?.ToString())?.Text
?? scene.SceneCharacters.FirstOrDefault(x => x.CharacterID == scene.POVCharacterID)?.CharacterName
?? "No POV set";
var primaryLocation = scene.LocationOptions.FirstOrDefault(x => x.Value == scene.PrimaryLocationID?.ToString())?.Text?.Trim()
@ -57,9 +57,10 @@
<article class="writing-context-card">
<p class="eyebrow">Continuity</p>
@if (scene.Warnings.Any() || scene.AgeContinuityWarnings.Any())
@if (scene.Warnings.Any() || scene.AgeContinuityWarnings.Any() || Model.AtPoint?.Warnings.Any()==true)
{
<ul class="writing-context-list">
@foreach(var check in (Model.AtPoint?.Warnings??[]).Take(4)){<li><strong>Continuity check:</strong> @check.Message</li>}
@foreach (var warning in scene.Warnings.Concat(scene.AgeContinuityWarnings).Take(4))
{
<li><strong>@warning.SeverityName</strong> @warning.Message</li>
@ -74,9 +75,9 @@
</div>
<div class="writing-context-grid writing-reference-desk">
<article class="writing-context-card"><p class="eyebrow">Around this story date</p>
<article class="writing-context-card"><p class="eyebrow">Earlier established scenes near this story date</p>
@if(!scene.StartDateTime.HasValue){<p>No absolute story date saved. Relative timing is shown above; no nearby dates are inferred.</p>}
else if(!Model.NearbyScenes.Any()){<p>No other dated scenes in this book within three days.</p>}
else if(!Model.NearbyScenes.Any()){<p>No earlier established scenes in this book within three days.</p>}
else{<ul class="writing-context-list">@foreach(var item in Model.NearbyScenes){<li><time>@item.StartDateTime?.ToString("d MMM · HH:mm")</time> <a asp-controller="Writing" asp-action="Context" asp-route-projectId="@Model.Context.Position.ProjectId" asp-route-bookId="@item.BookID" asp-route-sceneId="@item.SceneID" asp-route-pinned="true" asp-route-embedded="true">@item.Title</a></li>}</ul>}
</article>
<article class="writing-context-card"><p class="eyebrow">People at this point</p>
@ -98,3 +99,19 @@
<a asp-controller="PlotLineWorkspace" asp-action="Index" asp-route-projectId="@Model.Context.Position.ProjectId" asp-route-bookId="@scene.Book?.BookID">Plot Lines</a>
<a asp-controller="RelationshipMap" asp-action="Index" asp-route-projectId="@Model.Context.Position.ProjectId" asp-route-bookId="@scene.Book?.BookID" asp-route-sceneId="@scene.SceneID">Characters and relationships</a>
</nav>
<div class="writing-context-grid">
<article class="writing-context-card">
<p class="eyebrow">Viewpoint knowledge</p>
<p class="small text-muted">Verified records through this scene in manuscript order. States may include uncertainty or lack of knowledge. Reader knowledge is not independently recorded here.</p>
@if(scene.POVCharacterID is null){<p>No viewpoint character recorded. No viewpoint knowledge is inferred.</p>}
else if(Model.AtPoint?.ViewpointKnowledge.Any()!=true){<p>No verified knowledge records for this viewpoint at this point.</p>}
else{<ul class="writing-context-list">@foreach(var fact in Model.AtPoint.ViewpointKnowledge.Take(5)){<li><strong>@fact.KnowledgeStateName:</strong> @(fact.Description??fact.AssetName??fact.ThreadTitle??"Recorded knowledge") <a asp-controller="Scenes" asp-action="Edit" asp-route-id="@fact.SceneID">Source scene</a></li>}</ul><p>Open People for other participants’ knowledge records.</p>}
</article>
<article class="writing-context-card">
<p class="eyebrow">Relevant unresolved threads</p>
<p class="small text-muted">Established through this scene; prioritised by current events, knowledge records and this chapter. Author reference, not proof of viewpoint awareness.</p>
@if(!Model.RelevantThreads.Any()){<p>No established unresolved threads linked to this scene, its participants or this chapter.</p>}
else{<ul class="writing-context-list">@foreach(var thread in Model.RelevantThreads){<li><a asp-controller="PlotThreads" asp-action="Edit" asp-route-id="@thread.PlotThreadID">@thread.PlotLineName / @thread.Title</a> · @thread.State @if(thread.Source!=null){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@thread.Source.SceneID">Source scene</a>}</li>}</ul>}
</article>
</div>

View File

@ -17,7 +17,8 @@ else
<div class="writing-context-people-grid">
@foreach (var character in scene.SceneCharacters.OrderByDescending(x => x.CharacterID == povCharacterId).ThenBy(x => x.CharacterName))
{
var knowledge = scene.CharacterKnowledge.Where(x => x.CharacterID == character.CharacterID).ToList();
var known = Model.AtPoint?.Characters.FirstOrDefault(x=>x.Appearance.CharacterID==character.CharacterID);
var knowledge = Model.AtPoint?.Characters.FirstOrDefault(x=>x.Appearance.CharacterID==character.CharacterID)?.Knowledge.ToList() ?? [];
var attributes = scene.CharacterAttributeEvents.Where(x => x.CharacterID == character.CharacterID).ToList();
<article class="writing-context-card writing-context-person-card">
<div class="writing-context-person-heading">
@ -29,17 +30,19 @@ else
</div>
<dl class="writing-context-facts">
<dt>Location</dt><dd>@TextOr(character.LocationPath ?? character.LocationName, "Unknown")</dd>
<dt>Last recorded location</dt><dd>@(known?.State?.CurrentLocation ?? "Not recorded")</dd>
<dt>Emotional state</dt><dd>@TextOr(character.EmotionalState, "Not recorded")</dd>
<dt>Physical condition</dt><dd>@TextOr(character.PhysicalCondition, "Not recorded")</dd>
<dt>Outfit</dt><dd>@TextOr(character.OutfitDescription ?? character.AppearanceNotes, "Not recorded")</dd>
<dt>Movement</dt><dd>@TextOr(string.Join(" -> ", new[] { character.EntryLocationName, character.ExitLocationName }.Where(x => !string.IsNullOrWhiteSpace(x))), "No entry or exit recorded")</dd>
</dl>
<p class="small text-muted">@(character.CharacterID==povCharacterId?"Verified viewpoint knowledge at this narrative point":"Author reference: this character’s knowledge, not necessarily the viewpoint character’s")</p>
@if (knowledge.Any() || attributes.Any())
{
<div class="writing-context-mini-section">
@foreach (var item in knowledge.Take(3))
{
<p><strong>@item.KnowledgeStateName:</strong> @TextOr(item.Description, item.AssetName ?? item.ThreadTitle ?? "Knowledge change recorded.")</p>
<p><strong>@item.KnowledgeStateName:</strong> @TextOr(item.Description, item.AssetName ?? item.ThreadTitle ?? "Knowledge change recorded.") <a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">Source scene</a></p>
}
@foreach (var item in attributes.Take(3))
{

View File

@ -13,7 +13,7 @@
}
<div data-writing-component-fragment data-context-plot-cards class="writing-plot-context">
<div class="writing-plot-toolbar">
<p>Plot line context for the current scene, showing the previous, current and next developments.</p>
<p>Author plot overview, including planned and future developments. This is not viewpoint knowledge.</p>
<div class="writing-plot-categories" role="group" aria-label="Show plot lines">
<span>Show:</span>
<button type="button" class="btn btn-sm btn-outline-secondary" data-plot-category="active" aria-pressed="true">Active here <span data-plot-count="active">0</span></button>

View File

@ -32,7 +32,8 @@
</article>
<article class="writing-context-card writing-context-card--wide">
<p class="eyebrow">State At This Point</p>
<p class="eyebrow">Relationships at this point</p>
<p class="small text-muted">Author reference from established earlier records; not proof of viewpoint knowledge.</p>
@if (!relationships.Any())
{
<p>No visible relationships at this point.</p>

View File

@ -23,15 +23,15 @@
</article>
<article class="writing-context-card">
<p class="eyebrow">Knowledge</p>
@if (!scene.CharacterKnowledge.Any())
<p class="eyebrow">Verified viewpoint knowledge through this scene</p>
@if (!(Model.AtPoint?.ViewpointKnowledge ?? []).Any())
{
<p>No knowledge changes recorded.</p>
<p>No verified viewpoint knowledge recorded.</p>
}
else
{
<ul class="writing-context-list">
@foreach (var item in scene.CharacterKnowledge)
@foreach (var item in (Model.AtPoint?.ViewpointKnowledge ?? []))
{
<li><strong>@item.CharacterName</strong> @item.KnowledgeStateName: @TextOr(item.Description, item.AssetName ?? item.ThreadTitle ?? "Knowledge change recorded.")</li>
}
@ -40,7 +40,8 @@
</article>
<article class="writing-context-card">
<p class="eyebrow">Dependencies</p>
<p class="eyebrow">Author continuity dependencies</p>
<p class="small text-muted">Saved planning references may describe later scenes; they are not character knowledge.</p>
@if (!scene.DependenciesThisSceneNeeds.Any() && !scene.DependenciesNeedingThisScene.Any())
{
<p>No dependencies recorded.</p>

View File

@ -7,6 +7,7 @@
static string TextOr(string? value, string fallback) => string.IsNullOrWhiteSpace(value) ? fallback : value.Trim();
}
<p class="small text-muted">Saved author plan and scene reference. Opening this view does not rewrite intent or accept suggestions.</p>
<div class="writing-context-grid writing-context-grid--overview">
<article class="writing-context-card writing-context-card--hero">
<p class="eyebrow">Chapter Plan</p>
@ -19,7 +20,7 @@
</article>
<article class="writing-context-card">
<p class="eyebrow">Current Scene</p>
<p class="eyebrow">Saved scene reference</p>
@if (scene is null)
{
<p>No current scene. Chapter intent is shown until Word reports a scene.</p>
@ -33,6 +34,7 @@
<article class="writing-context-card">
<p class="eyebrow">Scene Purpose</p>
@if(scene!=null){<div class="writing-context-chip-row">@foreach(var purpose in scene.ScenePurposeTypes.Where(p=>scene.SelectedPurposeTypeIds.Contains(p.ScenePurposeTypeID)).OrderBy(p=>p.SortOrder)){<span>@purpose.PurposeName</span>}</div>}
<p>@TextOr(scene?.ScenePurposeNotes, "No scene-specific purpose notes yet.")</p>
</article>

View File

@ -49,7 +49,7 @@
let loadingSceneId = null;
let loadingChapterId = null;
let requestGeneration = 0;
let pendingRequest = null, navigationRequest = null;
let pendingRequest = null, pendingNativeRequest = false, navigationRequest = null;
let manualGeneration=0;
let selectedDocument = root.dataset.wordInstance && root.dataset.wordSession ? root.dataset.wordInstance + '/' + root.dataset.wordSession : '';
let nativePositionKey = '', nativeWasConnected = false, nativeLeases = [];
@ -274,6 +274,7 @@
pendingRequest?.abort();
const controller = new AbortController();
pendingRequest = controller;
pendingNativeRequest = position.source === 'WordCompanion';
loadingSceneId = hasScene ? position.sceneId : null;
loadingChapterId = !hasScene ? position.chapterId : null;
setStatus(config.updatingStatus);
@ -282,10 +283,15 @@
if (position.bookId) url.searchParams.set("bookId", position.bookId);
if (position.chapterId) url.searchParams.set("chapterId", position.chapterId);
if (hasScene) url.searchParams.set("sceneId", position.sceneId);
if(position.source==='WordCompanion'&&position.instanceId&&position.sessionId){url.searchParams.set('instanceId',position.instanceId);url.searchParams.set('sessionId',position.sessionId);}
try {
console.info(`[${config.source}] Loading writing position.`, position);
const response = await fetch(url, { signal: controller.signal, headers: { "X-Requested-With": "XMLHttpRequest" } });
if(response.status===409&&position.source==='WordCompanion'){
if(generation===requestGeneration)setStatus('Word mapping is awaiting verification · saved scene remains available');
return;
}
if (!response.ok || response.redirected) {
throw new Error(`${config.source} request failed: ${response.status}`);
}
@ -331,11 +337,16 @@
if (generation === requestGeneration) {
loadingSceneId = null;
loadingChapterId = null;
pendingRequest = null;
pendingRequest = null;pendingNativeRequest = false;
}
}
};
const suspendNativeRequest = () => {
if(!pendingNativeRequest)return;
++requestGeneration;pendingRequest?.abort();pendingRequest=null;pendingNativeRequest=false;
loadingSceneId=null;loadingChapterId=null;
};
const followNative = (leases) => {
nativeLeases = leases;
if(leases.reconnected)nativeWasConnected=false;
@ -344,12 +355,12 @@
const active = available.filter(l => l.active);
const chosen = selectedDocument ? available.filter(l => l.instanceId + '/' + l.sessionId === selectedDocument) : active.length === 1 ? active : available;
const lease = chosen.length === 1 ? chosen[0] : null;
if (!lease) { nativeWasConnected = false; nativePositionKey = ''; setStatus(available.length > 1 && !selectedDocument ? 'Choose a Word document using the connection indicator' : selectedDocument ? 'Selected Word document is disconnected · saved scene remains available' : leases.some(l=>l.wordAvailable) ? 'Saved scene · no live Word position for this book' : 'Word disconnected · saved scene remains available'); return; }
const key = [lease.instanceId, lease.sessionId, lease.chapterId, lease.sceneId, lease.wordSaved].join(':');
if ((!lease.sceneId && !(config.allowChapterOnly && lease.chapterId)) || lease.wordSaved === false) { nativeWasConnected = true; nativePositionKey = key; setStatus(lease.positionMessage?lease.positionMessage+' · saved scene remains available':lease.wordSaved===false?'Save Word, then synchronise to refresh its scene mapping · saved scene remains available':'Word scene mapping is unavailable · synchronise from Word; saved scene remains available'); return; }
if (!lease) { suspendNativeRequest();nativeWasConnected = false; nativePositionKey = ''; setStatus(available.length > 1 && !selectedDocument ? 'Choose a Word document using the connection indicator' : selectedDocument ? 'Selected Word document is disconnected · saved scene remains available' : leases.some(l=>l.wordAvailable) ? 'Saved scene · no live Word position for this book' : 'Word disconnected · saved scene remains available'); return; }
const key = [lease.instanceId, lease.sessionId, lease.manuscriptId, lease.revision, lease.chapterId, lease.sceneId, lease.wordSaved].join(':');
if ((!lease.sceneId && !(config.allowChapterOnly && lease.chapterId)) || lease.wordSaved !== true || lease.positionVerified === false) { suspendNativeRequest();nativeWasConnected = true; nativePositionKey = key; setStatus(lease.positionMessage?lease.positionMessage+' · saved scene remains available':lease.wordSaved===false?'Save Word before verifying its scene mapping · saved scene remains available':'Word scene mapping is awaiting verification · saved scene remains available'); return; }
if (!nativeWasConnected || key !== nativePositionKey || (!pendingRequest && Number(lease.sceneId)!==currentSceneId)) {
nativeWasConnected = true; nativePositionKey = key;
void loadPosition({source:'WordCompanion',projectId:scopedProjectId || parsePositiveInt(currentFragment?.dataset.projectId),bookId:Number(lease.bookId),chapterId:Number(lease.chapterId),sceneId:lease.sceneId?Number(lease.sceneId):null});
void loadPosition({source:'WordCompanion',instanceId:lease.instanceId,sessionId:lease.sessionId,projectId:scopedProjectId || parsePositiveInt(currentFragment?.dataset.projectId),bookId:Number(lease.bookId),chapterId:Number(lease.chapterId),sceneId:lease.sceneId?Number(lease.sceneId):null});
setStatus('Following Word');
}
};