-- Forward repair: native-ID adoption also updates the existing full-snapshot digest. SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON; GO CREATE OR ALTER PROCEDURE dbo.BookChapterSync @Action varchar(16),@UserID int,@BookID int,@ChapterID int=NULL,@SessionID uniqueidentifier=NULL,@ManuscriptID uniqueidentifier=NULL,@WordRevision bigint=NULL, @ExpectedRevision bigint=NULL,@RequestID uniqueidentifier=NULL,@Checkpoint nvarchar(max)=NULL,@Positions nvarchar(max)=NULL,@Bindings nvarchar(max)=NULL,@Position int=NULL,@SceneID int=NULL,@ParagraphID uniqueidentifier=NULL,@SnapshotHash char(64)=NULL AS BEGIN SET NOCOUNT ON;SET XACT_ABORT ON; DECLARE @ProjectID int; SELECT @ProjectID=b.ProjectID FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID; IF @ProjectID IS NULL THROW 51000,'Book access denied',1; IF @Action='list' BEGIN SELECT ChapterID,SessionID,WordRevision,ContentHash,IdentityHash,MappingHash,SourceRevision,ValidatedUtc,(SELECT MIN(p.StartPosition) FROM OPENJSON(Positions) WITH(StartPosition int '$.Start') p) StartPosition,(SELECT MAX(p.EndPosition) FROM OPENJSON(Positions) WITH(EndPosition int '$.End') p) EndPosition FROM dbo.BookChapterValidations WHERE BookID=@BookID AND UserID=@UserID AND SessionID=@SessionID AND WordRevision=@WordRevision AND ExpiresUtc>SYSUTCDATETIME();RETURN;END; IF @Action='scene-start' BEGIN SELECT TOP(1) CAST(1 AS bit) HasSnapshot,m.Revision,pos.ChapterID,pos.SceneID,pos.StartPosition FROM dbo.BookParagraphManuscripts m JOIN dbo.BookChapterValidations v ON v.BookID=m.BookID CROSS APPLY OPENJSON(m.Payload,'$.ChapterCheckpoints') WITH(ChapterID int '$.ChapterId',ContentHash char(64),IdentityHash char(64),MappingHash char(64)) c CROSS APPLY OPENJSON(v.Positions) WITH(ParagraphID uniqueidentifier '$.ParagraphId',StartPosition int '$.Start',ChapterID int '$.ChapterId',SceneID int '$.SceneId',Verified bit) pos JOIN dbo.Chapters ch ON ch.ChapterID=pos.ChapterID AND ch.BookID=m.BookID AND ch.IsArchived=0 JOIN dbo.Scenes scene ON scene.SceneID=pos.SceneID AND scene.ChapterID=pos.ChapterID AND scene.IsArchived=0 WHERE m.BookID=@BookID AND v.ChapterID=c.ChapterID AND pos.ChapterID=c.ChapterID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.ManuscriptID=@ManuscriptID AND v.WordRevision=@WordRevision AND v.ExpiresUtc>SYSUTCDATETIME() AND v.ContentHash=c.ContentHash AND v.IdentityHash=c.IdentityHash AND v.MappingHash=c.MappingHash AND pos.Verified=1 AND pos.SceneID=@SceneID AND pos.ParagraphID=@ParagraphID;RETURN; END; IF @Action='position' BEGIN SELECT CAST(1 AS bit) HasSnapshot,m.Revision,p.ChapterID,p.SceneID FROM dbo.BookParagraphManuscripts m OUTER APPLY(SELECT TOP(1) pos.ChapterID,CASE WHEN s.ChapterID=pos.ChapterID AND s.IsArchived=0 THEN pos.SceneID END SceneID FROM dbo.BookChapterValidations v CROSS APPLY OPENJSON(m.Payload,'$.ChapterCheckpoints') WITH(ChapterID int '$.ChapterId',ContentHash char(64),IdentityHash char(64),MappingHash char(64)) c CROSS APPLY OPENJSON(v.Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End',ChapterID int '$.ChapterId',SceneID int '$.SceneId',Verified bit) pos JOIN dbo.Chapters ch ON ch.ChapterID=pos.ChapterID AND ch.BookID=m.BookID AND ch.IsArchived=0 LEFT JOIN dbo.Scenes s ON s.SceneID=pos.SceneID WHERE v.BookID=m.BookID AND v.ChapterID=c.ChapterID AND pos.ChapterID=c.ChapterID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.ManuscriptID=@ManuscriptID AND v.WordRevision=@WordRevision AND v.ExpiresUtc>SYSUTCDATETIME() AND v.ContentHash=c.ContentHash AND v.IdentityHash=c.IdentityHash AND v.MappingHash=c.MappingHash AND pos.Verified=1 AND pos.StartPosition<=@Position AND pos.EndPosition>@Position) p WHERE m.BookID=@BookID;RETURN; END; IF @Action='review' BEGIN IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND AccessRole=N'Owner' AND IsActive=1) THROW 51000,'Project owner authority required',1; BEGIN TRANSACTION; DECLARE @ReviewPayload nvarchar(max),@ReviewRevision bigint,@ReviewIndex int; SELECT @ReviewPayload=Payload,@ReviewRevision=Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID; IF @ReviewRevision IS NULL OR @ExpectedRevision IS NULL OR @ReviewRevision<>@ExpectedRevision THROW 51000,'Manuscript changed before structural warning',1; SELECT @ReviewIndex=CONVERT(int,j.[key]) FROM OPENJSON(@ReviewPayload,'$.ChapterCheckpoints') j WHERE TRY_CONVERT(int,JSON_VALUE(j.value,'$.ChapterId'))=@ChapterID; IF @ReviewIndex IS NOT NULL BEGIN SET @ReviewPayload=JSON_MODIFY(@ReviewPayload,CONCAT('$.ChapterCheckpoints[',@ReviewIndex,'].Status'),'Needs review'); SET @ReviewPayload=JSON_MODIFY(@ReviewPayload,CONCAT('$.ChapterCheckpoints[',@ReviewIndex,'].Message'),'Document structure needs review; independently accepted scene positions are retained.'); UPDATE dbo.BookParagraphManuscripts SET Payload=@ReviewPayload WHERE BookID=@BookID; END; DELETE dbo.BookChapterValidations WHERE BookID=@BookID AND ChapterID=@ChapterID; COMMIT;RETURN; END; IF @Action<>'accept' THROW 51000,'Unknown chapter operation',1; IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND AccessRole=N'Owner' AND IsActive=1) THROW 51000,'Project owner authority required',1; IF COALESCE(ISJSON(@Checkpoint),0)<>1 OR COALESCE(ISJSON(@Positions),0)<>1 OR COALESCE(ISJSON(@Bindings),0)<>1 OR DATALENGTH(@Positions)>4*1024*1024 OR DATALENGTH(@Checkpoint)>16384 OR @SessionID IS NULL OR @RequestID IS NULL OR @WordRevision IS NULL OR @WordRevision<0 OR @ExpectedRevision IS NULL OR @ManuscriptID IS NULL OR @ChapterID IS NULL THROW 51000,'Invalid chapter validation',1; IF EXISTS(SELECT 1 FROM dbo.UserOnboardingState WHERE BookID=@BookID AND OnboardingCompletedUtc IS NULL) OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs WHERE BookID=@BookID AND Status IN ('Pending','Queued','Running','Processing','Preparing','ReadingScenes','AnalysingCharacters','AnalysingRelationships','AnalysingLocations','AnalysingAssets','AnalysingTimeline','Finalising')) THROW 51000,'Active import or analysis protected',1; BEGIN TRANSACTION; DECLARE @Payload nvarchar(max),@Revision bigint; SELECT @Payload=Payload,@Revision=Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID; IF @Revision IS NULL OR @Revision<>@ExpectedRevision OR TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId'))<>@ManuscriptID THROW 51000,'Accepted manuscript changed; chapter validation refused',1; IF NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChapterID AND BookID=@BookID AND IsArchived=0) OR TRY_CONVERT(int,JSON_VALUE(@Checkpoint,'$.ChapterId'))<>@ChapterID THROW 51000,'Cross-book chapter rejected',1; DECLARE @Native nvarchar(8),@Paragraph uniqueidentifier,@Index int,@Existing nvarchar(16); DECLARE bind CURSOR LOCAL FAST_FORWARD FOR SELECT ParagraphId,NativeId FROM OPENJSON(@Bindings) WITH(ParagraphId uniqueidentifier,NativeId nvarchar(8)); OPEN bind;FETCH NEXT FROM bind INTO @Paragraph,@Native; WHILE @@FETCH_STATUS=0 BEGIN SET @Index=NULL;SET @Existing=NULL; SELECT @Index=CONVERT(int,j.[key]),@Existing=JSON_VALUE(j.value,'$.Occurrence.NativeId') FROM OPENJSON(@Payload,'$.Paragraphs') j WHERE TRY_CONVERT(uniqueidentifier,JSON_VALUE(j.value,'$.Occurrence.Id'))=@Paragraph; IF @Index IS NULL OR COALESCE(@Existing,'') NOT IN ('',@Native) OR LEN(@Native)<>8 OR @Native LIKE '%[^0-9A-F]%' THROW 51000,'Native identity adoption conflicts with existing evidence',1; SET @Payload=JSON_MODIFY(@Payload,CONCAT('$.Paragraphs[',@Index,'].Occurrence.NativeId'),@Native); FETCH NEXT FROM bind INTO @Paragraph,@Native; END; CLOSE bind;DEALLOCATE bind; IF EXISTS(SELECT 1 FROM OPENJSON(@Bindings)) BEGIN IF @SnapshotHash IS NULL OR LEN(@SnapshotHash)<>64 OR @SnapshotHash LIKE '%[^0-9A-F]%' THROW 51000,'Complete adopted snapshot digest required',1; SET @Payload=JSON_MODIFY(@Payload,'$.SnapshotHash',@SnapshotHash); END; IF NOT EXISTS(SELECT 1 FROM OPENJSON(@Positions)) OR EXISTS(SELECT 1 FROM OPENJSON(@Positions) WITH(ParagraphId uniqueidentifier,ChapterId int,StartPosition int '$.Start',EndPosition int '$.End') p WHERE p.ParagraphId IS NULL OR p.ChapterId IS NULL OR p.ChapterId<>@ChapterID OR p.StartPosition IS NULL OR p.EndPosition IS NULL OR p.StartPosition<0 OR p.EndPosition<=p.StartPosition OR NOT EXISTS(SELECT 1 FROM OPENJSON(@Payload,'$.Paragraphs') a WHERE TRY_CONVERT(uniqueidentifier,JSON_VALUE(a.value,'$.Occurrence.Id'))=p.ParagraphId AND TRY_CONVERT(int,JSON_VALUE(a.value,'$.ChapterId'))=@ChapterID)) THROW 51000,'Chapter position refers to an unknown paragraph',1; IF EXISTS(SELECT ParagraphId FROM OPENJSON(@Positions) WITH(ParagraphId uniqueidentifier) GROUP BY ParagraphId HAVING COUNT(*)>1) THROW 51000,'Duplicate chapter paragraph positions',1; IF EXISTS(SELECT 1 FROM OPENJSON(@Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End') a JOIN OPENJSON(@Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End') b ON a.StartPositionb.StartPosition) THROW 51000,'Overlapping chapter paragraph positions',1; IF EXISTS(SELECT 1 FROM dbo.BookChapterValidations v CROSS APPLY OPENJSON(v.Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End') a CROSS APPLY OPENJSON(@Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End') b WHERE v.BookID=@BookID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.WordRevision=@WordRevision AND v.ChapterID<>@ChapterID AND v.ExpiresUtc>SYSUTCDATETIME() AND a.StartPositionb.StartPosition) THROW 51000,'Conflicting physical chapter ranges',1; IF EXISTS(SELECT 1 FROM dbo.BookChapterValidations WHERE UserID=@UserID AND BookID=@BookID AND RequestID=@RequestID AND (ChapterID<>@ChapterID OR SessionID<>@SessionID OR WordRevision<>@WordRevision OR Positions<>@Positions)) THROW 51000,'Request identity was reused for different chapter evidence',1; IF JSON_QUERY(@Payload,'$.ChapterCheckpoints') IS NULL SET @Payload=JSON_MODIFY(@Payload,'$.ChapterCheckpoints',JSON_QUERY('[]')); SET @Index=NULL;SELECT @Index=CONVERT(int,j.[key]) FROM OPENJSON(@Payload,'$.ChapterCheckpoints') j WHERE TRY_CONVERT(int,JSON_VALUE(j.value,'$.ChapterId'))=@ChapterID; IF @Index IS NULL SET @Payload=JSON_MODIFY(@Payload,'append $.ChapterCheckpoints',JSON_QUERY(@Checkpoint)); ELSE SET @Payload=JSON_MODIFY(@Payload,CONCAT('$.ChapterCheckpoints[',@Index,']'),JSON_QUERY(@Checkpoint)); DECLARE @PriorPositions nvarchar(max),@PriorContent char(64),@PriorIdentity char(64); SELECT @PriorPositions=Positions,@PriorContent=ContentHash,@PriorIdentity=IdentityHash FROM dbo.BookChapterValidations WHERE BookID=@BookID AND ChapterID=@ChapterID AND UserID=@UserID AND SessionID=@SessionID AND WordRevision=@WordRevision; IF @PriorPositions IS NOT NULL AND (@PriorContent<>JSON_VALUE(@Checkpoint,'$.ContentHash') OR @PriorIdentity<>JSON_VALUE(@Checkpoint,'$.IdentityHash') OR EXISTS(SELECT ParagraphId,StartPosition,EndPosition FROM OPENJSON(@Positions) WITH(ParagraphId uniqueidentifier,StartPosition int '$.Start',EndPosition int '$.End') EXCEPT SELECT ParagraphId,StartPosition,EndPosition FROM OPENJSON(@PriorPositions) WITH(ParagraphId uniqueidentifier,StartPosition int '$.Start',EndPosition int '$.End')) OR EXISTS(SELECT ParagraphId,StartPosition,EndPosition FROM OPENJSON(@PriorPositions) WITH(ParagraphId uniqueidentifier,StartPosition int '$.Start',EndPosition int '$.End') EXCEPT SELECT ParagraphId,StartPosition,EndPosition FROM OPENJSON(@Positions) WITH(ParagraphId uniqueidentifier,StartPosition int '$.Start',EndPosition int '$.End'))) THROW 51000,'Conflicting evidence for the same live Word revision',1; -- Metadata-only adoption: canonical prose, GUIDs, scene assignments and author decisions are not rewritten. UPDATE dbo.BookParagraphManuscripts SET Payload=@Payload WHERE BookID=@BookID; DELETE dbo.BookChapterValidations WHERE BookID=@BookID AND ExpiresUtc