Reject stale investigation guidance after a book changes project

This commit is contained in:
Nick Beckley 2026-11-17 23:59:36 +00:00
parent 5ebb9f82e8
commit 7177740ffb
3 changed files with 76 additions and 2 deletions

View File

@ -18,7 +18,7 @@ const base=live?'https://dev.plotdirector.com':'http://127.0.0.1:5238',out=proce
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');
await p.route('**/InvestigationCompanion/Update',r=>r.fulfill({status:503,json:{message:'Simulated unconfirmed progress save; previous state retained.'}}));await first.locator('select').selectOption('Skipped');await root.locator('[data-guidance-message]').filter({hasText:'unconfirmed progress'}).waitFor();assert.equal(await first.locator('select').inputValue(),'Done');await p.unroute('**/InvestigationCompanion/Update');
await p.route('**/InvestigationCompanion/Update',r=>r.fulfill({status:503,json:{message:'Simulated unconfirmed progress save; previous state retained.'}}));await first.locator('select').selectOption('Skipped');await root.locator('[data-guidance-message]').filter({hasText:'unconfirmed progress'}).waitFor();assert.equal(await first.locator('select').inputValue(),'Done');await p.unroute('**/InvestigationCompanion/Update');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 p.locator('[data-guidance-resize]').focus();for(let n=0;n<12;n++)await p.keyboard.press('ArrowRight');await p.setViewportSize({width:1100,height:1000});await p.waitForTimeout(200);assert((await p.locator('.plotline-help-main').boundingBox()).width>=560);assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));if(live)assert(await p.locator('.plot-workspace-controls').evaluate(n=>{const r=n.closest('.plotline-help-main').getBoundingClientRect();return [...n.querySelectorAll('input:not([type=hidden]),select,button')].every(c=>{const b=c.getBoundingClientRect();return b.left>=r.left&&b.right<=r.right;});}));await snap('Both-panels-minimum-centre');await p.setViewportSize({width:1440,height:1000});for(let n=0;n<12;n++)await p.keyboard.press('ArrowLeft');
@ -31,7 +31,7 @@ const base=live?'https://dev.plotdirector.com':'http://127.0.0.1:5238',out=proce
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.locator('[data-guidance-expand]').click();const resume=await q.getByRole('link',{name:'Open saved investigations',exact:true}).getAttribute('href');assert.equal(new URL(resume).searchParams.get('bookId'),String(w.otherBook));
// In-page book context changes use the same event as Calendar/At This Point and recheck server scope.
await q.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:book-context-changed',{detail:{bookId:0}})));await q.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('Choose a book'));await q.locator('[data-guidance-expand]').click();assert(!(new URL(await q.getByRole('link',{name:'Choose a book in Writer to resume an investigation'}).getAttribute('href'))).searchParams.has('bookId'));
await q.evaluate(book=>document.dispatchEvent(new CustomEvent('plotdirector:book-context-changed',{detail:{bookId:book}})),w.book);await q.locator('#guidance-finding').waitFor();
await q.evaluate(book=>{const url=new URL(location.href);url.searchParams.set('bookId',String(book));history.replaceState(history.state,'',url);document.dispatchEvent(new CustomEvent('plotdirector:book-context-changed',{detail:{bookId:book}}));},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);

View File

@ -0,0 +1,30 @@
-- Rollback-only fixtures; no existing author/project/book is changed.
IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Wrong database',1;
IF EXISTS(SELECT 1 FROM dbo.AppUser WHERE Email=N'phase15-book-move@example.invalid') THROW 51000,'Fixture account already exists',1;
BEGIN TRY
BEGIN TRANSACTION;
EXEC dbo.User_Create @Email=N'phase15-book-move@example.invalid',@DisplayName=N'Disposable book scope fixture',@PasswordHash=N'DISABLED-TEST-USER',@EmailConfirmed=1;
DECLARE @u int=(SELECT UserID FROM dbo.AppUser WHERE Email=N'phase15-book-move@example.invalid');
EXEC dbo.Project_Save @ProjectName=N'Disposable book scope source',@UserID=@u;
DECLARE @source int=(SELECT ProjectID FROM dbo.ProjectUserAccess WHERE UserID=@u);
EXEC dbo.Book_Save @ProjectID=@source,@BookTitle=N'Disposable book scope book',@BookNumber=1;
DECLARE @b int=(SELECT BookID FROM dbo.Books WHERE ProjectID=@source),@id uniqueidentifier=NEWID();
DECLARE @catalogue varchar(80)=(SELECT TOP(1) Version FROM dbo.WriterInvestigationCatalogues ORDER BY PublishedUtc DESC);
DECLARE @json nvarchar(max)=(SELECT @id ID,@u UserID,@source ProjectID,@b BookID,@catalogue CatalogueVersion,1 Version,JSON_QUERY('[]') Answers FOR JSON PATH,WITHOUT_ARRAY_WRAPPER);
EXEC dbo.WriterInvestigation @Action='save',@UserID=@u,@BookID=@b,@ProjectID=@source,@ID=@id,@CatalogueVersion=@catalogue,@ExpectedVersion=0,@Json=@json,@Event=N'{"operation":"scope-fixture","evaluation":{"Outcome":"InsufficientEvidence","Recommendations":[]}}';
EXEC dbo.WriterInvestigationGuidanceState @Action='activate',@UserID=@u,@BookID=@b,@ID=@id,@ExpectedVersion=0,@Json=N'{}';
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=@b,@ProjectID=@source;
IF (SELECT COUNT(*) FROM @r)<>1 THROW 51000,'Valid source guidance missing',1;
DELETE @r;
EXEC dbo.Project_Save @ProjectName=N'Disposable book scope destination',@UserID=@u;
DECLARE @destination int=(SELECT ProjectID FROM dbo.ProjectUserAccess WHERE UserID=@u AND ProjectID<>@source);
UPDATE dbo.Books SET ProjectID=@destination WHERE BookID=@b;
INSERT @r EXEC dbo.WriterInvestigationGuidanceState @Action='read',@UserID=@u,@BookID=@b,@ProjectID=@source;
IF EXISTS(SELECT 1 FROM @r) THROW 51000,'Moved book leaked stale source context',1;
INSERT @r EXEC dbo.WriterInvestigationGuidanceState @Action='read',@UserID=@u,@BookID=@b,@ProjectID=@destination;
IF EXISTS(SELECT 1 FROM @r) THROW 51000,'Moved book relabelled an old investigation',1;
ROLLBACK;
END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH;
IF EXISTS(SELECT 1 FROM dbo.AppUser WHERE Email=N'phase15-book-move@example.invalid') THROW 51000,'Fixture rollback failed',1;
SELECT 'PASS moved-book guidance scoping and complete fixture rollback' Result;

View File

@ -0,0 +1,44 @@
-- Forward-only scope hardening: moved books cannot retain stale project guidance access.
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.ProjectID=i.ProjectID 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.ProjectID=i.ProjectID 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