Complete core import independently of optional Story Intelligence

This commit is contained in:
Nick Beckley 2026-11-07 23:13:57 +00:00
parent 1048e193fd
commit 05e779f1af
10 changed files with 241 additions and 5 deletions

View File

@ -0,0 +1,24 @@
# Core import completion and paragraph synchronisation — 7 November 2026
## Cause and correction
Windows qualification commit `1048e193fd6555e21c1ce28f19ddb0fb4e30d39c` reproduced the defect with Companion 1.0.0.18 and disposable Development book **10151**, project **8173**. Character finalisation recorded `CoreImportComplete` in the in-memory review/build result, but never completed the persistent `UserOnboardingState`. The “Not now” link only navigated to the project. The paragraph write/status guards correctly saw the null completion timestamp as unfinished core import and refused saves and structure changes.
`OnboardingService.FinaliseCharacterReviewAsync` now completes the persistent lifecycle after all required character alias/mapping/POV work succeeds, before publishing the success result. The existing onboarding repository calls new stored procedure `UserOnboarding_CompleteCoreImport`; it validates the exact user, wizard, book, preview, owner authority, built scene mappings and completed location review. Completion is idempotent and cannot finish another book selected meanwhile. The completion page also reads the persistent timestamp when cached review results have disappeared.
Forward migration **242_CoreImportCompletion.sql** adds that procedure and corrects `UserOnboarding_SetCurrentStep`: navigation preserves completion. Explicit new setup/import actions still reset completion through the existing SaveWritingJourney/SaveBook operations. “Not now” needs no additional persistence action because core import has already finished. The stale “update Word” chapter-review toast now says “detect and import scenes”; no Word prose rewrite is implied.
Optional Story Intelligence remains separately book/job scoped. It can be started later through the existing book action. Pending/preparing/reading/analysing/finalising jobs retain the existing write protection; completed, failed and cancelled jobs do not. An interrupted job that is still genuinely active/recovering is not bypassed or force-cancelled. Neither optional analysis failure nor ordinary navigation reopens the completed core lifecycle. No existing job/import is modified by the migration.
## Verification
- Solution build: zero warnings/errors.
- Managed core completion regressions: required review/mapping failures cannot announce completion; real finalisation invokes scoped persistent completion without optional AI; retries preserve the timestamp; completion display recovers from cache loss.
- Full application regression harness: **455 passing checks**.
- Existing guarded synthetic SQL fixture: real completion and paragraph procedures verify Not now/optional navigation, later AI start, all active job stages, completed/failed/cancelled states, subsequent paragraph saves, explicit new-import protection and stale cross-book refusal. Entire fixture rolls back.
- Development **10151**: its already completed core import is repaired using the same scoped procedure, after backup. Only the onboarding completion timestamp/current step is repaired; paragraph/prose/chapter/scene data are retained.
- A separate exact-book rollback-only probe checks owner write status, persists its current snapshot and materialises a scene split, then rolls everything back and verifies the exact original paragraph payload and scene count. This is server persistence qualification, not live Word cursor following or proof of a new laptop save transfer.
No Companion source, installer, Production data, Reckoning import or Story Intelligence job is changed. No Word cursor-following success is claimed. Windows Codex should now save the disposable fixture, synchronise, test scene following and exercise structure controls.
Deployment identifiers and final running-site evidence are recorded below after publishing.

View File

@ -0,0 +1,41 @@
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
internal static class CoreImportCompletionTests
{
public static async Task Run()
{
var preview = new ManuscriptScanPreview { PreviewID=Guid.NewGuid(),UserID=7,OnboardingID=8,ProjectID=9,BookID=10,Chapters=[new(){TemporaryChapterKey="chapter-1",Title="Arrival"}] };
var state = new UserOnboardingState {UserID=7,UserOnboardingStateID=8,ProjectID=9,BookID=10,WritingSoftware=WritingSoftwareValues.MicrosoftWord};
var review=new ManuscriptScanReviewDecision{PreviewID=preview.PreviewID,Chapters=[new(){TemporaryChapterKey="chapter-1",ChapterNumber=1,Title="Arrival",Include=true}]};
var result=new OnboardingManuscriptBuildResult{BuildID=11,PreviewID=preview.PreviewID,ProjectID=9,BookID=10,SceneMappings=[new(){SceneID=12}]};
bool reviewReady=true,failMapping=false;int completions=0;
var calls=new List<string>();
var onboarding=NativeWorkflowTests.Proxy<IOnboardingRepository>((n,a)=>n switch {
"GetAsync"=>(object)Task.FromResult<UserOnboardingState?>(state),
"CompleteCoreImportAsync"=>Complete(a!),_=>throw new Exception(n)});
Task<UserOnboardingState> Complete(object?[] a){if((int)a[0]!!=7||(int)a![1]!!=8||(int)a[2]!!=10||(Guid)a[3]!!=preview.PreviewID)throw new Exception("Wrong core completion scope");state.OnboardingCompletedUtc??=DateTime.UtcNow;completions++;calls.Add("complete");return Task.FromResult(state);}
var scans=NativeWorkflowTests.Proxy<IManuscriptScanPreviewStore>((n,a)=>n switch {
"GetPreviewAsync"=>Task.FromResult<ManuscriptScanPreview?>(preview),"GetReviewAsync"=>Task.FromResult<ManuscriptScanReviewDecision?>(review),
"GetBuildResultAsync"=>Task.FromResult<OnboardingManuscriptBuildResult?>(result),
"SaveReviewAsync"=>Task.FromResult<ManuscriptScanReviewDecision?>((ManuscriptScanReviewDecision)a![1]!),
"SaveBuildResultAsync"=>Task.FromResult<OnboardingManuscriptBuildResult?>((OnboardingManuscriptBuildResult)a![1]!),_=>throw new Exception(n)});
var people=NativeWorkflowTests.Proxy<ICharacterRepository>((n,a)=>n=="ListCharactersAsync"?Task.FromResult<IReadOnlyList<Character>>(Array.Empty<Character>()):throw new Exception(n));
var projects=NativeWorkflowTests.Proxy<IProjectRepository>((n,a)=>Task.FromResult<Project?>(new(){ProjectID=9,AccessRole="Owner"}));
var books=NativeWorkflowTests.Proxy<IBookRepository>((n,a)=>Task.FromResult<Book?>(new(){BookID=10,ProjectID=9}));
var chapters=NativeWorkflowTests.Proxy<IChapterRepository>((n,a)=>Task.FromResult<IReadOnlyList<Chapter>>(Array.Empty<Chapter>()));
var locations=NativeWorkflowTests.Proxy<ICoreImportBasicLocationService>((n,a)=>Task.FromResult(reviewReady));
var mapping=NativeWorkflowTests.Proxy<ICoreImportCharacterMappingService>((n,a)=>{calls.Add("map");return failMapping?Task.FromException<CoreImportCharacterMappingResult>(new InvalidOperationException("interrupted required mapping")):Task.FromResult(new CoreImportCharacterMappingResult(0,0));});
var user=NativeWorkflowTests.Proxy<ICurrentUserService>((n,a)=>n=="get_UserId"?(int?)7:throw new Exception(n));
var deps=new Dictionary<Type,object>{{typeof(IOnboardingRepository),onboarding},{typeof(IManuscriptScanPreviewStore),scans},{typeof(ICharacterRepository),people},{typeof(IProjectRepository),projects},{typeof(IBookRepository),books},{typeof(IChapterRepository),chapters},{typeof(ICoreImportBasicLocationService),locations},{typeof(ICoreImportCharacterMappingService),mapping},{typeof(ICurrentUserService),user}};
var ctor=typeof(OnboardingService).GetConstructors().Single();var service=(OnboardingService)ctor.Invoke(ctor.GetParameters().Select(p=>deps.GetValueOrDefault(p.ParameterType)).ToArray());
reviewReady=false;await Refuses(()=>service.FinaliseCharacterReviewAsync(new(){PreviewID=preview.PreviewID}));Check(completions==0,"required location review cannot release active core import");
reviewReady=true;failMapping=true;await Refuses(()=>service.FinaliseCharacterReviewAsync(new(){PreviewID=preview.PreviewID}));Check(completions==0&&calls.Contains("map"),"interrupted required mapping cannot publish completion");
failMapping=false;var finished=await service.FinaliseCharacterReviewAsync(new(){PreviewID=preview.PreviewID});Check(finished?.Status=="CoreImportComplete"&&state.OnboardingCompletedUtc.HasValue&&calls.Last()=="complete","real character finalisation persists scoped core completion without any optional AI call");
var completedAt=state.OnboardingCompletedUtc;await service.FinaliseCharacterReviewAsync(new(){PreviewID=preview.PreviewID});Check(state.OnboardingCompletedUtc==completedAt,"repeated core completion preserves completed identity and timestamp");
result.Status="Complete";Check((await service.GetBuildResultAsync(preview.PreviewID))?.Status=="CoreImportComplete","completion page recovers durable state after cached review result is lost");
}
private static async Task Refuses(Func<Task<OnboardingManuscriptBuildResult?>> work){try{await work();throw new Exception("Expected refusal");}catch(InvalidOperationException){}}
private static void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);}
}

View File

@ -129,6 +129,7 @@ if(args.Contains("--native-installation")){await NativeInstallationTests.Run();C
if(args.Contains("--paragraph-view")){await ParagraphViewTests.Run();return;}
if(args.Contains("--paragraph-live-ai")){await ParagraphLiveAiTests.Run();return;}
if(args.Contains("--paragraph-backups")){ParagraphBackupTests.Run();return;}
if(args.Contains("--core-import-completion")){await CoreImportCompletionTests.Run();return;}
if(args.Contains("--paragraph-manuscripts")){ParagraphBackupTests.Run();ParagraphManuscriptTests.Run();await ParagraphWorkflowTests.Run();return;}
if(args.Contains("--native-import-corrections")){await NativeImportCorrectionTests.Run();return;}
if(args.Contains("--native-captured-evidence")){await NativeImportCorrectionTests.CapturedEvidence(args[1],args[2]);return;}

View File

@ -0,0 +1,78 @@
-- 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';

View File

@ -0,0 +1,41 @@
-- Explicitly authorised disposable Windows qualification book. All write probes roll back.
IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Development required',1;
SET NOCOUNT ON;SET XACT_ABORT ON;
DECLARE @Book int=10151,@Project int=8173,@User int;
IF NOT EXISTS(SELECT 1 FROM dbo.Books WHERE BookID=@Book AND ProjectID=@Project AND BookTitle LIKE N'%QA%') THROW 51000,'Disposable QA book identity mismatch',1;
SELECT @User=UserID FROM dbo.ProjectUserAccess WHERE ProjectID=@Project AND AccessRole=N'Owner' AND IsActive=1;
IF @User IS NULL THROW 51000,'QA owner missing',1;
DECLARE @Original nvarchar(max),@Revision bigint,@SceneCount int;
SELECT @Original=Payload,@Revision=Revision FROM dbo.BookParagraphManuscripts WHERE BookID=@Book;
IF @Original IS NULL OR (SELECT COUNT(*) FROM OPENJSON(@Original,'$.Paragraphs'))<>9 THROW 51000,'Expected qualified nine-paragraph snapshot',1;
SELECT @SceneCount=COUNT(*) FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@Book;
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=0 AND CanWrite=1) THROW 51000,'QA book remains paused',1;
PRINT 'PASS book 10151 owner can write and core import no longer pauses synchronisation';
BEGIN TRANSACTION;
CREATE TABLE #Saved(Payload nvarchar(max));
DECLARE @Request uniqueidentifier=NEWID();
INSERT #Saved EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=@Revision,@RequestID=@Request,@Payload=@Original;
IF (SELECT Revision FROM dbo.BookParagraphManuscripts WHERE BookID=@Book)<>@Revision+1 THROW 51000,'QA snapshot save refused',1;
DECLARE @Payload nvarchar(max)=(SELECT Payload FROM #Saved),@NewScene uniqueidentifier=NEWID(),@Chapter int,@Paragraph int;
-- Split at a body paragraph while retaining at least one preceding paragraph in its scene.
SELECT TOP(1) @Paragraph=CONVERT(int,p.[key]),@Chapter=TRY_CONVERT(int,JSON_VALUE(p.value,'$.ChapterId'))
FROM OPENJSON(@Payload,'$.Paragraphs') p
WHERE JSON_VALUE(p.value,'$.Story')='true' AND JSON_VALUE(p.value,'$.SceneId') IS NOT NULL
AND EXISTS(SELECT 1 FROM OPENJSON(@Payload,'$.Paragraphs') earlier WHERE CONVERT(int,earlier.[key])<CONVERT(int,p.[key]) AND JSON_VALUE(earlier.value,'$.SceneId')=JSON_VALUE(p.value,'$.SceneId'))
ORDER BY CONVERT(int,p.[key]);
IF @Paragraph IS NULL THROW 51000,'QA fixture has no splittable scene',1;
SET @Payload=JSON_MODIFY(@Payload,'append $.Scenes',JSON_QUERY((SELECT @NewScene Id,0 CanonicalId,@Chapter ChapterId,N'Rollback-only qualification split' Title,CAST(0 AS bit) Retired FOR JSON PATH,WITHOUT_ARRAY_WRAPPER)));
DECLARE @PriorScene nvarchar(36)=JSON_VALUE(@Payload,CONCAT('$.Paragraphs[',@Paragraph,'].SceneId')),@Index int;
DECLARE affected CURSOR LOCAL FAST_FORWARD FOR SELECT CONVERT(int,[key]) FROM OPENJSON(@Payload,'$.Paragraphs') WHERE CONVERT(int,[key])>=@Paragraph AND JSON_VALUE(value,'$.SceneId')=@PriorScene;
OPEN affected;FETCH NEXT FROM affected INTO @Index;
WHILE @@FETCH_STATUS=0 BEGIN DECLARE @Path nvarchar(100)=CONCAT('$.Paragraphs[',@Index,'].SceneId');SET @Payload=JSON_MODIFY(@Payload,@Path,CONVERT(nvarchar(36),@NewScene));FETCH NEXT FROM affected INTO @Index;END;
CLOSE affected;DEALLOCATE affected;
SET @Request=NEWID();TRUNCATE TABLE #Saved;SET @Revision=@Revision+1;
INSERT #Saved EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=@Revision,@RequestID=@Request,@Payload=@Payload;
IF (SELECT COUNT(*) FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@Book)<>@SceneCount+1 THROW 51000,'QA split refused',1;
PRINT 'PASS book 10151 accepts snapshot persistence and canonical scene split within rollback-only transaction';
ROLLBACK;
IF (SELECT Payload FROM dbo.BookParagraphManuscripts WHERE BookID=@Book)<>@Original OR (SELECT COUNT(*) FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@Book)<>@SceneCount THROW 51000,'QA probe did not restore original snapshot and scenes',1;
PRINT 'PASS book 10151 remains unchanged: original paragraph GUIDs, prose, snapshot revision, chapters and scenes retained';

View File

@ -837,7 +837,7 @@ public sealed class OnboardingController(
}
TempData["OnboardingReviewMessage"] = readyToImport
? "Chapter review saved. Next: import scenes and update Word."
? "Chapter review saved. Next: detect and import scenes."
: continueToCharacters ? "Chapter and scene review saved. Next: review detected characters."
: continueCharacterReview || backCharacterReview ? "Character review choices saved."
: "Review choices saved.";

View File

@ -15,6 +15,7 @@ public interface IOnboardingRepository
Task<UserOnboardingState> SaveProjectAsync(int userId, int projectId);
Task<UserOnboardingState> SaveBookAsync(int userId, int bookId);
Task<UserOnboardingState> MarkCompletedAsync(int userId);
Task<UserOnboardingState> CompleteCoreImportAsync(int userId, int onboardingId, int bookId, Guid previewId);
Task<bool> ShouldShowWordCompanionHeaderAsync(int userId);
}
@ -112,6 +113,15 @@ public sealed class OnboardingRepository(ISqlConnectionFactory connectionFactory
commandType: CommandType.StoredProcedure);
}
public async Task<UserOnboardingState> CompleteCoreImportAsync(int userId, int onboardingId, int bookId, Guid previewId)
{
using var connection = connectionFactory.CreateConnection();
return await connection.QuerySingleAsync<UserOnboardingState>(
"dbo.UserOnboarding_CompleteCoreImport",
new { UserID = userId, OnboardingID = onboardingId, BookID = bookId, PreviewID = previewId },
commandType: CommandType.StoredProcedure);
}
public async Task<bool> ShouldShowWordCompanionHeaderAsync(int userId)
{
using var connection = connectionFactory.CreateConnection();

View File

@ -308,7 +308,7 @@ public sealed class OnboardingManuscriptBuildResult
public int ProjectID { get; init; }
public int BookID { get; init; }
public int? ManuscriptDocumentID { get; init; }
public string Status { get; init; } = "Built";
public string Status { get; set; } = "Built";
public string MarkerStatus { get; init; } = "Pending";
public int ChaptersCreated { get; init; }
public int ScenesCreated { get; init; }

View File

@ -1010,8 +1010,12 @@ public sealed class OnboardingService(
public async Task<OnboardingManuscriptBuildResult?> GetBuildResultAsync(Guid previewId)
{
var userId = RequireUserId();
return await scanPreviews.GetBuildResultAsync(userId, previewId)
var result = await scanPreviews.GetBuildResultAsync(userId, previewId)
?? await builds.GetByPreviewAsync(userId, previewId);
var state = await onboarding.GetAsync(userId);
if (result is not null && state?.BookID == result.BookID && state.ProjectID == result.ProjectID && state.OnboardingCompletedUtc.HasValue)
result.Status = "CoreImportComplete";
return result;
}
public async Task<OnboardingManuscriptBuildResult?> FinaliseCharacterReviewAsync(ManuscriptScanReviewForm form)
@ -1144,11 +1148,13 @@ public sealed class OnboardingService(
MarkerWarning = build.MarkerWarning
};
await scanPreviews.SaveReviewAsync(userId, completedReview);
await scanPreviews.SaveBuildResultAsync(userId, completedResult);
await AddScanCharacterAliasesAsync(completedReview, completedResult);
await coreImportCharacterMapping.MapBookAsync(preview.ProjectID, preview.BookID);
await ResolvePersistedStructuralPovAsync(preview.ProjectID, preview.BookID);
// Core import owns this lifecycle. Optional AI work has its own job state and may run later.
await onboarding.CompleteCoreImportAsync(userId, preview.OnboardingID, preview.BookID, preview.PreviewID);
await scanPreviews.SaveReviewAsync(userId, completedReview);
await scanPreviews.SaveBuildResultAsync(userId, completedResult);
return completedResult;
}

View File

@ -0,0 +1,35 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
-- Final character review is the end of core import, not the start of an optional AI job.
-- Scope completion to the original wizard/book so a stale browser cannot finish another import.
CREATE OR ALTER PROCEDURE dbo.UserOnboarding_CompleteCoreImport
@UserID int,@OnboardingID int,@BookID int,@PreviewID uniqueidentifier
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
BEGIN TRANSACTION;
IF NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole=N'Owner'
JOIN dbo.UserOnboardingState o WITH(UPDLOCK,HOLDLOCK) ON o.UserID=@UserID AND o.UserOnboardingStateID=@OnboardingID AND o.BookID=b.BookID AND o.ProjectID=b.ProjectID
WHERE b.PreviewID=@PreviewID AND b.UserID=@UserID AND b.BookID=@BookID AND b.Status IN ('Built','Complete')
AND EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuildSceneMap m WHERE m.OnboardingManuscriptBuildID=b.OnboardingManuscriptBuildID)
AND EXISTS(SELECT 1 FROM dbo.CoreImportBasicLocationReviews r WHERE r.PreviewID=@PreviewID AND r.UserID=@UserID AND r.BookID=@BookID AND r.CompletedUtc IS NOT NULL))
BEGIN ROLLBACK;THROW 51000,'Core import context changed or required review is incomplete',1;END;
UPDATE dbo.UserOnboardingState SET CurrentStep=N'Complete',OnboardingCompletedUtc=COALESCE(OnboardingCompletedUtc,SYSUTCDATETIME()),UpdatedUtc=SYSUTCDATETIME()
WHERE UserID=@UserID AND UserOnboardingStateID=@OnboardingID AND BookID=@BookID;
COMMIT;
EXEC dbo.UserOnboarding_Get @UserID=@UserID;
END;
GO
-- Navigation is not a new import. Explicit setup/SaveBook actions already reset completion.
CREATE OR ALTER PROCEDURE dbo.UserOnboarding_SetCurrentStep @UserID int,@CurrentStep nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.UserOnboardingState WHERE UserID=@UserID) INSERT dbo.UserOnboardingState(UserID) VALUES(@UserID);
UPDATE dbo.UserOnboardingState SET CurrentStep=@CurrentStep,
OnboardingCompletedUtc=CASE WHEN @CurrentStep=N'Complete' THEN COALESCE(OnboardingCompletedUtc,SYSUTCDATETIME()) ELSE OnboardingCompletedUtc END,
UpdatedUtc=SYSUTCDATETIME() WHERE UserID=@UserID;
EXEC dbo.UserOnboarding_Get @UserID=@UserID;
END;
GO