Complete automatic paragraph imports, live scene context and portable recovery

This commit is contained in:
Nick Beckley 2026-11-07 22:35:35 +00:00
parent 4a3355df3b
commit 5021586c9f
36 changed files with 494 additions and 41 deletions

View File

@ -0,0 +1,36 @@
# Development paragraph synchronisation completion — 7 November 2026
## Delivered behaviour
The existing Word import wizard automatically requests paragraph capture when Development paragraph tracking is enabled and the selected Companion advertises support (1.0.0.18). No extra adoption or individual scene approval is required. The durable server import initializes paragraph/Word-position, chapter and scene correspondence after canonical scene creation; browser disconnection does not skip initialization. Existing checkpoint reuse and invalid-boundary whole-chapter fallback remain intact.
Word remains authoritative. On-save deltas use the existing authenticated session and paragraph protocol, without permanent Word markers, prose rewriting or automatic AI reanalysis. Uncertain correspondence fails safely; stale or unavailable Word cannot supply a live scene. Context and Intent show a visible live chapter/scene label and preserve independent manual navigation.
## UI
- Start a fresh import through **Projects → Import a manuscript**, selecting the connected Word document in the existing wizard.
- **Book details → Manuscript structure and evidence** (`/manuscript/paragraphs?bookId=<book>`). Existing split, boundary, merge, undo, evidence inspection/confirmation and synchronization controls use the PWA theme and book scope. The workspace is also linked from Context/Intent.
- Open **Context** or **Intent** through the website. Follow Word shows the current chapter and scene; pause/manual selection shows saved scene context instead.
- Use the existing **Back up books / Restore books** wizard; no separate paragraph export tool.
## Portability contract
Tracked backups use outer package **2.1**, project snapshot **1.5**. Untracked packages retain 2.0/1.4; historical readers remain supported. Paragraph occurrence/manuscript/scene/evidence GUIDs, exact prose, groupings, undo layouts and author evidence decisions are canonical portable data. Typed book/project/chapter/scene/event database IDs are remapped through the existing authorized recovery engine. Payload validation and post-write comparison occur inside the existing transaction/file rollback boundary.
Restored incoming roots clear live session, revision and request authority and default OnSave to Manual. Reconnect the intended Word document and request a snapshot before enabling save synchronization; backups do not resume an old device session. Unrelated live destination roots retain their bindings. Legacy snapshots cannot silently replace an existing tracked project while omitting its paragraph state. No blanket backup restriction remains.
## Database and rollout
Forward migrations **240_ParagraphManuscripts.sql** and **241_ParagraphRecovery.sql** are required in that order. Existing 240 is unchanged. 241 extends the established transactional recovery procedures and preserves StructuralFallback provenance and active-analysis save protections. Development uses the existing `Features__ParagraphManuscripts=true` setting; no new release gates. Production and Windows installations are untouched.
## Verification
- Solution build: zero warnings/errors.
- Full managed harness: 455 passing checks; paragraph workflow/backup checks: 39.
- Guarded real SQL recovery round trips: 38 passing checks, including new/existing projects, cross-account IDs, exact paragraph/prose/grouping/evidence/undo preservation, archived capacity, partial rollback and duplicate-safe imports.
- Native capture tests verify ordinary import automatically requests paragraph tracking from 1.0.0.18.
- Browser regressions cover live scene label, manual follow isolation, import connectivity and structure actions.
- Live Development AI configuration accepted the strict chapter schema and mapped two proposed scenes within four synthetic submitted paragraphs. No author prose or secrets were logged.
- Real Word COM/cursor/save responsiveness remains for the author's Windows test. Atlas did not package, install or drive Word.
Deployment and authenticated running-site results are appended after rollout. The application commit is the parent of the final deployment-evidence commit on the shared branch.

View File

@ -1,3 +1,5 @@
> **Superseded rollout status:** Companion 1.0.0.18 is now installed. Development rollout, automatic import capture and portable backup support are documented in [completion report](2026-11-07-development-paragraph-sync.md). Earlier staged/off/backup restrictions below describe the historical foundation, not the current rollout.
# Paragraph manuscript synchronisation foundation — 7 November 2026
## Delivery and operational boundaries

View File

@ -1,3 +1,5 @@
> **Superseded rollout status:** Companion 1.0.0.18 is now installed. Development rollout, automatic import capture and portable backup support are documented in [completion report](../2026-11-07-development-paragraph-sync.md). Earlier staged/off/backup restrictions below describe the historical foundation, not the current rollout.
# Windows handover — paragraph synchronisation source 1.0.0.18
## Scope and starting point

View File

@ -23,6 +23,7 @@ internal static class BookRecoveryDatabaseTests
var subscription = new SubscriptionService(new SubscriptionRepository(factory), NativeWorkflowTests.Proxy<IUserFileRepository>((n, a) => n == "GetStorageUsageForOwnerAsync" ? Task.FromResult(0L) : throw new Exception(n)));
var destinationProtection=new EphemeralDataProtectionProvider();var destinationBackups=new ProjectBackupRepository(factory,destinationProtection);var destinationRepository=new BookRecoveryRepository(factory,destinationProtection);
BookRecoveryService Service(int id) => id==other?new(destinationBackups,imports,destinationRepository,files,subscription,Actor(id),destinationProtection):new(backups, imports, repository, files, subscription, Actor(id), protection);
if(Environment.GetCommandLineArgs().Contains("--paragraph-recovery"))await SeedParagraphs(factory,backups,owner,project,book);
var source = Service(owner); var destination = Service(other); var package = await source.Export(project, [book]); var text = JsonSerializer.Serialize(package); var parsed = BookRecoveryService.Read(text);
var artifactDirectory="/srv/repos/plotdirector-phase2-artifacts/book-recovery-validation";Directory.CreateDirectory(artifactDirectory);await File.WriteAllTextAsync(Path.Combine(artifactDirectory,"latest.plotdirector"),text);
Check(parsed.Snapshot.Data.Books.Single().BookID == book && !parsed.Snapshot.Data.Chapters.Any(c => c.BookID == second), "single-book export excludes unrelated archived-book content");
@ -37,6 +38,7 @@ internal static class BookRecoveryDatabaseTests
var upload = Guid.NewGuid(); var preview = await destination.Preview(upload, parsed, [book], 0, "Recovered book project"); var restored = await destination.Restore(preview.Confirmation, _ => parsed); var after = (await destinationBackups.GetProjectBackupAsync(restored.ProjectID, other))!;
Check(after.Data.Books.Count == 1 && after.Recovery.NativeReviews.Single().DecisionsJson!.Contains("Edited author title") && after.Recovery.IntentAssessments.Count==2&&after.Recovery.IntentAssessments.Any(a=>a.DecisionsJson.Contains("deferred"))&&after.Recovery.IntentAssessments.Any(a=>a.DecisionsJson.Contains("achieved")), "cross-account restore with independent encryption keys preserves native and multi-author Intent decisions");
Check(after.Data.SceneManuscriptSources.Select(x => x.SourceText).SequenceEqual(parsed.Snapshot.Data.SceneManuscriptSources.Select(x => x.SourceText)), "exact saved manuscript prose survives book restore");
if(Environment.GetCommandLineArgs().Contains("--paragraph-recovery"))CompareParagraphs(parsed.Snapshot,after);
await files.CaptureAsync(after); Check(after.Files.Select(f => f.Sha256).Order().SequenceEqual(parsed.Snapshot.Files.Select(f => f.Sha256).Order()), "all uploaded image and attachment bytes match their restored SHA256 checksums");
Check(after.Data.MapFeatures.Count == parsed.Snapshot.Data.MapFeatures.Count && after.Data.FloorPlanBlocks.Count == parsed.Snapshot.Data.FloorPlanBlocks.Count, "map geometry and floor-plan blocks survive typed graph restoration");
var beforeRetry = await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Books"); await destination.Restore(preview.Confirmation, _ => parsed); Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Books") == beforeRetry, "same confirmation retry is durable and duplicate safe");
@ -47,6 +49,7 @@ internal static class BookRecoveryDatabaseTests
var reexported=await source.Export(allReceipt.ProjectID,[allAfter.Data.Books.Single(b=>b.IsArchived).BookID]);var reexportedBook=reexported.Snapshot.Data.Books.Single().BookID;
var next = await destination.Preview(Guid.NewGuid(), reexported, [reexportedBook], restored.ProjectID, ""); var appended = await destination.Restore(next.Confirmation, _ => reexported); after = (await destinationBackups.GetProjectBackupAsync(appended.ProjectID, other))!; Check(after.Data.Books.Count == 2 && after.Data.Books.Count(b => b.IsArchived) == 1, "restore into an existing project preserves existing book and adds archived book");
Check(await db.ExecuteScalarAsync<string>("SELECT EncryptedSource FROM dbo.NativeChapterReviews WHERE ReviewID=@id",new{id=keptReview.ReviewID})==liveCipher&&await db.ExecuteScalarAsync<string>("SELECT ResultJson FROM dbo.NativeChapterReviews WHERE ReviewID=@id",new{id=keptReview.ReviewID})==liveResultJson,"append restore preserves unrelated existing live native capture ciphertext and session binding exactly");
if(Environment.GetCommandLineArgs().Contains("--paragraph-recovery"))CompareParagraphs(parsed.Snapshot,after);
Check(after.Data.Characters.Count == parsed.Snapshot.Data.Characters.Count, "re-exported unchanged shared characters reuse scoped source identities despite different local database IDs");
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.NativeImportOperations o JOIN dbo.Books b ON b.BookID=o.BookID WHERE b.ProjectID=@id", new { id = restored.ProjectID }) == 0, "import receipts are not replayed as destination authority");
var conflictingPreview = await source.Preview(Guid.NewGuid(), package, [book], 0, "Independent edits"); var conflicting = await source.Restore(conflictingPreview.Confirmation, _ => package); var conflictBefore = (await backups.GetProjectBackupAsync(conflicting.ProjectID, owner))!;
@ -102,4 +105,23 @@ internal static class BookRecoveryDatabaseTests
Check(inactivePreview.Available==0&&await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects")==inactiveProjects&&(await destination.Restore(preview.Confirmation,_=>throw new UnauthorizedAccessException())).AlreadyCompleted,"read-only accounts can export and check receipts but cannot allocate restored books");
Console.WriteLine("PASS selective recovery real SQL new/existing project, cross-account identity, decisions, source, maps, archive capacity, corruption and retry");
}
static async Task SeedParagraphs(ISqlConnectionFactory factory,IProjectBackupRepository backups,int user,int project,int book)
{
var graph=(await backups.GetProjectBackupAsync(project,user))!;var chapters=graph.Data.Chapters.Where(c=>c.BookID==book).Select(c=>c.ChapterID).ToHashSet();
var scenes=graph.Data.Scenes.Where(s=>chapters.Contains(s.ChapterID)&&!s.IsArchived).ToArray();var rows=new List<PlotDirector.Companion.Protocol.Manuscript.ParagraphOccurrence>();var groups=new List<PlotLine.Models.ParagraphBootstrapScene>();int start=0;
foreach(var scene in scenes){var text=graph.Data.SceneManuscriptSources.FirstOrDefault(s=>s.SceneID==scene.SceneID)?.SourceText??"Synthetic saved scene.\r";if(text.Length==0)text="\r";var cut=Math.Max(1,text.Length/2);if(cut<text.Length&&char.IsHighSurrogate(text[cut-1])&&char.IsLowSurrogate(text[cut]))cut++;int first=rows.Count+1;foreach(var piece in new[]{text[..cut],text[cut..]}.Where(p=>p.Length>0)){rows.Add(new(){Text=piece,Start=start,End=start+piece.Length,NativeId=(rows.Count+1).ToString("X8")});start+=piece.Length;}groups.Add(new(){SceneId=scene.SceneID,ChapterId=scene.ChapterID,Title=scene.SceneTitle,Start=first,End=rows.Count});}
var state=PlotLine.Services.Manuscript.ParagraphManuscriptEngine.Bootstrap(book,project,Guid.NewGuid(),rows,groups);var repository=new ParagraphManuscriptRepository(factory);state.EventPositions=(await repository.Events(user,book)).ToList();state.SessionId=Guid.NewGuid();state.WordRevision=7;state.Mode="OnSave";
foreach(var item in state.EventPositions.Take(4)){var scene=state.Scenes.Single(s=>s.CanonicalId==item.SceneId);var paragraph=state.Paragraphs.First(p=>p.SceneId==scene.Id);PlotLine.Services.Manuscript.ParagraphManuscriptEngine.Anchor(state,item.Kind,item.Id,true,paragraph.Occurrence.Ordinal,paragraph.Occurrence.Ordinal,null,null);}
if(state.Evidence.Count>0){var first=state.Evidence[0];first.OriginalText=first.ConfirmedText="Earlier author-confirmed passage";var missing=Guid.NewGuid();state.Evidence.Add(new(){EventKind=first.EventKind,EventId=first.EventId,Primary=false,StartParagraph=missing,EndParagraph=missing,OriginalText="Removed supporting passage",ConfirmedText="Removed supporting passage"});PlotLine.Services.Manuscript.ParagraphManuscriptEngine.RefreshEvidence(state);}
state.Undo.Add(new(){SnapshotHash=state.SnapshotHash,Scenes=JsonSerializer.Deserialize<List<ParagraphScene>>(JsonSerializer.Serialize(state.Scenes))!,Chapters=JsonSerializer.Deserialize<List<ParagraphChapter>>(JsonSerializer.Serialize(state.Chapters))!,Assignments=state.Paragraphs.Select(p=>new ParagraphAssignment{ParagraphId=p.Occurrence.Id,SceneId=p.SceneId,ChapterId=p.ChapterId,PositionVerified=p.PositionVerified}).ToList(),EventPositions=JsonSerializer.Deserialize<List<ManuscriptEventOption>>(JsonSerializer.Serialize(state.EventPositions))!});
await repository.Save(user,state,-1,Guid.NewGuid());Check(state.Evidence.Any(e=>e.State=="Needs review")&&state.Evidence.Any(e=>e.State=="Missing"),"populated paragraph evidence fixture exists before recovery");
}
static void CompareParagraphs(ProjectBackupExport source,ProjectBackupExport restored)
{
var a=source.Recovery.ParagraphManuscripts!.Single();var b=restored.Recovery.ParagraphManuscripts!.Single();
Check(a.Paragraphs.Select(p=>(p.Occurrence.Id,p.Occurrence.Text,p.SceneId)).SequenceEqual(b.Paragraphs.Select(p=>(p.Occurrence.Id,p.Occurrence.Text,p.SceneId)))&&a.Scenes.Select(s=>s.Id).SequenceEqual(b.Scenes.Select(s=>s.Id)),"actual book recovery preserves paragraph GUIDs, exact prose and opaque scene groupings");
Check(a.Evidence.Select(e=>(e.Id,e.OriginalText,e.ConfirmedText,e.State)).SequenceEqual(b.Evidence.Select(e=>(e.Id,e.OriginalText,e.ConfirmedText,e.State)))&&b.SessionId==Guid.Empty&&b.WordRevision==-1,"actual recovery preserves evidence and author decisions without replaying live Word session");
PlotLine.Services.Manuscript.ParagraphRecovery.Validate(restored);
}
}

View File

@ -1,10 +1,10 @@
const {chromium}=require('playwright');const fs=require('node:fs');const path=require('node:path');const assert=require('node:assert/strict');
(async()=>{const browser=await chromium.launch();try{
const page=await browser.newPage();await page.goto('about:blank');await page.setContent('<main id="native-workspace" data-book="3" data-project="1" data-instance="instance" data-session="session" data-mode="context"><p id="native-presence-status"></p><select id="native-session"></select><input type="checkbox" id="native-follow"><button id="native-return">Return</button><select id="native-manual-scene"><option value="">Choose</option><option value="33" data-chapter="10">Manual scene</option></select><iframe id="native-story-workspace" hidden></iframe></main>');
await page.evaluate(()=>{window.polls=[];window.setInterval=f=>{polls.push(f);return 1;};window.live=[{instanceId:'instance',sessionId:'session',bookId:3,chapterId:10,sceneId:20,documentTitle:'Synthetic manuscript',wordAvailable:true,updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];window.requestCount=0;window.fetch=async()=>(requestCount++,{ok:true,json:async()=>live});window.hubHandlers={};window.signalR={HubConnectionBuilder:class{withUrl(){return this;}withAutomaticReconnect(){return this;}build(){return{on:(name,callback)=>hubHandlers[name]=callback,onreconnected:()=>{},start:async()=>{},stop:async()=>{}};}}};const OriginalURL=URL;window.URL=class extends OriginalURL{constructor(url,base){super(url,base==='null'?'https://fixture.invalid':base);}};});
const page=await browser.newPage();await page.goto('about:blank');await page.setContent('<main id="native-workspace" data-book="3" data-project="1" data-instance="instance" data-session="session" data-mode="context"><p id="native-current-scene"></p><p id="native-presence-status"></p><select id="native-session"></select><input type="checkbox" id="native-follow"><button id="native-return">Return</button><select id="native-manual-scene"><option value="">Choose</option><option value="33" data-chapter="10">Manual scene</option></select><iframe id="native-story-workspace" hidden></iframe></main>');
await page.evaluate(()=>{window.polls=[];window.setInterval=f=>{polls.push(f);return 1;};window.live=[{instanceId:'instance',sessionId:'session',bookId:3,chapterId:10,sceneId:20,chapterTitle:'Arrival',sceneTitle:'The letter',documentTitle:'Synthetic manuscript',wordAvailable:true,updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];window.requestCount=0;window.fetch=async()=>(requestCount++,{ok:true,json:async()=>live});window.hubHandlers={};window.signalR={HubConnectionBuilder:class{withUrl(){return this;}withAutomaticReconnect(){return this;}build(){return{on:(name,callback)=>hubHandlers[name]=callback,onreconnected:()=>{},start:async()=>{},stop:async()=>{}};}}};const OriginalURL=URL;window.URL=class extends OriginalURL{constructor(url,base){super(url,base==='null'?'https://fixture.invalid':base);}};});
await page.addScriptTag({content:fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/native-companion-workspace.js'),'utf8')});
await assert.doesNotReject(()=>page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('connected')));
await page.check('#native-follow');await page.waitForFunction(()=>document.querySelector('iframe').src.includes('sceneId=20'));assert.ok((await page.locator('iframe').getAttribute('src')).includes('pinned=true'));
await page.check('#native-follow');await page.waitForFunction(()=>document.querySelector('iframe').src.includes('sceneId=20'));assert.ok((await page.locator('iframe').getAttribute('src')).includes('pinned=true'));assert.match(await page.locator('#native-current-scene').textContent(),/Live from Word.*Arrival.*The letter/);
await page.evaluate(()=>{document.querySelector('#native-follow').checked=false;live[0].sceneId=21;polls[0]();});await page.waitForTimeout(30);assert.ok((await page.locator('iframe').getAttribute('src')).includes('sceneId=20'),'manual mode does not snap back to Word');
await page.evaluate(()=>{live=[];polls[0]();});await page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('disconnected'));assert.equal(await page.isChecked('#native-follow'),false);
await page.evaluate(()=>{live=[{wordAvailable:false,updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}];polls[0]();});await page.waitForFunction(()=>document.querySelector('#native-presence-status').textContent.includes('Word unavailable'));

View File

@ -1,3 +1,4 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using PlotDirector.Companion.Protocol;
@ -50,6 +51,10 @@ internal static class NativeManuscriptCaptureTests
store.Remove(7,"grant",source.InstanceId,source.SessionId);Check((await scans.GetPreviewAsync(7,source.RequestId))?.Chapters[0].ChapterText=="Words remain exact.\r","Accepted manuscript survives Word/agent disconnection");
var restarted=new ManuscriptScanPreviewStore(services.GetRequiredService<IServiceScopeFactory>(),NullLogger<ManuscriptScanPreviewStore>.Instance);Check((await restarted.GetStateAsync(7,4)).PreviewID==source.RequestId&&(await restarted.GetLatestPreviewAsync(7,4))?.NativeParagraphPositions[2]==10,"Server restart reloads accepted source and coordinate provenance");
Check(await restarted.GetPreviewAsync(8,source.RequestId)==null,"Recovered source remains account scoped");
var config=new Microsoft.Extensions.Configuration.ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"Features:ParagraphManuscripts","true"}}).Build();
var automatic=new NativeManuscriptCapture(store,scans,TimeProvider.System,captureServices.GetRequiredService<IServiceScopeFactory>(),config);
store.Put(7,"grant",DateTimeOffset.UtcNow.AddHours(1),source.InstanceId,source.SessionId,new(){BookId=3,ManuscriptId=source.ManuscriptId,Sequence=20,Revision=1,WordSaved=true,CanCapture=true,CanParagraphSync=true,Active=true,DocumentTitle="Version18 manuscript"});
await automatic.Start(7,4,1,3);Check(store.TakeNavigation(7,"grant",source.InstanceId,source.SessionId)?.ParagraphTracking==true,"Ordinary import automatically captures paragraph identities with Companion18; no extra opt-in/adoption step");
store.Map(7,3,source.ManuscriptId,source.SessionId,1,30,[(0,10,null),(10,10,20)]);lease.CursorStart=11;
Check(store.Resolve(7,lease,source.SessionId)?.Scene==20,"Approved saved capture resolves an exact-session scene");lease.WordSaved=false;Check(store.Resolve(7,lease,source.SessionId)==null,"Dirty Word state cannot reuse positional evidence");lease.WordSaved=true;lease.Revision=2;Check(store.Resolve(7,lease,source.SessionId)==null,"Changed revision cannot reuse positional evidence");
}

View File

@ -0,0 +1,23 @@
using System.Text.Json;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.Manuscript;
using PlotDirector.Companion.Protocol.Manuscript;
internal static class ParagraphBackupTests
{
public static void Run()
{
var state=ParagraphManuscriptEngine.Bootstrap(3,1,Guid.NewGuid(),[new(){Text="The letter arrived.\r",Start=0,End=20},new(){Text="She understood.\r",Start=20,End=36}],[new(){SceneId=5,ChapterId=4,Title="The letter",Start=1,End=2}]);
state.EventPositions=[new(){Kind="Knowledge",Id=6,SceneId=5}];ParagraphManuscriptEngine.Anchor(state,"Knowledge",6,true,0,0,null,null);state.SessionId=Guid.NewGuid();state.Mode="OnSave";
var graph=new ProjectBackupExport{FormatVersion="1.5",Project=new(){ProjectID=1,ProjectName="Portable paragraphs"},Data=new(){Books=[new(){BookID=3,ProjectID=1}],Chapters=[new(){ChapterID=4,BookID=3}],Scenes=[new(){SceneID=5,ChapterID=4}],CharacterKnowledge=[new(){CharacterKnowledgeID=6,SceneID=5}]},Recovery=new(){ParagraphManuscripts=[state]}};
ParagraphRecovery.Validate(graph);var ids=state.Paragraphs.Select(p=>p.Occurrence.Id).ToArray();var scene=state.Scenes.Single().Id;var evidence=state.Evidence.Single().Id;
var clone=BookBackupGraph.Clone(graph);clone.Project!.ProjectID=10;
ParagraphRecovery.Remap(clone,(type,id)=>id+100);
var restored=clone.Recovery.ParagraphManuscripts!.Single();
if(!restored.Paragraphs.Select(p=>p.Occurrence.Id).SequenceEqual(ids)||restored.Scenes.Single().Id!=scene||restored.Evidence.Single().Id!=evidence||restored.BookId!=103||restored.ProjectId!=10||restored.Scenes.Single().CanonicalId!=105||restored.Evidence.Single().EventId!=106||restored.Evidence.Single().DerivedSceneId!=105||restored.SessionId!=Guid.Empty||restored.WordRevision!=-1||restored.Mode!="Manual")throw new Exception("Paragraph portable identity/remapping/session detachment failed.");
if(JsonSerializer.Serialize(new ProjectRecoveryState()).Contains("ParagraphManuscripts"))throw new Exception("Legacy backup hashes changed.");
var incomplete=BookBackupGraph.Clone(graph);incomplete.Recovery.ParagraphManuscripts=null;try{ParagraphRecovery.Validate(incomplete);throw new Exception("Incomplete recovery accepted");}catch(ArgumentException){}
graph.Recovery.ParagraphManuscripts![0].Evidence[0].EventId=999;try{ParagraphRecovery.Validate(graph);throw new Exception("Unresolved event accepted");}catch(ArgumentException){}
Console.WriteLine("PASS paragraph backup contract: portable occurrence/scene/evidence GUIDs, typed local-ID remapping, legacy hashes, detached sessions and invalid reference refusal");
}
}

View File

@ -0,0 +1,28 @@
using System.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.FileProviders;
using PlotLine.Models;
using PlotLine.Services;
internal static class ParagraphLiveAiTests
{
private sealed class Host:IWebHostEnvironment{public string WebRootPath{get;set;}="";public IFileProvider WebRootFileProvider{get;set;}=new NullFileProvider();public string ApplicationName{get;set;}="PlotLine";public IFileProvider ContentRootFileProvider{get;set;}=new NullFileProvider();public string ContentRootPath{get;set;}="/srv/repos/PlotDirector/PlotLine";public string EnvironmentName{get;set;}="Development";}
public static async Task Run()
{
// Explicit live test only: synthetic prose, existing Development settings, no manuscript/user data.
var info=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};foreach(var value in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})info.ArgumentList.Add(value);using var process=Process.Start(info)!;var text=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new Exception("Development settings unavailable.");
var values=text.Split('\n').Where(l=>!l.StartsWith('#')&&l.Contains('=')).Select(l=>l.Split('=',2)).ToDictionary(v=>v[0].Replace("__",":"),v=>(string?)v[1].Trim().Trim('\'', '"'));
async Task<string> Read(string path){var read=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};foreach(var arg in new[]{"-n","cat",path})read.ArgumentList.Add(arg);using var child=Process.Start(read)!;var content=await child.StandardOutput.ReadToEndAsync();await child.WaitForExitAsync();if(child.ExitCode!=0)throw new Exception("Development configuration read failed.");return content;}
var configuration=new ConfigurationBuilder().AddJsonStream(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(await Read("/srv/apps/plotdirector-dev/current/appsettings.json")))).AddJsonStream(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(await Read("/srv/apps/plotdirector-dev/current/appsettings.Development.json")))).AddInMemoryCollection(values).Build();
var options=new StoryIntelligenceOptions();configuration.GetSection("OpenAI").Bind(options);configuration.GetSection("StoryIntelligence").Bind(options);if(string.IsNullOrWhiteSpace(options.ApiKey))throw new Exception("No Development AI credential configured.");
using var http=new HttpClient{Timeout=TimeSpan.FromMinutes(4)};using var cache=new MemoryCache(new MemoryCacheOptions());
var service=new ManuscriptStructureAnalysisService(new StoryPromptRepository(new Host(),cache,NullLogger<StoryPromptRepository>.Instance),new StoryPromptVersionService(),new StoryIntelligenceClient(http,Options.Create(options),NullLogger<StoryIntelligenceClient>.Instance,new StoryIntelligenceRequestLimiter(Options.Create(options))),new ChapterStructureValidator(),NullLogger<ManuscriptStructureAnalysisService>.Instance);
string[] paragraphs=["At dawn, Mara waited at the station. The porter handed her an unopened letter. She read the address and boarded the train.","She sat beside the window as the train left. The letter remained sealed in her coat pocket.","Three days later, on a distant island, Tomas extinguished the lighthouse lamp. He checked the silent radio and watched the storm approach.","He locked the lighthouse door and walked towards the empty harbour."];
var result=await service.AnalyseChapterAsync(new(){PrivateAnalysis=true,ConfidenceContractVersion=2,TemporaryChapterKey="synthetic-live",ChapterText=string.Join("\n\n",paragraphs),ParagraphMap=paragraphs.Select((p,i)=>new ManuscriptScanParagraphMap{StructuralParagraphOrdinal=i+1,WordParagraphIndex=i+1,Text=p}).ToArray(),SourceParagraphs=paragraphs.Select((p,i)=>new ManuscriptScanSourceParagraph{WordParagraphIndex=i+1,Text=p,IncludeInSourceText=true}).ToArray()});
if(!result.Success)throw new Exception("Live strict integer chapter analysis failed; no author source was submitted or changed.");
Console.WriteLine($"PASS live Development AI: schema2 integer chapter contract accepted, {result.Scenes.Count} scene proposals mapped within four submitted synthetic paragraphs");
}
}

View File

@ -127,7 +127,9 @@ if(args.Contains("--release-sprint")){ReleaseSprintTests.Run();Console.WriteLine
if(args.Contains("--native-import")){await NativeImportTests.Run();Console.WriteLine("PASS approved native import preview, source preservation, ownership, version and retry");return;}
if(args.Contains("--native-installation")){await NativeInstallationTests.Run();Console.WriteLine("PASS trusted installation access, renewal, process replacement, account isolation and revocation");return;}
if(args.Contains("--paragraph-view")){await ParagraphViewTests.Run();return;}
if(args.Contains("--paragraph-manuscripts")){ParagraphManuscriptTests.Run();await ParagraphWorkflowTests.Run();return;}
if(args.Contains("--paragraph-live-ai")){await ParagraphLiveAiTests.Run();return;}
if(args.Contains("--paragraph-backups")){ParagraphBackupTests.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;}
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;}

View File

@ -62,9 +62,6 @@ BEGIN TRY EXEC dbo.ParagraphManuscript @Action='save',@UserID=@User,@BookID=@Boo
IF @Denied=0 OR (SELECT Revision FROM dbo.BookParagraphManuscripts WHERE BookID=@Book)<>6 THROW 51000,'An unmapped author scene was silently reordered',1;
PRINT 'PASS unmapped canonical author scene causes refusal without snapshot mutation';
SET @Denied=0;
BEGIN TRY EXEC dbo.ProjectRecovery_State @ProjectID=@Project;END TRY BEGIN CATCH IF ERROR_MESSAGE() LIKE 'Paragraph manuscript recovery%' SET @Denied=1;END CATCH;
IF @Denied=0 THROW 51000,'Legacy backup silently omitted new author evidence',1;
PRINT 'PASS legacy backup refuses silent omission of paragraph evidence';
SET @Denied=0;
BEGIN TRY EXEC dbo.ParagraphManuscript @Action='get',@UserID=@Other,@BookID=@Book;END TRY BEGIN CATCH IF ERROR_MESSAGE()='Book access denied' SET @Denied=1;END CATCH;
IF @Denied=0 THROW 51000,'Cross-account manuscript leak',1;

View File

@ -19,10 +19,10 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC
input.Navigation=null;
if(input.BookId<0)return BadRequest();
var book=input.BookId>0?await access.GetBookStructureAsync(input.BookId,Author):null;if(input.BookId>0&&book==null)return Forbid();
if(book==null){input.ChapterId=null;input.SceneId=null;}
if(book==null||!input.WordAvailable){input.ChapterId=null;input.SceneId=null;}
if(input.CursorStart is <0)return BadRequest("Invalid cursor position.");
if(input.CanCapture&&input.WordSaved!=true){input.ChapterId=null;input.SceneId=null;}
var paragraphPosition=book!=null&&input.CanParagraphSync&&input.CursorStart.HasValue&&capture!=null?await capture.ResolveParagraphPosition(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value):null;
var paragraphPosition=book!=null&&input.WordAvailable&&input.CanParagraphSync&&input.CursorStart.HasValue&&capture!=null?await capture.ResolveParagraphPosition(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value):null;
if(paragraphPosition!=null){input.ParagraphRevision=paragraphPosition.Revision;input.ChapterId=input.WordSaved==true?paragraphPosition.ChapterID:null;input.SceneId=input.WordSaved==true?paragraphPosition.SceneID:null;}
if(paragraphPosition==null&&book!=null&&input.WordAvailable&&input.SceneId==null&&presence.Resolve(Author,input,session) is {} known){input.ChapterId=known.Chapter;input.SceneId=known.Scene;}
if(paragraphPosition==null&&book!=null&&input.WordAvailable&&input.SceneId==null&&input.CursorStart.HasValue&&positions!=null&&(!input.CanCapture||input.WordSaved==true)){var mapped=await positions.Resolve(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value);if(mapped!=null&&(!input.ChapterId.HasValue||input.ChapterId==mapped.ChapterID)){input.ChapterId=mapped.ChapterID;input.SceneId=mapped.SceneID;}}

View File

@ -19,8 +19,8 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB
[HttpGet("presence")]
public async Task<IActionResult> Presence(int bookId)
{
if(await access.GetBookStructureAsync(bookId,Author)==null)return Forbid();Response.Headers.CacheControl="no-store";
return Json(presence.Read(Author,bookId).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,manuscriptId=l.Position.ManuscriptId,l.Position.BookId,l.Position.ChapterId,l.Position.SceneId,l.Position.DocumentTitle,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
var structure=await access.GetBookStructureAsync(bookId,Author);if(structure==null)return Forbid();Response.Headers.CacheControl="no-store";
return Json(presence.Read(Author,bookId).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,manuscriptId=l.Position.ManuscriptId,chapterTitle=structure.Chapters.FirstOrDefault(c=>c.ChapterId==l.Position.ChapterId)?.Title,sceneTitle=structure.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault(s=>s.SceneId==l.Position.SceneId)?.Title,l.Position.CanParagraphSync,l.Position.BookId,l.Position.ChapterId,l.Position.SceneId,l.Position.DocumentTitle,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
}
[HttpPost("import/preview"),ValidateAntiForgeryToken]
public async Task<IActionResult> ImportPreview(int bookId,Guid[] reviews,[FromServices] NativeImportService importer)

View File

@ -17,6 +17,8 @@ public sealed class BookRecoveryRepository(ISqlConnectionFactory factory, IDataP
public static async Task<ProjectRecoveryState> ReadState(ISqlConnectionFactory factory, int project, IDataProtectionProvider? protection, IDbConnection? connection = null, IDbTransaction? transaction = null)
{
using var owned = connection == null ? factory.CreateConnection() : null; var db = connection ?? owned!; using var rows = await db.QueryMultipleAsync("dbo.ProjectRecovery_State", new { ProjectID = project }, transaction: transaction, commandType: CommandType.StoredProcedure); var result = new ProjectRecoveryState { NativeReviews = (await rows.ReadAsync<PortableNativeReview>()).ToList(), IntentAssessments = (await rows.ReadAsync<PortableIntentAssessment>()).ToList() }; var references = await rows.ReadSingleOrDefaultAsync<string>(); result.ExternalReferences = references == null ? [] : JsonSerializer.Deserialize<List<PortableExternalReference>>(references) ?? [];
if(!rows.IsConsumed){var paragraphs=(await rows.ReadAsync<string>()).Select(json=>JsonSerializer.Deserialize<ParagraphManuscript>(json)??throw new InvalidDataException("Invalid paragraph recovery state.")).ToList();if(paragraphs.Count>0)result.ParagraphManuscripts=paragraphs;}
foreach(var state in result.ParagraphManuscripts??[])PlotLine.Services.Manuscript.ParagraphRecovery.Detach(state);
foreach(var r in result.NativeReviews){
if(r.EncryptedSource!=null){if(protection==null)throw new InvalidOperationException("Source protection is required to export captured reviews safely.");var capture=JsonSerializer.Deserialize<PlotDirector.Companion.Protocol.AiChapterRequest>(protection.CreateProtector("NativeImport.Source.v1").Unprotect(r.EncryptedSource))??throw new InvalidDataException("Invalid captured source");capture.SessionId=Guid.Empty;r.SourceJson=JsonSerializer.Serialize(capture);r.EncryptedSource=null;}
var resultJson=System.Text.Json.Nodes.JsonNode.Parse(r.ResultJson)!.AsObject();resultJson.Remove("CaptureSession");r.ResultJson=resultJson.ToJsonString();
@ -26,7 +28,7 @@ public sealed class BookRecoveryRepository(ISqlConnectionFactory factory, IDataP
public static string ProtectState(ProjectRecoveryState state, IDataProtectionProvider? protection)
{
// The SQL apply path receives locally protected captures; exported JSON never contains this ciphertext.
return JsonSerializer.Serialize(new { Protected = true, state.ExternalReferences, NativeReviews = state.NativeReviews.Select(r => new { r.ReviewID, r.UserID, r.BookID, r.ManuscriptID, r.ChapterStart, r.ChapterEnd, r.ContentHash, r.ResultJson, r.DecisionsJson, r.Version, r.CreatedUtc, EncryptedSource = r.SourceJson == null ? null : (protection ?? throw new InvalidOperationException("Source protection unavailable")).CreateProtector("NativeImport.Source.v1").Protect(r.SourceJson) }), state.IntentAssessments });
return JsonSerializer.Serialize(new { Protected = true, state.ExternalReferences, NativeReviews = state.NativeReviews.Select(r => new { r.ReviewID, r.UserID, r.BookID, r.ManuscriptID, r.ChapterStart, r.ChapterEnd, r.ContentHash, r.ResultJson, r.DecisionsJson, r.Version, r.CreatedUtc, EncryptedSource = r.SourceJson == null ? null : (protection ?? throw new InvalidOperationException("Source protection unavailable")).CreateProtector("NativeImport.Source.v1").Protect(r.SourceJson) }), state.IntentAssessments, state.ParagraphManuscripts });
}
public static string Encode(ProjectBackupExport backup, IDataProtectionProvider? protection,int[]? appendBooks=null) { var node = System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(backup))!; node["Recovery"] = System.Text.Json.Nodes.JsonNode.Parse(ProtectState(backup.Recovery, protection));if(appendBooks!=null){node["Recovery"]!["AppendOnly"]=true;node["Recovery"]!["AppendBooks"]=JsonSerializer.SerializeToNode(appendBooks);} return node.ToJsonString(); }
public async Task ApplyState(int project, ProjectRecoveryState state) { using var db = factory.CreateConnection(); await db.ExecuteAsync("dbo.ProjectRecovery_Apply", new { ProjectID = project, StateJson = ProtectState(state, protection) }, commandType: CommandType.StoredProcedure); }

View File

@ -306,6 +306,7 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
}
};
backup.Recovery=await BookRecoveryRepository.ReadState(connectionFactory,projectId,protection,connection,transaction);
if(backup.Recovery.ParagraphManuscripts!=null)backup.FormatVersion="1.5";
transaction?.Commit();
return backup;
}

View File

@ -36,3 +36,9 @@ Restored native review captures are historical and disconnected from live Word s
Saved **Restore Points** rewind the same project and create a safety snapshot first. They are separate from adding books from a downloaded backup. **Unarchive** only brings an existing book back into view.
Packages are limited to 64 MiB; choose fewer books if needed. Restore previews identify special files that must be recovered as binary downloads for safety. Their original bytes are preserved.
## Word paragraph data
Current backups include saved Word paragraph identities, scene groupings, evidence passages and author review decisions. Books with this data use project snapshot format 1.5 inside book package 2.1. Older supported backups remain readable.
Restoring preserves paragraph, scene and evidence identities while remapping database references to the destination. Live Word sessions are not restored. Select the restored book in Companion and use **Manuscript structure and evidence → Synchronise from Word**; choose On Save there if you want subsequent saved changes synchronised automatically.

View File

@ -61,3 +61,11 @@ Access credentials last ten minutes and renew automatically. The separate instal
The connection states are **Connected**, **Reconnecting**, **Disconnected** and **Action required**. A connected agent does not mean a Word document is connected. Check document registration separately. If access to a book is removed, its saved association cannot authorise a manuscript transfer.
Version 1.0.0.13 never stored installation approval. After upgrading to 1.0.0.14 and the matching server update, approve this installation once; subsequent normal reconnects do not need approval. Windows-protected storage and native startup still require qualification on your actual Windows profile. Do not use a private Codex profile as evidence of a normal-user installation.
## Manuscript import and scene following
With Companion 1.0.0.18, use the existing **Import manuscript** wizard. Paragraph identities and chapter/scene mappings are captured automatically; no separate adoption step or individual scene approval is needed. Save Word normally so its document identity is retained.
After structure import, open **Book → Manuscript structure and evidence** to split or merge scenes, move boundaries, undo layout changes and review story evidence. Saved Word changes synchronise after import/analysis finishes. No Word prose is rewritten.
Open **Context** or **Intent** from PlotDirector. **Live from Word** shows the current chapter and scene. Manual navigation pauses following; **Return to current Word scene** resumes it. Unsaved, stale or ambiguous positions do not claim a live scene. Saved information remains available when Word is disconnected.

View File

@ -283,7 +283,7 @@ public sealed class WordCompanionFollowHub(
}
if(nativeCapture!=null&&await nativeCapture.Built(userId,previewId,result)){
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildProgress",new OnboardingBuildProgress{Status="Complete",Message="Chapters, scenes and manuscript sources are saved in PlotDirector. Continue the existing review stages. Word text and markers have not been rewritten; live scene mapping is limited to this unchanged saved capture.",PercentComplete=100,PreviewID=previewId,BuildID=result.BuildID});
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildProgress",new OnboardingBuildProgress{Status="Complete",Message="Chapters, scenes and manuscript sources are saved in PlotDirector. Paragraph-capable imports have their scene mappings ready; continue the existing review stages. Word text and markers have not been rewritten.",PercentComplete=100,PreviewID=previewId,BuildID=result.BuildID});
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildCompleted",result);
return result;
}

View File

@ -13,6 +13,8 @@ public sealed class BookRecoveryReceipt { public bool AlreadyCompleted { get; se
public sealed class BookRecoveryMapping { public string PortableKey { get; set; } = ""; public string Collection { get; set; } = ""; public int DestinationID { get; set; } public string SourceHash { get; set; } = ""; public string DestinationHash { get; set; } = ""; }
public sealed class ProjectRecoveryState
{
[System.Text.Json.Serialization.JsonIgnore(Condition=System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public List<ParagraphManuscript>? ParagraphManuscripts {get;set;}
public List<PortableExternalReference> ExternalReferences { get; set; } = [];
public List<PortableNativeReview> NativeReviews { get; set; } = []; public List<PortableIntentAssessment> IntentAssessments { get; set; } = [];
}

View File

@ -73,6 +73,7 @@ public sealed class ManuscriptEventOption {public string Kind {get;set;}="";publ
public sealed class ParagraphBootstrapScene {public int SceneId {get;set;}public int ChapterId {get;set;}public string Title {get;set;}="";public int Start {get;set;}public int End {get;set;}public bool NeedsRefinement {get;set;}}
public sealed class ParagraphWorkspaceModel
{
public int BookID=>State.BookId;public int ProjectID=>State.ProjectId;
public ParagraphManuscript State {get;set;}=new();public string BookTitle {get;set;}="";public IReadOnlyList<ManuscriptEventOption> Events {get;set;}=[];public int Page {get;set;}=1;public int EvidencePage {get;set;}=1;public string? Message {get;set;}
}

View File

@ -3,7 +3,7 @@ namespace PlotLine.Models;
public sealed class ProjectBackupExport
{
public string Format { get; init; } = "PlotDirector.ProjectBackup";
public string FormatVersion { get; init; } = "1.4";
public string FormatVersion { get; set; } = "1.4";
public ProjectRecoveryState Recovery {get;set;}=new();
public DateTime ExportedAtUtc { get; init; }
public string SourceApplication { get; init; } = "PlotDirector";

View File

@ -52,6 +52,7 @@ public static class BookBackupGraph
SetRows(b, "TimelineViewPresets", retainedPresets);
var error = ProjectBackupMapValidation.Validate(b) ?? ProjectBackupGraphValidation.Validate(b, true); if (error != null) throw new ArgumentException("The selection has a dependency outside these books. Include the related books. " + error);
b.Recovery.NativeReviews = b.Recovery.NativeReviews.Where(r => books.Contains(r.BookID)).ToList(); b.Recovery.IntentAssessments = b.Recovery.IntentAssessments.Where(r => scenes.Contains(r.SceneID)).ToList();
if(b.Recovery.ParagraphManuscripts!=null)b.Recovery.ParagraphManuscripts=b.Recovery.ParagraphManuscripts.Where(s=>books.Contains(s.BookId)).ToList();
SetRows(b, "ProjectAccess", []); SetRows(b, "UserFiles", []);
ProjectBackupFiles.Prune(b); return b;
}
@ -70,6 +71,7 @@ public static class BookBackupGraph
if (p.Name == "TimelineMetricSettings") next = next.Where(r => !original.Any(o => Equals(Value(o, "ProjectID"), Value(r, "ProjectID")) && Equals(Value(o, "MetricTypeID"), Value(r, "MetricTypeID")))).ToArray();
SetRows(destination, p.Name, original.Concat(next).DistinctBy(r => StoredHash(p.Name, r)));
}
if(incoming.Recovery.ParagraphManuscripts!=null){destination.FormatVersion="1.5";destination.Recovery.ParagraphManuscripts??=[];destination.Recovery.ParagraphManuscripts.AddRange(incoming.Recovery.ParagraphManuscripts);}
destination.Recovery.ExternalReferences.AddRange(incoming.Recovery.ExternalReferences);
destination.Recovery.NativeReviews.AddRange(incoming.Recovery.NativeReviews); destination.Recovery.IntentAssessments.AddRange(incoming.Recovery.IntentAssessments);
}
@ -77,6 +79,7 @@ public static class BookBackupGraph
{
int Id(string type, int old) => maps.TryGetValue(type, out var rows) && rows.TryGetValue(old, out var value) ? value : throw new ArgumentException("Recovery state has an unresolved " + type + " reference.");
string Key(string key) => key.StartsWith("checklist-", StringComparison.Ordinal) && int.TryParse(key[10..], out var old) ? maps.TryGetValue("SceneChecklistItems", out var ids) && ids.TryGetValue(old, out var mapped) ? "checklist-" + mapped : "historical-" + key : key;
PlotLine.Services.Manuscript.ParagraphRecovery.Remap(b,Id);
var manuscripts = new Dictionary<(Guid, int), Guid>();
foreach (var review in b.Recovery.NativeReviews)
{
@ -94,8 +97,9 @@ public static class BookBackupGraph
}
public static string Validate(BookBackupPackage package)
{
if (package.Snapshot.FormatVersion != "1.4") throw new ArgumentException("Current book backup requires a complete recovery snapshot.");
if (package.Format != "PlotDirector.BookBackup" || package.FormatVersion != "2.0" || package.SourceProjectKey == Guid.Empty) throw new ArgumentException("Unsupported book backup version.");
if (package.Snapshot.FormatVersion is not ("1.4" or "1.5")) throw new ArgumentException("Current book backup requires a complete recovery snapshot.");
if (package.Format != "PlotDirector.BookBackup" || package.FormatVersion is not ("2.0" or "2.1") || package.SourceProjectKey == Guid.Empty) throw new ArgumentException("Unsupported book backup version.");
if((package.Snapshot.FormatVersion=="1.5")!=(package.FormatVersion=="2.1"))throw new ArgumentException("Backup package and paragraph recovery versions do not match.");
var expected = Hash(new { package.SourceProjectKey, package.Snapshot, package.Identities, package.Warnings }); if (!string.Equals(expected, package.Integrity, StringComparison.Ordinal)) throw new ArgumentException("Backup integrity check failed.");
return ProjectBackupMapValidation.Validate(package.Snapshot) ?? ProjectBackupGraphValidation.Validate(package.Snapshot, true) ?? ProjectBackupFiles.Validate(package.Snapshot) ?? "";
}

View File

@ -26,7 +26,7 @@ public sealed class BookRecoveryService(IProjectBackupRepository backups, IImpor
if(!used.Add(candidate))throw new ArgumentException("Ambiguous portable identities require an independent backup project.");identities[entity.Collection+":"+id]=candidate;
}
graph.Recovery.ExternalReferences=graph.Recovery.ExternalReferences.Select(r=>{var pieces=r.TargetKey.Split('/');return pieces.Length==3&&pieces[0]==origin.ToString("N")&&identities.TryGetValue(pieces[1]+":"+pieces[2],out var key)?r with{TargetKey=key}:r;}).ToList();
var package=new BookBackupPackage{SourceProjectKey=origin,Snapshot=graph};
var package=new BookBackupPackage{SourceProjectKey=origin,Snapshot=graph,FormatVersion=graph.FormatVersion=="1.5"?"2.1":"2.0"};
foreach(var entity in ProjectBackupGraphValidation.Entities.Where(e=>e.Identity!=null))foreach(var row in BookBackupGraph.Rows(graph,entity.Collection))if(BookBackupGraph.Value(row,entity.Identity!) is int id)package.Identities[entity.Collection+":"+id]=identities[entity.Collection+":"+id];
package.Warnings = ["Contains saved books and common project definitions. Keep this file private. Download does not delete books or prove a safe local copy.", "Native review captures are historical and unbound. Import receipts, credentials, live sessions and job authority are not replayed."];
var aliases=new List<BookRecoveryMapping>();foreach(var (collection,id) in forks.Where(f=>package.Identities.ContainsKey(f.Collection+":"+f.ID))){var identity=BookBackupGraph.Identity(collection)!;var row=BookBackupGraph.Rows(graph,collection).Single(r=>Equals(BookBackupGraph.Value(r,identity),id));var actual=BookBackupGraph.Rows(source,collection).Single(r=>Equals(BookBackupGraph.Value(r,identity),id));aliases.Add(new(){Collection=collection,DestinationID=id,PortableKey=package.Identities[collection+":"+id],SourceHash=SourceFingerprint(package,graph,collection,row),DestinationHash=SourceHash(graph,collection,actual)});}if(aliases.Count>0)await repository.RegisterForks(project,User,aliases);
@ -43,7 +43,7 @@ public sealed class BookRecoveryService(IProjectBackupRepository backups, IImpor
if(package.Snapshot.Recovery.ExternalReferences.Any(r=>r==null||r.TargetKey==null)||package.Snapshot.Recovery.NativeReviews.Any(r=>r==null)||package.Snapshot.Recovery.IntentAssessments.Any(r=>r==null))throw new ArgumentException("The backup contains invalid recovery records.");
if(!doc.RootElement.EnumerateObject().Any(p=>p.Name.Equals("FormatVersion",StringComparison.OrdinalIgnoreCase)&&p.Value.ValueKind==JsonValueKind.String))throw new ArgumentException("The backup version is missing.");
var error = BookBackupGraph.Validate(package); if (error != "") throw new ArgumentException(error);
var snapshot = doc.RootElement.EnumerateObject().First(p => p.Name.Equals("Snapshot", StringComparison.OrdinalIgnoreCase)).Value;RejectServerCiphertext(snapshot);if(!snapshot.EnumerateObject().Any(p=>p.Name.Equals("FormatVersion",StringComparison.OrdinalIgnoreCase)&&p.Value.ValueKind==JsonValueKind.String&&p.Value.GetString()=="1.4"))throw new ArgumentException("The recovery snapshot version is missing or unsupported.");
var snapshot = doc.RootElement.EnumerateObject().First(p => p.Name.Equals("Snapshot", StringComparison.OrdinalIgnoreCase)).Value;RejectServerCiphertext(snapshot);if(!snapshot.EnumerateObject().Any(p=>p.Name.Equals("FormatVersion",StringComparison.OrdinalIgnoreCase)&&p.Value.ValueKind==JsonValueKind.String&&p.Value.GetString() is "1.4" or "1.5"))throw new ArgumentException("The recovery snapshot version is missing or unsupported.");
if (!ProjectBackupCollectionPresence.HasRecovery(snapshot.GetRawText()) || ProjectBackupCollectionPresence.AbsentPersistentCollections(snapshot.GetRawText()).Count > 0 || ProjectBackupStoredFieldContract.Missing(snapshot.GetRawText(), true).Count > 0) throw new ArgumentException("Current backup is incomplete. Required recovery data cannot be inferred.");
}
else
@ -62,6 +62,7 @@ public sealed class BookRecoveryService(IProjectBackupRepository backups, IImpor
private static void RejectDuplicateProperties(JsonElement node) { if (node.ValueKind == JsonValueKind.Object) { var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var field in node.EnumerateObject()) { if (!names.Add(field.Name)) throw new ArgumentException("Backup contains ambiguous duplicate JSON fields."); RejectDuplicateProperties(field.Value); } } else if (node.ValueKind == JsonValueKind.Array) foreach (var item in node.EnumerateArray()) RejectDuplicateProperties(item); }
private static void ValidateState(ProjectBackupExport graph)
{
PlotLine.Services.Manuscript.ParagraphRecovery.Validate(graph);
if (graph.Recovery == null || graph.Recovery.NativeReviews == null || graph.Recovery.IntentAssessments == null||graph.Recovery.ExternalReferences==null||graph.Recovery.NativeReviews.Any(r=>r==null)||graph.Recovery.IntentAssessments.Any(r=>r==null)||graph.Recovery.ExternalReferences.Any(r=>r==null||r.TargetKey==null)) throw new ArgumentException("Recovery decisions are missing.");
foreach (var reference in graph.Recovery.ExternalReferences) { var schema = ProjectBackupGraphValidation.Entities.FirstOrDefault(e => e.Collection == reference.Collection); var parts = reference.TargetKey.Split('/'); if (schema == null || !BookBackupGraph.Common.Contains(reference.Collection) || schema.Identity == null || parts.Length != 3 || !Guid.TryParse(parts[0], out _) || !int.TryParse(parts[2], out var id) || id < 1 || !schema.Links.Any(l => l.Column == reference.Field && l.TargetCollection == parts[1] && l.TargetCollection is "Books" or "Chapters" or "Scenes")) throw new ArgumentException("Invalid external reference metadata."); }
if (graph.Recovery.NativeReviews.Select(r => r.ReviewID).Distinct().Count() != graph.Recovery.NativeReviews.Count) throw new ArgumentException("Duplicate native review identities.");
@ -173,7 +174,7 @@ public sealed class BookRecoveryService(IProjectBackupRepository backups, IImpor
var error = ProjectBackupMapValidation.Validate(graph) ?? ProjectBackupGraphValidation.Validate(graph); if (error != null) throw new ArgumentException(error);
await imports.ApplyProjectBackupJsonAsync(project, BookRecoveryRepository.Encode(graph, protection,target==null?null:prepared.Graph.Data.Books.Select(b=>b.BookID).ToArray()));
foreach(var map in graph.Data.StoryMaps)map.Revision=Math.Max(map.Revision,previousMapRevision)+1; // Audited SQL invalidates prior map edit tokens.
var verified = await backups.GetProjectBackupAsync(project, User) ?? throw new InvalidOperationException("Committed graph verification failed."); await files.CaptureAsync(verified); var mappings = new List<BookRecoveryMapping>(); foreach (var source in prepared.Sources) { var table = BookBackupGraph.Table(source.Collection); if (!prepared.Maps.TryGetValue(table, out var map) || !map.TryGetValue(source.Source, out var id)) continue; var identity = BookBackupGraph.Identity(source.Collection)!; var row = BookBackupGraph.Rows(verified, source.Collection).SingleOrDefault(r => Equals(BookBackupGraph.Value(r, identity), id)) ?? throw new InvalidOperationException("Restored entity verification failed."); var expected=BookBackupGraph.Rows(graph,source.Collection).SingleOrDefault(r=>Equals(BookBackupGraph.Value(r,identity),id));if(source.Collection is not ("GenreMetricPresets" or "GenreMetricPresetMetrics")&&expected!=null&&BookBackupGraph.StoredHash(source.Collection,expected)!=BookBackupGraph.StoredHash(source.Collection,row))throw new InvalidOperationException("Stored "+source.Collection+" fields differ: "+string.Join(",",ProjectBackupStoredFieldContract.Columns(source.Collection).Where(field=>JsonSerializer.Serialize(BookBackupGraph.Value(expected,field))!=JsonSerializer.Serialize(BookBackupGraph.Value(row,field))))+"; nothing was committed.");mappings.Add(new() { PortableKey = source.Key, Collection = source.Collection, DestinationID = id, SourceHash = source.Hash, DestinationHash = SourceHash(verified, source.Collection, row) }); }
var verified = await backups.GetProjectBackupAsync(project, User) ?? throw new InvalidOperationException("Committed graph verification failed."); await files.CaptureAsync(verified); PlotLine.Services.Manuscript.ParagraphRecovery.VerifyStored(graph,verified,prepared.Graph.Data.Books.Select(b=>b.BookID)); var mappings = new List<BookRecoveryMapping>(); foreach (var source in prepared.Sources) { var table = BookBackupGraph.Table(source.Collection); if (!prepared.Maps.TryGetValue(table, out var map) || !map.TryGetValue(source.Source, out var id)) continue; var identity = BookBackupGraph.Identity(source.Collection)!; var row = BookBackupGraph.Rows(verified, source.Collection).SingleOrDefault(r => Equals(BookBackupGraph.Value(r, identity), id)) ?? throw new InvalidOperationException("Restored entity verification failed."); var expected=BookBackupGraph.Rows(graph,source.Collection).SingleOrDefault(r=>Equals(BookBackupGraph.Value(r,identity),id));if(source.Collection is not ("GenreMetricPresets" or "GenreMetricPresetMetrics")&&expected!=null&&BookBackupGraph.StoredHash(source.Collection,expected)!=BookBackupGraph.StoredHash(source.Collection,row))throw new InvalidOperationException("Stored "+source.Collection+" fields differ: "+string.Join(",",ProjectBackupStoredFieldContract.Columns(source.Collection).Where(field=>JsonSerializer.Serialize(BookBackupGraph.Value(expected,field))!=JsonSerializer.Serialize(BookBackupGraph.Value(row,field))))+"; nothing was committed.");mappings.Add(new() { PortableKey = source.Key, Collection = source.Collection, DestinationID = id, SourceHash = source.Hash, DestinationHash = SourceHash(verified, source.Collection, row) }); }
await repository.Complete(plan.Operation, project, User, selected.Data.Books.Count, requestHash, mappings); receipt = new() { ProjectID = project, BooksCreated = selected.Data.Books.Count, RequestHash = requestHash }; transaction.Complete();staged?.Commit(); // Retain bytes if the SQL commit outcome becomes uncertain; receipt retry resolves it safely.
}
staged?.Commit(); return receipt!;

View File

@ -364,7 +364,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
validation.Warnings.Add("Unfinished analysis will be copied as cancelled audit history. No paid analysis is restarted; retained source and raw result JSON remain historical audit data.");
if(backup.Data.OnboardingManuscriptBuilds.Any(build=>build.Status is not ("Built" or "Complete" or "Completed" or "Failed" or "Cancelled") || build.Status=="Built" && build.MarkerStatus is not ("UserConfirmedSave" or "Completed" or "Complete")))
validation.Warnings.Add("Unfinished Word import operations will be copied as cancelled history. They will not restart or send markers to the original document.");
if (backup.FormatVersion is not ("1.3" or "1.4") && ProjectBackupFiles.HasUploads(backup))
if (backup.FormatVersion is not ("1.3" or "1.4" or "1.5") && ProjectBackupFiles.HasUploads(backup))
validation.Warnings.Add("This older backup does not contain uploaded file bytes. Imported copies retain text and link metadata, but uploaded images, covers and attachments must be added again.");
if (duplicate)
{
@ -638,7 +638,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
validation.Errors.Add("The project backup does not contain a project name.");
}
if(backup.FormatVersion=="1.4"&&!ProjectBackupCollectionPresence.HasRecovery(jsonText)){validation.Errors.Add("Recovery decisions are missing from this current-format backup.");return true;}
if((backup.FormatVersion is "1.4" or "1.5")&&!ProjectBackupCollectionPresence.HasRecovery(jsonText)){validation.Errors.Add("Recovery decisions are missing from this current-format backup.");return true;}
try{PlotLine.Services.Manuscript.ParagraphRecovery.Validate(backup);}catch(ArgumentException e){validation.Errors.Add(e.Message);return true;}
var mapError = ProjectBackupMapValidation.Validate(backup) ?? ProjectBackupGraphValidation.Validate(backup) ?? ProjectBackupNarrative.ValidatePortableSources(backup) ?? ProjectBackupFiles.Validate(backup);
if(mapError is null && backup.Data.StoryMemoryLocations.Any(location=>location.ParentLocationID.HasValue))
mapError="This backup contains a story-memory parent identifier whose portable relationship is not defined. Same-project restore retains it, but import as a copy is not supported for this field.";
@ -871,7 +872,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
"ScenarioWarnings"
];
private static readonly string[] SupportedProjectBackupVersions = ["1.0", "1.1", "1.2", "1.3", "1.4"];
private static readonly string[] SupportedProjectBackupVersions = ["1.0", "1.1", "1.2", "1.3", "1.4", "1.5"];
internal static Dictionary<string,Dictionary<int,int>> RemapProjectBackupForImport(
ProjectBackupExport backup,
@ -1925,7 +1926,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
image.ProjectID=projectId;
}
foreach (var character in backup.Data.Characters)
character.AvatarSourceCharacterImageID=backup.FormatVersion is ("1.3" or "1.4") ? ExistingOrNewNullable("CharacterImages",character.AvatarSourceCharacterImageID) : null;
character.AvatarSourceCharacterImageID=backup.FormatVersion is ("1.3" or "1.4" or "1.5") ? ExistingOrNewNullable("CharacterImages",character.AvatarSourceCharacterImageID) : null;
foreach (var link in backup.Data.WordCompanionSceneAssets)
{
link.WordCompanionSceneAssetID=NewId("WordCompanionSceneAssets",link.WordCompanionSceneAssetID);

View File

@ -0,0 +1,50 @@
using PlotLine.Models;
namespace PlotLine.Services.Manuscript;
// Recovery uses the existing typed graph maps. Occurrence/scene/evidence GUIDs survive; live leases do not.
public static class ParagraphRecovery
{
public static void Validate(ProjectBackupExport graph)
{
if(graph.Recovery==null){if(graph.FormatVersion=="1.5")throw new ArgumentException("Paragraph recovery state is missing.");return;}
var states=graph.Recovery.ParagraphManuscripts;
if(graph.FormatVersion=="1.5"&&states==null)throw new ArgumentException("Paragraph recovery state is missing from this backup.");
if(states==null)return;
if(graph.FormatVersion!="1.5"||states.Any(s=>s==null))throw new ArgumentException("Paragraph recovery requires project format 1.5.");
if(states.Select(s=>s.BookId).Distinct().Count()!=states.Count)throw new ArgumentException("Duplicate paragraph manuscripts.");
foreach(var state in states){
if(state.Paragraphs==null||state.Scenes==null||state.Chapters==null||state.Evidence==null||state.Undo==null||state.EventPositions==null||state.Paragraphs.Any(p=>p?.Occurrence?.Text==null)||state.Scenes.Any(s=>s==null)||state.Evidence.Any(e=>e==null||e.OriginalText==null||e.ConfirmedText==null||e.CurrentText==null)||state.Chapters.Any(c=>c==null)||state.EventPositions.Any(e=>e==null)||state.Undo.Any(l=>l==null||l.Scenes==null||l.Chapters==null||l.EventPositions==null||l.Assignments==null||l.Scenes.Any(s=>s==null)||l.Chapters.Any(c=>c==null)||l.EventPositions.Any(e=>e==null)||l.Assignments.Any(a=>a==null)))throw new ArgumentException("Paragraph recovery is incomplete.");
ParagraphManuscriptEngine.Validate(state);
if(state.Evidence.Any(e=>e.State is not ("Verified" or "Needs review" or "Missing"))||state.Evidence.GroupBy(e=>(e.EventKind,e.EventId)).Any(g=>g.Count(e=>e.Primary)>1))throw new ArgumentException("Paragraph evidence state or primary passage is invalid.");
int end=0;for(int n=0;n<state.Paragraphs.Count;n++){var p=state.Paragraphs[n].Occurrence;if(p.Ordinal!=n||p.Start!=end||p.End<=p.Start||p.End>16*1024*1024)throw new ArgumentException("Paragraph positions are not contiguous.");end=p.End;}
if(state.Version!=1||state.ManuscriptId==Guid.Empty||state.ProjectId!=graph.Project?.ProjectID||!graph.Data.Books.Any(b=>b.BookID==state.BookId))throw new ArgumentException("Paragraph manuscript scope is invalid.");
bool Chapter(int id)=>graph.Data.Chapters.Any(c=>c.ChapterID==id&&c.BookID==state.BookId);
bool Scene(int id)=>graph.Data.Scenes.Any(s=>s.SceneID==id&&Chapter(s.ChapterID));
bool Event(ManuscriptEventOption e)=>e.Kind switch{"Knowledge"=>graph.Data.CharacterKnowledge.Any(k=>k.CharacterKnowledgeID==e.Id&&Scene(k.SceneID)),"Relationship"=>graph.Data.RelationshipEvents.Any(r=>r.RelationshipEventID==e.Id&&Scene(r.SceneID)),_=>false};
void Layout(IEnumerable<ParagraphScene> scenes,IEnumerable<ParagraphChapter> chapters,IEnumerable<ManuscriptEventOption> events){if(scenes.Any(s=>!Chapter(s.ChapterId)||(s.CanonicalId>0&&!Scene(s.CanonicalId)))||chapters.Any(c=>c.CanonicalId>0&&!Chapter(c.CanonicalId))||events.Any(e=>!Event(e)||!Scene(e.SceneId)))throw new ArgumentException("Paragraph recovery has an unresolved chapter, scene or event reference.");}
Layout(state.Scenes,state.Chapters,state.EventPositions);foreach(var layout in state.Undo)Layout(layout.Scenes,layout.Chapters,layout.EventPositions);
if(state.Paragraphs.Any(p=>p.ChapterId.HasValue&&!Chapter(p.ChapterId.Value))||state.Evidence.Any(e=>!Event(new(){Kind=e.EventKind,Id=e.EventId})||(e.DerivedSceneId>0&&!Scene(e.DerivedSceneId.Value))))throw new ArgumentException("Paragraph evidence belongs to another book.");
var ids=state.Paragraphs.Select(p=>p.Occurrence.Id).ToHashSet();var sceneIds=state.Scenes.Select(s=>s.Id).ToHashSet();
if(state.Undo.Any(l=>l.Assignments.Any(a=>!ids.Contains(a.ParagraphId)||(a.ChapterId.HasValue&&!Chapter(a.ChapterId.Value))||(a.SceneId.HasValue&&!sceneIds.Contains(a.SceneId.Value)))))throw new ArgumentException("Paragraph undo state has unresolved identities.");
}
}
public static void Remap(ProjectBackupExport graph,Func<string,int,int> id)
{
foreach(var state in graph.Recovery.ParagraphManuscripts??[]){
state.BookId=id("Books",state.BookId);state.ProjectId=graph.Project!.ProjectID;
int EventId(string kind,int value)=>id(kind=="Knowledge"?"CharacterKnowledge":kind=="Relationship"?"RelationshipEvents":throw new ArgumentException("Unknown evidence type."),value);
void Layout(IEnumerable<ParagraphScene> scenes,IEnumerable<ParagraphChapter> chapters,IEnumerable<ManuscriptEventOption> events){foreach(var s in scenes){if(s.CanonicalId>0)s.CanonicalId=id("Scenes",s.CanonicalId);s.ChapterId=id("Chapters",s.ChapterId);}foreach(var c in chapters)if(c.CanonicalId>0)c.CanonicalId=id("Chapters",c.CanonicalId);foreach(var e in events){e.Id=EventId(e.Kind,e.Id);e.SceneId=id("Scenes",e.SceneId);}}
Layout(state.Scenes,state.Chapters,state.EventPositions);
foreach(var p in state.Paragraphs)if(p.ChapterId.HasValue)p.ChapterId=id("Chapters",p.ChapterId.Value);
foreach(var e in state.Evidence){e.EventId=EventId(e.EventKind,e.EventId);if(e.DerivedSceneId>0)e.DerivedSceneId=id("Scenes",e.DerivedSceneId.Value);}
foreach(var layout in state.Undo){Layout(layout.Scenes,layout.Chapters,layout.EventPositions);foreach(var a in layout.Assignments)if(a.ChapterId.HasValue)a.ChapterId=id("Chapters",a.ChapterId.Value);}
Detach(state);
}
}
public static void VerifyStored(ProjectBackupExport expected,ProjectBackupExport actual,IEnumerable<int> books)
{
var scope=books.ToHashSet();var left=(expected.Recovery.ParagraphManuscripts??[]).Where(s=>scope.Contains(s.BookId)).ToArray();var right=(actual.Recovery.ParagraphManuscripts??[]).Where(s=>scope.Contains(s.BookId)).ToArray();
if(left.Length!=right.Length)throw new InvalidOperationException("Paragraph recovery verification failed; nothing was committed.");
foreach(var source in left){var saved=right.SingleOrDefault(s=>s.BookId==source.BookId);var canonical=ParagraphManuscriptEngine.Clone(source);Detach(canonical);if(saved==null||System.Text.Json.JsonSerializer.Serialize(canonical)!=System.Text.Json.JsonSerializer.Serialize(saved))throw new InvalidOperationException("Restored paragraph identities, groupings or evidence differ; nothing was committed.");}
}
public static void Detach(ParagraphManuscript state){state.SessionId=Guid.Empty;state.WordRevision=-1;state.LastRequestId=Guid.Empty;if(state.Mode!="Off")state.Mode="Manual";}
}

View File

@ -28,6 +28,7 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc
if(documents.Length==0)return null;
var active=documents.Where(l=>l.Position.Active).ToArray();
var selected=active.Length==1?active[0]:documents.Length==1?documents[0]:throw new InvalidOperationException("More than one Word document is linked to this book. Activate the intended document, then retry.");
paragraphs=paragraphs||(configuration?.GetValue<bool>("Features:ParagraphManuscripts")==true&&selected.Position.CanParagraphSync);
if(pending.Values.Any(p=>p.User==user&&p.Hash==null))throw new InvalidOperationException("A manuscript transfer is already pending. Wait for it to finish or expire before retrying.");
if(pending.Count>=128)throw new InvalidOperationException("Manuscript transfers are busy. Try again later.");
var state=await scans.StartAsync(user,onboarding,project,book);var id=state.ScanID!.Value;

View File

@ -53,7 +53,7 @@ public sealed class OnboardingService(
IManuscriptTextStatisticsService manuscriptTextStatistics,
ICoreImportCharacterMappingService coreImportCharacterMapping,
ICoreImportBasicLocationService coreImportBasicLocations,
ICurrentUserService currentUser,IManuscriptCaptureRepository? captureRepository=null) : IOnboardingService
ICurrentUserService currentUser,IManuscriptCaptureRepository? captureRepository=null,PlotLine.Services.Manuscript.ParagraphManuscriptService? paragraphManuscripts=null) : IOnboardingService
{
private static readonly HashSet<string> WritingJourneys = new(StringComparer.Ordinal)
{
@ -359,6 +359,7 @@ public sealed class OnboardingService(
await manuscriptTextStatistics.RecalculateBookAsync(preview.BookID);
}
await InitialiseParagraphsAsync(userId,preview);
var resumed = await BuildExistingStructureResultAsync(userId, preview, review, existingBuild);
await scanPreviews.SaveBuildResultAsync(userId, resumed);
await PublishBuildProgress(
@ -441,6 +442,7 @@ public sealed class OnboardingService(
await coreImportCharacterMapping.MapBookAsync(preview.ProjectID, preview.BookID);
await ApplyStructuralChronologyAsync(structuralScenes, result);
await ApplyStructuralPovAsync(preview, structuralScenes, result);
await InitialiseParagraphsAsync(userId,preview);
var canonicalSceneSources = await builds.ListSceneManuscriptSourcesByBookAsync(preview.BookID);
var locationReview = await coreImportBasicLocations.EnsurePreparedAsync(
userId,
@ -466,6 +468,13 @@ public sealed class OnboardingService(
return result;
}
private async Task InitialiseParagraphsAsync(int user,ManuscriptScanPreview preview)
{
if(!preview.ParagraphTracking||paragraphManuscripts==null)return;
if(captureRepository!=null)await captureRepository.CompleteBuild(user,preview.PreviewID);
await paragraphManuscripts.Initialise(user,preview,await builds.ListSceneManuscriptSourcesByBookAsync(preview.BookID),preview.ProjectID,"OnSave");
}
private async Task<IReadOnlyList<ManuscriptStructureSceneBoundary>> AnalyseApprovedChaptersAsync(
int userId,
ManuscriptScanPreview preview,

View File

@ -79,7 +79,7 @@ public sealed class ProjectBackupFiles(IUploadStorageService storage) : IProject
public static string? Validate(ProjectBackupExport backup)
{
if(backup.Files is null || backup.Files.Any(file=>file is null))return "Project backup contains invalid file records.";
if(backup.FormatVersion is not ("1.3" or "1.4") && backup.Files.Count>0)return "Embedded files require project backup format 1.3.";
if(backup.FormatVersion is not ("1.3" or "1.4" or "1.5") && backup.Files.Count>0)return "Embedded files require project backup format 1.3.";
var references=References(backup).Where(IsFile).ToArray();
if(references.Any(reference=>!ValidPath(reference)))return "Project backup contains a file path outside its owning entity's upload folder.";
if(backup.Files.Select(file=>file.Path).Distinct(StringComparer.Ordinal).Count()!=backup.Files.Count)return "Project backup contains duplicate file paths.";
@ -87,7 +87,7 @@ public sealed class ProjectBackupFiles(IUploadStorageService storage) : IProject
foreach(var file in backup.Files)
if(file.Path is null || !referenced.Contains(file.Path) || file.Data is null || !string.Equals(file.Sha256,Convert.ToHexString(SHA256.HashData(file.Data)),StringComparison.OrdinalIgnoreCase))
return "Project backup contains an unreferenced file or file bytes do not match their checksum.";
if(backup.FormatVersion is ("1.3" or "1.4") && references.Any(reference=>!backup.Files.Any(file=>file.Path==reference.Path)))
if(backup.FormatVersion is ("1.3" or "1.4" or "1.5") && references.Any(reference=>!backup.Files.Any(file=>file.Path==reference.Path)))
return "Project backup is missing bytes for a referenced uploaded file.";
return null;
}
@ -115,7 +115,7 @@ public sealed class ProjectBackupFiles(IUploadStorageService storage) : IProject
{
foreach(var file in backup.Files){file.RestoredPath=null;file.EntityType=null;file.EntityID=0;}
var references=References(backup).Where(IsFile).ToArray();
if(backup.FormatVersion is not ("1.3" or "1.4"))
if(backup.FormatVersion is not ("1.3" or "1.4" or "1.5"))
{
foreach(var reference in references)
{

View File

@ -135,7 +135,7 @@ public sealed class ProjectRestoreService(
return "Restore point format is not recognised. No project data was changed.";
}
if (backup.FormatVersion is not ("1.0" or "1.1" or "1.2" or "1.3" or "1.4"))
if (backup.FormatVersion is not ("1.0" or "1.1" or "1.2" or "1.3" or "1.4" or "1.5"))
{
return "Restore point format version is not supported. No project data was changed.";
}
@ -145,6 +145,7 @@ public sealed class ProjectRestoreService(
return "This restore point does not belong to the selected project. No project data was changed.";
}
try{PlotLine.Services.Manuscript.ParagraphRecovery.Validate(backup);}catch(ArgumentException e){return e.Message;}
var graphError = ProjectBackupMapValidation.Validate(backup) ?? ProjectBackupGraphValidation.Validate(backup) ?? ProjectBackupFiles.Validate(backup);
if (graphError is not null) return graphError + " No project data was changed.";

View File

@ -0,0 +1,242 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.ProjectParagraphRecovery_Apply @ProjectID int,@StateJson nvarchar(max),@KeepLiveSession bit=0
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
IF @@TRANCOUNT=0 OR ISJSON(@StateJson)<>1 THROW 51000,'Paragraph recovery requires an enclosing transaction',1;
DECLARE @Append bit=CASE WHEN JSON_VALUE(@StateJson,'$.AppendOnly')='true' THEN 1 ELSE 0 END;
DECLARE @Targets table(BookID int PRIMARY KEY);
INSERT @Targets SELECT BookID FROM dbo.Books WHERE ProjectID=@ProjectID AND (@Append=0 OR BookID IN(SELECT TRY_CONVERT(int,value) FROM OPENJSON(@StateJson,'$.AppendBooks')));
DECLARE @States table(BookID int PRIMARY KEY,Payload nvarchar(max));
INSERT @States SELECT TRY_CONVERT(int,JSON_VALUE(value,'$.BookId')),value FROM OPENJSON(@StateJson,'$.ParagraphManuscripts') WHERE @Append=0 OR TRY_CONVERT(int,JSON_VALUE(value,'$.BookId')) IN(SELECT BookID FROM @Targets);
IF EXISTS(SELECT 1 FROM @States m WHERE NOT EXISTS(SELECT 1 FROM @Targets t WHERE t.BookID=m.BookID) OR TRY_CONVERT(int,JSON_VALUE(m.Payload,'$.ProjectId'))<>@ProjectID OR JSON_VALUE(m.Payload,'$.Version')<>'1' OR TRY_CONVERT(uniqueidentifier,JSON_VALUE(m.Payload,'$.ManuscriptId')) IS NULL) THROW 51000,'Paragraph recovery scope is invalid',1;
IF EXISTS(SELECT 1 FROM @States m CROSS APPLY OPENJSON(m.Payload,'$.Scenes') WITH(CanonicalId int,ChapterId int) s LEFT JOIN dbo.Chapters c ON c.ChapterID=s.ChapterId AND c.BookID=m.BookID LEFT JOIN dbo.Scenes actual ON actual.SceneID=s.CanonicalId AND actual.ChapterID=s.ChapterId WHERE c.ChapterID IS NULL OR (s.CanonicalId>0 AND actual.SceneID IS NULL)) THROW 51000,'Paragraph scene reference crosses book boundaries',1;
DELETE p FROM dbo.BookParagraphPositions p JOIN @Targets t ON t.BookID=p.BookID;
DELETE e FROM dbo.ManuscriptEvidenceIndex e JOIN @Targets t ON t.BookID=e.BookID;
DELETE m FROM dbo.BookParagraphManuscripts m JOIN @Targets t ON t.BookID=m.BookID;
DECLARE @Book int,@Payload nvarchar(max),@Request uniqueidentifier,@Revision bigint;
DECLARE manuscripts CURSOR LOCAL FAST_FORWARD FOR SELECT BookID,Payload FROM @States;
OPEN manuscripts;FETCH NEXT FROM manuscripts INTO @Book,@Payload;
WHILE @@FETCH_STATUS=0 BEGIN
IF @KeepLiveSession=0 BEGIN
SET @Payload=JSON_MODIFY(@Payload,'$.SessionId',N'00000000-0000-0000-0000-000000000000');SET @Payload=JSON_MODIFY(@Payload,'$.WordRevision',-1);
IF JSON_VALUE(@Payload,'$.Mode')<>N'Off' SET @Payload=JSON_MODIFY(@Payload,'$.Mode',N'Manual');
SET @Request=NEWID();SET @Payload=JSON_MODIFY(@Payload,'$.LastRequestId',CONVERT(nvarchar(36),@Request));
END ELSE SET @Request=COALESCE(TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.LastRequestId')),NEWID());
SET @Revision=COALESCE(TRY_CONVERT(bigint,JSON_VALUE(@Payload,'$.Revision')),1);
INSERT dbo.BookParagraphManuscripts(BookID,ManuscriptID,Revision,RequestID,Payload) VALUES(@Book,CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId')),@Revision,@Request,@Payload);
INSERT dbo.BookParagraphPositions(BookID,StartPosition,EndPosition,ChapterID,SceneID,Verified)
SELECT @Book,p.StartPosition,p.EndPosition,COALESCE(s.ChapterId,p.ChapterId),s.CanonicalId,p.PositionVerified FROM OPENJSON(@Payload,'$.Paragraphs') WITH(Occurrence nvarchar(max) AS JSON,ChapterId int,SceneId uniqueidentifier,PositionVerified bit) row CROSS APPLY OPENJSON(row.Occurrence) WITH(StartPosition int '$.Start',EndPosition int '$.End') span
CROSS APPLY(SELECT span.StartPosition,span.EndPosition,row.ChapterId,row.PositionVerified) p
OUTER APPLY(SELECT * FROM OPENJSON(@Payload,'$.Scenes') WITH(Id uniqueidentifier,ChapterId int,CanonicalId int) scene WHERE scene.Id=row.SceneId) s;
INSERT dbo.ManuscriptEvidenceIndex(BookID,EvidenceID,EventKind,EventID,IsPrimary,EvidenceState,DerivedSceneID)
SELECT @Book,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 OPENJSON(@Payload,'$.Scenes') WITH(Id uniqueidentifier,CanonicalId int) s ON s.Id=e.CurrentScene;
IF EXISTS(SELECT 1 FROM dbo.ManuscriptEvidenceIndex e WHERE e.BookID=@Book 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=@Book)) 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=@Book)))) THROW 51000,'Paragraph evidence reference crosses book boundaries',1;
FETCH NEXT FROM manuscripts INTO @Book,@Payload;
END;CLOSE manuscripts;DEALLOCATE manuscripts;
END;
GO
CREATE OR ALTER PROCEDURE dbo.ProjectRecovery_State @ProjectID int
AS
BEGIN
SET NOCOUNT ON;
SELECT r.* FROM dbo.NativeChapterReviews r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID;
SELECT r.* FROM dbo.WritingIntentAssessments r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
SELECT ReferencesJson FROM dbo.BookRecoveryExternalReferences WHERE ProjectID=@ProjectID;
SELECT m.Payload FROM dbo.BookParagraphManuscripts m JOIN dbo.Books b ON b.BookID=m.BookID WHERE b.ProjectID=@ProjectID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.ProjectRecovery_Apply @ProjectID int,@StateJson nvarchar(max),@PriorBooks nvarchar(max)=NULL
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
IF @@TRANCOUNT=0 OR ISJSON(@StateJson)<>1 THROW 51000,'Recovery state requires a transaction',1;
DECLARE @Append bit=CASE WHEN JSON_VALUE(@StateJson,'$.AppendOnly')='true' THEN 1 ELSE 0 END;
DECLARE @NewBooks table(ID int PRIMARY KEY);IF @Append=1 INSERT @NewBooks SELECT CONVERT(int,value) FROM OPENJSON(@StateJson,'$.AppendBooks');
IF EXISTS(SELECT 1 FROM OPENJSON(@StateJson,'$.NativeReviews') WITH(BookID int) r WHERE NOT EXISTS(SELECT 1 FROM dbo.Books WHERE BookID=r.BookID AND ProjectID=@ProjectID)) THROW 51000,'Review belongs to another project',1;
IF EXISTS(SELECT 1 FROM OPENJSON(@StateJson,'$.IntentAssessments') WITH(SceneID int) r WHERE NOT EXISTS(SELECT 1 FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE s.SceneID=r.SceneID AND b.ProjectID=@ProjectID)) THROW 51000,'Intent belongs to another project',1;
DELETE r FROM dbo.NativeChapterReviews r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID AND (@Append=0 OR b.BookID IN(SELECT ID FROM @NewBooks));
DELETE r FROM dbo.WritingIntentAssessments r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID AND (@Append=0 OR b.BookID IN(SELECT ID FROM @NewBooks));
INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,Version,CreatedUtc,EncryptedSource)
SELECT ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,Version,CreatedUtc,EncryptedSource FROM OPENJSON(@StateJson,'$.NativeReviews') WITH(ReviewID uniqueidentifier,UserID int,BookID int,ManuscriptID uniqueidentifier,ChapterStart int,ChapterEnd int,ContentHash varchar(64),ResultJson nvarchar(max),DecisionsJson nvarchar(max),Version int,CreatedUtc datetime2,EncryptedSource nvarchar(max)) WHERE @Append=0 OR BookID IN(SELECT ID FROM @NewBooks);
INSERT dbo.WritingIntentAssessments(UserID,SceneID,InputHash,ResultsJson,DecisionsJson,Model,CreatedUtc)
SELECT UserID,SceneID,InputHash,ResultsJson,DecisionsJson,Model,CreatedUtc FROM OPENJSON(@StateJson,'$.IntentAssessments') WITH(UserID int,SceneID int,InputHash char(64),ResultsJson nvarchar(max),DecisionsJson nvarchar(max),Model nvarchar(200),CreatedUtc datetime2) r WHERE @Append=0 OR EXISTS(SELECT 1 FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE s.SceneID=r.SceneID AND c.BookID IN(SELECT ID FROM @NewBooks));
DELETE FROM dbo.BookRecoveryExternalReferences WHERE ProjectID=@ProjectID;
INSERT dbo.BookRecoveryExternalReferences(ProjectID,ReferencesJson) VALUES(@ProjectID,COALESCE(JSON_QUERY(@StateJson,'$.ExternalReferences'),N'[]'));
DECLARE @Affected table(BookID int PRIMARY KEY);INSERT @Affected SELECT BookID FROM dbo.Books WHERE ProjectID=@ProjectID UNION SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int);
-- Never preserve receipts that claim removed canonical chapters/builds still exist.
DELETE r FROM dbo.NativeReviewImports r WHERE r.BookID IN(SELECT BookID FROM @Affected) AND (NOT EXISTS(SELECT 1 FROM dbo.Chapters c JOIN dbo.Books b ON b.BookID=c.BookID WHERE c.ChapterID=r.ChapterID AND b.BookID=r.BookID) OR NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds WHERE OnboardingManuscriptBuildID=r.BuildID));
DELETE r FROM dbo.NativeImportOperations r WHERE r.BookID IN(SELECT BookID FROM @Affected) AND (r.ChaptersCreated<>(SELECT COUNT(*) FROM dbo.NativeReviewImports i JOIN dbo.Chapters c ON c.ChapterID=i.ChapterID AND c.BookID=i.BookID WHERE i.BuildID=r.BuildID AND i.BookID=r.BookID) OR r.ScenesCreated<>(SELECT COUNT(*) FROM dbo.OnboardingManuscriptBuildSceneMap m JOIN dbo.Scenes s ON s.SceneID=m.SceneID WHERE m.OnboardingManuscriptBuildID=r.BuildID));
EXEC dbo.ProjectParagraphRecovery_Apply @ProjectID,@StateJson;
END;
GO
CREATE OR ALTER PROCEDURE dbo.ProjectRestore_ApplyFromJson @ProjectID int,@SourceRestorePointID int=NULL,@SafetyRestorePointID int=NULL,@JsonData nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
DECLARE @State nvarchar(max)=JSON_QUERY(@JsonData,'$.Recovery');
IF @State IS NULL AND (EXISTS(SELECT 1 FROM dbo.NativeChapterReviews r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID) OR EXISTS(SELECT 1 FROM dbo.BookRecoveryExternalReferences WHERE ProjectID=@ProjectID AND ReferencesJson<>N'[]') OR EXISTS(SELECT 1 FROM dbo.WritingIntentAssessments r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID)) THROW 51000,'Older snapshot omits native or Intent author decisions. Replacement refused.',1;
IF JSON_VALUE(@JsonData,'$.FormatVersion') IN ('1.4','1.5') SET @JsonData=JSON_MODIFY(@JsonData,'$.FormatVersion','1.3');
IF ISNULL(JSON_VALUE(@State,'$.AppendOnly'),'false')<>'true' AND JSON_QUERY(@State,'$.ParagraphManuscripts') IS NULL AND EXISTS(SELECT 1 FROM dbo.BookParagraphManuscripts m JOIN dbo.Books b ON b.BookID=m.BookID WHERE b.ProjectID=@ProjectID) THROW 51000,'This older backup omits paragraph evidence present in the destination. Restore it as a new project instead.',1;
BEGIN TRANSACTION;
BEGIN TRY
DECLARE @PriorBooks nvarchar(max)=(SELECT BookID FROM dbo.Books WITH(UPDLOCK,HOLDLOCK) WHERE ProjectID=@ProjectID FOR JSON PATH);
DECLARE @AppendOnly bit=CASE WHEN JSON_VALUE(@State,'$.AppendOnly')='true' THEN 1 ELSE 0 END;
IF @AppendOnly=1 AND (@SourceRestorePointID IS NOT NULL OR NOT EXISTS(SELECT 1 FROM OPENJSON(@State,'$.AppendBooks')) OR EXISTS(SELECT 1 FROM OPENJSON(@PriorBooks) WITH(BookID int) p WHERE NOT EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.Books') WITH(BookID int) b WHERE b.BookID=p.BookID)) OR EXISTS(SELECT 1 FROM OPENJSON(@State,'$.AppendBooks') n WHERE EXISTS(SELECT 1 FROM OPENJSON(@PriorBooks) WITH(BookID int) p WHERE p.BookID=TRY_CONVERT(int,n.value)))) THROW 51000,'Append mode must preserve existing books and identify only new books',1;
DECLARE @ReservationID uniqueidentifier=NULL;
IF @SourceRestorePointID IS NOT NULL BEGIN
DECLARE @Delta int=(SELECT COUNT(*) FROM OPENJSON(@JsonData,'$.Data.Books'))-(SELECT COUNT(*) FROM dbo.Books WHERE ProjectID=@ProjectID);
IF @Delta>0 BEGIN
DECLARE @Owner int=(SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND AccessRole='Owner' AND IsActive=1),@Now datetime2=SYSUTCDATETIME();
DECLARE @Capacity table(Allowed bit,ReservationID uniqueidentifier,CurrentUsage int,MaximumAllowed int,Message nvarchar(max));
INSERT @Capacity EXEC dbo.SubscriptionEntitlement_TryReserveBookSlots @Owner,@Delta,@Now;
IF EXISTS(SELECT 1 FROM @Capacity WHERE Allowed=0) THROW 51000,'Not enough book capacity to rewind this project',1;
SELECT @ReservationID=ReservationID FROM @Capacity;
END;
END;
IF @State IS NOT NULL AND ISNULL(JSON_VALUE(@State,'$.Protected'),'false')<>'true' THROW 51000,'Recovery state must be validated and protected by the application',1;
IF @State IS NOT NULL AND @AppendOnly=0 BEGIN
DELETE r FROM dbo.NativeChapterReviews r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID;
DELETE r FROM dbo.WritingIntentAssessments r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
END;
IF @AppendOnly=0 BEGIN
-- Receipts are operational authority, not snapshot author data. Even matching IDs cannot prove old imports.
DELETE FROM dbo.NativeReviewImports WHERE BookID IN(SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int));
DELETE FROM dbo.NativeImportOperations WHERE BookID IN(SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int));
END;
DECLARE @RetainedParagraphs nvarchar(max)=(SELECT JSON_QUERY(COALESCE(N'['+STRING_AGG(CONVERT(nvarchar(max),m.Payload),N',')+N']',N'[]')) AS ParagraphManuscripts FROM dbo.BookParagraphManuscripts m JOIN dbo.Books b ON b.BookID=m.BookID WHERE b.ProjectID=@ProjectID FOR JSON PATH,WITHOUT_ARRAY_WRAPPER);
EXEC dbo.ProjectRestore_ApplyGraph236 @ProjectID,@SourceRestorePointID,@SafetyRestorePointID,@JsonData;
IF @AppendOnly=1 EXEC dbo.ProjectParagraphRecovery_Apply @ProjectID,@RetainedParagraphs,1;
-- Protected state is supplied by the application after validating/decrypting the portable representation.
IF @State IS NOT NULL AND JSON_VALUE(@State,'$.Protected')='true' EXEC dbo.ProjectRecovery_Apply @ProjectID,@State,@PriorBooks;
ELSE BEGIN
DELETE r FROM dbo.NativeReviewImports r WHERE r.BookID IN(SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int)) AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=r.ChapterID AND BookID=r.BookID);
DELETE r FROM dbo.NativeImportOperations r WHERE r.BookID IN(SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int)) AND NOT EXISTS(SELECT 1 FROM dbo.NativeReviewImports WHERE BuildID=r.BuildID AND BookID=r.BookID);
END;
IF @ReservationID IS NOT NULL EXEC dbo.SubscriptionEntitlement_ReleaseBookSlots @ReservationID;
COMMIT;
END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH;
END;
GO
-- Preserve explicit fallback provenance and pause source updates throughout active analysis stages.
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);
INSERT @Paragraphs SELECT p.Id,p.Ordinal,p.StartPosition,p.EndPosition,p.Text,x.SceneId,x.ChapterId,x.Story,x.PositionVerified 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)) p;
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 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

View File

@ -6,6 +6,6 @@
<section class="edit-panel"><form method="get"><label for="projectId" class="form-label">Project</label><div class="input-group"><select name="projectId" id="projectId" class="form-select">@foreach(var p in Model.Projects){<option value="@p.ProjectID" selected="@(p.ProjectID==Model.ProjectID)">@p.ProjectName @(p.IsArchived?"· Archived project":"")</option>}</select><button class="btn btn-outline-primary">Choose project</button></div></form></section>
@if(Model.Source is not null){<section class="edit-panel mt-3"><form asp-action="ReviewBackup" method="post"><input type="hidden" name="projectId" value="@Model.ProjectID"/><h2>Choose books</h2>@if(Model.Source.Data.Books.Count==0){<p class="alert alert-info">This project has no books to back up.</p>}<p>Archived books are included when selected. Archive status does not release subscription capacity.</p><div class="button-row"><button type="button" class="btn btn-outline-secondary btn-sm" data-books-all>Select all</button><button type="button" class="btn btn-outline-secondary btn-sm" data-books-none>Clear selection</button></div>
@foreach(var b in Model.Source.Data.Books.OrderBy(b=>b.SortOrder)){<div class="form-check my-3"><input class="form-check-input" type="checkbox" name="books" value="@b.BookID" id="book-@b.BookID" checked="@(!Model.BookID.HasValue||Model.BookID==b.BookID)"/><label class="form-check-label" for="book-@b.BookID"><strong>@b.BookDisplayTitle</strong> @(b.IsArchived?"· Archived":"")</label></div>}
<details class="my-3"><summary>What is included?</summary><p>Selected chapters, scenes, saved prose, planning and author review decisions; common characters, locations, relationships, maps, floor plans, plot lines, assets and required files. A selection with an unresolved cross-book dependency is refused rather than losing it.</p></details>
<details class="my-3"><summary>What is included?</summary><p>Selected chapters, scenes, saved prose, planning, paragraph identities, scene groupings, story evidence and author review decisions; common characters, locations, relationships, maps, floor plans, plot lines, assets and required files. A selection with an unresolved cross-book dependency is refused rather than losing it.</p></details>
<p class="alert alert-info">Keep backup files private: they may contain manuscript prose, research and personal information. Downloading does not delete books, release capacity or prove your file is safely stored. Verify your local copy before separately choosing Delete Forever.</p><button class="btn btn-primary" disabled="@(Model.Source.Data.Books.Count==0)">Review selected backup</button> <a asp-action="Restore" class="btn btn-outline-secondary">Restore books</a></form></section>}
@section Scripts{<script src="~/js/book-recovery.js" asp-append-version="true"></script>}

View File

@ -1,4 +1,4 @@
@model BookRecoveryPage
@{ViewData["Title"]="Review book restore";var p=Model.Preview!;}
<div class="page-heading" data-pwa-header><h1>4. Review your restore</h1></div><section class="edit-panel"><p class="form-text">Backup file: @Model.UploadName</p><h2>@(p.Plan.Destination==0?"New project: "+p.Plan.Name:"Add books to: "+p.Plan.Name)</h2><ul>@foreach(var b in p.Selected.Data.Books){<li>@b.BookDisplayTitle @(b.IsArchived?"(archived)":"")</li>}</ul><dl><dt>Book slots required</dt><dd>@p.Selected.Data.Books.Count</dd><dt>Available slots now</dt><dd>@p.Available</dd><dt>Compatible common records reused</dt><dd>@p.Reused</dd><dt>Independent common records created</dt><dd>@p.Created</dd><dt>Uploaded files</dt><dd>@p.Selected.Files.Count</dd></dl><p>Common data is reused only with a verified source mapping and compatible saved content. Divergent data is copied independently. Existing work stays intact. Books are appended after existing books; chapter and scene order is preserved. Slot availability and destination state are checked again when you confirm.</p>@foreach(var warning in p.Warnings){<p class="alert alert-info">@warning</p>}@if(p.Available<p.Selected.Data.Books.Count){<p class="alert alert-warning">There are not enough book slots. Choose fewer books or free capacity separately; archiving does not release slots.</p>}<p>Confirmation starts a single transaction. Wait for its result; retrying the same confirmation is safe. Cancel below to leave without restoring.</p><form asp-action="Confirm" method="post"><input name="confirmation" type="hidden" value="@p.Confirmation"/><div class="form-check my-3"><input name="confirm" value="true" type="checkbox" required id="confirm" class="form-check-input"/><label for="confirm" class="form-check-label">Restore these books into the destination shown above. This uses @p.Selected.Data.Books.Count book slots.</label></div><button class="btn btn-primary" disabled="@(p.Available<p.Selected.Data.Books.Count)">Restore books</button> <a asp-action="Restore" class="btn btn-outline-secondary">Cancel</a></form></section>
<div class="page-heading" data-pwa-header><h1>4. Review your restore</h1></div><section class="edit-panel"><p class="form-text">Backup file: @Model.UploadName</p><h2>@(p.Plan.Destination==0?"New project: "+p.Plan.Name:"Add books to: "+p.Plan.Name)</h2><ul>@foreach(var b in p.Selected.Data.Books){<li>@b.BookDisplayTitle @(b.IsArchived?"(archived)":"")</li>}</ul><dl><dt>Book slots required</dt><dd>@p.Selected.Data.Books.Count</dd><dt>Available slots now</dt><dd>@p.Available</dd><dt>Compatible common records reused</dt><dd>@p.Reused</dd><dt>Independent common records created</dt><dd>@p.Created</dd><dt>Uploaded files</dt><dd>@p.Selected.Files.Count</dd></dl><p>Common data is reused only with a verified source mapping and compatible saved content. Divergent data is copied independently. Existing work stays intact. Books are appended after existing books; chapter and scene order is preserved. Slot availability and destination state are checked again when you confirm.</p>@foreach(var warning in p.Warnings){<p class="alert alert-info">@warning</p>}@if(p.Available<p.Selected.Data.Books.Count){<p class="alert alert-warning">There are not enough book slots. Choose fewer books or free capacity separately; archiving does not release slots.</p>}@if(p.Selected.Recovery.ParagraphManuscripts?.Count>0){<p class="alert alert-info">Paragraph identities, scene groupings and story evidence are included. Restored manuscripts start with manual synchronisation; live Word sessions are not restored. Associate the restored book in Companion, then synchronise its saved manuscript.</p>}<p>Confirmation starts a single transaction. Wait for its result; retrying the same confirmation is safe. Cancel below to leave without restoring.</p><form asp-action="Confirm" method="post"><input name="confirmation" type="hidden" value="@p.Confirmation"/><div class="form-check my-3"><input name="confirm" value="true" type="checkbox" required id="confirm" class="form-check-input"/><label for="confirm" class="form-check-label">Restore these books into the destination shown above. This uses @p.Selected.Data.Books.Count book slots.</label></div><button class="btn btn-primary" disabled="@(p.Available<p.Selected.Data.Books.Count)">Restore books</button> <a asp-action="Restore" class="btn btn-outline-secondary">Cancel</a></form></section>
@section Scripts{<script src="~/js/book-recovery.js" asp-append-version="true"></script>}

View File

@ -3,11 +3,12 @@
<div class="container-fluid px-3 py-3 @(Model.Mode=="book"?"":"native-writing-workspace")" id="native-workspace" data-book="@Model.Book" data-project="@Model.Project" data-instance="@Model.Instance" data-session="@Model.Session" data-mode="@Model.Mode">
<h1 class="h3">@Model.Title</h1><p>Word Companion · live manuscript connection and saved PlotDirector workspaces</p>
<div class="card mb-3"><div class="card-body">
<p id="native-current-scene" class="fw-semibold" role="status">Saved workspace · waiting for a current Word scene</p>
<p id="native-presence-status" role="status">Checking Companion presence…</p>
<label for="native-session">Word document session</label><select id="native-session" class="form-select mb-2"><option value="">Choose a connected manuscript</option></select>
<div class="d-flex flex-wrap gap-3 align-items-center"><label><input type="checkbox" id="native-follow" /> Follow this manuscript’s saved chapter and scene</label><button type="button" id="native-return" class="btn btn-sm btn-outline-primary">Return to current Word scene</button></div>
<p class="small text-muted">Manual navigation pauses following. No Word commands or manuscript text are sent by this page. Context and Intent remain available without Word.</p>
<nav class="d-flex gap-3"><a target="_blank" rel="noopener" href="/Books/Details/@Model.Book">Book workspace</a><button class="btn btn-link p-0" type="button" data-native-open-role="Context">Open Context</button><button class="btn btn-link p-0" type="button" data-native-open-role="Intent">Open Intent</button></nav>
<nav class="d-flex gap-3"><a target="_blank" rel="noopener" href="/Books/Details/@Model.Book">Book workspace</a><a href="/manuscript/paragraphs?bookId=@Model.Book" target="_blank" rel="noopener">Manuscript structure and evidence</a><button class="btn btn-link p-0" type="button" data-native-open-role="Context">Open Context</button><button class="btn btn-link p-0" type="button" data-native-open-role="Intent">Open Intent</button></nav>
</div></div>
@if(Model.Mode is "context" or "intent"){
<label class="form-label" for="native-manual-scene">Explore a saved scene · Word is optional</label><select id="native-manual-scene" class="form-select mb-2"><option value="">Choose a saved scene</option>@foreach(var chapter in Model.Chapters??[]){<optgroup label="@chapter.Title">@foreach(var scene in chapter.Scenes){<option value="@scene.SceneId" data-chapter="@chapter.ChapterId">@scene.Title</option>}</optgroup>}</select>}

View File

@ -346,7 +346,7 @@
data-scan-status="@Model.ScanState.Status"
aria-label="Manuscript scan">
<p class="small text-muted">Import manuscript reads the linked Word document and saves a server-side capture. Review and confirm before story records are created. After PlotDirector acknowledges receipt, analysis and review no longer need Word or the Companion.</p>
@if(ParagraphConfiguration.GetValue<bool>("Features:ParagraphManuscripts")){<label class="d-block mb-2"><input type="checkbox" data-paragraph-tracking/> Enable paragraph tracking after import, including updates after Word saves or reconnects. AI runs only through this import workflow.</label>}
@if(ParagraphConfiguration.GetValue<bool>("Features:ParagraphManuscripts")){<p class="small text-muted">Companion 1.0.0.18 automatically captures paragraph identities and scene positions during import. After import, saved Word changes synchronise without running AI again.</p>}
<div class="onboarding-scan-status">
<span data-onboarding-scan-message>@ScanMessage(Model.ScanState)</span>
<strong data-onboarding-scan-percent>@ScanPercent(Model.ScanState)</strong>

View File

@ -11,12 +11,10 @@
<div class="container-fluid py-3">
<a asp-controller="Books" asp-action="Details" asp-route-id="@state.BookId">Back to @Model.BookTitle</a>
<h1>Manuscript structure and evidence</h1>
<div class="alert alert-warning">Preview feature: book backup and saved-point replacement are blocked for tracked books until paragraph evidence portability is qualified. Use isolated test books; keep your original Word document.</div>
<p class="text-muted">Word remains the source of your prose. These tools organise saved paragraphs and story evidence; they never edit your Word document.</p>
@if(Model.Message!=null){<div role="status" class="alert alert-info">@Model.Message</div>}
@if(state.Paragraphs.Count==0){
<div class="card p-3"><h2>Enable paragraph tracking</h2><p>After completing a native manuscript import, adopt its accepted paragraph map. Existing unfinished imports are protected. No content is sent from Word by this action.</p>
<form asp-action="Enable" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><input name="mode" type="hidden" value="Manual"/><button class="btn btn-primary">Use saved manuscript capture</button></form></div>
<div class="card p-3"><h2>Import your manuscript from Word</h2><p>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.</p><a asp-controller="Onboarding" asp-action="Index" class="btn btn-primary">Open manuscript import</a></div>
}else{
@if(state.Paragraphs.Any(p=>p.Story&&!p.PositionVerified)){<div class="alert alert-warning">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.</div>}
<div class="card p-3 mb-3"><h2>Saved manuscript</h2><p>@state.Paragraphs.Count.ToString("N0") paragraphs · @current.Length scenes · Updated @state.UpdatedUtc.ToString("u")</p>

View File

@ -1,11 +1,16 @@
{
"Admin": {
"AllowedEmails": ["nickbeckley5@gmail.com"]
"AllowedEmails": [
"nickbeckley5@gmail.com"
]
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Features": {
"ParagraphManuscripts": true
}
}

View File

@ -6,6 +6,9 @@
const scope={projectID:Number(root.dataset.project),bookID:Number(root.dataset.book)};
root.querySelectorAll('[data-native-open-role]').forEach(button=>button.addEventListener('click',()=>window.PlotDirectorWritingWorkspace?.openRoleWindow(button.dataset.nativeOpenRole,scope)));
if(['context','intent'].includes(root.dataset.mode)&&window.PlotDirectorWritingWorkspace)void window.PlotDirectorWritingWorkspace.registerWindow({...scope,writingRole:root.dataset.mode==='context'?'Context':'Intent'}).catch(()=>{});
const sceneIndicator=root.querySelector("#native-current-scene");
const sceneLabel=lease=>[lease?.chapterTitle,lease?.sceneTitle].filter(Boolean).join(" · ")||root.querySelector(`#native-manual-scene option[value="${Number(lease?.sceneId)||0}"]`)?.textContent||"Current manuscript scene";
const indicate=(lease,live)=>{if(sceneIndicator)sceneIndicator.textContent=lease?.sceneId?(live?"Live from Word · ":"Saved scene · ")+sceneLabel(lease):"No trustworthy current Word scene · saved information remains available";};
const setStatus=text=>{if(status.textContent!==text)status.textContent=text;};
const show=lease=>{
if(!['context','intent'].includes(root.dataset.mode))return;
@ -13,9 +16,9 @@
const url=new URL('/Writing/'+(root.dataset.mode==='intent'?'Intent':'Context'),location.origin);url.searchParams.set('projectId',root.dataset.project);url.searchParams.set('bookId',root.dataset.book);url.searchParams.set('pinned','true');url.searchParams.set('embedded','true');if(lease?.chapterId)url.searchParams.set('chapterId',lease.chapterId);if(lease?.sceneId)url.searchParams.set('sceneId',lease.sceneId);frame.src=url.pathname+url.search;frame.hidden=false;
};
root.querySelector('#native-return')?.addEventListener('click',()=>{if(!lastLive?.sceneId||Date.parse(lastLive.expires)<=Date.now()){setStatus('No live Word scene. Your manual selection is kept.');return;}manual=false;position='';follow.checked=true;void poll();});
root.querySelector('#native-manual-scene')?.addEventListener('change',event=>{const option=event.target.selectedOptions[0];if(!option?.value)return;manual=true;follow.checked=false;position='';show({chapterId:Number(option.dataset.chapter),sceneId:Number(option.value)});setStatus('Manual scene · following paused');});
root.querySelector('#native-manual-scene')?.addEventListener('change',event=>{const option=event.target.selectedOptions[0];if(!option?.value)return;manual=true;follow.checked=false;position='';const choice={chapterId:Number(option.dataset.chapter),sceneId:Number(option.value),sceneTitle:option.textContent};show(choice);indicate(choice,false);setStatus('Manual scene · following paused');});
frame.addEventListener('load',()=>{try{const pause=()=>{manual=true;follow.checked=false;setStatus('Manual navigation · following paused');};frame.contentDocument.addEventListener('change',pause);frame.contentDocument.addEventListener('click',event=>{if(event.target.closest('a'))pause();});}catch{follow.checked=false;}});
sessions.addEventListener('change',()=>{manual=true;selected=sessions.value;position='';follow.checked=false;void poll();});follow.addEventListener('change',()=>{if(!follow.checked)manual=true;position='';void poll();});
sessions.addEventListener('change',()=>{manual=true;selected=sessions.value;position='';follow.checked=false;indicate(null,false);void poll();});follow.addEventListener('change',()=>{if(!follow.checked){manual=true;indicate(lastLive,false);}position='';void poll();});
async function poll(){
if(loading||document.hidden)return;loading=true;const current=++generation;
try{
@ -24,9 +27,9 @@
if(sessions.dataset.signature!==signature){sessions.dataset.signature=signature;sessions.replaceChildren(new Option('Choose a connected manuscript',''));for(const lease of live.filter(l=>l.wordAvailable))sessions.add(new Option(lease.documentTitle+(lease.active?' (active in Word)':''),lease.instanceId+'/'+lease.sessionId));sessions.value=selected;}
if(!manual){const active=live.filter(l=>l.active&&l.wordAvailable);if(active.length===1){selected=active[0].instanceId+'/'+active[0].sessionId;sessions.value=selected;follow.checked=true;}}
const lease=live.find(l=>l.instanceId+'/'+l.sessionId===selected);lastLive=lease;
if(lease){setStatus('Companion connected · Word '+(lease.wordAvailable?'available':'unavailable')+' · '+lease.documentTitle+' · last update '+new Date(lease.updated).toLocaleTimeString()+(follow.checked?(lease.sceneId?' · following saved position':' · no trustworthy live scene mapping; saved information only'):' · manual navigation'));if(follow.checked&&lease.sceneId)show(lease);else if(!position)show(null);}
else{setStatus(live.some(l=>!l.wordAvailable)?'Companion connected · Word unavailable. Saved Context and Intent remain available.':'Companion disconnected or stale for the selected manuscript. Saved workspaces remain available.');follow.checked=false;if(!position)show(null);}
}catch{setStatus('Connection status unavailable · following paused; saved data remains available');follow.checked=false;}
if(lease){setStatus('Companion connected · Word '+(lease.wordAvailable?'available':'unavailable')+' · '+lease.documentTitle+' · last update '+new Date(lease.updated).toLocaleTimeString()+(follow.checked?(lease.sceneId?' · following saved position':' · no trustworthy live scene mapping; saved information only'):' · manual navigation'));if(follow.checked&&lease.wordAvailable&&lease.wordSaved!==false&&lease.sceneId){show(lease);indicate(lease,true);}else{if(follow.checked)indicate(null,false);if(!position)show(null);}}
else{indicate(null,false);setStatus(live.some(l=>!l.wordAvailable)?'Companion connected · Word unavailable. Saved Context and Intent remain available.':'Companion disconnected or stale for the selected manuscript. Saved workspaces remain available.');follow.checked=false;if(!position)show(null);}
}catch{indicate(null,false);setStatus('Connection status unavailable · following paused; saved data remains available');follow.checked=false;}
finally{loading=false;}
}
document.addEventListener('visibilitychange',()=>{if(!document.hidden)void poll();});window.addEventListener('pagehide',()=>clearInterval(timer));show(null);void poll();timer=setInterval(()=>void poll(),15000);