-- Disposable synthetic database only. New author/book fixture is always rolled back. IF DB_NAME()<>N'PlotDirector_Phase2_20261103_2305' OR NOT EXISTS(SELECT 1 FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true') THROW 51000,'Guarded synthetic target required',1; SET XACT_ABORT ON; BEGIN TRANSACTION; DECLARE @Level int,@User int,@Other int,@Project int,@Book int,@Preview uniqueidentifier=NEWID(); INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@capture.invalid',N'Capture fixture',N'not-a-credential');SET @User=SCOPE_IDENTITY(); INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@capture.invalid',N'Other capture fixture',N'not-a-credential');SET @Other=SCOPE_IDENTITY(); INSERT dbo.SubscriptionLevel(Name,DisplayName,MaxBooks,MaxChaptersPerBook,MaxScenesPerBook,MaxCharactersPerProject,MaxStorageMB,MaxCollaborators,SortOrder,RequiresStripeSubscription) VALUES(CONVERT(nvarchar(36),NEWID()),N'Capture fixture',2,100,100,100,100,0,0,0);SET @Level=SCOPE_IDENTITY(); INSERT dbo.UserSubscription(UserID,SubscriptionLevelID,IsActive,IsTrial,TrialExpiryDateUTC) VALUES(@User,@Level,1,1,'2030-01-01'); INSERT dbo.Projects(ProjectName) VALUES(N'Native capture fixture');SET @Project=SCOPE_IDENTITY(); INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@Project,@User,N'Owner',1); INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@Project,N'Native capture fixture',1,1);SET @Book=SCOPE_IDENTITY(); DECLARE @Chapter int,@Scene int,@Character int,@Knowledge int,@Manuscript uniqueidentifier=NEWID(),@SceneKey uniqueidentifier=NEWID(),@Paragraph uniqueidentifier=NEWID(),@Evidence uniqueidentifier=NEWID(),@Request uniqueidentifier=NEWID(); INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) SELECT @Book,1,N'Arrival',1,MIN(RevisionStatusID) FROM dbo.RevisionStatuses;SET @Chapter=SCOPE_IDENTITY(); INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) SELECT @Chapter,1,N'The letter',1,(SELECT MIN(TimeModeID) FROM dbo.TimeModes),(SELECT MIN(TimeConfidenceID) FROM dbo.TimeConfidences),(SELECT MIN(RevisionStatusID) FROM dbo.RevisionStatuses);SET @Scene=SCOPE_IDENTITY(); INSERT dbo.Characters(ProjectID,CharacterName) VALUES(@Project,N'Mira');SET @Character=SCOPE_IDENTITY(); INSERT dbo.CharacterKnowledge(CharacterID,SceneID,KnowledgeStateID,Description) SELECT @Character,@Scene,MIN(KnowledgeStateID),N'Understands the letter' FROM dbo.KnowledgeStates;SET @Knowledge=SCOPE_IDENTITY(); DECLARE @Payload nvarchar(max)=(SELECT 1 Version,@Book BookId,@Project ProjectId,@Manuscript ManuscriptId,N'Manual' Mode,NEWID() SessionId,3 WordRevision,N'synthetic-hash' SnapshotHash, JSON_QUERY((SELECT @SceneKey Id,@Scene CanonicalId,@Chapter ChapterId,N'The letter' Title,CAST(0 AS bit) Retired FOR JSON PATH)) Scenes, JSON_QUERY((SELECT JSON_QUERY((SELECT @Paragraph Id,0 Ordinal,N'The keeper handed Mira the letter.'+CHAR(13) Text,0 Start,34 [End],10 Outline FOR JSON PATH,WITHOUT_ARRAY_WRAPPER)) Occurrence,@SceneKey SceneId,@Chapter ChapterId,CAST(1 AS bit) Story,CAST(1 AS bit) PositionVerified FOR JSON PATH)) Paragraphs, JSON_QUERY((SELECT @Evidence Id,N'Knowledge' EventKind,@Knowledge EventId,CAST(1 AS bit) [Primary],N'Verified' State,@Paragraph StartParagraph,@Paragraph EndParagraph,@SceneKey CurrentScene FOR JSON PATH)) Evidence, JSON_QUERY((SELECT N'Knowledge' Kind,@Knowledge Id,@Scene SceneId FOR JSON PATH)) EventPositions FOR JSON PATH,WITHOUT_ARRAY_WRAPPER); CREATE TABLE #State(Payload nvarchar(max)); INSERT #State EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=-1,@RequestID=@Request,@Payload=@Payload; DECLARE @Onboarding int,@Build int; INSERT dbo.UserOnboardingState(UserID,ProjectID,BookID,CurrentStep,WritingSoftware,UsesWordCompanion) VALUES(@User,@Project,@Book,N'NextPathPreview',N'MicrosoftWord',1);SET @Onboarding=SCOPE_IDENTITY(); INSERT dbo.OnboardingManuscriptBuilds(PreviewID,UserID,ProjectID,BookID,Status,MarkerStatus) VALUES(@Preview,@User,@Project,@Book,N'Complete',N'NotRequested');SET @Build=SCOPE_IDENTITY(); INSERT dbo.OnboardingManuscriptBuildSceneMap(OnboardingManuscriptBuildID,TemporarySceneKey,SceneID) VALUES(@Build,N'scene-1',@Scene); INSERT dbo.CoreImportBasicLocationReviews(PreviewID,UserID,ProjectID,BookID,BuildID,Status,CompletedUtc) VALUES(@Preview,@User,@Project,@Book,@Build,N'Completed',SYSUTCDATETIME()); CREATE TABLE #Status(BookID int,ManuscriptID uniqueidentifier,Revision bigint,SnapshotHash nvarchar(100),Mode nvarchar(16),SessionId uniqueidentifier,WordRevision bigint,CanWrite bit,Paused bit); INSERT #Status EXEC dbo.ParagraphManuscript @Action='status',@UserID=@User,@BookID=@Book; IF NOT EXISTS(SELECT 1 FROM #Status WHERE Paused=1) THROW 51000,'Unfinished core review must remain protected',1; DECLARE @Before nvarchar(max)=(SELECT Payload FROM dbo.BookParagraphManuscripts WHERE BookID=@Book); EXEC dbo.UserOnboarding_CompleteCoreImport @UserID=@User,@OnboardingID=@Onboarding,@BookID=@Book,@PreviewID=@Preview; TRUNCATE TABLE #Status;INSERT #Status EXEC dbo.ParagraphManuscript @Action='status',@UserID=@User,@BookID=@Book; IF NOT EXISTS(SELECT 1 FROM #Status WHERE Paused=0) THROW 51000,'Core completion/Not now still locks saved book',1; IF @Before<>(SELECT Payload FROM dbo.BookParagraphManuscripts WHERE BookID=@Book) THROW 51000,'Completion changed paragraph snapshot',1; DECLARE @Completed datetime2=(SELECT OnboardingCompletedUtc FROM dbo.UserOnboardingState WHERE UserID=@User); EXEC dbo.UserOnboarding_CompleteCoreImport @UserID=@User,@OnboardingID=@Onboarding,@BookID=@Book,@PreviewID=@Preview; EXEC dbo.UserOnboarding_SetCurrentStep @UserID=@User,@CurrentStep=N'NextPathPreview'; IF (SELECT OnboardingCompletedUtc FROM dbo.UserOnboardingState WHERE UserID=@User)<>@Completed THROW 51000,'Optional navigation/reactivation changed completed core lifecycle',1; PRINT 'PASS core completion/Not now unlocks immediately, is idempotent, preserves paragraph identities and survives optional navigation'; DECLARE @Consent int,@Job uniqueidentifier=NEWID(); INSERT dbo.StoryIntelligenceConsents(UserID,UserOnboardingStateID,ProjectID,BookID,ConsentText) VALUES(@User,@Onboarding,@Project,@Book,N'Synthetic optional job regression');SET @Consent=SCOPE_IDENTITY(); INSERT dbo.StoryIntelligenceJobs(StoryIntelligenceJobID,StoryIntelligenceConsentID,UserID,ProjectID,BookID,Status) VALUES(@Job,@Consent,@User,@Project,@Book,N'Pending'); DECLARE @Stages table(Status nvarchar(40),Paused bit); INSERT @Stages VALUES('Pending',1),('Preparing',1),('ReadingScenes',1),('AnalysingCharacters',1),('AnalysingRelationships',1),('AnalysingLocations',1),('AnalysingAssets',1),('AnalysingTimeline',1),('Finalising',1),('Completed',0),('Failed',0),('Cancelled',0); DECLARE @Stage nvarchar(40),@Paused bit; DECLARE stages CURSOR LOCAL FAST_FORWARD FOR SELECT Status,Paused FROM @Stages; OPEN stages;FETCH NEXT FROM stages INTO @Stage,@Paused; WHILE @@FETCH_STATUS=0 BEGIN UPDATE dbo.StoryIntelligenceJobs SET Status=@Stage WHERE StoryIntelligenceJobID=@Job; TRUNCATE TABLE #Status;INSERT #Status EXEC dbo.ParagraphManuscript @Action='status',@UserID=@User,@BookID=@Book; IF NOT EXISTS(SELECT 1 FROM #Status WHERE Paused=@Paused) THROW 51000,'Optional analysis status incorrectly locks or unlocks completed core',1; FETCH NEXT FROM stages INTO @Stage,@Paused; END; CLOSE stages;DEALLOCATE stages; PRINT 'PASS later optional AI starts independently; active stages remain protected, successful/failed/cancelled optional jobs release protection'; -- Exercise real snapshot/structure persistence after optional cancellation, not just its status response. SET @Request=NEWID();TRUNCATE TABLE #State; INSERT #State EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=1,@RequestID=@Request,@Payload=@Payload; IF (SELECT Revision FROM dbo.BookParagraphManuscripts WHERE BookID=@Book)<>2 THROW 51000,'Completed core still refuses paragraph writes',1; PRINT 'PASS paragraph snapshot/structure save accepted after optional interrupted/cancelled work'; EXEC dbo.UserOnboarding_SaveBook @UserID=@User,@BookID=@Book; TRUNCATE TABLE #Status;INSERT #Status EXEC dbo.ParagraphManuscript @Action='status',@UserID=@User,@BookID=@Book; IF NOT EXISTS(SELECT 1 FROM #Status WHERE Paused=1) THROW 51000,'Explicit new import lost protection',1; PRINT 'PASS explicit new core import reactivates protection while ordinary navigation does not'; DECLARE @SecondBook int,@Refused bit=0; INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@Project,N'Separate new import',2,2);SET @SecondBook=SCOPE_IDENTITY(); EXEC dbo.UserOnboarding_SaveBook @UserID=@User,@BookID=@SecondBook; BEGIN TRY EXEC dbo.UserOnboarding_CompleteCoreImport @UserID=@User,@OnboardingID=@Onboarding,@BookID=@Book,@PreviewID=@Preview;END TRY BEGIN CATCH IF ERROR_MESSAGE()='Core import context changed or required review is incomplete' SET @Refused=1;ELSE THROW;END CATCH; IF @Refused<>1 THROW 51000,'Stale core completion finished another book import',1; IF @@TRANCOUNT>0 ROLLBACK; IF EXISTS(SELECT 1 FROM dbo.AppUser WHERE UserID=@User) THROW 51000,'Fixture failed to roll back',1; PRINT 'PASS stale completion cannot finish a different book import; isolated fixture rolled back';