Add persistent private investigation guidance and correct ribbon Back placement

This commit is contained in:
Nick Beckley 2026-11-17 23:39:20 +00:00
parent 2a865f0374
commit fccc0d8b4f
24 changed files with 491 additions and 19 deletions

View File

@ -0,0 +1,51 @@
const {chromium}=require('playwright'),fs=require('fs'),assert=require('node:assert/strict');
const live=!!process.env.PD_GUIDANCE_IDENTITY,w=live?JSON.parse(fs.readFileSync(process.env.PD_GUIDANCE_IDENTITY)):{UserID:4,project:7,book:12,otherBook:13};
const base=live?'https://dev.plotdirector.com':'http://127.0.0.1:5238',out=process.env.PD_GUIDANCE_SCREENSHOTS;
(async()=>{const b=await chromium.launch();let state;try{
const c=await b.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(u=>{Object.defineProperty(navigator,'standalone',{value:true});localStorage.setItem('plotdirector.desktop.v1.'+u,JSON.stringify({dismissedAt:Date.now()}));},w.UserID);
const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));
const snap=async name=>{if(out){fs.mkdirSync(out,{recursive:true});await p.mouse.move(2,995);await p.waitForTimeout(150);await p.screenshot({path:out+'/'+name+'.png'});}};
const expandRibbon=async()=>{const toggle=p.locator('[data-ribbon-collapse]');if(await toggle.getAttribute('aria-expanded')==='false')await toggle.click();};
if(live){await p.goto(base+'/Account/Login');await p.locator('[name=Email]').fill(w.Email);await p.locator('[name=Password]').fill(w.Password);await Promise.all([p.waitForURL('**/Projects'),p.locator('button[type=submit]').click()]);}
await p.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);await expandRibbon();await p.getByRole('link',{name:'Explore a concern',exact:true}).click();
if(live){await p.locator(`a[href*="id=${w.investigation}"]`).first().click();}
else{await p.locator('[name=concern][value=A]').check();await p.getByRole('button',{name:'Begin',exact:true}).click();for(const[q,o]of[['Q02','B'],['Q03','C'],['Q17','F'],['Q19','F'],['Q04','A'],['Q14','D'],['Q15','A'],['Q16','E']]){assert.equal(await p.locator('[data-investigation-answer] [name=question]').inputValue(),q);await p.locator(`[name=option][value=${o}]`).check();await p.getByRole('button',{name:'Continue',exact:true}).click();}w.investigation=await p.locator('[data-investigation-id]').getAttribute('data-investigation-id');}
await p.locator('[data-conclusion]').waitFor();assert.equal(await p.locator('form[target=_blank]').count(),0);const pages=c.pages().length;
if(live){await p.locator('form[action$="/Investigate/Open"]').first().getByRole('button').click();await p.waitForURL(/\/PlotLineWorkspace/);}
else{await p.getByRole('button',{name:'Keep this investigation alongside my work'}).click();await p.goto(`${base}/Writer/Write?projectId=${w.project}&bookId=${w.book}`);}
const root=p.locator('[data-investigation-companion]'),content=root.locator('[data-guidance-content]');await root.locator('#guidance-finding').waitFor();assert.equal(c.pages().length,pages);
assert.equal(await root.getAttribute('data-collapsed'),'false');assert(await p.locator('[data-app-back]').evaluate(n=>!!n.closest('#ribbon-surface')));assert.equal(await p.locator('.pd-ribbon-heading [data-app-back]').count(),0);await snap('Left-expanded-ribbon-Back');
assert((await root.locator('#guidance-finding option').count())>=2);await root.locator('#guidance-finding').selectOption('causality');await p.waitForFunction(()=>document.querySelector('#guidance-finding')?.value==='causality'&&!document.querySelector('#guidance-finding').disabled);await p.reload();await root.locator('#guidance-finding').waitFor();assert.equal(await root.locator('#guidance-finding').inputValue(),'causality');await root.locator('#guidance-finding').selectOption('disconnected');await p.waitForFunction(()=>document.querySelectorAll('.pd-guidance-tool').length===2&&!document.querySelector('#guidance-finding').disabled);
await root.getByText('Answers that informed this suggestion',{exact:true}).click();await root.locator('details').getByText('You answered:',{exact:true}).waitFor();
const first=root.locator('.pd-guidance-tool[data-capability=threads]');if(live)assert.equal(await first.locator('select').inputValue(),'Exploring');await first.locator('select').selectOption('Done');await p.waitForFunction(()=>document.querySelector('.pd-guidance-tool[data-capability=threads] select')?.value==='Done'&&!document.querySelector('#guidance-finding').disabled);await p.reload();await first.waitFor();assert.equal(await first.locator('select').inputValue(),'Done');
// Right Help opens independently and does not replace guidance.
await p.evaluate(()=>PlotLineHelpDrawer.open('plotLines.workspace'));await p.locator('[data-help-content] .help-drawer-article').waitFor();await p.locator('[data-help-pin]').click();assert.equal(await root.getAttribute('data-collapsed'),'false');assert(await p.locator('[data-help-drawer]').isVisible());assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));assert((await p.locator('.plotline-help-main').boundingBox()).width>=560);await snap('Both-panels-expanded');
await root.locator('[data-guidance-collapse]').click();assert.equal(await root.getAttribute('data-collapsed'),'true');await snap('Left-collapsed-tab');await p.reload();await root.locator('[data-guidance-expand]').waitFor();assert.equal(await root.getAttribute('data-collapsed'),'true');await root.locator('[data-guidance-expand]').click();await root.locator('#guidance-finding').waitFor();
if(live){await root.locator('.pd-guidance-tool[data-capability=timeline] form button').click();await p.waitForURL(/\/Timeline/);await root.locator('#guidance-finding').waitFor();assert.equal(c.pages().length,pages);assert.equal(await root.locator('.pd-guidance-tool[data-capability=timeline]').getAttribute('data-selected'),'true');await snap('Second-destination-Timeline');}
else{await p.goto(`${base}/Writer/Review?bookId=${w.book}&projectId=${w.project}`);await root.locator('#guidance-finding').waitFor();}
await expandRibbon();await p.getByRole('tab',{name:'Writer',exact:true}).click();await p.waitForURL(u=>/\/Writer(?:\/Index)?$/.test(u.pathname));await root.locator('#guidance-finding').waitFor();await expandRibbon();await p.locator('[data-app-back]').click();await p.waitForURL(live?/\/Timeline/:/\/Writer\/Review/);await root.locator('#guidance-finding').waitFor();assert(await first.locator('select').inputValue()==='Done');await snap('Ribbon-Back-retains-guidance');
await p.setViewportSize({width:800,height:1000});assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await snap('Narrow-in-flow');await p.setViewportSize({width:1440,height:1000});
state=await c.storageState();await c.close();const reopened=await b.newContext({storageState:state,viewport:{width:1440,height:1000}});await reopened.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const q=await reopened.newPage();await q.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);await q.locator('#guidance-finding').waitFor();assert.equal(await q.locator('.pd-guidance-tool[data-capability=threads] select').inputValue(),'Done');
await q.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.otherBook}`);await q.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('No active investigation'));assert.equal(await q.locator('#guidance-finding').count(),0);assert.equal(await q.locator('[data-investigation-companion]').getAttribute('data-collapsed'),'true');
await q.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);await q.locator('#guidance-finding').waitFor();
// Server-side failure paths retain the active guidance; forged IDs never expose it.
const token=await q.locator('[data-guidance-token] [name=__RequestVerificationToken]').inputValue();const response=await q.request.post(base+'/InvestigationCompanion/Open',{form:{__RequestVerificationToken:token,bookId:w.book,id:w.investigation,finding:'disconnected',capability:'invented'}});assert.equal(response.status(),400);
const wrong=await q.request.get(base+`/InvestigationCompanion/Evidence?bookId=${w.otherBook}&id=${w.investigation}&finding=disconnected`);assert.equal(wrong.status(),404);
const invalid=await q.request.get(base+`/InvestigationCompanion/Evidence?bookId=${w.book}&id=00000000-0000-0000-0000-000000000000&finding=disconnected`);assert.equal(invalid.status(),404);
// Old/invalid presentation preferences recover without changing server progress.
await q.evaluate(u=>localStorage.setItem(`plotdirector.investigationPanel.v1.${u.user}.${u.book}`,JSON.stringify({width:-99,positions:'stale'})),{user:w.UserID,book:w.book});await q.reload();await q.locator('#guidance-finding').waitFor();assert.equal(await q.locator('.pd-guidance-tool[data-capability=threads] select').inputValue(),'Done');
await q.route('**/InvestigationCompanion/Summary?*',r=>r.fulfill({status:503,body:'unavailable'}));await q.reload();await q.locator('[data-guidance-expand]').click();await q.getByRole('button',{name:'Retry',exact:true}).waitFor();await q.unroute('**/InvestigationCompanion/Summary?*');await q.getByRole('button',{name:'Retry',exact:true}).click();await q.locator('#guidance-finding').waitFor();
// Pin has the same restore-on-navigation meaning as contextual Help.
await q.locator('[data-guidance-pin]').click();await q.reload();await q.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('Full investigation results'));assert.equal(await q.locator('[data-investigation-companion]').getAttribute('data-collapsed'),'true');await q.locator('[data-guidance-expand]').click();await q.locator('[data-guidance-pin]').click();await q.reload();await q.locator('#guidance-finding').waitFor();assert.equal(await q.locator('[data-investigation-companion]').getAttribute('data-collapsed'),'false');
const full=await q.getByRole('link',{name:'Full investigation results',exact:true}).getAttribute('href');await q.getByRole('button',{name:'Dismiss guidance',exact:true}).click();await q.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('No active investigation'));await q.goto(base+full);await q.getByRole('button',{name:'Keep this investigation alongside my work'}).click();await q.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);await q.waitForFunction(()=>document.querySelector('#guidance-finding'));assert.equal(await q.locator('[data-investigation-companion]').getAttribute('data-collapsed'),'true');await q.locator('[data-guidance-expand]').click();await q.locator('#guidance-finding').waitFor();
assert.deepEqual(errors,[]);await reopened.close();
if(live&&process.env.PD_GUIDANCE_OTHER_IDENTITY){
const other=JSON.parse(fs.readFileSync(process.env.PD_GUIDANCE_OTHER_IDENTITY)),oc=await b.newContext(),op=await oc.newPage();await op.goto(base+'/Account/Login');await op.locator('[name=Email]').fill(other.Email);await op.locator('[name=Password]').fill(other.Password);await Promise.all([op.waitForURL('**/Projects'),op.locator('button[type=submit]').click()]);
const view=await op.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);assert.equal(view.status(),200);await op.locator('[data-guidance-token]').waitFor({state:'attached'});const ot=await op.locator('[data-guidance-token] [name=__RequestVerificationToken]').inputValue();
const summary=await op.request.get(`${base}/InvestigationCompanion/Summary?projectId=${w.project}&bookId=${w.book}`);assert.equal(summary.status(),200);assert.equal((await summary.json()).active,false);
assert.equal((await op.request.get(`${base}/InvestigationCompanion/Evidence?bookId=${w.book}&id=${w.investigation}&finding=disconnected`)).status(),404);
assert.equal((await op.request.post(base+'/InvestigationCompanion/Update',{form:{__RequestVerificationToken:ot,bookId:w.book,id:w.investigation,version:0,operation:'activate'}})).status(),404);await oc.close();
}
console.log('PASS '+(live?'authenticated Development':'isolated Razor/HTTP')+' investigation companion: saved results, same-window destinations, two findings, private server progress, Help coexistence, collapse/expand, refresh and reopened PWA session, Back ribbon action, book isolation, invalid IDs and unavailable destination');
}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});

View File

@ -15,10 +15,10 @@ const paths=['Write','Explore','Plan','Review','Reflect'];
if(!before){
await p.goto(`${base}/Writer/Review?bookId=${w.book}&chapterId=${w.chapter}`);const t=p.locator('[data-writer-companion-toggle]');if(await p.locator('.writer3-reference').isVisible())await t.click();const centred=await p.locator('.reader-page').evaluate(n=>{const a=n.getBoundingClientRect(),b=n.closest('.writer3-main').getBoundingClientRect();return Math.abs((a.left+a.right-b.left-b.right)/2)});assert(centred<3);const nav=await p.locator('.reader-controls').evaluate(n=>({width:n.getBoundingClientRect().width,main:n.closest('.writer3-main').clientWidth}));assert(nav.width>nav.main*.9);await snap('Review-centred-toolbar');await p.locator('.reader-mode-controls a').click();assert(await p.locator('.writer3-reference').isHidden());await snap('Reading-mode');await p.locator('#reader-focus').click();assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');await snap('Focus-reading');await p.locator('.reader-controls a[rel=next]').click();assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');assert.equal(await p.locator('.manuscript-reader').getAttribute('data-chapter-id'),String(w.chapter2));await snap('Focus-next-chapter');await p.locator('#reader-focus').click();assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'false');
for(const width of[1920,1024,800]){await p.setViewportSize({width,height:1000});await p.goto(`${base}/Writer/Review?bookId=${w.book}`);assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await snap('Review-'+width);}
await p.setViewportSize({width:1440,height:1000});await p.goto(`${base}/Writer/Review?bookId=${w.book}`);if(await p.locator('.writer3-reference').isHidden())await p.locator('[data-writer-companion-toggle]').click();for(const collapsed of[false,true]){const collapse=p.locator('[data-ribbon-collapse]');if((await collapse.getAttribute('aria-expanded')==='false')!==collapsed)await collapse.click();await p.evaluate(()=>window.scrollTo(0,1100));await p.waitForTimeout(200);const pos=await p.evaluate(()=>({top:document.querySelector('.writer3-reference').getBoundingClientRect().top,bottom:document.querySelector('.pd-application-header').getBoundingClientRect().bottom}));if(pwa)assert(pos.top>=pos.bottom-1);await snap(collapsed?'Sticky-collapsed':'Sticky-expanded');await p.evaluate(()=>window.scrollTo(0,0));}
await p.setViewportSize({width:1440,height:1000});await p.goto(`${base}/Writer/Review?bookId=${w.book}&reader-long=true`);if(await p.locator('.writer3-reference').isHidden())await p.locator('[data-writer-companion-toggle]').click();for(const collapsed of[false,true]){const collapse=p.locator('[data-ribbon-collapse]');if((await collapse.getAttribute('aria-expanded')==='false')!==collapsed)await collapse.click();await p.evaluate(()=>window.scrollTo(0,1100));await p.waitForTimeout(200);const pos=await p.evaluate(()=>({top:document.querySelector('.writer3-reference').getBoundingClientRect().top,bottom:document.querySelector('.pd-application-header').getBoundingClientRect().bottom}));if(pwa)assert(pos.top>=pos.bottom-1);await snap(collapsed?'Sticky-collapsed':'Sticky-expanded');await p.evaluate(()=>window.scrollTo(0,0));}
// An external history boundary must be disabled; all subsequent Back actions stay native/internal.
await c.route('http://outside.invalid/**',r=>r.fulfill({contentType:'text/html',body:`<a href="${base}/Writer/Index?projectId=${w.project}&bookId=${w.book}">Enter</a>`}));await p.goto('http://outside.invalid/start');await p.getByText('Enter').click();await expand();assert(await p.locator('[data-app-back]').isDisabled());
for(const d of['Write','Explore','Plan'])await p.locator('#ribbon-panel-writer').getByRole('link',{name:d,exact:true}).click();await p.locator('[data-ribbon-collapse]').click();for(const d of['Explore','Write','Index']){await p.locator('[data-app-back]').click();await p.waitForURL(u=>u.pathname.toLowerCase()==='/writer/'+d.toLowerCase());}assert(await p.locator('[data-app-back]').isDisabled());await snap('Ribbon-back-boundary');
for(const d of['Write','Explore','Plan'])await p.locator('#ribbon-panel-writer').getByRole('link',{name:d,exact:true}).click();await expand();for(const d of['Explore','Write','Index']){await p.locator('[data-app-back]').click();await p.waitForURL(u=>u.pathname.toLowerCase()==='/writer/'+d.toLowerCase());}assert(await p.locator('[data-app-back]').isDisabled());await snap('Ribbon-back-boundary');
if(identity){
// Follow actual authenticated ribbon links and nested entry points across modules.
const trail=[];

View File

@ -0,0 +1,52 @@
using System.Text.Json;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using PlotLine.Data;
using PlotLine.Models.Investigations;
using PlotLine.Services.Investigations;
internal static class InvestigationGuidanceTests
{
public static async Task Run()
{
void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS Investigation companion "+name);}
var repo=new InvestigationMemoryRepository();var store=new GuidanceMemoryRepository(repo);var service=new InvestigationGuidanceService(store,repo,new MemoryCache(new MemoryCacheOptions()),new ConfigurationBuilder().Build());
var c=(await repo.Catalogue())!;var hypotheses=c.Hypotheses.Where(h=>h.Capabilities.Count>0).Take(2).ToArray();
var i=new Investigation{ID=Guid.NewGuid(),UserID=4,BookID=12,ProjectID=7,CatalogueVersion=c.Version,Concern=c.Concerns[0].Id};
var evaluation=new Evaluation{Outcome="SupportedRecommendation",Recommendations=hypotheses.Select(h=>h.Id).ToList()};await repo.Save(i,0,"fixture",evaluation);
var r=(await store.Read(4,7,12,i.ID))!;var before=JsonSerializer.Serialize(await repo.Read(4,12,i.ID),CatalogueValidator.Json);var events=await repo.Replay(4,12,i.ID);
var summary=service.Summary(r,c);Check(summary.Findings.Count==2,"multiple saved findings and their mapped tools");
var h=hypotheses[0];var cap=h.Capabilities[0];var route=await service.Open(4,r,c,h.Id,cap);r=(await store.Read(4,7,12))!;
Check(route.Controller!="WritingProblems"&&r.IsActive,"same-window trusted authenticated destination and activation");
var s=InvestigationGuidanceService.Decode(r).State;Check(s.Progress[InvestigationGuidanceService.Key(h.Id,cap)]=="Exploring","opening starts exploration, never Done");
s.Progress[InvestigationGuidanceService.Key(h.Id,cap)]="Done";await service.Save(4,r,s,"save");r=(await store.Read(4,7,12))!;await service.Open(4,r,c,h.Id,cap);r=(await store.Read(4,7,12))!;
Check(InvestigationGuidanceService.Decode(r).State.Progress[InvestigationGuidanceService.Key(h.Id,cap)]=="Done","explicit completion survives reopening and resume");
s=InvestigationGuidanceService.Decode(r).State;service.Select(r,c,s,hypotheses[1].Id,null);await service.Save(4,r,s,"save");r=(await store.Read(4,7,12))!;Check(InvestigationGuidanceService.Decode(r).State.Finding==hypotheses[1].Id,"selected finding persists");
try{service.Select(r,c,s,"invented",cap);throw new Exception("invalid selection accepted");}catch(ArgumentException){Check(true,"invalid finding rejected");}
var disabled=new InvestigationGuidanceService(store,repo,new MemoryCache(new MemoryCacheOptions()),new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"WriterInvestigations:Capabilities:"+cap+":Enabled","false"}}).Build());
try{await disabled.Open(4,r,c,h.Id,cap);throw new Exception("unavailable destination accepted");}catch(ArgumentException){Check(true,"unavailable destination retains investigation");}
Check(await store.Read(5,7,12,i.ID)==null&&await store.Read(4,7,13,i.ID)==null,"private author and book boundaries");
await service.Save(4,r,s,"finish");Check(await store.Read(4,7,12)==null&&(await store.Read(4,7,12,i.ID))!.Finished,"finished journey is inactive but retained");
r=(await store.Read(4,7,12,i.ID))!;await service.Save(4,r,s,"activate");Check((await store.Read(4,7,12))!.IsActive,"finished investigation can be reactivated");
var afterEvents=await repo.Replay(4,12,i.ID);var after=await repo.Read(4,12,i.ID);
Check(before==JsonSerializer.Serialize(after,CatalogueValidator.Json)&&events.SequenceEqual(afterEvents),"canonical answers, diagnostic scores and event history unchanged");
r.InvestigationJson=JsonSerializer.Serialize(new Investigation{ID=i.ID,UserID=4,ProjectID=7,BookID=12,CatalogueVersion=c.Version,Concern=c.Concerns[0].Id},CatalogueValidator.Json);r.EvaluationJson=null;Check(service.Summary(r,c).Findings.Count==0,"old records without snapshots remain readable without invented advice");
}
}
// Transport-only fixture. SQL permission/concurrency tests separately exercise the actual stored procedure.
internal sealed class GuidanceMemoryRepository(IInvestigationRepository investigations):IInvestigationGuidanceRepository
{
readonly Dictionary<Guid,(int User,int Book,string Json,int Version,bool Active,bool Finished)> rows=[];
public async Task<GuidanceRecord?> Read(int user,int? project,int? book,Guid? id=null)
{
if(id==null)id=rows.Where(x=>x.Value.User==user&&(book==null||x.Value.Book==book)&&x.Value.Active).Select(x=>(Guid?)x.Key).FirstOrDefault();if(id==null)return null;
var scopedBook=book??(rows.TryGetValue(id.Value,out var existing)?existing.Book:12);var i=await investigations.Read(user,scopedBook,id.Value);if(i==null||project!=null&&i.ProjectID!=project)return null;
rows.TryGetValue(id.Value,out var state);var events=await investigations.Replay(user,i.BookID,id.Value);using var ev=JsonDocument.Parse(events.Last());
return new(){ID=i.ID,ProjectID=i.ProjectID,BookID=i.BookID,BookTitle="Fixture book",InvestigationJson=JsonSerializer.Serialize(i,CatalogueValidator.Json),EvaluationJson=ev.RootElement.GetProperty("evaluation").GetRawText(),GuidanceJson=state.Json,GuidanceVersion=state.Version,IsActive=state.Active,Finished=state.Finished};
}
public async Task Save(int user,int book,Guid id,int version,string operation,string json)
{
var i=await investigations.Read(user,book,id)??throw new UnauthorizedAccessException();rows.TryGetValue(id,out var old);if(old.Version!=version)throw new ArgumentException("Stale guidance");
if(operation=="activate")foreach(var other in rows.Keys.ToArray()){var x=rows[other];if(x.User==user&&x.Book==book)rows[other]=(x.User,x.Book,x.Json,x.Version,false,x.Finished);}
rows[id]=(user,book,json,version+1,operation=="activate"||operation=="save"&&old.Active,operation=="finish"||operation!="activate"&&old.Finished);
}
}

View File

@ -173,6 +173,7 @@ var tests = new (string Name, Action Test)[]
("Release triage and browser-only onboarding preserve author decisions", ReleaseSprintTests.Run),
("Approved native import source and confirmation remain safe", () => NativeImportTests.Run().GetAwaiter().GetResult()),
("Native installation renewal and revocation remain account/security scoped", () => NativeInstallationTests.Run().GetAwaiter().GetResult()),
("Persistent investigation companion",()=>InvestigationGuidanceTests.Run().GetAwaiter().GetResult()),
("Guided investigation evidence, validation, revision and deterministic simulation",()=>InvestigationTests.Run()),
("Guided investigation diagnostic corrective acceptance",()=>InvestigationDiagnosticTests.Run()),
("Production Guided Investigation editorial acceptance",()=>ProductionInvestigationTests.Run()),

View File

@ -0,0 +1,54 @@
-- Run only against a disposable fixture owned by the named audit account. Never selects a real author's ID.
IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Wrong database',1;
DECLARE @u int=(SELECT UserID FROM dbo.AppUser WHERE Email=N'pwa-browser-writeraudit-20261116@example.invalid' AND DisplayName=N'Disposable Writer Audit 20261116');
DECLARE @id uniqueidentifier,@book int,@project int;
SELECT TOP(1) @id=ID,@book=BookID,@project=ProjectID FROM dbo.WriterInvestigations WHERE UserID=@u ORDER BY CreatedUtc DESC;
IF @id IS NULL THROW 51000,'Disposable investigation fixture required',1;
DECLARE @before varbinary(32)=HASHBYTES('SHA2_256',(SELECT Json FROM dbo.WriterInvestigations WHERE ID=@id));
DECLARE @events varbinary(32)=HASHBYTES('SHA2_256',(SELECT Event FROM dbo.WriterInvestigationEvents WHERE InvestigationID=@id ORDER BY Version FOR JSON PATH));
DECLARE @r TABLE(ID uniqueidentifier,ProjectID int,BookID int,BookTitle nvarchar(500),InvestigationJson nvarchar(max),EvaluationJson nvarchar(max),GuidanceJson nvarchar(max),GuidanceVersion int,IsActive bit,Finished bit);
INSERT @r EXEC dbo.WriterInvestigationGuidanceState @Action='read',@UserID=@u,@BookID=@book,@ID=@id;
IF (SELECT COUNT(*) FROM @r)<>1 OR NOT EXISTS(SELECT 1 FROM @r WHERE JSON_QUERY(EvaluationJson,'$.Recommendations') IS NOT NULL AND JSON_QUERY(InvestigationJson,'$.Presented') IS NULL) THROW 51000,'Compact saved evaluation unavailable',1;
PRINT 'PASS compact canonical snapshot projection';
DELETE @r;
INSERT @r EXEC dbo.WriterInvestigationGuidanceState @Action='read',@UserID=-123456,@BookID=@book,@ID=@id;
IF EXISTS(SELECT 1 FROM @r) THROW 51000,'Cross-author leakage',1;
INSERT @r EXEC dbo.WriterInvestigationGuidanceState @Action='read',@UserID=@u,@BookID=-1,@ID=@id;
IF EXISTS(SELECT 1 FROM @r) THROW 51000,'Cross-book leakage',1;
DECLARE @member int=(SELECT UserID FROM dbo.AppUser WHERE Email=N'pwa-phase15-other@example.invalid' AND DisplayName=N'Disposable Phase15 Other');
IF @member IS NOT NULL BEGIN
INSERT @r EXEC dbo.WriterInvestigationGuidanceState @Action='read',@UserID=@member,@BookID=@book,@ID=@id;
IF EXISTS(SELECT 1 FROM @r) THROW 51000,'Shared project member saw another author investigation',1;
END;
PRINT 'PASS real SQL author and book isolation, including shared project owners';
DECLARE @v int=ISNULL((SELECT Version FROM dbo.WriterInvestigationGuidance WHERE InvestigationID=@id),0);
EXEC dbo.WriterInvestigationGuidanceState @Action='activate',@UserID=@u,@BookID=@book,@ID=@id,@ExpectedVersion=@v,@Json=N'{"Finding":"disconnected","Capability":"threads","Progress":{"disconnected/threads":"Done"}}';
SET @v+=1;
DECLARE @rejected bit=0;
BEGIN TRY
EXEC dbo.WriterInvestigationGuidanceState @Action='save',@UserID=@u,@BookID=@book,@ID=@id,@ExpectedVersion=0,@Json=N'{}';
END TRY BEGIN CATCH IF ERROR_NUMBER()=51002 SET @rejected=1;ELSE THROW;END CATCH;
IF @rejected<>1 THROW 51000,'Stale write accepted',1;
IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigationGuidance WHERE InvestigationID=@id AND JSON_VALUE(Json,'$.Progress."disconnected/threads"')='Done' AND Version=@v) THROW 51000,'Progress lost after stale write',1;
PRINT 'PASS explicit progress durability and optimistic concurrency';
SET @rejected=0;
BEGIN TRY
EXEC dbo.WriterInvestigationGuidanceState @Action='activate',@UserID=-123456,@BookID=@book,@ID=@id,@ExpectedVersion=0,@Json=N'{}';
END TRY BEGIN CATCH IF ERROR_NUMBER()=51000 SET @rejected=1;ELSE THROW;END CATCH;
IF @rejected<>1 THROW 51000,'Cross-author mutation accepted',1;
DECLARE @clone uniqueidentifier=NEWID(),@json nvarchar(max),@ev nvarchar(max),@catalogue varchar(80);
SELECT @json=JSON_MODIFY(Json,'$.ID',CONVERT(nvarchar(36),@clone)),@catalogue=CatalogueVersion FROM dbo.WriterInvestigations WHERE ID=@id;
SELECT @ev=JSON_MODIFY(Event,'$.state.ID',CONVERT(nvarchar(36),@clone)) FROM dbo.WriterInvestigationEvents WHERE InvestigationID=@id AND Version=1;
EXEC dbo.WriterInvestigation @Action='save',@UserID=@u,@BookID=@book,@ProjectID=@project,@ID=@clone,@CatalogueVersion=@catalogue,@ExpectedVersion=0,@Json=@json,@Event=@ev;
EXEC dbo.WriterInvestigationGuidanceState @Action='activate',@UserID=@u,@BookID=@book,@ID=@clone,@ExpectedVersion=0,@Json=N'{}';
IF (SELECT COUNT(*) FROM dbo.WriterInvestigationGuidance WHERE UserID=@u AND BookID=@book AND IsActive=1)<>1 OR EXISTS(SELECT 1 FROM dbo.WriterInvestigationGuidance WHERE InvestigationID=@id AND IsActive=1) THROW 51000,'Active guidance not exclusive',1;
PRINT 'PASS explicit switching retains previous progress and has one active investigation per book';
DELETE dbo.WriterInvestigations WHERE ID=@clone AND UserID=@u;
IF EXISTS(SELECT 1 FROM dbo.WriterInvestigationGuidance WHERE InvestigationID=@clone) THROW 51000,'Guidance cascade failed',1;
PRINT 'PASS canonical investigation deletion cascades private guidance';
EXEC dbo.WriterInvestigationGuidanceState @Action='activate',@UserID=@u,@BookID=@book,@ID=@id,@ExpectedVersion=@v,@Json=N'{"Finding":"disconnected","Capability":"threads","Progress":{"disconnected/threads":"Done"}}';SET @v+=1;
EXEC dbo.WriterInvestigationGuidanceState @Action='finish',@UserID=@u,@BookID=@book,@ID=@id,@ExpectedVersion=@v,@Json=N'{"Finding":"disconnected","Capability":"threads","Progress":{"disconnected/threads":"Done"}}';
IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigationGuidance WHERE InvestigationID=@id AND IsActive=0 AND Finished=1) THROW 51000,'Finish failed',1;
IF @before<>HASHBYTES('SHA2_256',(SELECT Json FROM dbo.WriterInvestigations WHERE ID=@id)) OR @events<>HASHBYTES('SHA2_256',(SELECT Event FROM dbo.WriterInvestigationEvents WHERE InvestigationID=@id ORDER BY Version FOR JSON PATH)) THROW 51000,'Canonical investigation modified',1;
PRINT 'PASS lifecycle leaves diagnostic JSON and questionnaire events unchanged';
SELECT 'PASS real SQL investigation companion qualification' Result;

View File

@ -129,6 +129,9 @@ internal static class ToolbarBrowserHost
builder.Services.AddSignalR();
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationAccess>();
builder.Services.AddSingleton<IInvestigationRepository,InvestigationMemoryRepository>();
builder.Services.AddSingleton<IInvestigationGuidanceRepository,GuidanceMemoryRepository>();
builder.Services.AddMemoryCache();
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationGuidanceService>();
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationService>();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<IWordCompanionPresenceService, WordCompanionPresenceService>();

View File

@ -0,0 +1,49 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Data;
using PlotLine.Services.Investigations;
namespace PlotLine.Controllers;
[Authorize,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class InvestigationCompanionController(InvestigationAccess gate,IInvestigationGuidanceRepository repository,InvestigationGuidanceService service,IInvestigationRepository investigations):Controller
{
IActionResult Error(int status,string message){
if(ControllerContext.ActionDescriptor.ActionName==nameof(Open)){
Response.StatusCode=status;ViewData["Failure"]=message;
if(int.TryParse(Request.Form["bookId"],out var book))ViewData["BookID"]=book;
if(Guid.TryParse(Request.Form["id"],out var id))ViewData["InvestigationID"]=id;
return View("~/Views/InvestigationCompanion/Failure.cshtml");
}
return StatusCode(status,new{message});
}
int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
async Task<IActionResult> Guard(Func<Task<IActionResult>> run){if(!gate.Enabled)return NotFound();Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";try{return await run();}catch(Exception e)when(e is UnauthorizedAccessException or KeyNotFoundException){return NotFound();}catch(ArgumentException e){return Error(400,e.Message);}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){return Error(409,"Guidance changed in another window. Refresh before trying again.");}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){return Error(503,"Guidance is temporarily unavailable. Your saved investigation is retained.");}}
async Task<(GuidanceRecord,PlotLine.Models.Investigations.Catalogue)> Verify(GuidanceRecord r){var(i,_,_)=InvestigationGuidanceService.Decode(r);if(i.UserID!=Author||i.BookID!=r.BookID||i.ProjectID!=r.ProjectID)throw new UnauthorizedAccessException();var c=await service.Catalogue(i.CatalogueVersion);if(c.Synthetic&&!(await HttpContext.RequestServices.GetRequiredService<IAuthorizationService>().AuthorizeAsync(User,null,"AdminOnly")).Succeeded)throw new UnauthorizedAccessException();return(r,c);}
async Task<(GuidanceRecord,PlotLine.Models.Investigations.Catalogue)> Load(int? project,int? book,Guid? id)=>await Verify(await repository.Read(Author,project,book,id)??throw new KeyNotFoundException());
[HttpGet("/InvestigationCompanion/Summary")]
public Task<IActionResult> Summary(int? projectId,int? bookId)=>Guard(async()=>{
if(projectId is not >0&&bookId is not >0)return Json(new{active=false});
var r=await repository.Read(Author,projectId,bookId);if(r==null)return Json(new{active=false});
var(verified,c)=await Verify(r); // same ownership guard as explicit IDs
return Json(new{active=true,summary=service.Summary(verified,c),resultsUrl=Url.Action("Index","WriterInvestigations",new{bookId=r.BookID,id=r.ID})});
});
[HttpGet("/InvestigationCompanion/Evidence")]
public Task<IActionResult> Evidence(int bookId,Guid id,string finding)=>Guard(async()=>{
var(r,c)=await Load(null,bookId,id);var(i,_,s)=InvestigationGuidanceService.Decode(r);service.Select(r,c,s,finding,null);
var full=await investigations.Read(Author,bookId,id)??throw new KeyNotFoundException();
return Json(full.Answers.Where(a=>c.Questions.Any(q=>q.Id==a.Question&&q.Options.Any(o=>o.Id==a.Option&&o.Contributions.Any(v=>v.Hypothesis==finding&&v.Weight>0)))).Take(5).Select(a=>{var q=c.Questions.Single(q=>q.Id==a.Question);return new{question=q.Text,answer=q.Options.Single(o=>o.Id==a.Option).Text,explanation=a.Explanation};}));
});
[HttpPost("/InvestigationCompanion/Update"),ValidateAntiForgeryToken]
public Task<IActionResult> Update(int bookId,Guid id,int version,string operation,string? finding,string? capability,string? progress)=>Guard(async()=>{
var(r,c)=await Load(null,bookId,id);if(r.GuidanceVersion!=version)return Error(409,"Guidance changed in another window. Refresh before trying again.");var(_,_,s)=InvestigationGuidanceService.Decode(r);
if(operation is "select" or "progress"){
if(!r.IsActive)throw new ArgumentException("Activate this investigation first.");service.Select(r,c,s,finding??"",capability);
if(operation=="progress"){if(capability==null||!InvestigationGuidanceService.ProgressStates.Contains(progress))throw new ArgumentException("Choose a progress state.");s.Progress[InvestigationGuidanceService.Key(finding!,capability)]=progress!;}
}else if(operation is not("activate" or "dismiss" or "finish"))throw new ArgumentException("Unknown guidance action.");
await service.Save(Author,r,s,operation is "select" or "progress"?"save":operation);
if(operation=="activate")return RedirectToAction("Index","WriterInvestigations",new{bookId,id});
return Json(new{ok=true});
});
[HttpPost("/InvestigationCompanion/Open"),ValidateAntiForgeryToken]
public Task<IActionResult> Open(int bookId,Guid id,string finding,string capability)=>Guard(async()=>{var(r,c)=await Load(null,bookId,id);var target=await service.Open(Author,r,c,finding,capability);return RedirectToAction(target.Action,target.Controller,target.Values);});
}

View File

@ -8,7 +8,7 @@ using PlotLine.Services.Investigations;
namespace PlotLine.Controllers;
[Authorize]
[ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class WriterInvestigationsController(InvestigationAccess gate,IInvestigationRepository repository,InvestigationService service):Controller
public sealed class WriterInvestigationsController(InvestigationAccess gate,IInvestigationRepository repository,InvestigationService service,IInvestigationGuidanceRepository guidance,InvestigationGuidanceService companion):Controller
{
async Task<bool> IsAdmin()=> (await HttpContext.RequestServices.GetRequiredService<IAuthorizationService>().AuthorizeAsync(User,null,"AdminOnly")).Succeeded;
async Task EnsureCatalogue(Catalogue c){if(c.Synthetic&&!await IsAdmin())throw new UnauthorizedAccessException();}
@ -16,6 +16,7 @@ public sealed class WriterInvestigationsController(InvestigationAccess gate,IInv
async Task<IActionResult> Guard(Func<Task<IActionResult>> run){if(!gate.Enabled)return NotFound();Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";try{return await run();}catch(Exception e)when(e is UnauthorizedAccessException or KeyNotFoundException){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){Response.StatusCode=409;ViewData["Failure"]=e.Message;return View("Failure");}catch(ArgumentException e){Response.StatusCode=400;ViewData["Failure"]=e.Message;return View("Failure");}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){Response.StatusCode=503;ViewData["Failure"]="Investigations are temporarily unavailable. No unconfirmed save should be assumed successful. Return to Explore to resume.";return View("Failure");}}
[HttpGet("/Writer/Explore/Investigate")]
public Task<IActionResult> Index(int bookId,Guid? id,string? question=null,string? catalogueVersion=null)=>Guard(async()=>{
if(id.HasValue)ViewData["GuidanceVersion"]=(await guidance.Read(Author,null,bookId,id.Value))?.GuidanceVersion??0;
var project=await service.Project(bookId);Catalogue c;Investigation? row=null;Evaluation? state=null;
if(id.HasValue){(row,c)=await service.Read(Author,bookId,id.Value);await EnsureCatalogue(c);state=service.Current(c,row);if(question!=null&&!row.Presented.Contains(question))return BadRequest();ViewData["Question"]=question??state.NextQuestion;}
else {if(catalogueVersion!=null&&!await IsAdmin())return NotFound();c=await (catalogueVersion==null?service.AuthorCatalogue():repository.Catalogue(catalogueVersion))??throw new ArgumentException("The investigation catalogue is not available yet.");await EnsureCatalogue(c);}
@ -42,11 +43,11 @@ public sealed class WriterInvestigationsController(InvestigationAccess gate,IInv
});
[HttpPost("/Writer/Explore/Investigate/Open"),ValidateAntiForgeryToken]
public Task<IActionResult> Open(int bookId,Guid id,int version,string capability)=>Guard(async()=>{
var(i,c)=await service.Read(Author,bookId,id);await EnsureCatalogue(c);if(version!=i.Version)throw new ArgumentException("Resume the latest version before opening a tool.");var result=service.Current(c,i);var d=c.Capabilities.SingleOrDefault(d=>d.Id==capability);
if(d==null||!InvestigationService.CanOpen(c,result,capability))throw new ArgumentException("This destination is not currently recommended.");
var target=DestinationRegistry.Resolve(d,i.ProjectID,i.BookID,true,i.Answers.ToDictionary(a=>a.Question));if(target==null)throw new ArgumentException("This tool is unavailable. Your investigation is retained.");
i.SelectedDestination=capability;await service.Persist(i,c,version,"open-destination");TempData["InvestigationReturn"] = Url.Action(nameof(Index),new{bookId,id});
return RedirectToAction(target.Value.Action,target.Value.Controller,target.Value.Values);
var(i,c)=await service.Read(Author,bookId,id);await EnsureCatalogue(c);if(version!=i.Version)throw new ArgumentException("Resume the latest version before opening a tool.");
var r=await guidance.Read(Author,i.ProjectID,bookId,id)??throw new KeyNotFoundException();
var saved=InvestigationGuidanceService.Decode(r);var finding=InvestigationGuidanceService.Recommended(saved.Investigation,saved.Evaluation).FirstOrDefault(h=>c.Hypotheses.Single(x=>x.Id==h).Capabilities.Contains(capability))??throw new ArgumentException("This destination is not currently recommended.");
var target=await companion.Open(Author,r,c,Request.Form["finding"].FirstOrDefault()??finding,capability);
return RedirectToAction(target.Action,target.Controller,target.Values);
});
[Authorize(Policy="AdminOnly"),HttpGet("/admin/writer-investigations")]
public Task<IActionResult> Admin()=>Guard(async()=>View("Admin",await repository.Catalogue()));

View File

@ -0,0 +1,19 @@
using System.Data;
using Dapper;
namespace PlotLine.Data;
public sealed class GuidanceRecord
{
public Guid ID {get;set;} public int ProjectID {get;set;} public int BookID {get;set;} public string BookTitle {get;set;}="";
public string InvestigationJson {get;set;}="";public string? EvaluationJson {get;set;}public string? GuidanceJson {get;set;}
public int GuidanceVersion {get;set;}public bool IsActive {get;set;}public bool Finished {get;set;}
}
public interface IInvestigationGuidanceRepository
{
Task<GuidanceRecord?> Read(int user,int? project,int? book,Guid? id=null);
Task Save(int user,int book,Guid id,int version,string operation,string json);
}
public sealed class InvestigationGuidanceRepository(ISqlConnectionFactory factory):IInvestigationGuidanceRepository
{
public async Task<GuidanceRecord?> Read(int user,int? project,int? book,Guid? id=null){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<GuidanceRecord>("dbo.WriterInvestigationGuidanceState",new{Action="read",UserID=user,ProjectID=project,BookID=book,ID=id},commandType:CommandType.StoredProcedure);}
public async Task Save(int user,int book,Guid id,int version,string operation,string json){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterInvestigationGuidanceState",new{Action=operation,UserID=user,BookID=book,ID=id,ExpectedVersion=version,Json=json},commandType:CommandType.StoredProcedure);}
}

View File

@ -142,6 +142,8 @@ public class Program
builder.Services.AddScoped<ApplicationNavigation>();
builder.Services.AddScoped<IWritingSolverRepository, WritingSolverRepository>();
builder.Services.AddScoped<PlotLine.Data.IInvestigationRepository,PlotLine.Data.InvestigationRepository>();
builder.Services.AddScoped<PlotLine.Data.IInvestigationGuidanceRepository,PlotLine.Data.InvestigationGuidanceRepository>();
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationGuidanceService>();
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationService>();
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationAccess>();
builder.Services.AddScoped<IWritingSolverWorkspaceContext, WritingSolverWorkspaceContext>();

View File

@ -0,0 +1,49 @@
using System.Text.Json;
using Microsoft.Extensions.Caching.Memory;
using PlotLine.Data;
using PlotLine.Models.Investigations;
namespace PlotLine.Services.Investigations;
public sealed class GuidanceState
{
public string? Finding {get;set;}public string? Capability {get;set;}
public Dictionary<string,string> Progress {get;set;}=[];
}
public sealed record GuidanceTool(string Id,string Name,string Why,string Action,string Progress,bool Available);
public sealed record GuidanceFinding(string Id,string Title,string Explanation,string Action,string Uncertainty,IReadOnlyList<GuidanceTool> Tools);
public sealed record GuidanceSummary(Guid ID,int ProjectID,int BookID,string BookTitle,int Version,bool Active,bool Finished,string Concern,string Message,string? Finding,string? Capability,IReadOnlyList<GuidanceFinding> Findings);
public sealed class InvestigationGuidanceService(IInvestigationGuidanceRepository guidance,IInvestigationRepository investigations,IMemoryCache cache,IConfiguration configuration)
{
public static readonly string[] ProgressStates=["Not started","Exploring","Done","Skipped"];
public static string Key(string finding,string capability)=>finding+"/"+capability;
public static (Investigation Investigation,Evaluation? Evaluation,GuidanceState State) Decode(GuidanceRecord r)=>
(JsonSerializer.Deserialize<Investigation>(r.InvestigationJson,CatalogueValidator.Json)!,r.EvaluationJson==null?null:JsonSerializer.Deserialize<Evaluation>(r.EvaluationJson,CatalogueValidator.Json),r.GuidanceJson==null?new():JsonSerializer.Deserialize<GuidanceState>(r.GuidanceJson,CatalogueValidator.Json)??new());
public async Task<Catalogue> Catalogue(string version)=>await cache.GetOrCreateAsync("guidance-catalogue:"+version,async entry=>{entry.AbsoluteExpirationRelativeToNow=TimeSpan.FromMinutes(30);return await investigations.Catalogue(version)??throw new KeyNotFoundException();})??throw new KeyNotFoundException();
public static IReadOnlyList<string> Recommended(Investigation i,Evaluation? e)=>i.CurrentQuestion==null&&e?.Outcome!="Investigating"?e?.Recommendations??[]:[];
public bool Available(Capability d,Investigation i)=>configuration.GetValue($"WriterInvestigations:Capabilities:{d.Id}:Enabled",true)&&DestinationRegistry.Resolve(d,i.ProjectID,i.BookID,true,i.Answers.ToDictionary(a=>a.Question))!=null;
public GuidanceSummary Summary(GuidanceRecord r,Catalogue c)
{
var(i,e,s)=Decode(r);var ids=Recommended(i,e);
var findings=ids.Select(id=>{
var h=c.Hypotheses.Single(h=>h.Id==id);var authored=c.Editorial?.Results.SingleOrDefault(x=>x.Hypothesis==id);
var explanation=authored?.Explanation??h.Reason;var action=authored?.Action??"Use the suggested tool to explore this possibility.";
return new GuidanceFinding(id,authored?.Title??h.Summary,explanation,action,h.Uncertainty,c.Capabilities.Where(d=>h.Capabilities.Contains(d.Id)).Select(d=>new GuidanceTool(d.Id,d.Name,d.Description,d.ActionText,s.Progress.GetValueOrDefault(Key(id,d.Id),"Not started"),Available(d,i))).ToArray());
}).ToArray();
var message=e==null?"This older investigation has no saved result. Open the full investigation to continue.":i.CurrentQuestion!=null?"Continue the saved investigation before choosing a tool.":ids.Count==0?"Your saved answers do not yet support a specific tool recommendation. Open the full results to review the uncertainty and next steps.":"These suggestions reflect your questionnaire answers, not verified manuscript analysis.";
return new(r.ID,r.ProjectID,r.BookID,r.BookTitle,r.GuidanceVersion,r.IsActive,r.Finished,c.Concerns.SingleOrDefault(x=>x.Id==i.Concern)?.Text??"Saved story concern",message,s.Finding,s.Capability,findings);
}
public void Select(GuidanceRecord r,Catalogue c,GuidanceState state,string finding,string? capability)
{
var(i,e,_)=Decode(r);if(!Recommended(i,e).Contains(finding))throw new ArgumentException("This finding is no longer recommended. Open the full results.");
if(capability!=null&&!c.Hypotheses.Single(h=>h.Id==finding).Capabilities.Contains(capability))throw new ArgumentException("This tool does not belong to this finding.");
state.Finding=finding;state.Capability=capability;
}
public Task Save(int user,GuidanceRecord r,GuidanceState state,string operation)=>guidance.Save(user,r.BookID,r.ID,r.GuidanceVersion,operation,JsonSerializer.Serialize(state,CatalogueValidator.Json));
public async Task<(string Controller,string Action,object Values)> Open(int user,GuidanceRecord r,Catalogue c,string finding,string capability)
{
var(i,_,s)=Decode(r);Select(r,c,s,finding,capability);var d=c.Capabilities.SingleOrDefault(d=>d.Id==capability)??throw new ArgumentException("Tool unavailable.");
if(!Available(d,i))throw new ArgumentException("This tool is currently unavailable. Your investigation is retained.");
// Opening never completes a step, nor resets an explicit Done/Skipped decision.
var key=Key(finding,capability);if(s.Progress.GetValueOrDefault(key,"Not started")=="Not started")s.Progress[key]="Exploring";
await Save(user,r,s,"activate");return DestinationRegistry.Resolve(d,i.ProjectID,i.BookID,true,i.Answers.ToDictionary(a=>a.Question))!.Value;
}
}

View File

@ -0,0 +1,12 @@
-- Phase 1.5: private follow-through state only. Canonical investigations/events remain untouched.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
IF OBJECT_ID('dbo.WriterInvestigationGuidance') IS NULL
CREATE TABLE dbo.WriterInvestigationGuidance(
InvestigationID uniqueidentifier NOT NULL PRIMARY KEY REFERENCES dbo.WriterInvestigations(ID) ON DELETE CASCADE,
UserID int NOT NULL, BookID int NOT NULL, IsActive bit NOT NULL DEFAULT 1, Finished bit NOT NULL DEFAULT 0,
Version int NOT NULL, Json nvarchar(max) NOT NULL CHECK(ISJSON(Json)=1), UpdatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME());
IF NOT EXISTS(SELECT 1 FROM sys.indexes WHERE object_id=OBJECT_ID('dbo.WriterInvestigationGuidance') AND name='IX_Guidance_Active')
CREATE UNIQUE INDEX IX_Guidance_Active ON dbo.WriterInvestigationGuidance(UserID,BookID) WHERE IsActive=1;
GO

View File

@ -0,0 +1,44 @@
-- Forward-only procedure correction after migration 275 table creation.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.WriterInvestigationGuidanceState
@Action varchar(12),@UserID int,@ProjectID int=NULL,@BookID int=NULL,@ID uniqueidentifier=NULL,
@ExpectedVersion int=NULL,@Json nvarchar(max)=NULL AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
IF @Action='read' BEGIN
SELECT TOP(1) i.ID,i.ProjectID,i.BookID,b.BookTitle,
JSON_MODIFY(JSON_MODIFY(JSON_MODIFY(i.Json,'$.Answers',JSON_QUERY((SELECT a.Question,a.[Option] FROM OPENJSON(i.Json,'$.Answers') WITH(Question varchar(100),[Option] varchar(100)) a FOR JSON PATH))),'$.Presented',NULL),'$.Recommendations',NULL) InvestigationJson,
CASE WHEN e.Event IS NULL THEN NULL ELSE (SELECT JSON_VALUE(e.Event,'$.evaluation.Outcome') Outcome,JSON_QUERY(e.Event,'$.evaluation.Recommendations') Recommendations FOR JSON PATH,WITHOUT_ARRAY_WRAPPER) END EvaluationJson,g.Json GuidanceJson,ISNULL(g.Version,0) GuidanceVersion,ISNULL(g.IsActive,0) IsActive,ISNULL(g.Finished,0) Finished
FROM dbo.WriterInvestigations i
JOIN dbo.Books b ON b.BookID=i.BookID AND b.IsArchived=0
JOIN dbo.Projects p ON p.ProjectID=i.ProjectID AND p.IsArchived=0
JOIN dbo.ProjectUserAccess a ON a.ProjectID=i.ProjectID AND a.UserID=@UserID AND a.IsActive=1
LEFT JOIN dbo.WriterInvestigationGuidance g ON g.InvestigationID=i.ID AND g.UserID=@UserID AND g.BookID=i.BookID
OUTER APPLY(SELECT TOP(1) Event FROM dbo.WriterInvestigationEvents WHERE InvestigationID=i.ID AND Version=i.Version) e
WHERE i.UserID=@UserID AND (@BookID IS NULL OR i.BookID=@BookID) AND (@ProjectID IS NULL OR i.ProjectID=@ProjectID)
AND ((@ID IS NOT NULL AND i.ID=@ID) OR (@ID IS NULL AND g.IsActive=1))
AND (@ID IS NOT NULL OR @ProjectID IS NOT NULL OR @BookID IS NOT NULL)
ORDER BY g.UpdatedUtc DESC,i.ID;
RETURN;
END;
IF @Action NOT IN('activate','save','dismiss','finish') OR @ID IS NULL OR @BookID IS NULL OR @ExpectedVersion IS NULL OR ISJSON(@Json)<>1 OR DATALENGTH(@Json)>65536 THROW 51000,'Invalid guidance request',1;
BEGIN TRY
BEGIN TRANSACTION;
IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations i JOIN dbo.Books b ON b.BookID=i.BookID AND b.IsArchived=0 JOIN dbo.Projects p ON p.ProjectID=i.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=i.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE i.ID=@ID AND i.UserID=@UserID AND i.BookID=@BookID AND (@ProjectID IS NULL OR i.ProjectID=@ProjectID)) THROW 51000,'Guidance unavailable',1;
DECLARE @actual int;
SELECT @actual=Version FROM dbo.WriterInvestigationGuidance WITH(UPDLOCK,HOLDLOCK) WHERE InvestigationID=@ID AND UserID=@UserID AND BookID=@BookID;
IF ISNULL(@actual,0)<>@ExpectedVersion THROW 51002,'Guidance changed in another window. Refresh before trying again.',1;
IF @Action='activate' UPDATE dbo.WriterInvestigationGuidance SET IsActive=0 WHERE UserID=@UserID AND BookID=@BookID AND IsActive=1 AND InvestigationID<>@ID;
IF @actual IS NULL BEGIN
IF @Action<>'activate' THROW 51000,'Activate this investigation first',1;
INSERT dbo.WriterInvestigationGuidance(InvestigationID,UserID,BookID,Version,Json) VALUES(@ID,@UserID,@BookID,1,@Json);
END ELSE UPDATE dbo.WriterInvestigationGuidance SET Json=@Json,Version=Version+1,UpdatedUtc=SYSUTCDATETIME(),
IsActive=CASE WHEN @Action='activate' THEN 1 WHEN @Action IN('dismiss','finish') THEN 0 ELSE IsActive END,
Finished=CASE WHEN @Action='activate' THEN 0 WHEN @Action='finish' THEN 1 ELSE Finished END
WHERE InvestigationID=@ID AND UserID=@UserID AND BookID=@BookID;
COMMIT;
END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH;
END;
GO

View File

@ -0,0 +1,5 @@
@{ViewData["Title"]="Investigation guidance";}
<h1>We couldn't open that suggestion</h1>
<p role="alert">@ViewData["Failure"]</p>
<p>Your saved investigation and confirmed progress are retained.</p>
<a asp-controller="WriterInvestigations" asp-action="Index" asp-route-bookId="@ViewData["BookID"]" asp-route-id="@ViewData["InvestigationID"]">Return to the full investigation</a>

View File

@ -113,7 +113,6 @@
</div>
</div>
<div class="pd-ribbon-heading">
<button type="button" class="pd-history-back" data-app-back disabled aria-label="Back" title="Back to previous PlotDirector page"><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon("back").IconPath" /></svg><span>Back</span></button>
<div class="pd-ribbon-tabs" role="tablist" aria-label="Command categories">
@foreach (var category in ApplicationRibbon.Categories)
{
@ -128,6 +127,7 @@
<button type="button" class="pd-ribbon-collapse" data-ribbon-collapse aria-expanded="@(!appearance.RibbonCollapsed ? "true" : "false")" aria-controls="ribbon-surface" title="Collapse or expand ribbon">@(appearance.RibbonCollapsed ? "Expand ribbon" : "Collapse ribbon") <span aria-hidden="true">⌃</span></button>
</div>
<div id="ribbon-surface" class="pd-ribbon-surface" hidden="@appearance.RibbonCollapsed">
<div class="pd-ribbon-group pd-ribbon-history" role="group" aria-label="Navigation"><div class="pd-ribbon-commands"><button type="button" class="pd-ribbon-command pd-ribbon-back" data-app-back disabled aria-label="Back" title="Back to previous PlotDirector page"><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon("back").IconPath" /></svg><span>Back</span></button></div><span class="pd-ribbon-group-label">Navigation</span></div>
@foreach (var category in ApplicationRibbon.Categories)
{
<div class="pd-ribbon-panel" id="ribbon-panel-@category.Key" role="tabpanel" aria-labelledby="ribbon-tab-@category.Key" hidden="@(category.Key != selectedCategory)">

View File

@ -0,0 +1,14 @@
@model ApplicationNavigationViewModel
<aside class="pd-investigation" data-investigation-companion data-collapsed="true" data-user="@User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value" data-project="@Model.Project?.ProjectID" data-book="@Model.Book?.BookID"
data-summary-url="@Url.Action("Summary","InvestigationCompanion")" data-update-url="@Url.Action("Update","InvestigationCompanion")" data-open-url="@Url.Action("Open","InvestigationCompanion")" data-evidence-url="@Url.Action("Evidence","InvestigationCompanion")" data-start-url="@(Model.Book is not null ? Url.Action("Index","WriterInvestigations",new{bookId=Model.Book.BookID}) : Url.Action("Index","Writer",new{projectId=Model.Project?.ProjectID}))" aria-label="Investigation companion">
<button type="button" class="pd-investigation-tab" data-guidance-expand aria-label="Expand investigation companion" title="Expand investigation companion" aria-expanded="false" aria-controls="investigation-panel">Investigation</button>
<div class="plotline-help-drawer-panel pd-investigation-panel" id="investigation-panel">
<header class="plotline-help-drawer-header"><div><p class="eyebrow mb-0">Investigation</p><strong data-guidance-title>Your story concern</strong></div>
<div class="btn-group btn-group-sm" role="group" aria-label="Investigation panel controls"><button class="btn btn-outline-secondary" type="button" data-guidance-pin aria-pressed="true">Unpin</button><button class="btn btn-outline-secondary" type="button" data-guidance-collapse aria-label="Collapse investigation companion">Collapse</button></div>
</header>
<div class="plotline-help-drawer-content" data-guidance-content><p>Loading saved guidance…</p></div>
<p class="pd-guidance-message" role="status" data-guidance-message></p>
</div>
<form hidden data-guidance-token>@Html.AntiForgeryToken()</form>
</aside>
<div class="pd-investigation-splitter" data-guidance-resize role="separator" tabindex="0" aria-label="Resize investigation companion" aria-orientation="vertical" aria-valuemin="280" aria-valuemax="440" aria-valuenow="320" title="Drag to resize; use Left and Right arrow keys"></div>

View File

@ -4,6 +4,7 @@
@inject IConfiguration Configuration
@inject IFeatureRequestService FeatureRequestService
@inject ApplicationNavigation Navigation
@inject PlotLine.Services.Investigations.InvestigationAccess InvestigationGate
@inject PlotLine.Data.IAppearanceRepository AppearancePreferences
@inject IOnboardingService OnboardingService
@inject IStoryIntelligenceGlobalProgressService StoryIntelligenceGlobalProgress
@ -93,6 +94,7 @@
}
@if (isApplication)
{
<link rel="stylesheet" href="~/css/investigation-companion.css" asp-append-version="true" />
<script src="~/js/application-display-mode.js" asp-append-version="true"></script>
<partial name="_ApplicationThemeBootstrap" model="appearance" />
}
@ -264,6 +266,7 @@
}
<partial name="_WritingConnectionDetails" />
<div class="plotline-help-layout" data-help-layout>
@if(isApplication&&InvestigationGate.Enabled){<partial name="_InvestigationCompanion" model="appNavigation" />}
<div class="plotline-help-main">
<div class="container-fluid plotline-shell @ViewData["ShellClass"] @(ViewData["DesktopLayout"] is string desktopLayout ? $"pd-record-canvas pd-record-canvas--{desktopLayout}" : null)">
<main data-pwa-page-content role="main" class="pb-3">
@ -341,6 +344,7 @@
<script src="~/js/site.js" asp-append-version="true"></script>
@if (User.Identity?.IsAuthenticated == true)
{
<script src="~/js/investigation-companion.js" asp-append-version="true"></script>
<script src="~/js/application-history.js" asp-append-version="true"></script>
<script src="~/js/application-navigation.js" asp-append-version="true"></script>
@if (!isMarketingPage)

View File

@ -44,7 +44,7 @@
}</ul>
@if(state!.Recommendations.Contains(finding.Hypothesis)){
@foreach(var cap in Model.Catalogue.Capabilities.Where(d=>Model.Catalogue.Hypotheses.Single(h=>h.Id==finding.Hypothesis).Capabilities.Contains(d.Id)&&state.AvailableCapabilities.Contains(d.Id))){
<p>@cap.Description</p><form asp-action="Open" method="post" target="_blank"><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/><button class="btn btn-primary" name="capability" value="@cap.Id">@cap.ActionText <span class="visually-hidden">(opens another tab; return here afterwards)</span></button></form>
<p>@cap.Description</p><form asp-action="Open" method="post"><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/><input type="hidden" name="finding" value="@finding.Hypothesis"/><button class="btn btn-primary" name="capability" value="@cap.Id">@cap.ActionText</button></form>
}
}
</section>
@ -55,11 +55,11 @@
<h2 id="investigation-question" data-conclusion="@conclusion.Kind">@conclusion.Title</h2>
<p>@conclusion.Message</p>
@if(conclusion.Areas.Length>0){<p>Areas your answers touched on:</p><ul>@foreach(var area in conclusion.Areas){<li>@area</li>}</ul>}
@if(state!.Recommendations.Count>0){<p class="writer3-caption">Tools open in another tab. Your investigation stays here so you can return to it.</p>}
@if(state!.Recommendations.Count>0){<p class="writer3-caption">Opening a tool makes this investigation your active guidance for this book. Your other saved investigations are kept.</p>}
@if(row.Answers.Count>=Model.Catalogue.MaxAnswers&&state.Recommendations.Count==0){<p>We've reached the question limit for this test. You can still change earlier answers or save and return later.</p>}
@foreach(var id in state.Recommendations){var h=Model.Catalogue.Hypotheses.Single(h=>h.Id==id);<section class="writer3-inset"><h3>@h.Summary</h3><p>@h.Reason</p><p class="muted">@h.Uncertainty</p>
<p>Answers that informed this suggestion:</p><ul>@foreach(var evidence in state.Evidence.Where(e=>e.Hypothesis==id&&e.Raw>0&&!e.Uncertain).DistinctBy(e=>e.Question).Take(3)){var q=Model.Catalogue.Questions.Single(q=>q.Id==evidence.Question);<li>@q.Text — @q.Options.Single(o=>o.Id==evidence.Option).Text</li>}</ul>
@foreach(var cap in Model.Catalogue.Capabilities.Where(d=>h.Capabilities.Contains(d.Id)&&state.AvailableCapabilities.Contains(d.Id))){<p>@cap.Description</p><form asp-action="Open" method="post" target="_blank"><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/><button class="btn btn-primary" name="capability" value="@cap.Id">@cap.ActionText <span class="visually-hidden">(opens another tab; return here afterwards)</span></button></form>}
@foreach(var cap in Model.Catalogue.Capabilities.Where(d=>h.Capabilities.Contains(d.Id)&&state.AvailableCapabilities.Contains(d.Id))){<p>@cap.Description</p><form asp-action="Open" method="post"><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/><input type="hidden" name="finding" value="@id"/><button class="btn btn-primary" name="capability" value="@cap.Id">@cap.ActionText</button></form>}
</section>}
}
@if(row.Accepted){<p role="status">Your response is saved. Return to this investigation whenever you need it.</p>}
@ -69,12 +69,13 @@
@if(row.Answers.Count<Model.Catalogue.MaxAnswers&&state.Candidates.Count>0){<button class="btn btn-outline-secondary" name="operation" value="further">I'd like to investigate further</button>}
<button class="btn btn-outline-secondary" name="operation" value="save">Save for later</button></div></form>
}
@if(row!=null){<form asp-controller="InvestigationCompanion" asp-action="Update" method="post"><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@ViewData["GuidanceVersion"]"/><button class="btn btn-outline-secondary" name="operation" value="activate">Keep this investigation alongside my work</button></form>}
<p class="writer3-caption"><a asp-controller="Writer" asp-action="Explore" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">Return to Explore</a> · <a asp-action="Index" asp-route-bookId="@Model.BookID">Start another investigation</a></p>
</section>
<aside class="writer3-panel" aria-label="Your investigations">
@if(row!=null){<h2>Your answers</h2><p>Your answers are saved when you continue. Changing one recomputes the investigation; earlier versions remain in its history.</p><ol>@foreach(var a in row.Answers){var q=Model.Catalogue.Questions.Single(q=>q.Id==a.Question);<li><a asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-id="@row.ID" asp-route-question="@a.Question">@q.Text</a><p>@q.Options.Single(o=>o.Id==a.Option).Text</p></li>}</ol>}
<h2>Continue later</h2><ul>@foreach(var saved in Model.Saved){<li><a asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-id="@saved.ID">@(((Dictionary<Guid,string>)ViewData["SavedConcernLabels"]!)[saved.ID]) · @saved.UpdatedUtc.ToString("dd MMM HH:mm") UTC</a></li>}</ul>
@if((await Authorization.AuthorizeAsync(User,null,"AdminOnly")).Succeeded){<p><a href="/admin/writer-investigations">Catalogue administration and simulator</a></p>@if(row!=null){<a href="/admin/writer-investigations/simulator?bookId=@Model.BookID&id=@row.ID" target="_blank">Private diagnostics and replay</a>}}
@if((await Authorization.AuthorizeAsync(User,null,"AdminOnly")).Succeeded){<p><a href="/admin/writer-investigations">Catalogue administration and simulator</a></p>@if(row!=null){<a href="/admin/writer-investigations/simulator?bookId=@Model.BookID&id=@row.ID">Private diagnostics and replay</a>}}
</aside>
</div>
</div>

View File

@ -738,8 +738,10 @@ html[data-app-theme] .writing-context-page .writing-workspace-role-indicator {
border-color: var(--pd-border); background: var(--pd-selected); color: var(--pd-text);
}
.pd-history-back{display:inline-flex;align-items:center;gap:.3rem;border:0;background:transparent;color:var(--pd-text);padding:.5rem;flex:none}
.pd-history-back svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:1.8}
.pd-history-back:disabled{opacity:.4}.pd-history-back:focus-visible{outline:2px solid var(--pd-focus)}
.app-layout .plotline-shell.writer3-shell{max-width:none;width:100%;padding-inline:clamp(8px,1.2vw,24px)}
@media(max-width:700px){.pd-history-back span{display:none}}
/* One global Back action in the primary ribbon row, independent of selected tab. */
#ribbon-surface:not([hidden]){display:flex;align-items:stretch}
#ribbon-surface>.pd-ribbon-panel{flex:1;min-width:0;position:relative}
.pd-ribbon-history{padding-left:0;margin-right:12px;justify-content:space-between}
.pd-shell .pd-ribbon-back:disabled{opacity:.4;cursor:default;background:transparent}

View File

@ -0,0 +1,42 @@
/* Independent left guidance and existing right Help, sharing the application's drawer shell. */
.plotline-help-layout:has([data-investigation-companion]){--context-sticky-top:8px;--investigation-width:320px}
.pd-investigation{flex:0 0 var(--investigation-width);width:var(--investigation-width);min-width:0;border-right:1px solid var(--pd-border-subtle);background:var(--pd-surface);color:var(--pd-text)}
.pd-investigation-panel{top:var(--context-sticky-top);max-height:calc(100dvh - var(--context-sticky-top) - 8px)}
.pd-investigation .plotline-help-drawer-header{flex-wrap:wrap;padding:.85rem}
.pd-investigation .plotline-help-drawer-content{padding:.85rem;min-height:0;overscroll-behavior:contain}
.pd-investigation-tab{display:none}
.pd-investigation[data-collapsed=true]{flex-basis:36px;width:36px}
.pd-investigation[data-collapsed=true]>.pd-investigation-panel{display:none}
.pd-investigation[data-collapsed=true]>.pd-investigation-tab{display:block;position:sticky;top:var(--context-sticky-top);writing-mode:vertical-rl;min-height:140px;width:36px;border:0;background:var(--pd-surface-2);color:var(--pd-text);padding:1rem .5rem;font:inherit;cursor:pointer}
.pd-investigation-tab:focus-visible,.pd-investigation-splitter:focus-visible{outline:2px solid var(--pd-focus);outline-offset:-2px}
.pd-investigation-splitter{flex:0 0 8px;cursor:col-resize;touch-action:none;background:linear-gradient(90deg,transparent,var(--pd-border-subtle),transparent)}
.pd-investigation[data-collapsed=true]+.pd-investigation-splitter{display:none}
.pd-guidance-message{margin:0;padding:0 .85rem .5rem;font-size:.85rem}
.pd-investigation h2{font-size:1.1rem}.pd-investigation h3{font-size:1rem}.pd-investigation p,.pd-investigation label{font-size:.9rem}
.pd-guidance-tool{border:1px solid var(--pd-border-subtle);border-radius:6px;margin:1rem 0;padding:.65rem}
.pd-guidance-tool[data-selected=true]{border-color:var(--pd-accent);box-shadow:inset 3px 0 var(--pd-accent)}
.pd-guidance-tool button,.pd-guidance-tool select{max-width:100%;white-space:normal}
.pd-investigation select{width:100%;min-width:0}.pd-investigation .btn{white-space:normal}
/* Correct existing Help sticky containment without coupling its business state to Investigation. */
.plotline-help-layout:has([data-investigation-companion])>.plotline-help-drawer>.plotline-help-drawer-panel{top:var(--context-sticky-top);max-height:calc(100dvh - var(--context-sticky-top) - 8px)}
.plotline-help-layout:has([data-investigation-companion])>.plotline-help-drawer .plotline-help-drawer-content{min-height:0}
.plotline-help-layout:has([data-investigation-companion]) .plotline-help-collapsed-strip{position:sticky;top:var(--context-sticky-top);min-height:140px}
/* Bound all three columns: reserve at least 560px for the central surface at desktop widths. */
@media(min-width:1100px){.plotline-help-layout:has(.pd-investigation[data-collapsed=false]).help-open:not(.help-collapsed)>.plotline-help-drawer{min-width:240px;max-width:max(240px,calc(100% - var(--investigation-width) - 576px));flex-basis:clamp(240px,var(--help-drawer-width),360px)}}
@media(max-width:1099px){
.pd-investigation[data-collapsed=false]{flex-basis:min(var(--investigation-width),calc(100% - 480px));width:min(var(--investigation-width),calc(100% - 480px))}
/* Small windows use an in-flow, full-width guidance row. No overlay and no lost main controls. */
.plotline-help-layout:has(.pd-investigation[data-collapsed=false]){flex-wrap:wrap}
.plotline-help-layout>.pd-investigation[data-collapsed=false]{flex:0 0 100%;width:100%;border-bottom:1px solid var(--pd-border)}
.pd-investigation[data-collapsed=false]+.pd-investigation-splitter{display:none}
.pd-investigation-panel{position:relative;top:0;max-height:55dvh}
.plotline-help-layout:has([data-investigation-companion]).help-open>.plotline-help-drawer{flex-basis:36px;min-width:36px;max-width:36px}
.plotline-help-layout:has([data-investigation-companion]).help-open>.plotline-help-drawer .plotline-help-drawer-panel{display:none}
.plotline-help-layout:has([data-investigation-companion]).help-open>.plotline-help-drawer .plotline-help-collapsed-strip{display:flex;width:36px;writing-mode:vertical-rl;cursor:pointer}
.plotline-help-layout:has([data-investigation-companion]).help-open>.plotline-help-splitter{display:none}
.plotline-help-layout:has([data-investigation-companion]).help-open[data-narrow-help=true]>.plotline-help-drawer{flex:0 0 100%;width:100%;max-width:100%;order:4}
.plotline-help-layout:has([data-investigation-companion]).help-open[data-narrow-help=true]{flex-wrap:wrap}
.plotline-help-layout[data-narrow-help=true]>.plotline-help-drawer .plotline-help-drawer-panel{display:flex;position:relative;top:0;max-height:55dvh}
.plotline-help-layout[data-narrow-help=true]>.plotline-help-drawer .plotline-help-collapsed-strip{display:none}
}
body.reader-focused .pd-investigation,body.reader-focused .pd-investigation-splitter{visibility:hidden}

View File

@ -13,6 +13,7 @@
const id = pointBook?.value ?? context?.dataset.navigationBookId ?? '';
if (id === currentBook) return;
currentBook = id;
document.dispatchEvent(new CustomEvent("plotdirector:book-context-changed", {detail:{bookId:Number(id)||0}}));
const selected = choices.find(x => x.dataset.appBookChoice === id);
label.textContent = selected?.dataset.appBookTitle || 'Book';
label.closest('button').title = label.textContent;

View File

@ -0,0 +1,64 @@
// Private server-owned guidance; browser storage contains only per-author presentation preferences.
(() => {
const root=document.querySelector('[data-investigation-companion]');if(!root)return;
const layout=root.closest('[data-help-layout]'),content=root.querySelector('[data-guidance-content]'),message=root.querySelector('[data-guidance-message]'),tab=root.querySelector('[data-guidance-expand]'),splitter=layout.querySelector('[data-guidance-resize]');
const token=root.querySelector('[name=__RequestVerificationToken]').value;
let current=null,resultsUrl=null,epoch=0,request,busy=false,preference={},drag=null;
const storageKey=()=>`plotdirector.investigationPanel.v1.${root.dataset.user}.${current?.bookID||root.dataset.book||root.dataset.project||'none'}`;
const read=()=>{try{const value=JSON.parse(localStorage.getItem(storageKey()));if(!value||typeof value!=='object'||Array.isArray(value))return {};if(!value.positions||typeof value.positions!=='object'||Array.isArray(value.positions))value.positions={};return value;}catch{return {};}};
const save=()=>{try{localStorage.setItem(storageKey(),JSON.stringify(preference));}catch{}};
const element=(tag,text,cls)=>{const n=document.createElement(tag);if(text!=null)n.textContent=text;if(cls)n.className=cls;return n;};
const btn=(text,fn)=>{const n=element('button',text,'btn btn-outline-secondary btn-sm');n.type='button';n.addEventListener('click',fn);return n;};
function collapse(value,persist=true){root.dataset.collapsed=String(value);tab.setAttribute('aria-expanded',String(!value));if(persist){preference.collapsed=value;save();}measure();}
function paintPreference(){root.querySelector('[data-guidance-pin]').textContent=preference.pinned===false?'Pin':'Unpin';root.querySelector('[data-guidance-pin]').setAttribute('aria-pressed',String(preference.pinned!==false));setWidth(preference.width||320,false);collapse(preference.collapsed===true||preference.pinned===false||!current,false);}
function setWidth(value,persist=true){const width=Math.max(280,Math.min(440,Number(value)||320));layout.style.setProperty('--investigation-width',width+'px');splitter.setAttribute('aria-valuenow',String(width));if(persist){preference.width=width;save();}}
function measure(){const h=document.querySelector('.pd-application-header'),top=h&&getComputedStyle(h).position==='sticky'?h.getBoundingClientRect().height:0;layout.style.setProperty('--context-sticky-top',Math.ceil(top)+8+'px');}
function failure(text){message.textContent=text;}
function startLink(){const a=element('a',root.dataset.book?'Open saved investigations':'Choose a book in Writer to resume an investigation');a.href=root.dataset.startUrl;return a;}
function render(){
content.replaceChildren();message.textContent='';root.querySelector('[data-guidance-title]').textContent=current?.bookTitle||'Your story concern';
if(!current){content.append(element('p','No active investigation for this context.'),startLink());return;}
const summary=element('a','Full investigation results');summary.href=resultsUrl;content.append(summary,element('h2',current.concern),element('p',current.message));
if(current.findings.length){
const label=element('label','Finding');label.htmlFor='guidance-finding';const select=element('select',null,'form-select');select.id='guidance-finding';
for(const f of current.findings){const o=element('option',f.title);o.value=f.id;select.append(o);}select.value=current.findings.some(f=>f.id===current.finding)?current.finding:current.findings[0].id;
select.addEventListener('change',()=>mutate('select',{finding:select.value}));content.append(label,select);
const f=current.findings.find(f=>f.id===select.value);content.append(element('p',f.explanation),element('h3','A practical next step'),element('p',f.action));if(f.uncertainty)content.append(element('p',f.uncertainty,'muted'));
const details=element('details'),heading=element('summary','Answers that informed this suggestion'),answers=element('div');details.append(heading,answers);let loaded=false;
details.addEventListener('toggle',async()=>{if(!details.open||loaded)return;loaded=true;const stamp=epoch;answers.textContent='Loading your answers…';try{const url=new URL(root.dataset.evidenceUrl,location.origin);url.search=new URLSearchParams({bookId:current.bookID,id:current.id,finding:f.id});const response=await fetch(url,{cache:'no-store'});if(!response.ok)throw Error('Your answers could not be loaded. Reopen this section to retry.');const rows=await response.json();if(stamp!==epoch)return;answers.replaceChildren(element('p','You answered:'));for(const a of rows){answers.append(element('p',a.question+' — '+a.answer));if(a.explanation)answers.append(element('blockquote',a.explanation));}if(!rows.length)answers.append(element('p','Open the full results for your saved observations.'));}catch(e){loaded=false;answers.textContent=e.message;}});
content.append(details,element('h3','Suggested tools'));
for(const tool of f.tools){
const card=element('section',null,'pd-guidance-tool');card.dataset.selected=String(current.finding===f.id&&current.capability===tool.id);card.dataset.capability=tool.id;
card.append(element('h3',tool.name),element('p',tool.why));
if(tool.available){const form=element('form');form.method='post';form.action=root.dataset.openUrl;for(const [name,value]of Object.entries({__RequestVerificationToken:token,bookId:current.bookID,id:current.id,finding:f.id,capability:tool.id})){const input=element('input');input.type='hidden';input.name=name;input.value=value;form.append(input);}const open=element('button',tool.action||'Open tool','btn btn-primary btn-sm');open.type='submit';form.append(open);card.append(form);}
else card.append(element('p','This destination is currently unavailable. Your investigation and progress are retained.'));
const label=element('label','Your progress'),select=element('select',null,'form-select form-select-sm');label.append(select);for(const state of['Not started','Exploring','Done','Skipped']){const o=element('option',state);o.value=state;select.append(o);}select.value=tool.progress;select.setAttribute('aria-label',tool.name+' progress');select.addEventListener('change',()=>mutate('progress',{finding:f.id,capability:tool.id,progress:select.value}));card.append(label);content.append(card);
}
}
content.append(btn('Dismiss guidance',()=>mutate('dismiss')),btn('Finish this journey',()=>mutate('finish')));
const position=preference.positions?.[current.id]||0;requestAnimationFrame(()=>content.scrollTop=position);
}
async function load(){
const stamp=++epoch;request?.abort();request=new AbortController();
try{const url=new URL(root.dataset.summaryUrl,location.origin);if(root.dataset.project)url.searchParams.set('projectId',root.dataset.project);if(root.dataset.book)url.searchParams.set('bookId',root.dataset.book);
const response=await fetch(url,{cache:'no-store',signal:request.signal});if(response.redirected||response.status===401){throw Error('Sign in again to resume your saved investigation.');}if(!response.ok)throw Error('Saved guidance could not be loaded. Retry when your connection returns.');const data=await response.json();if(stamp!==epoch)return;
current=data.active?data.summary:null;resultsUrl=data.resultsUrl;preference=read();render();paintPreference();
}catch(e){if(e.name==='AbortError'||stamp!==epoch)return;current=null;content.replaceChildren(element('p',e.message),btn('Retry',load),startLink());collapse(true,false);}
}
async function mutate(operation,extra={}){
if(busy||!current)return;busy=true;const selected=current.id;failure('Saving…');content.querySelectorAll('button,select').forEach(n=>n.disabled=true);
try{const data=new URLSearchParams({__RequestVerificationToken:token,bookId:current.bookID,id:current.id,version:current.version,operation,...extra});const response=await fetch(root.dataset.updateUrl,{method:'POST',body:data,cache:'no-store'});if(!response.ok){let body;try{body=await response.json();}catch{}throw Error(body?.message||'Your change was not confirmed. Retry or refresh your saved guidance.');}if(current?.id===selected){if(operation==='dismiss'||operation==='finish')collapse(true);await load();}}
catch(e){render();failure(e.message);}finally{busy=false;}
}
tab.addEventListener('click',()=>collapse(false));root.querySelector('[data-guidance-collapse]').addEventListener('click',()=>{collapse(true);tab.focus();});
root.querySelector('[data-guidance-pin]').addEventListener('click',()=>{preference.pinned=preference.pinned===false;save();const wasCollapsed=root.dataset.collapsed;paintPreference();root.dataset.collapsed=wasCollapsed;});
let scrollFrame=0;content.addEventListener('scroll',()=>{if(scrollFrame||!current)return;scrollFrame=requestAnimationFrame(()=>{scrollFrame=0;if(!current||root.dataset.collapsed==='true')return;preference.positions||={};preference.positions[current.id]=content.scrollTop;const keys=Object.keys(preference.positions);if(keys.length>20)delete preference.positions[keys[0]];save();});});
splitter.addEventListener('keydown',e=>{if(e.key!=='ArrowLeft'&&e.key!=='ArrowRight')return;e.preventDefault();setWidth((preference.width||320)+(e.key==='ArrowRight'?10:-10));});
splitter.addEventListener('pointerdown',e=>{if(e.button!==0)return;drag=e.pointerId;splitter.setPointerCapture(e.pointerId);e.preventDefault();});splitter.addEventListener('pointermove',e=>{if(drag===e.pointerId)setWidth(e.clientX-layout.getBoundingClientRect().left);});for(const event of['pointerup','pointercancel','lostpointercapture'])splitter.addEventListener(event,()=>drag=null);
const observer=new ResizeObserver(measure);const header=document.querySelector('.pd-application-header');if(header)observer.observe(header);window.addEventListener('resize',measure);window.addEventListener('plotdirector:ribbon-layout-changed',measure);
// A narrow Help drawer becomes an in-flow row when explicitly opened; its stored pin/collapse remains independent.
const help=layout.querySelector('[data-help-expand]');help?.addEventListener('click',()=>layout.dataset.narrowHelp='true');help?.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' ')layout.dataset.narrowHelp='true';});
layout.querySelector('[data-help-collapse]')?.addEventListener('click',()=>delete layout.dataset.narrowHelp);document.addEventListener('plotline:help-more',()=>layout.dataset.narrowHelp='true');document.addEventListener('click',e=>{if(e.target.closest?.('[data-help-open]'))layout.dataset.narrowHelp='true';});
document.addEventListener('plotdirector:book-context-changed',e=>{root.dataset.book=String(e.detail.bookId);current=null;content.replaceChildren(element('p','Loading guidance for the selected book…'));collapse(true,false);load();});
window.addEventListener('pageshow',e=>{if(e.persisted)load();});measure();load();
})();

View File

@ -20,7 +20,7 @@
const subdued=new Map();
const setFocus = enabled => {
if(enabled){for(const node of document.querySelectorAll('.pd-application-header,.writer3-header,.writer3-reference')){if(!subdued.has(node))subdued.set(node,node.inert);node.inert=true;}}
if(enabled){for(const node of document.querySelectorAll('.pd-application-header,.writer3-header,.writer3-reference,.pd-investigation,.pd-investigation-splitter,.plotline-help-drawer,.plotline-help-splitter')){if(!subdued.has(node))subdued.set(node,node.inert);node.inert=true;}}
else{for(const [node,previous] of subdued)node.inert=previous;subdued.clear();}
root.dataset.focus = String(enabled);
const exit=root.querySelector('[data-reader-exit-focus]');if(exit)exit.hidden=true; // Link remains a no-script exit; the live toolbar has its own focus toggle.

View File

@ -559,7 +559,9 @@
}
})();
if (readBool(storage.pinned) && pinnedKey) {
openDrawer(pinnedKey, { keepCollapsed: true });
// Pinned contextual Help follows the current page when it declares an existing guide.
const pageGuide=document.querySelector('main h1 [data-help-key][data-help-url], [data-pwa-source] h1 [data-help-key][data-help-url]');
openDrawer(pageGuide?.dataset.helpKey || pinnedKey, { keepCollapsed: true });
}
})();