diff --git a/PlotLine.Tests/Browser/investigation-companion.cjs b/PlotLine.Tests/Browser/investigation-companion.cjs
new file mode 100644
index 00000000..0b01bf2e
--- /dev/null
+++ b/PlotLine.Tests/Browser/investigation-companion.cjs
@@ -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});
diff --git a/PlotLine.Tests/Browser/writer-layout-phase1.cjs b/PlotLine.Tests/Browser/writer-layout-phase1.cjs
index 4228d647..149078f3 100644
--- a/PlotLine.Tests/Browser/writer-layout-phase1.cjs
+++ b/PlotLine.Tests/Browser/writer-layout-phase1.cjs
@@ -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:`Enter`}));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=[];
diff --git a/PlotLine.Tests/InvestigationGuidanceTests.cs b/PlotLine.Tests/InvestigationGuidanceTests.cs
new file mode 100644
index 00000000..25188549
--- /dev/null
+++ b/PlotLine.Tests/InvestigationGuidanceTests.cs
@@ -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{{"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 rows=[];
+ public async Task 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);
+ }
+}
diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs
index 170c4f50..a4d30818 100644
--- a/PlotLine.Tests/Program.cs
+++ b/PlotLine.Tests/Program.cs
@@ -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()),
diff --git a/PlotLine.Tests/Sql/InvestigationGuidanceRegression.sql b/PlotLine.Tests/Sql/InvestigationGuidanceRegression.sql
new file mode 100644
index 00000000..34665be4
--- /dev/null
+++ b/PlotLine.Tests/Sql/InvestigationGuidanceRegression.sql
@@ -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;
diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs
index 6effb445..8bb4935a 100644
--- a/PlotLine.Tests/ToolbarBrowserHost.cs
+++ b/PlotLine.Tests/ToolbarBrowserHost.cs
@@ -129,6 +129,9 @@ internal static class ToolbarBrowserHost
builder.Services.AddSignalR();
builder.Services.AddScoped();
builder.Services.AddSingleton();
+ builder.Services.AddSingleton();
+ builder.Services.AddMemoryCache();
+ builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton();
diff --git a/PlotLine/Controllers/InvestigationCompanionController.cs b/PlotLine/Controllers/InvestigationCompanionController.cs
new file mode 100644
index 00000000..37420067
--- /dev/null
+++ b/PlotLine/Controllers/InvestigationCompanionController.cs
@@ -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 Guard(Func> 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().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 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 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 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 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);});
+}
diff --git a/PlotLine/Controllers/WriterInvestigationsController.cs b/PlotLine/Controllers/WriterInvestigationsController.cs
index 94723467..494768a0 100644
--- a/PlotLine/Controllers/WriterInvestigationsController.cs
+++ b/PlotLine/Controllers/WriterInvestigationsController.cs
@@ -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 IsAdmin()=> (await HttpContext.RequestServices.GetRequiredService().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 Guard(Func> 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 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 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 Admin()=>Guard(async()=>View("Admin",await repository.Catalogue()));
diff --git a/PlotLine/Data/InvestigationGuidanceRepository.cs b/PlotLine/Data/InvestigationGuidanceRepository.cs
new file mode 100644
index 00000000..abe23078
--- /dev/null
+++ b/PlotLine/Data/InvestigationGuidanceRepository.cs
@@ -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 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 Read(int user,int? project,int? book,Guid? id=null){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync("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);}
+}
diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs
index 523a613d..21042bf7 100644
--- a/PlotLine/Program.cs
+++ b/PlotLine/Program.cs
@@ -142,6 +142,8 @@ public class Program
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
+ builder.Services.AddScoped();
+ builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
diff --git a/PlotLine/Services/Investigations/InvestigationGuidanceService.cs b/PlotLine/Services/Investigations/InvestigationGuidanceService.cs
new file mode 100644
index 00000000..4b9ad4e8
--- /dev/null
+++ b/PlotLine/Services/Investigations/InvestigationGuidanceService.cs
@@ -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 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 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 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(r.InvestigationJson,CatalogueValidator.Json)!,r.EvaluationJson==null?null:JsonSerializer.Deserialize(r.EvaluationJson,CatalogueValidator.Json),r.GuidanceJson==null?new():JsonSerializer.Deserialize(r.GuidanceJson,CatalogueValidator.Json)??new());
+ public async Task 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 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;
+ }
+}
diff --git a/PlotLine/Sql/275_InvestigationGuidance.sql b/PlotLine/Sql/275_InvestigationGuidance.sql
new file mode 100644
index 00000000..090a84fb
--- /dev/null
+++ b/PlotLine/Sql/275_InvestigationGuidance.sql
@@ -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
diff --git a/PlotLine/Sql/276_InvestigationGuidanceProcedure.sql b/PlotLine/Sql/276_InvestigationGuidanceProcedure.sql
new file mode 100644
index 00000000..000b837a
--- /dev/null
+++ b/PlotLine/Sql/276_InvestigationGuidanceProcedure.sql
@@ -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
diff --git a/PlotLine/Views/InvestigationCompanion/Failure.cshtml b/PlotLine/Views/InvestigationCompanion/Failure.cshtml
new file mode 100644
index 00000000..844220d0
--- /dev/null
+++ b/PlotLine/Views/InvestigationCompanion/Failure.cshtml
@@ -0,0 +1,5 @@
+@{ViewData["Title"]="Investigation guidance";}
+
We couldn't open that suggestion
+
@ViewData["Failure"]
+
Your saved investigation and confirmed progress are retained.
+Return to the full investigation
diff --git a/PlotLine/Views/Shared/_ApplicationShell.cshtml b/PlotLine/Views/Shared/_ApplicationShell.cshtml
index 888316ac..f80beb77 100644
--- a/PlotLine/Views/Shared/_ApplicationShell.cshtml
+++ b/PlotLine/Views/Shared/_ApplicationShell.cshtml
@@ -113,7 +113,6 @@
-
@foreach (var category in ApplicationRibbon.Categories)
{
@@ -128,6 +127,7 @@
+
Navigation
@foreach (var category in ApplicationRibbon.Categories)
{
We've reached the question limit for this test. You can still change earlier answers or save and return later.
}
@foreach(var id in state.Recommendations){var h=Model.Catalogue.Hypotheses.Single(h=>h.Id==id);
@h.Summary
@h.Reason
@h.Uncertainty
Answers that informed this suggestion:
@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);