From f543b7ac877bfddb17f8bd82d8eb84eb7b85d11a Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Sat, 7 Nov 2026 23:36:38 +0000 Subject: [PATCH] Constrain paragraph reconciliation and scene proposals to chapter boundaries --- ...6-11-07-chapter-boundary-reconciliation.md | 30 +++++ .../ParagraphChapterQualificationTests.cs | 46 +++++++ PlotLine.Tests/ParagraphChapterTests.cs | 35 +++++ PlotLine.Tests/Program.cs | 4 +- .../Sql/ParagraphChapterBoundaries.sql | 59 +++++++++ .../Manuscript/ParagraphManuscriptEngine.cs | 68 ++++++++-- .../Sql/243_ParagraphChapterBoundaries.sql | 122 ++++++++++++++++++ .../Views/ParagraphManuscript/Index.cshtml | 4 +- 8 files changed, 356 insertions(+), 12 deletions(-) create mode 100644 Docs/WordCompanion/2026-11-07-chapter-boundary-reconciliation.md create mode 100644 PlotLine.Tests/ParagraphChapterQualificationTests.cs create mode 100644 PlotLine.Tests/ParagraphChapterTests.cs create mode 100644 PlotLine.Tests/Sql/ParagraphChapterBoundaries.sql create mode 100644 PlotLine/Sql/243_ParagraphChapterBoundaries.sql diff --git a/Docs/WordCompanion/2026-11-07-chapter-boundary-reconciliation.md b/Docs/WordCompanion/2026-11-07-chapter-boundary-reconciliation.md new file mode 100644 index 00000000..d9958453 --- /dev/null +++ b/Docs/WordCompanion/2026-11-07-chapter-boundary-reconciliation.md @@ -0,0 +1,30 @@ +# Chapter-bounded paragraph reconciliation — 7 November 2026 + +## Reproduction and root cause + +Windows reproduction `94d99d93057b3d6aac03bffd753524c756cf624f` used Companion 1.0.0.18 against Development and disposable book **10151**, project **8173**. Chapter headings are paragraphs 1 and 6; paragraph 7 was edited; both chapters contain repeated short prose. Word supplied no native paragraph hints. + +Global matching could not recover a later scene start when its first paragraph changed and repeated text competed across chapters. `ParagraphManuscriptEngine.Reconcile` then carried the last global scene boundary past the recognised next chapter heading. Paragraphs 7–9 retained Chapter 2's chapter ID but received Chapter 1's scene GUID as an unverified proposal. The existing live-position safety check correctly withheld that scene. The chapter-two canonical scene and immutable accepted capture still existed. + +An additional persistence defect was confirmed: when a scene had no assigned surviving paragraphs, the scene-text projection wrote an empty string to its canonical manuscript source. This had happened to scene 9072; its canonical scene identity and original build map were not deleted. The latest raw Word text remained in the paragraph snapshot and original source/identities remained in the immutable capture. + +## Correction + +- Matched chapter headings establish independent occurrence-comparison windows. Repeated prose in another chapter cannot compete for local identity. Exact unique Word headings survive insertions on both sides; an anchored single rewritten occurrence can retain its original GUID. No synthetic Word IDs, permanent markers or native changes are introduced. +- Scene-start candidates and carry-forward are restricted to their recognised chapter. Existing own-chapter assignments survive when supported; absent local evidence produces **Scene unresolved in this chapter**, with no scene GUID or trusted position, rather than an earlier chapter's proposal. +- Lost canonical chapter boundaries refuse the ambiguous update without replacing the accepted snapshot. Missing scene starts can retain local surviving groups for refinement; they cannot borrow another chapter's scene. +- Manuscript validation and grouping confirmation reject cross-chapter assignments before a confirmation can overwrite chapter metadata. +- Forward migration **243_ParagraphChapterBoundaries.sql** adds the same persistence check. An absent group cannot erase canonical prose; a partly unresolved chapter cannot truncate canonical text to only its recognised paragraphs. Existing authorisation, active-job protection, CAS, idempotency and ownership checks are retained. +- The workspace distinguishes unresolved body paragraphs from headings/front matter. Context/Intent still withhold an ambiguous or stale mapping; they have not been made permissive. + +## Focused evidence + +`--paragraph-manuscripts` includes the exact nine-paragraph/no-hints/changed-chapter-two-opening fixture, repeated text, insertion on either side of a chapter heading, missing/all-lost scene anchors, lost chapter boundary refusal, unchanged save/reopen identity continuity and rejection of invalid grouping confirmation. The original GUID sequence is asserted, not just counts. + +`PlotLine.Tests/Sql/ParagraphChapterBoundaries.sql` runs only in the existing guarded synthetic database and rolls back its fixture. It verifies missing/partly unresolved group projection protection, retained raw prose, exact-session chapter-two position resolution versus withheld unresolved positions, and SQL refusal of an unverified cross-chapter proposal. + +The dedicated test-harness command `--paragraph-chapter-dev` is read-only by default. It accepts only the exact disposable book/project/preview and nine-paragraph, one-edited-paragraph fixture, with no evidence or undo decisions. It reconstructs original grouping from the immutable original paragraph GUIDs and the unmodified two-scene canonical build maps, then replays the latest saved Word paragraphs through the corrected engine. It refuses if original identity continuity cannot be established. `--repair` uses the existing repository/CAS save, restores the original opaque scene identities and canonical projection, and verifies paragraph 2/7 saved-position lookups plus an unchanged subsequent reconciliation. This is an explicitly scoped qualification repair, not a production adoption endpoint or a general project backfill. No incorrect grouping is confirmed. + +No Word/agent/IPC/installer code, Reckoning data, active analysis job or Production is changed. Native 1.0.0.18 remains the installed qualification baseline. Real Word cursor following after this deployment remains Windows Codex's responsibility. + +Deployment, final regression counts and book 10151 verification are appended after rollout. diff --git a/PlotLine.Tests/ParagraphChapterQualificationTests.cs b/PlotLine.Tests/ParagraphChapterQualificationTests.cs new file mode 100644 index 00000000..7e6be294 --- /dev/null +++ b/PlotLine.Tests/ParagraphChapterQualificationTests.cs @@ -0,0 +1,46 @@ +using System.Text.Json; +using Dapper; +using Microsoft.Data.SqlClient; +using Microsoft.Extensions.Configuration; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services.Manuscript; +internal static class ParagraphChapterQualificationTests +{ + // Explicit disposable Windows fixture only; not an application migration or an adoption endpoint. + public static async Task Run(bool repair) + { + var line=File.ReadLines("/etc/plotdirector/plotdirector.env").Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")); + var connection=line[(line.IndexOf('=')+1)..].Trim().Trim('"','\'');var builder=new SqlConnectionStringBuilder(connection); + if(builder.InitialCatalog!="PlotDirector_Development")throw new Exception("Development required"); + await using var db=new SqlConnection(connection);await db.OpenAsync();if(await db.ExecuteScalarAsync("SELECT DB_NAME()")!="PlotDirector_Development")throw new Exception("Wrong effective database"); + if(!await db.ExecuteScalarAsync("SELECT CAST(CASE WHEN EXISTS(SELECT 1 FROM dbo.Books WHERE BookID=10151 AND ProjectID=8173 AND BookTitle LIKE N'%QA%') THEN 1 ELSE 0 END AS bit)"))throw new Exception("Disposable fixture identity changed"); + var user=await db.QuerySingleAsync("SELECT UserID FROM dbo.ProjectUserAccess WHERE ProjectID=8173 AND AccessRole=N'Owner' AND IsActive=1"); + var configuration=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary{{"ConnectionStrings:DefaultConnection",connection}}).Build(); + var repository=new ParagraphManuscriptRepository(new SqlConnectionFactory(configuration)); + var current=await repository.Get(user,10151)??throw new Exception("Missing qualification manuscript"); + var source=await repository.Capture(user,10151)??throw new Exception("Missing immutable accepted capture"); + var raw=source.NativeParagraphs??throw new Exception("Missing original paragraph identities"); + if(current.ProjectId!=8173||current.Paragraphs.Count!=9||raw.Length!=9||current.Evidence.Count!=0||current.Undo.Count!=0||current.Scenes.Count!=2||current.Scenes.Any(s=>s.Retired)||current.Chapters.Count!=2||source.PreviewID!=Guid.Parse("50e741d8-d42a-47bc-be48-2ad23f91b83d")||!Guid.TryParse(source.CompanionDocumentIdentifier,out var manuscript)||current.ManuscriptId!=manuscript)throw new Exception("Qualified source or author decisions changed; refusing automatic fixture repair"); + if((await repository.Status(user,10151))?.Paused!=false)throw new Exception("Fixture analysis/import active"); + var original=raw.OrderBy(p=>p.Ordinal).ToArray();var headings=current.Chapters.OrderBy(c=>Array.FindIndex(original,p=>p.Id==c.HeadingId)).ToArray(); + if(headings.Any(c=>c.HeadingId==Guid.Empty)||original[0].Id!=headings[0].HeadingId||original[5].Id!=headings[1].HeadingId||original.Where((p,i)=>p.Text!=current.Paragraphs[i].Occurrence.Text).Count()>1)throw new Exception("Fixture no longer matches the qualified single-edit source"); + // One original scene in each chapter makes the original import grouping exact, not inferred by name. + var groups=new List(); + for(int n=0;ns.ChapterId==chapter.CanonicalId);var start=Array.FindIndex(original,p=>p.Id==chapter.HeadingId)+2;var end=n+1p.Id==headings[n+1].HeadingId):original.Length;groups.Add(new(){SceneId=scene.CanonicalId,ChapterId=chapter.CanonicalId,Title=scene.Title,Start=start,End=end});} + var candidate=ParagraphManuscriptEngine.Bootstrap(10151,8173,current.ManuscriptId,original,groups); + foreach(var scene in candidate.Scenes){var generated=scene.Id;scene.Id=current.Scenes.Single(s=>s.CanonicalId==scene.CanonicalId).Id;foreach(var row in candidate.Paragraphs.Where(p=>p.SceneId==generated))row.SceneId=scene.Id;} + candidate.DocumentName=current.DocumentName;candidate.Mode=current.Mode;candidate.Revision=current.Revision;candidate.SessionId=current.SessionId;candidate.WordRevision=current.WordRevision;candidate.EventPositions=current.EventPositions; + ParagraphManuscriptEngine.Reconcile(candidate,current.Paragraphs.Select(p=>p.Occurrence).ToArray()); + if(!candidate.Paragraphs.Select(p=>p.Occurrence.Id).SequenceEqual(original.Select(p=>p.Id))||!candidate.Paragraphs.Select(p=>p.Occurrence.Text).SequenceEqual(current.Paragraphs.Select(p=>p.Occurrence.Text))||candidate.Paragraphs.Skip(6).Any(p=>p.ChapterId!=headings[1].CanonicalId||p.SceneId!=candidate.Scenes[1].Id||!p.PositionVerified))throw new Exception("Original source continuity or chapter-local recovery could not be established"); + var maps=await db.QueryAsync("SELECT m.SceneID FROM dbo.OnboardingManuscriptBuilds b JOIN dbo.OnboardingManuscriptBuildSceneMap m ON m.OnboardingManuscriptBuildID=b.OnboardingManuscriptBuildID WHERE b.PreviewID=@preview",new{preview=source.PreviewID}); + if(!maps.Order().SequenceEqual(candidate.Scenes.Select(s=>s.CanonicalId).Order()))throw new Exception("Original canonical build mapping changed"); + Console.WriteLine("PASS book 10151: immutable original nine GUIDs and two canonical build maps survive; chapter-local replay preserves latest raw Word prose and chapter-two membership"); + if(!repair)return; + var saved=await repository.Save(user,candidate,current.Revision,Guid.NewGuid()); + foreach(var ordinal in new[]{1,6}){var p=saved.Paragraphs[ordinal];var expected=saved.Scenes.Single(s=>s.Id==p.SceneId).CanonicalId;var position=await repository.Position(user,10151,saved.ManuscriptId,saved.SessionId,saved.WordRevision,p.Occurrence.Start);if(position?.SceneID!=expected||position.ChapterID!=p.ChapterId)throw new Exception("Saved cursor map verification failed");} + var repeated=ParagraphManuscriptEngine.Clone(saved);ParagraphManuscriptEngine.Reconcile(repeated,saved.Paragraphs.Select(p=>p.Occurrence).ToArray()); + if(!repeated.Paragraphs.Select(p=>(p.Occurrence.Id,p.SceneId,p.ChapterId,p.PositionVerified)).SequenceEqual(saved.Paragraphs.Select(p=>(p.Occurrence.Id,p.SceneId,p.ChapterId,p.PositionVerified))))throw new Exception("Subsequent unchanged save changes restored mapping"); + Console.WriteLine("PASS repaired only disposable book 10151 using CAS: original opaque scene IDs retained, paragraph 2/7 positional lookups resolve their own scenes, unchanged re-sync remains stable; no grouping confirmation or Word edits"); + } +} diff --git a/PlotLine.Tests/ParagraphChapterTests.cs b/PlotLine.Tests/ParagraphChapterTests.cs new file mode 100644 index 00000000..59a072b3 --- /dev/null +++ b/PlotLine.Tests/ParagraphChapterTests.cs @@ -0,0 +1,35 @@ +using PlotLine.Models; +using PlotLine.Services.Manuscript; +using PlotDirector.Companion.Protocol.Manuscript; +internal static class ParagraphChapterTests +{ + internal static ParagraphOccurrence[] Rows(IEnumerable<(string Text,int Outline)> source) + { + int start=0;return source.Select((row,i)=>{var p=new ParagraphOccurrence{Text=row.Text,Outline=row.Outline,Ordinal=i,Start=start,End=start+row.Text.Length};start=p.End;return p;}).ToArray(); + } + private static ParagraphManuscript Initial()=>ParagraphManuscriptEngine.Bootstrap(4,2,Guid.NewGuid(),Rows(new[]{("Chapter 1 - The signal\r",1),("Ari checked the radio.\r",10),("No.\r",10),("The harbour was quiet.\r",10),("\r",10),("Chapter 2 - The crossing\r",1),("Bea moved the log.\r",10),("No.\r",10),("The crossing was clear.\r",10)}),[new(){SceneId=41,ChapterId=11,Title="Harbour radio check",Start=2,End=5},new(){SceneId=42,ChapterId=12,Title="Bea Moves the Log",Start=7,End=9}]); + private static ParagraphOccurrence[] Edited(ParagraphManuscript state,Func,List<(string Text,int Outline)>> edit)=>Rows(edit(state.Paragraphs.Select(p=>(p.Occurrence.Text,p.Occurrence.Outline)).ToList())); + private static void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);} + private static void InChapter(ParagraphManuscript state){var scenes=state.Scenes.ToDictionary(s=>s.Id);Check(state.Paragraphs.All(p=>!p.SceneId.HasValue||p.ChapterId==scenes[p.SceneId.Value].ChapterId),"No assigned occurrence crosses its chapter boundary");} + public static void Run() + { + var original=Initial();var ids=original.Paragraphs.Select(p=>p.Occurrence.Id).ToArray();var second=original.Scenes[1].Id;var state=ParagraphManuscriptEngine.Clone(original); + var edited=Edited(state,rows=>{rows[6]=(rows[6].Text.TrimEnd('\r')+" Rain tapped on the window.\r",10);return rows;}); + ParagraphManuscriptEngine.Reconcile(state,edited);InChapter(state); + Check(state.Paragraphs.Skip(6).All(p=>p.SceneId==second&&p.ChapterId==12&&p.PositionVerified),"Nine-paragraph Windows reproduction: changed chapter-two start with no native hints keeps its own reliable scene"); + Check(state.Paragraphs.Select(p=>p.Occurrence.Id).SequenceEqual(ids),"Chapter-local rewrite and repeated prose preserve every original imported occurrence GUID"); + ParagraphManuscriptEngine.Reconcile(state,Rows(state.Paragraphs.Select(p=>(p.Occurrence.Text,p.Occurrence.Outline)))); + Check(state.Paragraphs.Select(p=>p.Occurrence.Id).SequenceEqual(ids)&&state.Paragraphs.Skip(6).All(p=>p.SceneId==second),"Save/reopen unchanged sequence retains chapter-two mapping and canonical occurrence continuity"); + state=ParagraphManuscriptEngine.Clone(original);ParagraphManuscriptEngine.Reconcile(state,Edited(state,r=>{r.RemoveAt(6);return r;}));InChapter(state); + Check(state.Paragraphs.Skip(6).All(p=>p.SceneId==second&&p.ChapterId==12)&&state.Scenes[1].NeedsRefinement,"Missing scene start preserves surviving assignments within its own chapter for refinement"); + state=ParagraphManuscriptEngine.Clone(original);ParagraphManuscriptEngine.Reconcile(state,Edited(state,r=>{r.Insert(5,("New end of chapter one.\r",10));r.Insert(7,("New chapter-two opening.\r",10));return r;}));InChapter(state); + Check(state.Paragraphs[5].ChapterId==11&&state.Paragraphs[7].ChapterId==12&&state.Paragraphs[7].SceneId==second&&!state.Paragraphs[7].PositionVerified,"Insertions on both sides of chapter heading never inherit the previous chapter scene"); + Check(ids.All(id=>state.Paragraphs.Any(p=>p.Occurrence.Id==id)),"Insertions near a chapter boundary retain all prior IDs, including repeated text in both chapters"); + state=ParagraphManuscriptEngine.Clone(original);ParagraphManuscriptEngine.Reconcile(state,Edited(state,r=>r.Take(6).Concat(new[]{("Entirely new first passage.\r",10),("Unrelated second passage.\r",10),("Another new passage.\r",10),("No recognised local anchor.\r",10)}).ToList()));InChapter(state); + Check(state.Paragraphs.Skip(6).All(p=>p.ChapterId==12&&!p.SceneId.HasValue&&!p.PositionVerified)&&state.Scenes[1].NeedsRefinement,"No surviving scene anchor leaves unresolved raw paragraphs in chapter two, without inventing a grouping"); + state=ParagraphManuscriptEngine.Clone(original);var raw=string.Concat(state.Paragraphs.Select(p=>p.Occurrence.Text));bool refused=false;try{ParagraphManuscriptEngine.Reconcile(state,Edited(state,r=>{r.RemoveAt(5);return r;}));}catch(InvalidOperationException){refused=true;} + Check(refused&&string.Concat(state.Paragraphs.Select(p=>p.Occurrence.Text))==raw,"Lost chapter heading refuses a destructive cross-chapter carry-forward without changing accepted prose"); + state=ParagraphManuscriptEngine.Clone(original);state.Paragraphs[6].SceneId=state.Scenes[0].Id;refused=false;try{ParagraphManuscriptEngine.Validate(state);}catch(ArgumentException){refused=true;}Check(refused,"Persistable manuscript validation rejects even unverified cross-chapter proposals"); + refused=false;try{ParagraphManuscriptEngine.ConfirmGrouping(state,state.Scenes[0].Id);}catch(ArgumentException){refused=true;}Check(refused&&state.Paragraphs[6].ChapterId==12,"Grouping confirmation cannot erase a chapter boundary to legitimise a bad proposal"); + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index ae6173a6..6fdb72ee 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -130,7 +130,9 @@ 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("--paragraph-chapter-dev")){await ParagraphChapterQualificationTests.Run(args.Contains("--repair"));return;} +if(args.Contains("--paragraph-chapters")){ParagraphChapterTests.Run();return;} +if(args.Contains("--paragraph-manuscripts")){ParagraphChapterTests.Run();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;} if(args.Contains("--native-tray")){await NativeTrayIntegrationTests.Run();await NativeManuscriptCaptureTests.Run();Console.WriteLine("PASS native tray presence, expiry, scope and persistent PWA review decisions");return;} diff --git a/PlotLine.Tests/Sql/ParagraphChapterBoundaries.sql b/PlotLine.Tests/Sql/ParagraphChapterBoundaries.sql new file mode 100644 index 00000000..7e2189cd --- /dev/null +++ b/PlotLine.Tests/Sql/ParagraphChapterBoundaries.sql @@ -0,0 +1,59 @@ +-- 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 @SecondChapter int,@SecondScene int,@SecondKey uniqueidentifier=NEWID(),@NewParagraph uniqueidentifier=NEWID(); +INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) SELECT @Book,2,N'Later chapter',2,MIN(RevisionStatusID) FROM dbo.RevisionStatuses;SET @SecondChapter=SCOPE_IDENTITY(); +INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) SELECT @SecondChapter,1,N'Later scene',1,(SELECT MIN(TimeModeID) FROM dbo.TimeModes),(SELECT MIN(TimeConfidenceID) FROM dbo.TimeConfidences),(SELECT MIN(RevisionStatusID) FROM dbo.RevisionStatuses);SET @SecondScene=SCOPE_IDENTITY(); +EXEC dbo.SceneManuscriptSource_Save @ProjectID=@Project,@BookID=@Book,@ChapterID=@SecondChapter,@SceneID=@SecondScene,@SourceText=N'Accepted second-chapter prose.',@SourceWordCount=3,@SourceCharacterCount=30,@WordStartParagraphIndex=2,@WordEndParagraphIndex=2,@SourceKind=N'ParagraphSync'; +SET @Payload=JSON_MODIFY(@Payload,'append $.Scenes',JSON_QUERY((SELECT @SecondKey Id,@SecondScene CanonicalId,@SecondChapter ChapterId,N'Later scene' Title,CAST(0 AS bit) Retired FOR JSON PATH,WITHOUT_ARRAY_WRAPPER))); +SET @Request=NEWID();TRUNCATE TABLE #State; +INSERT #State EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=1,@RequestID=@Request,@Payload=@Payload; +IF NOT EXISTS(SELECT 1 FROM dbo.SceneManuscriptSources WHERE SceneID=@SecondScene AND SourceText=N'Accepted second-chapter prose.') THROW 51000,'Missing scene anchor cleared accepted canonical source',1; +PRINT 'PASS missing scene group does not project empty prose over the accepted canonical scene'; +SET @Payload=(SELECT Payload FROM #State); +SET @Payload=JSON_MODIFY(@Payload,'append $.Paragraphs',JSON_QUERY((SELECT JSON_QUERY((SELECT @NewParagraph Id,1 Ordinal,N'Unresolved new Word passage.' Text,34 Start,62 [End],10 Outline FOR JSON PATH,WITHOUT_ARRAY_WRAPPER)) Occurrence,@SecondChapter ChapterId,CAST(0 AS bit) Story,CAST(0 AS bit) PositionVerified FOR JSON PATH,WITHOUT_ARRAY_WRAPPER))); +SET @Request=NEWID();TRUNCATE TABLE #State; +INSERT #State EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=2,@RequestID=@Request,@Payload=@Payload; +IF NOT EXISTS(SELECT 1 FROM #State WHERE JSON_VALUE(Payload,'$.Paragraphs[1].ChapterId')=CONVERT(nvarchar(20),@SecondChapter) AND JSON_VALUE(Payload,'$.Paragraphs[1].SceneId') IS NULL) OR NOT EXISTS(SELECT 1 FROM dbo.SceneManuscriptSources WHERE SceneID=@SecondScene AND SourceText=N'Accepted second-chapter prose.') THROW 51000,'Unresolved own-chapter prose was lost or replaced canonical content',1; +PRINT 'PASS unresolved own-chapter raw capture persists while canonical prose is protected'; +SET @Payload=(SELECT Payload FROM #State);DECLARE @KnownParagraph uniqueidentifier=NEWID(); +SET @Payload=JSON_MODIFY(@Payload,'append $.Paragraphs',JSON_QUERY((SELECT JSON_QUERY((SELECT @KnownParagraph Id,2 Ordinal,N'Known second-chapter passage.' Text,62 Start,90 [End],10 Outline FOR JSON PATH,WITHOUT_ARRAY_WRAPPER)) Occurrence,@SecondChapter ChapterId,@SecondKey SceneId,CAST(1 AS bit) Story,CAST(1 AS bit) PositionVerified FOR JSON PATH,WITHOUT_ARRAY_WRAPPER))); +SET @Request=NEWID();TRUNCATE TABLE #State; +INSERT #State EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=3,@RequestID=@Request,@Payload=@Payload; +IF NOT EXISTS(SELECT 1 FROM dbo.SceneManuscriptSources WHERE SceneID=@SecondScene AND SourceText=N'Accepted second-chapter prose.') THROW 51000,'Partly unresolved chapter truncated the canonical scene to its known rows',1; +PRINT 'PASS partial unresolved chapter retains canonical prose rather than projecting only its recognised rows'; +DECLARE @Session uniqueidentifier=TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.SessionId')); +CREATE TABLE #Position(HasSnapshot bit,Revision bigint,ChapterID int NULL,SceneID int NULL); +INSERT #Position EXEC dbo.ParagraphManuscript @Action='position',@UserID=@User,@BookID=@Book,@ManuscriptID=@Manuscript,@SessionID=@Session,@WordRevision=3,@Position=40; +IF EXISTS(SELECT 1 FROM #Position WHERE SceneID IS NOT NULL) THROW 51000,'Unresolved prose reported a trusted scene',1; +TRUNCATE TABLE #Position;INSERT #Position EXEC dbo.ParagraphManuscript @Action='position',@UserID=@User,@BookID=@Book,@ManuscriptID=@Manuscript,@SessionID=@Session,@WordRevision=3,@Position=70; +IF NOT EXISTS(SELECT 1 FROM #Position WHERE SceneID=@SecondScene AND ChapterID=@SecondChapter) THROW 51000,'Known chapter-two position did not resolve inside the same session',1; +PRINT 'PASS unresolved positions withhold scene while recognised chapter-two positions resolve in the same exact session'; +SET @Payload=(SELECT Payload FROM #State);SET @Payload=JSON_MODIFY(@Payload,'$.Paragraphs[1].SceneId',CONVERT(nvarchar(36),@SceneKey));SET @Payload=JSON_MODIFY(@Payload,'$.Paragraphs[1].Story',CAST(1 AS bit));SET @Request=NEWID();DECLARE @Denied bit=0; +BEGIN TRY EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Book,@ExpectedRevision=4,@RequestID=@Request,@Payload=@Payload;END TRY +BEGIN CATCH IF ERROR_MESSAGE()='Paragraph scene assignment crosses chapter boundaries' SET @Denied=1;ELSE THROW;END CATCH; +IF @Denied<>1 THROW 51000,'Persistence accepted a cross-chapter unverified grouping',1; +IF @@TRANCOUNT>0 ROLLBACK; +PRINT 'PASS SQL rejects cross-chapter proposals, including unverified proposals; isolated fixture rolled back'; diff --git a/PlotLine/Services/Manuscript/ParagraphManuscriptEngine.cs b/PlotLine/Services/Manuscript/ParagraphManuscriptEngine.cs index ecc98d99..e6a9f028 100644 --- a/PlotLine/Services/Manuscript/ParagraphManuscriptEngine.cs +++ b/PlotLine/Services/Manuscript/ParagraphManuscriptEngine.cs @@ -26,16 +26,18 @@ public static class ParagraphManuscriptEngine public static void Reconcile(ParagraphManuscript state,IReadOnlyList rows) { var comparison=ParagraphReconciliation.Compare(state.Paragraphs.Select(p=>p.Occurrence).ToArray(),rows);var old=state.Paragraphs.ToDictionary(p=>p.Occurrence.Id);var next=comparison.Current; + RefineChapterIdentities(state,rows,next); var index=next.Select((p,i)=>(p.Id,i)).ToDictionary(p=>p.Id,p=>p.i); var chapterHeadings=state.Chapters.Where(c=>index.ContainsKey(c.HeadingId)).ToDictionary(c=>c.HeadingId); if(state.Chapters.Any(c=>c.CanonicalId==0&&c.HeadingId!=Guid.Empty&&!index.ContainsKey(c.HeadingId)))throw new InvalidOperationException("An excluded manuscript section boundary cannot be reliably identified. Review the Word structure before synchronising; no saved manuscript was changed."); + if(state.Chapters.Any(c=>c.CanonicalId>0&&c.HeadingId!=Guid.Empty&&!index.ContainsKey(c.HeadingId)))throw new InvalidOperationException("A saved chapter boundary cannot be reliably identified. Review the Word chapter structure before synchronising; no saved manuscript was changed."); var excludedAt=new bool[next.Length];bool excluded=false; var chapterAt=new int?[next.Length];int? currentChapter=state.Chapters.FirstOrDefault(c=>c.HeadingId==Guid.Empty)?.CanonicalId; for(int n=0;np.SceneId.HasValue).GroupBy(p=>p.SceneId!.Value).ToDictionary(g=>g.Key,g=>g.ToArray()); var starts=new List<(int At,ParagraphScene Scene,bool Verified)>(); foreach(var scene in state.Scenes.Where(s=>!s.Retired)){ - var prior=oldGroups.GetValueOrDefault(scene.Id)??[];if(prior.Length==0)continue; + var prior=oldGroups.GetValueOrDefault(scene.Id)??[];if(prior.Length==0){scene.NeedsRefinement=true;continue;} if(index.TryGetValue(prior[0].Occurrence.Id,out var at)){ // A moved scene-start paragraph alone is not proof that the whole scene moved. var positions=prior.Where(p=>index.ContainsKey(p.Occurrence.Id)).Select(p=>index[p.Occurrence.Id]).Order().ToArray(); @@ -46,26 +48,73 @@ public static class ParagraphManuscriptEngine starts.Add((at,scene,verified)); }else{ var surviving=prior.Where(p=>index.ContainsKey(p.Occurrence.Id)).Select(p=>index[p.Occurrence.Id]).Order().ToArray(); - if(surviving.Length>0){starts.Add((surviving[0],scene,false));scene.NeedsRefinement=true;} + scene.NeedsRefinement=true; + if(surviving.Length>0)starts.Add((surviving[0],scene,false)); } } - starts=starts.OrderBy(s=>s.At).ToList();var current=new List();int boundaryIndex=-1; - foreach(var p in next){while(boundaryIndex+1=0?starts[boundaryIndex]:default;var before=old.GetValueOrDefault(p.Id);var scene=boundary.Scene; - // Heading 1 is structure, not prose. Front matter before an imported boundary stays outside the story. - if(scene==null&&p.Outline!=1&&chapterAt[p.Ordinal].HasValue){var first=starts.FirstOrDefault(s=>s.Scene.ChapterId==chapterAt[p.Ordinal]);if(first.Scene!=null){scene=first.Scene;scene.NeedsRefinement=true;}} + // A scene boundary is applicable only inside its own recognised chapter. + var chapterStarts=starts.Where(s=>chapterAt[s.At]==s.Scene.ChapterId).GroupBy(s=>s.Scene.ChapterId) + .ToDictionary(g=>g.Key,g=>g.OrderBy(s=>s.At).ToArray()); + var activeScenes=state.Scenes.Where(s=>!s.Retired).ToDictionary(s=>s.Id); + var current=new List();var boundaryIndices=new Dictionary(); + foreach(var p in next){ + var chapter=chapterAt[p.Ordinal];var candidates=chapter.HasValue?chapterStarts.GetValueOrDefault(chapter.Value)??[]:[]; + int boundaryIndex=chapter.HasValue?boundaryIndices.GetValueOrDefault(chapter.Value,-1):-1; + while(boundaryIndex+1=0?candidates[boundaryIndex]:default;var scene=boundary.Scene; + if(scene==null&&p.Outline!=1&&chapter.HasValue){ + // Retain a surviving occurrence's own assignment before making any local proposal. + if(old.TryGetValue(p.Id,out var prior)&&prior.ChapterId==chapter&&prior.SceneId.HasValue&&activeScenes.TryGetValue(prior.SceneId.Value,out var saved)&&saved.ChapterId==chapter)scene=saved; + else if(candidates.Length>0)scene=candidates[0].Scene; + if(scene!=null)scene.NeedsRefinement=true; + } var story=!excludedAt[p.Ordinal]&&p.Outline!=1&&scene!=null; - current.Add(new(){Occurrence=p,Story=story,SceneId=story?scene!.Id:null,ChapterId=chapterAt[p.Ordinal],PositionVerified=(p.Outline==1&&chapterAt[p.Ordinal]>0)||(story&&boundary.Scene!=null&&boundary.Scene.Id==scene?.Id&&boundary.Verified&&p.Resolution!="Ambiguous"&&chapterAt[p.Ordinal]==scene?.ChapterId)}); + current.Add(new(){Occurrence=p,Story=story,SceneId=story?scene!.Id:null,ChapterId=chapter, + PositionVerified=(p.Outline==1&&chapter>0)||(story&&boundary.Scene?.Id==scene?.Id&&boundary.Verified&&p.Resolution!="Ambiguous")}); } - // If a boundary disappeared, preserve that scene's surviving paragraph grouping as unresolved. - foreach(var p in current.Where(p=>p.SceneId==null&&p.Occurrence.Outline!=1&&!excludedAt[p.Occurrence.Ordinal]))if(old.TryGetValue(p.Occurrence.Id,out var prior)&&prior.Story){p.Story=true;p.SceneId=prior.SceneId;p.ChapterId=prior.ChapterId;p.PositionVerified=false;} + // No local anchor/evidence means unresolved prose in its chapter, never inheritance from another chapter. foreach(var scene in state.Scenes.Where(s=>!s.Retired))if(current.Any(p=>p.SceneId==scene.Id&&!p.PositionVerified))scene.NeedsRefinement=true; state.Paragraphs=current;var hash=Hash(rows);if(hash!=state.SnapshotHash)state.Undo.Clear();state.SnapshotHash=hash;state.UpdatedUtc=DateTime.UtcNow;RefreshEvidence(state);Validate(state); } + private static void RefineChapterIdentities(ParagraphManuscript state,IReadOnlyList incoming,ParagraphOccurrence[] next) + { + // Heading identities establish hard comparison windows. Repeated prose in another chapter + // cannot compete with a local occurrence or prevent a locally evidenced single rewrite. + var prior=state.Paragraphs.Select(p=>p.Occurrence).ToArray(); + var oldIndex=prior.Select((p,i)=>(p.Id,i)).ToDictionary(p=>p.Id,p=>p.i); + var oldTextCounts=prior.GroupBy(p=>p.Text,StringComparer.Ordinal).ToDictionary(g=>g.Key,g=>g.Count(),StringComparer.Ordinal); + var newTextPositions=incoming.Select((p,i)=>(p.Text,p.Outline,i)).GroupBy(p=>p.Text,StringComparer.Ordinal).Where(g=>g.Count()==1).ToDictionary(g=>g.Key,g=>g.Single(),StringComparer.Ordinal); + foreach(var chapter in state.Chapters.Where(c=>c.HeadingId!=Guid.Empty))if(oldIndex.TryGetValue(chapter.HeadingId,out var at)){ + var heading=prior[at];if(heading.Outline!=1||oldTextCounts[heading.Text]!=1||!newTextPositions.TryGetValue(heading.Text,out var match)||match.Outline!=1)continue; + // An exact, unique Word heading is still the boundary when new prose was inserted on both sides. + var found=next[match.i];found.Id=heading.Id;found.PreviousText=heading.Text;found.Change="Unchanged";found.Resolution="Unique chapter heading"; + } + var newIndex=next.Select((p,i)=>(p.Id,i)).ToDictionary(p=>p.Id,p=>p.i); + var headings=state.Chapters.Select(c=>c.HeadingId).Where(id=>id!=Guid.Empty).ToHashSet(); + var incomingText=incoming.Select(p=>p.Text).ToHashSet(StringComparer.Ordinal); + foreach(var chapter in state.Chapters.Where(c=>c.HeadingId!=Guid.Empty)){ + if(!oldIndex.TryGetValue(chapter.HeadingId,out var a)||!newIndex.TryGetValue(chapter.HeadingId,out var b))continue; + int oldEnd=a+1,newEnd=b+1;while(oldEnd(p.Id,i)).ToDictionary(p=>p.Id,p=>p.i); + var used=local.Where(p=>positions.ContainsKey(p.Id)).Select(p=>p.Id).ToHashSet(); + for(int n=1;n+1p.Id).Distinct().Count()!=next.Length)throw new InvalidOperationException("Chapter occurrence identities are ambiguous. No saved manuscript was changed."); + for(int n=0;n0?next[n-1].Id:null;next[n].NextId=n+1new(){Chapters=state.Chapters.Select(c=>new ParagraphChapter{CanonicalId=c.CanonicalId,HeadingId=c.HeadingId,Title=c.Title}).ToList(),SnapshotHash=state.SnapshotHash,EventPositions=state.EventPositions.Select(e=>new ManuscriptEventOption{Kind=e.Kind,Id=e.Id,SceneId=e.SceneId,Description=e.Description}).ToList(),Scenes=state.Scenes.Select(s=>new ParagraphScene{Id=s.Id,CanonicalId=s.CanonicalId,ChapterId=s.ChapterId,Title=s.Title,Retired=s.Retired,MergedInto=s.MergedInto,NeedsRefinement=s.NeedsRefinement}).ToList(),Assignments=state.Paragraphs.Select(p=>new ParagraphAssignment{ParagraphId=p.Occurrence.Id,ChapterId=p.ChapterId,SceneId=p.SceneId,PositionVerified=p.PositionVerified}).ToList()}; private static void Remember(ParagraphManuscript state){var limit=Math.Clamp(100000/Math.Max(1,state.Paragraphs.Count),1,12);while(state.Undo.Count>=limit)state.Undo.RemoveAt(0);state.Undo.Add(Layout(state));} public static void ConfirmGrouping(ParagraphManuscript state,Guid sceneId) { var scene=state.Scenes.Single(s=>s.Id==sceneId&&!s.Retired);var rows=state.Paragraphs.Where(p=>p.SceneId==sceneId&&p.Story).ToArray();if(rows.Length==0)throw new ArgumentException("No surviving scene paragraphs to confirm."); + if(rows.Any(p=>p.ChapterId!=scene.ChapterId))throw new ArgumentException("A scene grouping cannot cross chapter boundaries."); Remember(state);foreach(var p in rows){p.PositionVerified=true;p.ChapterId=scene.ChapterId;}scene.NeedsRefinement=false; foreach(var heading in state.Paragraphs.Where(p=>p.Occurrence.Outline==1&&p.Occurrence.Ordinal>=rows[0].Occurrence.Ordinal-1&&p.Occurrence.Ordinal<=rows[^1].Occurrence.Ordinal&&state.Chapters.All(c=>c.HeadingId!=p.Occurrence.Id)))state.Chapters.Add(new(){CanonicalId=scene.ChapterId,HeadingId=heading.Occurrence.Id,Title=heading.Occurrence.Text.Trim()}); RefreshEvidence(state);Validate(state); @@ -132,6 +181,7 @@ public static class ParagraphManuscriptEngine if(state.Evidence.Any(e=>e.Id==Guid.Empty)||state.Evidence.Select(e=>e.Id).Distinct().Count()!=state.Evidence.Count)throw new ArgumentException("Duplicate or empty evidence identities."); if(state.Paragraphs.Any(p=>p.Occurrence.Id==Guid.Empty)||state.Scenes.Any(s=>s.Id==Guid.Empty)||state.Paragraphs.Select(p=>p.Occurrence.Id).Distinct().Count()!=state.Paragraphs.Count||state.Scenes.Select(s=>s.Id).Distinct().Count()!=state.Scenes.Count)throw new ArgumentException("Duplicate manuscript identities."); var scenes=state.Scenes.Where(s=>!s.Retired).ToDictionary(s=>s.Id);if(state.Paragraphs.Any(p=>p.Story&&(!p.SceneId.HasValue||!scenes.ContainsKey(p.SceneId.Value))))throw new ArgumentException("Every story paragraph must belong to one current scene."); + if(state.Paragraphs.Any(p=>p.SceneId.HasValue&&scenes.TryGetValue(p.SceneId.Value,out var scene)&&p.ChapterId!=scene.ChapterId))throw new ArgumentException("A paragraph scene assignment cannot cross chapter boundaries."); var completed=new HashSet();Guid? last=null;foreach(var p in state.Paragraphs.Where(p=>p.Story)){if(p.SceneId!=last){if(p.SceneId.HasValue&&completed.Contains(p.SceneId.Value))throw new ArgumentException("Scene groups must be contiguous.");if(last.HasValue)completed.Add(last.Value);last=p.SceneId;}} } } diff --git a/PlotLine/Sql/243_ParagraphChapterBoundaries.sql b/PlotLine/Sql/243_ParagraphChapterBoundaries.sql new file mode 100644 index 00000000..2dee5a7a --- /dev/null +++ b/PlotLine/Sql/243_ParagraphChapterBoundaries.sql @@ -0,0 +1,122 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.ParagraphManuscript + @Action varchar(16),@UserID int,@BookID int,@ExpectedRevision bigint=NULL,@RequestID uniqueidentifier=NULL,@Payload nvarchar(max)=NULL,@SessionID uniqueidentifier=NULL,@ManuscriptID uniqueidentifier=NULL,@WordRevision bigint=NULL,@Position int=NULL,@Mode nvarchar(16)=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='position' + BEGIN + SELECT CAST(1 AS bit) AS HasSnapshot,m.Revision,p.ChapterID,p.SceneID + FROM dbo.BookParagraphManuscripts m OUTER APPLY(SELECT TOP(1) position.ChapterID,position.SceneID FROM dbo.BookParagraphPositions position + WHERE position.BookID=m.BookID AND position.Verified=1 AND position.StartPosition<=@Position AND position.EndPosition>@Position + AND m.ManuscriptID=@ManuscriptID AND TRY_CONVERT(uniqueidentifier,JSON_VALUE(m.Payload,'$.SessionId'))=@SessionID AND TRY_CONVERT(bigint,JSON_VALUE(m.Payload,'$.WordRevision'))=@WordRevision) p WHERE m.BookID=@BookID;RETURN; + END; + IF @Action='get' BEGIN SELECT Payload FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;RETURN;END; + IF @Action='status' BEGIN SELECT BookID,ManuscriptID,Revision,JSON_VALUE(Payload,'$.SnapshotHash') AS SnapshotHash,JSON_VALUE(Payload,'$.Mode') AS Mode,TRY_CONVERT(uniqueidentifier,JSON_VALUE(Payload,'$.SessionId')) AS SessionId,TRY_CONVERT(bigint,JSON_VALUE(Payload,'$.WordRevision')) AS WordRevision, + CAST(CASE WHEN EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND AccessRole=N'Owner' AND IsActive=1) THEN 1 ELSE 0 END AS bit) AS CanWrite, + CAST(CASE WHEN EXISTS(SELECT 1 FROM dbo.UserOnboardingState o WHERE o.BookID=@BookID AND o.OnboardingCompletedUtc IS NULL) OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs j WHERE j.BookID=@BookID AND j.Status IN ('Pending','Queued','Running','Processing','Preparing','ReadingScenes','AnalysingCharacters','AnalysingRelationships','AnalysingLocations','AnalysingAssets','AnalysingTimeline','Finalising')) THEN 1 ELSE 0 END AS bit) AS Paused + FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;RETURN;END; + IF @Action='capture' BEGIN SELECT TOP(1) c.Payload FROM dbo.OnboardingManuscriptCaptures c WHERE c.BookID=@BookID AND EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds b WHERE b.PreviewID=c.PreviewID AND b.BookID=@BookID AND b.Status IN ('Complete','Built')) ORDER BY c.CreatedUtc DESC;RETURN;END; + IF @Action='events' + BEGIN + SELECT CAST('Knowledge' AS varchar(16)) AS Kind,k.CharacterKnowledgeID AS Id,k.SceneID,CONCAT(c.CharacterName,N': ',COALESCE(k.Description,N'Knowledge event')) AS Description + FROM dbo.CharacterKnowledge k JOIN dbo.Characters c ON c.CharacterID=k.CharacterID JOIN dbo.Scenes s ON s.SceneID=k.SceneID JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID WHERE ch.BookID=@BookID + UNION ALL SELECT 'Relationship',r.RelationshipEventID,r.SceneID,CONCAT(ca.CharacterName,N' / ',cb.CharacterName,N': ',COALESCE(r.Description,N'Relationship event')) + FROM dbo.RelationshipEvents r JOIN dbo.CharacterRelationships rel ON rel.CharacterRelationshipID=r.CharacterRelationshipID JOIN dbo.Characters ca ON ca.CharacterID=rel.CharacterAID JOIN dbo.Characters cb ON cb.CharacterID=rel.CharacterBID JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID WHERE ch.BookID=@BookID;RETURN; + END; + -- Conservative mutation contract: use the established project owner role, never expand collaborator permissions. + IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND IsActive=1 AND AccessRole=N'Owner') THROW 51000,'Project owner authority required',1; + IF @Action='mode' + BEGIN + IF COALESCE(@Mode,'') NOT IN ('Off','Manual','OnSave') THROW 51000,'Unsupported synchronisation mode',1; + BEGIN TRANSACTION; + DECLARE @PreferenceRevision bigint; + SELECT @Payload=Payload,@PreferenceRevision=Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID; + IF @PreferenceRevision IS NULL OR @PreferenceRevision<>@ExpectedRevision THROW 51000,'Manuscript changed; refresh before changing preferences',1; + IF JSON_VALUE(@Payload,'$.Mode')<>@Mode BEGIN + SET @RequestID=NEWID();SET @PreferenceRevision+=1;SET @Payload=JSON_MODIFY(@Payload,'$.Mode',@Mode);SET @Payload=JSON_MODIFY(@Payload,'$.Revision',@PreferenceRevision);SET @Payload=JSON_MODIFY(@Payload,'$.LastRequestId',CONVERT(nvarchar(36),@RequestID)); + UPDATE dbo.BookParagraphManuscripts SET Payload=@Payload,Revision=@PreferenceRevision,RequestID=@RequestID,UpdatedUtc=SYSUTCDATETIME() WHERE BookID=@BookID; + END; + COMMIT;SELECT @Payload;RETURN; + END; + IF @Action<>'save' THROW 51000,'Unknown manuscript operation',1; + IF ISJSON(@Payload)<>1 OR DATALENGTH(@Payload)>128*1024*1024 OR @RequestID IS NULL OR @ExpectedRevision IS NULL THROW 51000,'Invalid manuscript state',1; + IF COALESCE(TRY_CONVERT(int,JSON_VALUE(@Payload,'$.BookId')),-1)<>@BookID OR COALESCE(TRY_CONVERT(int,JSON_VALUE(@Payload,'$.ProjectId')),-1)<>@ProjectID OR TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId')) IS NULL THROW 51000,'Manuscript scope mismatch',1; + IF COALESCE(JSON_VALUE(@Payload,'$.Mode'),'') NOT IN ('Off','Manual','OnSave') THROW 51000,'Unsupported synchronisation mode',1; + -- Do not adopt or replace a book while its accepted import is still awaiting a completed build. + IF EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptCaptures c WHERE c.BookID=@BookID AND c.IsCurrent=1 AND COALESCE(JSON_VALUE(c.Payload,'$.ParagraphTracking'),'false')<>'true' AND NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds b WHERE b.PreviewID=c.PreviewID AND b.Status IN ('Complete','Built'))) THROW 51000,'Active import protected; finish the existing import before enabling paragraph tracking',1; + IF @ExpectedRevision>=0 AND (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; synchronisation paused',1; + BEGIN TRANSACTION; + DECLARE @Revision bigint,@Previous nvarchar(max),@LastRequest uniqueidentifier; + SELECT @Revision=Revision,@Previous=Payload,@LastRequest=RequestID FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID; + IF @LastRequest=@RequestID BEGIN SELECT Payload FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;COMMIT;RETURN;END; + IF (@Revision IS NULL AND @ExpectedRevision<>-1) OR (@Revision IS NOT NULL AND @Revision<>@ExpectedRevision) THROW 51000,'Manuscript changed; refresh before retrying',1; + DECLARE @Scenes table(JsonIndex int,Id uniqueidentifier PRIMARY KEY,CanonicalId int,ChapterId int,Title nvarchar(200),Retired bit,MergedInto uniqueidentifier); + INSERT @Scenes SELECT CONVERT(int,j.[key]),s.Id,s.CanonicalId,s.ChapterId,s.Title,s.Retired,s.MergedInto FROM OPENJSON(@Payload,'$.Scenes') j CROSS APPLY OPENJSON(j.value) WITH(Id uniqueidentifier,CanonicalId int,ChapterId int,Title nvarchar(200),Retired bit,MergedInto uniqueidentifier) s; + IF EXISTS(SELECT 1 FROM @Scenes x LEFT JOIN dbo.Chapters c ON c.ChapterID=x.ChapterId AND c.BookID=@BookID WHERE c.ChapterID IS NULL) OR EXISTS(SELECT 1 FROM @Scenes x WHERE x.CanonicalId>0 AND NOT EXISTS(SELECT 1 FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE s.SceneID=x.CanonicalId AND c.BookID=@BookID)) THROW 51000,'Cross-book scene reference rejected',1; + IF EXISTS(SELECT 1 FROM dbo.Scenes actual WHERE actual.IsArchived=0 AND EXISTS(SELECT 1 FROM @Scenes tracked WHERE tracked.ChapterId=actual.ChapterID) AND NOT EXISTS(SELECT 1 FROM @Scenes tracked WHERE tracked.CanonicalId=actual.SceneID)) THROW 51000,'This chapter contains a scene outside the accepted paragraph map; review it before synchronising',1; + -- A snapshot is not authority to undo newer author archive/chapter decisions made elsewhere. + IF @Previous IS NULL AND EXISTS(SELECT 1 FROM @Scenes state JOIN dbo.Scenes actual ON actual.SceneID=state.CanonicalId WHERE actual.IsArchived<>state.Retired) THROW 51000,'An imported scene was archived; review its association before adoption',1; + IF @Previous IS NOT NULL AND EXISTS(SELECT 1 FROM OPENJSON(@Previous,'$.Scenes') WITH(CanonicalId int,ChapterId int,Retired bit) prior JOIN dbo.Scenes actual ON actual.SceneID=prior.CanonicalId WHERE actual.IsArchived<>prior.Retired OR actual.ChapterID<>prior.ChapterId) THROW 51000,'Canonical scene decisions changed after this snapshot; automatic replacement refused',1; + DECLARE @Paragraphs table(Id uniqueidentifier PRIMARY KEY,Ordinal int UNIQUE,StartPosition int,EndPosition int,Text nvarchar(max),SceneId uniqueidentifier NULL,ChapterId int NULL,Story bit,Verified bit,Outline int); + INSERT @Paragraphs SELECT p.Id,p.Ordinal,p.StartPosition,p.EndPosition,p.Text,x.SceneId,x.ChapterId,x.Story,x.PositionVerified,p.Outline FROM OPENJSON(@Payload,'$.Paragraphs') WITH(Occurrence nvarchar(max) AS JSON,SceneId uniqueidentifier,ChapterId int,Story bit,PositionVerified bit) x CROSS APPLY OPENJSON(x.Occurrence) WITH(Id uniqueidentifier,Ordinal int,StartPosition int '$.Start',EndPosition int '$.End',Text nvarchar(max),Outline int) p; + IF EXISTS(SELECT 1 FROM @Paragraphs p JOIN @Scenes s ON s.Id=p.SceneId WHERE p.ChapterId IS NULL OR p.ChapterId<>s.ChapterId) THROW 51000,'Paragraph scene assignment crosses chapter boundaries',1; + IF EXISTS(SELECT 1 FROM @Paragraphs p WHERE p.Story=1 AND NOT EXISTS(SELECT 1 FROM @Scenes s WHERE s.Id=p.SceneId AND s.Retired=0)) THROW 51000,'Story paragraph has no current scene',1; + IF (SELECT COUNT(*) FROM @Paragraphs)>100000 OR EXISTS(SELECT 1 FROM @Paragraphs HAVING MIN(Ordinal)<>0 OR MAX(Ordinal)<>COUNT(*)-1) THROW 51000,'Invalid paragraph ordering',1; + -- New scene identities materialise through the existing canonical scene table; existing metadata is not overwritten. + DECLARE @SceneKey uniqueidentifier,@Chapter int,@Title nvarchar(200),@JsonIndex int,@NewID int; + DECLARE createScenes CURSOR LOCAL FAST_FORWARD FOR SELECT Id,ChapterId,Title,JsonIndex FROM @Scenes WHERE CanonicalId=0 AND Retired=0; + OPEN createScenes;FETCH NEXT FROM createScenes INTO @SceneKey,@Chapter,@Title,@JsonIndex; + WHILE @@FETCH_STATUS=0 + BEGIN + INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) + SELECT @Chapter,COALESCE((SELECT MAX(SceneNumber) FROM dbo.Scenes WHERE ChapterID=@Chapter),0)+1,@Title,COALESCE((SELECT MAX(SortOrder) FROM dbo.Scenes WHERE ChapterID=@Chapter),0)+1,COALESCE((SELECT TimeModeID FROM dbo.TimeModes WHERE TimeModeName=N'Unknown'),template.TimeModeID),template.TimeConfidenceID,template.RevisionStatusID FROM(SELECT TOP(1) TimeModeID,TimeConfidenceID,RevisionStatusID FROM dbo.Scenes WHERE ChapterID=@Chapter ORDER BY SceneID) template; + IF @@ROWCOUNT<>1 THROW 51000,'A canonical source scene is required for splitting',1; + SET @NewID=SCOPE_IDENTITY();UPDATE @Scenes SET CanonicalId=@NewID WHERE Id=@SceneKey;SET @Payload=JSON_MODIFY(@Payload,CONCAT('$.Scenes[',@JsonIndex,'].CanonicalId'),@NewID); + FETCH NEXT FROM createScenes INTO @SceneKey,@Chapter,@Title,@JsonIndex; + END;CLOSE createScenes;DEALLOCATE createScenes; + UPDATE existing SET ChapterID=state.ChapterId,IsArchived=state.Retired,UpdatedDate=SYSUTCDATETIME() FROM dbo.Scenes existing JOIN @Scenes state ON state.CanonicalId=existing.SceneID; + ;WITH ordering AS(SELECT s.CanonicalId,ROW_NUMBER() OVER(PARTITION BY s.ChapterId ORDER BY MIN(p.Ordinal),s.CanonicalId) AS Sequence FROM @Scenes s JOIN @Paragraphs p ON p.SceneId=s.Id WHERE s.Retired=0 GROUP BY s.CanonicalId,s.ChapterId) + UPDATE scene SET SortOrder=o.Sequence,SceneNumber=o.Sequence FROM dbo.Scenes scene JOIN ordering o ON o.CanonicalId=scene.SceneID; + DELETE dbo.BookParagraphPositions WHERE BookID=@BookID; + INSERT dbo.BookParagraphPositions(BookID,StartPosition,EndPosition,ChapterID,SceneID,Verified) + SELECT @BookID,p.StartPosition,p.EndPosition,COALESCE(s.ChapterId,p.ChapterId),s.CanonicalId,p.Verified FROM @Paragraphs p LEFT JOIN @Scenes s ON s.Id=p.SceneId; + -- Explicit merge/undo positions, scoped to this book. Anchored verified primary passages take precedence below. + ;WITH positions AS(SELECT * FROM OPENJSON(@Payload,'$.EventPositions') WITH(Kind varchar(16),Id int,SceneId int)) + UPDATE k SET SceneID=p.SceneId,UpdatedDate=SYSUTCDATETIME() FROM dbo.CharacterKnowledge k JOIN positions p ON p.Kind='Knowledge' AND p.Id=k.CharacterKnowledgeID JOIN dbo.Scenes old ON old.SceneID=k.SceneID JOIN dbo.Chapters oc ON oc.ChapterID=old.ChapterID JOIN dbo.Scenes dest ON dest.SceneID=p.SceneId JOIN dbo.Chapters dc ON dc.ChapterID=dest.ChapterID WHERE oc.BookID=@BookID AND dc.BookID=@BookID; + ;WITH positions AS(SELECT * FROM OPENJSON(@Payload,'$.EventPositions') WITH(Kind varchar(16),Id int,SceneId int)) + UPDATE r SET SceneID=p.SceneId,UpdatedDate=SYSUTCDATETIME() FROM dbo.RelationshipEvents r JOIN positions p ON p.Kind='Relationship' AND p.Id=r.RelationshipEventID JOIN dbo.Scenes old ON old.SceneID=r.SceneID JOIN dbo.Chapters oc ON oc.ChapterID=old.ChapterID JOIN dbo.Scenes dest ON dest.SceneID=p.SceneId JOIN dbo.Chapters dc ON dc.ChapterID=dest.ChapterID WHERE oc.BookID=@BookID AND dc.BookID=@BookID; + DELETE dbo.ManuscriptEvidenceIndex WHERE BookID=@BookID; + INSERT dbo.ManuscriptEvidenceIndex(BookID,EvidenceID,EventKind,EventID,IsPrimary,EvidenceState,DerivedSceneID) + SELECT @BookID,e.Id,e.EventKind,e.EventId,e.[Primary],e.State,CASE WHEN e.State=N'Verified' THEN s.CanonicalId END FROM OPENJSON(@Payload,'$.Evidence') WITH(Id uniqueidentifier,EventKind varchar(16),EventId int,[Primary] bit,State nvarchar(20),CurrentScene uniqueidentifier) e LEFT JOIN @Scenes s ON s.Id=e.CurrentScene; + IF EXISTS(SELECT 1 FROM dbo.ManuscriptEvidenceIndex e WHERE e.BookID=@BookID AND ((e.EventKind='Knowledge' AND NOT EXISTS(SELECT 1 FROM dbo.CharacterKnowledge k JOIN dbo.Scenes s ON s.SceneID=k.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE k.CharacterKnowledgeID=e.EventID AND c.BookID=@BookID)) OR(e.EventKind='Relationship' AND NOT EXISTS(SELECT 1 FROM dbo.RelationshipEvents r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE r.RelationshipEventID=e.EventID AND c.BookID=@BookID)))) THROW 51000,'Evidence event does not belong to this book',1; + UPDATE k SET SceneID=e.DerivedSceneID,UpdatedDate=SYSUTCDATETIME() FROM dbo.CharacterKnowledge k JOIN dbo.ManuscriptEvidenceIndex e ON e.EventKind='Knowledge' AND e.EventID=k.CharacterKnowledgeID AND e.BookID=@BookID AND e.IsPrimary=1 AND e.EvidenceState=N'Verified' WHERE e.DerivedSceneID>0; + UPDATE r SET SceneID=e.DerivedSceneID,UpdatedDate=SYSUTCDATETIME() FROM dbo.RelationshipEvents r JOIN dbo.ManuscriptEvidenceIndex e ON e.EventKind='Relationship' AND e.EventID=r.RelationshipEventID AND e.BookID=@BookID AND e.IsPrimary=1 AND e.EvidenceState=N'Verified' WHERE e.DerivedSceneID>0; + -- Current prose projections remain in the established source service's tables. No planning/AI records are rewritten. + DECLARE @Canonical int,@SceneText nvarchar(max),@First int,@Last int,@Words int,@Characters int,@ProjectionKind nvarchar(40); + DECLARE sceneText CURSOR LOCAL FAST_FORWARD FOR SELECT s.CanonicalId,s.ChapterId,COALESCE(STRING_AGG(CONVERT(nvarchar(max),p.Text),N'') WITHIN GROUP(ORDER BY p.Ordinal),N''),MIN(p.Ordinal)+1,MAX(p.Ordinal)+1 FROM @Scenes s LEFT JOIN @Paragraphs p ON p.SceneId=s.Id AND p.Story=1 WHERE s.CanonicalId>0 AND s.Retired=0 AND EXISTS(SELECT 1 FROM @Paragraphs assigned WHERE assigned.SceneId=s.Id AND assigned.Story=1) AND NOT EXISTS(SELECT 1 FROM @Paragraphs unassigned WHERE unassigned.ChapterId=s.ChapterId AND unassigned.SceneId IS NULL AND COALESCE(unassigned.Outline,10)<>1) AND NOT EXISTS(SELECT 1 FROM @Paragraphs unresolved WHERE unresolved.SceneId=s.Id AND unresolved.Story=1 AND unresolved.Verified=0) GROUP BY s.CanonicalId,s.ChapterId; + OPEN sceneText;FETCH NEXT FROM sceneText INTO @Canonical,@Chapter,@SceneText,@First,@Last; + WHILE @@FETCH_STATUS=0 + BEGIN + SET @Words=(SELECT COUNT(*) FROM STRING_SPLIT(REPLACE(REPLACE(REPLACE(@SceneText,CHAR(13),N' '),CHAR(10),N' '),CHAR(9),N' '),N' ') WHERE value<>N''); + SET @Characters=DATALENGTH(@SceneText)/2; + SET @ProjectionKind=CASE WHEN EXISTS(SELECT 1 FROM OPENJSON(@Payload,'$.Scenes') WITH(CanonicalId int,NeedsRefinement bit) state JOIN dbo.SceneManuscriptSources source ON source.SceneID=state.CanonicalId WHERE state.CanonicalId=@Canonical AND state.NeedsRefinement=1 AND source.SourceKind=N'StructuralFallback') THEN N'StructuralFallback' ELSE N'ParagraphSync' END; + EXEC dbo.SceneManuscriptSource_Save @ProjectID=@ProjectID,@BookID=@BookID,@ChapterID=@Chapter,@SceneID=@Canonical,@SourceText=@SceneText,@SourceWordCount=@Words,@SourceCharacterCount=@Characters,@SourceStartParagraph=@First,@SourceEndParagraph=@Last,@WordStartParagraphIndex=@First,@WordEndParagraphIndex=@Last,@SourceKind=@ProjectionKind; + FETCH NEXT FROM sceneText INTO @Canonical,@Chapter,@SceneText,@First,@Last; + END;CLOSE sceneText;DEALLOCATE sceneText; + DECLARE @ActualEvents nvarchar(max)=(SELECT Kind,Id,SceneId,Description FROM( + SELECT CAST('Knowledge' AS varchar(16)) AS Kind,k.CharacterKnowledgeID AS Id,k.SceneID AS SceneId,COALESCE(k.Description,N'') AS Description FROM dbo.CharacterKnowledge k JOIN dbo.Scenes s ON s.SceneID=k.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@BookID + UNION ALL SELECT 'Relationship',r.RelationshipEventID,r.SceneID,COALESCE(r.Description,N'') FROM dbo.RelationshipEvents r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@BookID) rows FOR JSON PATH); + SET @Payload=JSON_MODIFY(@Payload,'$.EventPositions',JSON_QUERY(COALESCE(@ActualEvents,N'[]'))); + SET @Revision=COALESCE(@Revision,0)+1;SET @Payload=JSON_MODIFY(@Payload,'$.Revision',@Revision);SET @Payload=JSON_MODIFY(@Payload,'$.LastRequestId',CONVERT(nvarchar(36),@RequestID)); + IF @Previous IS NULL INSERT dbo.BookParagraphManuscripts(BookID,ManuscriptID,Revision,RequestID,Payload) VALUES(@BookID,CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId')),@Revision,@RequestID,@Payload); + ELSE UPDATE dbo.BookParagraphManuscripts SET ManuscriptID=CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId')),Revision=@Revision,RequestID=@RequestID,Payload=@Payload,UpdatedUtc=SYSUTCDATETIME() WHERE BookID=@BookID; + EXEC dbo.Dynamics_RunContinuityChecks @ProjectID=@ProjectID,@BookID=@BookID; + COMMIT;SELECT @Payload; +END; +GO diff --git a/PlotLine/Views/ParagraphManuscript/Index.cshtml b/PlotLine/Views/ParagraphManuscript/Index.cshtml index d23070fb..55c944ee 100644 --- a/PlotLine/Views/ParagraphManuscript/Index.cshtml +++ b/PlotLine/Views/ParagraphManuscript/Index.cshtml @@ -16,7 +16,7 @@ @if(state.Paragraphs.Count==0){

Import your manuscript from Word

Companion 1.0.0.18 establishes paragraph identities and scene mappings automatically during manuscript import. Once it finishes, this workspace contains your scenes and story evidence.

Open manuscript import
}else{ - @if(state.Paragraphs.Any(p=>p.Story&&!p.PositionVerified)){
Some scene groupings need review. Their latest Word paragraphs are saved below; existing scene prose is retained until you confirm or adjust the grouping. Uncertain passages are not used as verified story evidence.
} + @if(state.Paragraphs.Any(p=>!p.PositionVerified&&(p.Story||(p.Occurrence.Outline!=1&&p.ChapterId>0)))){
Some scene groupings need review. Their latest Word paragraphs are saved below; existing scene prose is retained until you confirm or adjust the grouping. Uncertain passages are not used as verified story evidence.
}

Saved manuscript

@state.Paragraphs.Count.ToString("N0") paragraphs · @current.Length scenes · Updated @state.UpdatedUtc.ToString("u")

@@ -32,7 +32,7 @@

Paragraphs

Page @currentPage of @Math.Max(1,(state.Paragraphs.Count+99)/100). Paragraph numbers describe this saved snapshot, not permanent identities.

- @foreach(var row in rows){var scene=current.FirstOrDefault(s=>s.Id==row.SceneId);
Paragraph @(row.Occurrence.Ordinal+1) · @(scene?.Title??"Heading / front matter") @if(!row.PositionVerified&&row.Story){ · Position needs review}

@row.Occurrence.Text

+ @foreach(var row in rows){var scene=current.FirstOrDefault(s=>s.Id==row.SceneId);
Paragraph @(row.Occurrence.Ordinal+1) · @(scene?.Title??(row.Occurrence.Outline!=1&&row.ChapterId>0?"Scene unresolved in this chapter":"Heading / front matter")) @if(!row.PositionVerified&&(row.Story||(row.Occurrence.Outline!=1&&row.ChapterId>0))){ · Position needs review}

@row.Occurrence.Text

@if(row.Story){var boundaryChoices=current.Where((s,i)=>i>0&&s.ChapterId==current[i-1].ChapterId&&scenePositions.ContainsKey(s.Id)&&scenePositions.ContainsKey(current[i-1].Id)&&(s.Id==row.SceneId||current[i-1].Id==row.SceneId)&&row.Occurrence.Ordinal>scenePositions[current[i-1].Id]).ToArray();
Adjust structure@if(scenePositions.GetValueOrDefault(row.SceneId!.Value,-1)!=row.Occurrence.Ordinal){
}else{

This paragraph already starts a scene.

} @if(boundaryChoices.Length>0){
}
}
}