From bf515d20af5bcaaf9d07a5e97edf46a27570ac99 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Thu, 5 Nov 2026 23:01:04 +0000 Subject: [PATCH] Connect approved chapter reviews to safe canonical imports with retained-source consent --- .../Agent/ChapterAiWork.cs | 2 +- .../Agent/CloudGateway.cs | 2 +- .../Agent/TrayApplication.cs | 2 +- .../Agent/TrayCoordinator.cs | 2 +- .../DeveloperVersion.props | 2 +- .../Protocol/AiContracts.cs | 2 + .../Protocol/Messages.cs | 1 + .../Protocol/TrayContracts.cs | 1 + .../Vsto/Properties/AssemblyInfo.cs | 4 +- .../Vsto/WordAdapter.cs | 6 +- PlotLine.Tests/NativeImportTests.cs | 35 ++++++++ PlotLine.Tests/Program.cs | 1 + PlotLine.Tests/Sql/NativeApprovedImport.sql | 26 ++++++ .../Controllers/NativeCompanionController.cs | 6 +- .../Controllers/NativeWorkspaceController.cs | 6 ++ PlotLine/Data/NativeImportRepository.cs | 24 +++++ PlotLine/Data/NativeReviewRepository.cs | 4 +- PlotLine/Program.cs | 2 + .../NativeCompanion/NativeImportService.cs | 55 ++++++++++++ PlotLine/Sql/232_NativeApprovedImport.sql | 88 +++++++++++++++++++ .../Views/NativeWorkspace/ImportCommit.cshtml | 3 + .../NativeWorkspace/ImportPreview.cshtml | 8 ++ PlotLine/Views/NativeWorkspace/Review.cshtml | 2 +- .../Views/NativeWorkspace/Workspace.cshtml | 2 +- 24 files changed, 269 insertions(+), 17 deletions(-) create mode 100644 PlotLine.Tests/NativeImportTests.cs create mode 100644 PlotLine.Tests/Sql/NativeApprovedImport.sql create mode 100644 PlotLine/Data/NativeImportRepository.cs create mode 100644 PlotLine/Services/NativeCompanion/NativeImportService.cs create mode 100644 PlotLine/Sql/232_NativeApprovedImport.sql create mode 100644 PlotLine/Views/NativeWorkspace/ImportCommit.cshtml create mode 100644 PlotLine/Views/NativeWorkspace/ImportPreview.cshtml diff --git a/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs b/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs index 9dd98bb8..34e34cba 100644 --- a/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs +++ b/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs @@ -17,7 +17,7 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable if(request.SnapshotId==Guid.Empty||request.BookId<=0||request.Start<0||request.End<=request.Start||request.End-request.Start>120000){answer.Status="invalid-ai-chapter";return answer;} if(!jobs.ContainsKey(descriptor.SessionId)&&jobs.Count>=32){answer.Status="ai-capacity";return answer;} Clear(descriptor.SessionId); - var chapter=new AiChapterRequest{RequestId=request.SnapshotId,BookId=request.BookId,SessionId=descriptor.SessionId,ManuscriptId=descriptor.ManuscriptId,Revision=descriptor.Revision,ChapterTitle=request.ChapterTitle.Length<=200?request.ChapterTitle:request.ChapterTitle[..200],ChapterStart=request.Start,ChapterEnd=request.End}; + var chapter=new AiChapterRequest{RetainForImport=request.RetainForImport,RequestId=request.SnapshotId,BookId=request.BookId,SessionId=descriptor.SessionId,ManuscriptId=descriptor.ManuscriptId,Revision=descriptor.Revision,ChapterTitle=request.ChapterTitle.Length<=200?request.ChapterTitle:request.ChapterTitle[..200],ChapterStart=request.Start,ChapterEnd=request.End}; jobs[descriptor.SessionId]=new(chapter,request.AuthenticationContext);return answer; } if(!jobs.TryGetValue(descriptor.SessionId,out var job)||job.Chapter.RequestId!=request.SnapshotId){answer.Status="obsolete-ai-request";return answer;} diff --git a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs index d0a06405..5550510f 100644 --- a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs +++ b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs @@ -92,7 +92,7 @@ public sealed class CloudGateway : IDisposable { var fingerprint=expectedContext+":"+chapter.BookId+":"+chapter.ManuscriptId+":"+Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{chapter.ChapterStart,chapter.ChapterEnd,chapter.Paragraphs}))); Uri site;string access; - lock(gate){Expire();if(successful.TryGetValue(fingerprint,out var prior)&&authenticationContext==expectedContext&&token!=null)return new(){RequestId=chapter.RequestId,DocumentRevision=chapter.Revision,ChapterTitle=chapter.ChapterTitle,State="complete",Message="Unchanged chapter: reused saved AI suggestions without uploading prose.",ReviewPath=prior.ReviewPath,Scenes=prior.Scenes};if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");} + lock(gate){Expire();if(successful.TryGetValue(fingerprint,out var prior)&&authenticationContext==expectedContext&&token!=null&&(!chapter.RetainForImport||prior.SourceRetained))return new(){SourceRetained=prior.SourceRetained,RequestId=chapter.RequestId,DocumentRevision=chapter.Revision,ChapterTitle=chapter.ChapterTitle,State="complete",Message="Unchanged chapter: reused saved AI suggestions without uploading prose.",ReviewPath=prior.ReviewPath,Scenes=prior.Scenes};if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");} using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/analyse-chapter")){Content=JsonContent.Create(chapter,options:Json)}; request.Headers.Authorization=new AuthenticationHeaderValue("Bearer",access); HttpResponseMessage responseValue; diff --git a/PlotDirector.NativeCompanion/Agent/TrayApplication.cs b/PlotDirector.NativeCompanion/Agent/TrayApplication.cs index b44def1d..7073cd0c 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayApplication.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayApplication.cs @@ -57,7 +57,7 @@ internal sealed class CompanionWindow:Form chapters.ItemCheck+=(_,e)=>{if(refreshing||renderedSession==Guid.Empty)return;if(!selections.TryGetValue(renderedSession,out var chosen)){if(selections.Count>=64)selections.Clear();selections[renderedSession]=chosen=[];}var start=((ChapterItem)chapters.Items[e.Index]).Start;if(e.NewValue==CheckState.Checked)chosen.Add(start);else chosen.Remove(start);}; detect.Click+=(_,_)=>Safe(()=>control.Detect(selected));cancel.Click+=(_,_)=>Safe(()=>control.Cancel(selected)); bookButton.Click+=(_,_)=>Safe(()=>{if(books.SelectedItem is not Protocol.CompanionBook book)return;if(remember.Checked&&MessageBox.Show("Remember this book in Word document metadata? This marks the document modified. It does not save or change prose.","Remember association",MessageBoxButtons.OKCancel)!=DialogResult.OK)return;control.SelectBook(selected,book.BookId,remember.Checked);}); - analyse.Click+=(_,_)=>Safe(()=>{var chosen=chapters.CheckedItems.Cast().ToArray();if(chosen.Length==0)throw new InvalidOperationException("Select one or more chapters first.");var d=Current??throw new InvalidOperationException("Open a Word document.");if(MessageBox.Show($"Send {chosen.Length} selected chapters for the chosen book to PlotDirector AI? This uploads manuscript prose and may incur AI costs. Existing Word text and saved story records will not change.","Confirm chapter analysis",MessageBoxButtons.OKCancel)==DialogResult.OK)control.Analyse(d.Session,chosen.Select(c=>c.Start));}); + analyse.Click+=(_,_)=>Safe(()=>{var chosen=chapters.CheckedItems.Cast().ToArray();if(chosen.Length==0)throw new InvalidOperationException("Select one or more chapters first.");var d=Current??throw new InvalidOperationException("Open a Word document.");if(MessageBox.Show($"Send {chosen.Length} selected chapters for the chosen book to PlotDirector AI? This uploads manuscript prose, retains an encrypted capture for your reviewed import, and may incur AI costs. Existing Word text and saved story records will not change.","Confirm chapter analysis",MessageBoxButtons.OKCancel)==DialogResult.OK)control.Analyse(d.Session,chosen.Select(c=>c.Start));}); review.Click+=(_,_)=>Safe(()=>Open("review")); var menu=new ContextMenuStrip();menu.Items.Add("Open Companion",null,(_,_)=>Reveal());menu.Items.Add("Connect / Sign In",null,(_,_)=>{Reveal();site.Focus();});menu.Items.Add("Select Book",null,(_,_)=>{Reveal();books.Focus();}); var detectMenu=menu.Items.Add("Detect Chapters",null,(_,_)=>Safe(()=>control.Detect(selected)));var analyseMenu=menu.Items.Add("Analyse Manuscript",null,(_,_)=>{Reveal();chapters.Focus();});var openMenu=menu.Items.Add("Open PlotDirector",null,(_,_)=>Safe(()=>Open("book")));menu.Items.Add("Connection Status",null,(_,_)=>Reveal());menu.Items.Add("Settings",null,(_,_)=>{Reveal();tabs.SelectedIndex=1;});menu.Items.Add("Exit",null,(_,_)=>Exit()); diff --git a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs index 5f4427ab..09a59601 100644 --- a/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs +++ b/PlotDirector.NativeCompanion/Agent/TrayCoordinator.cs @@ -72,7 +72,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C if(doc.Done>0&&!string.IsNullOrEmpty(doc.ReviewPath))_ = Task.Run(()=>{try{cloud.OpenCompanionPage($"/native-companion/workspace?bookId={doc.Book}&instanceId={doc.Instance}&sessionId={doc.Session}",doc.Authentication);}catch(Exception e)when(e is InvalidOperationException or IOException or System.ComponentModel.Win32Exception){}}); return;} doc.Current=doc.Pending.Dequeue();doc.Job=Guid.NewGuid();doc.Started=DateTime.UtcNow;doc.Status=$"Chapter {doc.Done+1}/{doc.Total}: {doc.Current.Title}";doc.Progress=0; - if(!Queue(doc,new(){Id=doc.Job,Kind="extract-ai",Chapter=doc.Current,BookId=doc.Book,AuthenticationContext=doc.Authentication})){doc.Job=Guid.Empty;doc.Pending.Clear();} + if(!Queue(doc,new(){Id=doc.Job,Kind="extract-ai",RetainForImport=true,Chapter=doc.Current,BookId=doc.Book,AuthenticationContext=doc.Authentication})){doc.Job=Guid.Empty;doc.Pending.Clear();} } public void Cancel(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Status="Cancelled. Successful server suggestions remain available.";}} private void Cancel(TrayDocument doc){if(doc.Job!=Guid.Empty)ai.Clear(doc.Session);doc.Job=Guid.Empty;doc.Pending.Clear();if(commands.TryGetValue(doc.Instance,out var q))commands[doc.Instance]=new(q.Where(c=>c.SessionId!=doc.Session));Queue(doc,new(){Kind="cancel"});} diff --git a/PlotDirector.NativeCompanion/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props index 8078395d..4df4b918 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.10 +1.0.0.11 diff --git a/PlotDirector.NativeCompanion/Protocol/AiContracts.cs b/PlotDirector.NativeCompanion/Protocol/AiContracts.cs index 56aa3915..f777edd7 100644 --- a/PlotDirector.NativeCompanion/Protocol/AiContracts.cs +++ b/PlotDirector.NativeCompanion/Protocol/AiContracts.cs @@ -4,6 +4,7 @@ namespace PlotDirector.Companion.Protocol; [DataContract] public sealed class AiChapterRequest { + [DataMember] public bool RetainForImport {get;set;} [DataMember] public string ChapterTitle {get;set;}=""; [DataMember] public Guid RequestId { get; set; } [DataMember] public int BookId { get; set; } @@ -26,6 +27,7 @@ public sealed class AiParagraph [DataContract] public sealed class AiChapterResult { + [DataMember] public bool SourceRetained {get;set;} [DataMember] public long DocumentRevision {get;set;} [DataMember] public string ChapterTitle {get;set;}=""; [DataMember] public string ReviewPath {get;set;}=""; diff --git a/PlotDirector.NativeCompanion/Protocol/Messages.cs b/PlotDirector.NativeCompanion/Protocol/Messages.cs index aa173b22..ee5816f4 100644 --- a/PlotDirector.NativeCompanion/Protocol/Messages.cs +++ b/PlotDirector.NativeCompanion/Protocol/Messages.cs @@ -25,6 +25,7 @@ public static class ProtocolVersion [DataContract] public sealed class Message { + [DataMember] public bool RetainForImport {get;set;} [DataMember] public AdapterCommand? Command {get;set;} [DataMember] public string OperationMessage {get;set;}=""; [DataMember] public int Version { get; set; } = ProtocolVersion.Current; diff --git a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs index d44325b0..7b078669 100644 --- a/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs +++ b/PlotDirector.NativeCompanion/Protocol/TrayContracts.cs @@ -3,6 +3,7 @@ namespace PlotDirector.Companion.Protocol; [DataContract] public sealed class AdapterCommand { + [DataMember] public bool RetainForImport {get;set;} [DataMember] public Guid Id {get;set;}=Guid.NewGuid(); [DataMember] public string Kind {get;set;}=""; [DataMember] public Guid SessionId {get;set;} diff --git a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs index d097f02b..a3f8d250 100644 --- a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs +++ b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs @@ -3,6 +3,6 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("PlotDirector Word Companion — Native development")] [assembly: AssemblyCompany("Nick Beckley")] [assembly: AssemblyProduct("PlotDirector")] -[assembly: AssemblyVersion("1.0.0.10")] -[assembly: AssemblyFileVersion("1.0.0.10")] +[assembly: AssemblyVersion("1.0.0.11")] +[assembly: AssemblyFileVersion("1.0.0.11")] [assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs index e1e46da1..dee38c70 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs @@ -233,7 +233,7 @@ namespace PlotDirector.WordAddIn var chapter=command.Chapter; if(chapter.Start<0||chapter.End<=chapter.Start||chapter.End>doc.End||DocumentEnd(doc.Document)!=doc.End)throw new InvalidOperationException("Chapter changed. Detect chapters again."); CancelExtraction(doc);doc.AiChapter=command.Chapter;doc.AiBook=command.BookId;doc.AiAuthenticationContext=command.AuthenticationContext;doc.AiJob=command.Id; - doc.Extraction=new Extraction{Snapshot=command.Id,Revision=doc.Revision,Position=chapter.Start,Limit=chapter.End,IsAi=true}; + doc.Extraction=new Extraction{Snapshot=command.Id,Revision=doc.Revision,Position=chapter.Start,Limit=chapter.End,IsAi=true,RetainForImport=command.RetainForImport}; if(!scheduler.Post("extract:"+doc.Session,()=>ExtractBatch(doc))){CancelExtraction(doc);throw new InvalidOperationException("Word queue is busy.");} } else if(command.Kind=="cancel"){CancelExtraction(doc);doc.AiJob=Guid.Empty;} @@ -272,7 +272,7 @@ namespace PlotDirector.WordAddIn { if(!extraction.Begun) { - if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-begin":"snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,Start=extraction.Position,End=extraction.Limit,BookId=doc.AiBook,AuthenticationContext=doc.AiAuthenticationContext,RequestAnalysis=extraction.Analyse,ChapterTitle=doc.AiChapter?.Title??""}))return; + if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-begin":"snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,Start=extraction.Position,End=extraction.Limit,BookId=doc.AiBook,AuthenticationContext=doc.AiAuthenticationContext,RetainForImport=extraction.RetainForImport,RequestAnalysis=extraction.Analyse,ChapterTitle=doc.AiChapter?.Title??""}))return; extraction.Begun=true; } // At most four <=2048-character fragments and a cooperative ~20ms budget. @@ -541,6 +541,6 @@ namespace PlotDirector.WordAddIn public LocalDocument(Word.Document document){Document=document;} } private sealed class Extraction - {public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex,Limit;public int OutlineLevel;public bool Begun,Analyse,IsAi;public Message Pending;} + {public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex,Limit;public int OutlineLevel;public bool Begun,Analyse,IsAi,RetainForImport;public Message Pending;} } } diff --git a/PlotLine.Tests/NativeImportTests.cs b/PlotLine.Tests/NativeImportTests.cs new file mode 100644 index 00000000..04928e58 --- /dev/null +++ b/PlotLine.Tests/NativeImportTests.cs @@ -0,0 +1,35 @@ +using System.Security.Cryptography; +using System.Text.Json; +using Microsoft.AspNetCore.DataProtection; +using PlotDirector.Companion.Protocol; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; +using PlotLine.Services.NativeCompanion; +internal static class NativeImportTests +{ + public static async Task Run() + { + void Check(bool value,string name){if(!value)throw new Exception(name);} + var reviews=new MemoryNativeReviews();var writes=new Imports();var access=NativeWorkflowTests.Proxy((n,a)=>n=="GetBookStructureAsync"?Task.FromResult((int)a![0]! ==3?new WordCompanionBookStructureResponse{BookId=3}:null):throw new Exception("Unexpected write")); + var allowed=true;var subscriptions=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(new EntitlementDecision{Allowed=allowed})); + var service=new NativeImportService(reviews,access,writes,new EphemeralDataProtectionProvider(),subscriptions); + var capture=new AiChapterRequest{RequestId=Guid.NewGuid(),BookId=3,ManuscriptId=Guid.NewGuid(),SessionId=Guid.NewGuid(),ChapterStart=10,ChapterEnd=30,Paragraphs=[new(){Index=1,Start=10,End=20,Text="First scene.\r"},new(){Index=2,Start=20,End=30,Text="Second scene.\r"}]}; + var row=await reviews.Save(new(){ReviewID=capture.RequestId,UserID=7,BookID=3,ManuscriptID=capture.ManuscriptId,ChapterStart=10,ChapterEnd=30,ContentHash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{capture.ChapterStart,capture.ChapterEnd,capture.Paragraphs}))),EncryptedSource=service.Protect(capture),ResultJson=JsonSerializer.Serialize(new AiChapterResult{ChapterTitle="Opening",Scenes=[new(){Title="First",Start=10,End=20},new(){Title="Second",Start=20,End=30}]}),DecisionsJson=JsonSerializer.Serialize(new[]{new PlotLine.Controllers.NativeSceneDecision{Index=0,State="approved",Title="Edited title",Summary="Author-approved summary"},new PlotLine.Controllers.NativeSceneDecision{Index=1,State="rejected",Title="Second",Summary=""}})}); + var preview=await service.Preview(7,3,[row.ReviewID]);Check(preview.Items.Single().Scenes.Single().Text=="First scene.\r"&&preview.Skipped==1&&preview.Items[0].Scenes[0].Title=="Edited title"&&writes.Count==0,"Preview uses encrypted exact prose and author decisions without writing"); + var result=await service.Commit(7,preview.Ticket);Check(result.ChaptersCreated==1&&writes.Count==1,"Explicit confirmed plan reaches canonical import repository"); + await service.Commit(7,preview.Ticket);Check(writes.Count==1,"Retry reuses operation receipt without another import"); + var again=await service.Preview(7,3,[row.ReviewID]);Check(again.Items.Length==0&&again.Skipped==2,"Already-imported identical approved chapter matches and skips"); + writes.Rows.Clear();writes.Receipts.Clear();var stale=await service.Preview(7,3,[row.ReviewID]);row.Version++;try{await service.Commit(7,stale.Ticket);throw new Exception("Stale decisions accepted");}catch(ArgumentException){}Check(writes.Count==1,"Changed review cannot commit an old confirmation"); + allowed=false;try{await service.Preview(7,3,[row.ReviewID]);throw new Exception("Expired import entitlement accepted");}catch(UnauthorizedAccessException){} + try{await service.Commit(8,preview.Ticket);throw new Exception("Foreign confirmation accepted");}catch(UnauthorizedAccessException){} + Check(writes.Count==1,"Entitlement and cross-account checks preserve import data"); + } + private sealed class Imports:INativeImportRepository + { + public int Count;public List Rows=[];public Dictionary Receipts=[]; + public Task> List(int user,int book)=>Task.FromResult>(Rows.ToArray()); + public Task Result(int user,Guid operation)=>Task.FromResult(Receipts.GetValueOrDefault(operation)); + public Task Commit(int user,Guid operation,NativeImportPlan plan){Count++;foreach(var item in plan.Items)Rows.Add(new(){ChapterKey=item.Key,ContentHash=item.Hash,ReviewVersion=item.Version});var result=new NativeImportResult{BuildID=1,ChaptersCreated=plan.Items.Length,ScenesCreated=plan.Items.Sum(i=>i.Scenes.Length)};Receipts[operation]=result;return Task.FromResult(result);} + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 28aa0887..c3d6842e 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -122,6 +122,7 @@ if (args.Contains("--plot-lines")) return; } +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-tray")){await NativeTrayIntegrationTests.Run();Console.WriteLine("PASS native tray presence, expiry, scope and persistent PWA review decisions");return;} if(args.Contains("--native-workflow")){await NativeWorkflowTests.Run();Console.WriteLine("PASS native saved workspace and safe import preview validation");return;} if(args.Contains("--native-companion-http")){await NativeCompanionHttpTests.Run();return;} diff --git a/PlotLine.Tests/Sql/NativeApprovedImport.sql b/PlotLine.Tests/Sql/NativeApprovedImport.sql new file mode 100644 index 00000000..726c0ea1 --- /dev/null +++ b/PlotLine.Tests/Sql/NativeApprovedImport.sql @@ -0,0 +1,26 @@ +-- Run inside an outer rollback transaction in Development only. No author rows modified. +IF DB_NAME()<>N'PlotDirector_Development' OR @@TRANCOUNT<>1 THROW 51000,'Run in a Development rollback transaction',1; +DECLARE @User int=(SELECT TOP(1) UserID FROM dbo.AppUser ORDER BY UserID); +IF @User IS NULL THROW 51000,'Fixture requires an existing identity',1; +INSERT dbo.Projects(ProjectName) VALUES(N'Native import isolated fixture');DECLARE @Project int=SCOPE_IDENTITY(); +INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole) VALUES(@Project,@User,N'Owner'); +INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@Project,N'Native import isolated book',1,1);DECLARE @Book int=SCOPE_IDENTITY(); +DECLARE @Review uniqueidentifier=NEWID(),@Doc uniqueidentifier=NEWID(),@Operation uniqueidentifier=NEWID(); +DECLARE @Key nvarchar(80)=CONCAT('native:',REPLACE(CONVERT(nvarchar(36),@Doc),'-',''),':10'); +INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,EncryptedSource) +VALUES(@Review,@User,@Book,@Doc,10,30,'fixture-hash',N'{"Scenes":[]}',N'[]',N'fixture-encrypted-source'); +DECLARE @Items nvarchar(max)=(SELECT @Review ReviewID,1 Version,@Key [Key],'fixture-hash' Hash,N'Approved opening' Title,10 Start,30 [End],JSON_QUERY((SELECT CONCAT(@Key,':10') [Key],N'Approved scene' Title,N'An author-approved summary.' Summary,N'Preserved source prose.' [Text],1 StartParagraph,1 EndParagraph,3 Words FOR JSON PATH)) Scenes FOR JSON PATH); +EXEC dbo.NativeReviewImport @Action='Commit',@UserID=@User,@BookID=@Book,@OperationID=@Operation,@DocumentGuid=@Doc,@ItemsJson=@Items; +IF (SELECT COUNT(*) FROM dbo.Chapters WHERE BookID=@Book AND IsArchived=0)<>1 THROW 51000,'Wrong chapter creation count',1; +IF (SELECT COUNT(*) FROM dbo.NativeReviewImports WHERE BookID=@Book)<>1 THROW 51000,'Provenance missing',1; +IF NOT EXISTS(SELECT 1 FROM dbo.SceneManuscriptSources s JOIN dbo.Scenes sc ON sc.SceneID=s.SceneID WHERE s.BookID=@Book AND s.SourceText=N'Preserved source prose.' AND sc.StructuralSummary=N'An author-approved summary.') THROW 51000,'Approved prose/summary not preserved',1; +EXEC dbo.NativeReviewImport @Action='Commit',@UserID=@User,@BookID=@Book,@OperationID=@Operation,@DocumentGuid=@Doc,@ItemsJson=@Items; +IF (SELECT COUNT(*) FROM dbo.Chapters WHERE BookID=@Book AND IsArchived=0)<>1 THROW 51000,'Retry duplicated chapter',1; +-- Incremental new chapter appends; existing author relationships/scene are untouched. +DECLARE @Review2 uniqueidentifier=NEWID(),@Operation2 uniqueidentifier=NEWID(),@Key2 nvarchar(80)=CONCAT('native:',REPLACE(CONVERT(nvarchar(36),@Doc),'-',''),':30'); +INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,EncryptedSource) VALUES(@Review2,@User,@Book,@Doc,30,50,'next-hash',N'{}',N'[]',N'fixture'); +SET @Items=(SELECT @Review2 ReviewID,1 Version,@Key2 [Key],'next-hash' Hash,N'Approved continuation' Title,30 Start,50 [End],JSON_QUERY((SELECT CONCAT(@Key2,':30') [Key],N'Next approved scene' Title,N'Next summary.' Summary,N'Next preserved source.' [Text],2 StartParagraph,2 EndParagraph,3 Words FOR JSON PATH)) Scenes FOR JSON PATH); +EXEC dbo.NativeReviewImport @Action='Commit',@UserID=@User,@BookID=@Book,@OperationID=@Operation2,@DocumentGuid=@Doc,@ItemsJson=@Items; +IF NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE BookID=@Book AND ChapterNumber=2 AND ChapterTitle=N'Approved continuation') THROW 51000,'Incremental chapter ordering failed',1; +IF (SELECT COUNT(*) FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@Book AND s.IsArchived=0)<>2 THROW 51000,'Incremental scene count failed',1; +SELECT 'PASS canonical native initial import, source/summary preservation, retry and incremental append'; diff --git a/PlotLine/Controllers/NativeCompanionController.cs b/PlotLine/Controllers/NativeCompanionController.cs index 331ea5ee..451124fb 100644 --- a/PlotLine/Controllers/NativeCompanionController.cs +++ b/PlotLine/Controllers/NativeCompanionController.cs @@ -11,7 +11,7 @@ using PlotLine.Services.NativeCompanion; namespace PlotLine.Controllers; [ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")] -public sealed class NativeCompanionController(IWordCompanionRepository repository,NativeAnalysisCache cache,IServiceScopeFactory scopes,IConfiguration configuration,ISubscriptionService subscriptions,INativeReviewRepository? reviews=null):ControllerBase +public sealed class NativeCompanionController(IWordCompanionRepository repository,NativeAnalysisCache cache,IServiceScopeFactory scopes,IConfiguration configuration,ISubscriptionService subscriptions,INativeReviewRepository? reviews=null,NativeImportService? importService=null):ControllerBase { private int UserId=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); [HttpGet("books")] @@ -32,13 +32,13 @@ public sealed class NativeCompanionController(IWordCompanionRepository repositor { var mapped=NativeChapterMapping.Build(request,Math.Clamp(configuration.GetValue("NativeCompanion:MaxChapterCharacters",120000),10000,500000)); var contentHash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{request.ChapterStart,request.ChapterEnd,request.Paragraphs}))); - if(reviews!=null){var prior=await reviews.Find(UserId,request.BookId,request.ManuscriptId,contentHash);if(prior!=null){var saved=JsonSerializer.Deserialize(prior.ResultJson)!;saved.RequestId=request.RequestId;saved.DocumentRevision=request.Revision;saved.ReviewPath=$"/native-companion/reviews/{prior.ReviewID}";return Ok(saved);}} + if(reviews!=null){var prior=await reviews.Find(UserId,request.BookId,request.ManuscriptId,contentHash);if(prior!=null){if(request.RetainForImport&&prior.EncryptedSource==null&&importService!=null){prior.EncryptedSource=importService.Protect(request);await reviews.Save(prior);}var saved=JsonSerializer.Deserialize(prior.ResultJson)!;saved.SourceRetained=prior.EncryptedSource!=null;saved.RequestId=request.RequestId;saved.DocumentRevision=request.Revision;saved.ReviewPath=$"/native-companion/reviews/{prior.ReviewID}";return Ok(saved);}} var hash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(request))); var author=UserId;var task=cache.Run(author,request.RequestId,hash,async cancellation=>{ await using var scope=scopes.CreateAsyncScope(); var result=await scope.ServiceProvider.GetRequiredService().AnalyseChapterAsync(mapped,cancellation); var mappedResult=NativeChapterMapping.Map(request,result); - if(mappedResult.State=="complete"&&reviews!=null){var row=await scope.ServiceProvider.GetRequiredService().Save(new(){ReviewID=request.RequestId,UserID=author,BookID=request.BookId,ManuscriptID=request.ManuscriptId,ChapterStart=request.ChapterStart,ChapterEnd=request.ChapterEnd,ContentHash=contentHash,ResultJson=JsonSerializer.Serialize(mappedResult)});mappedResult.ReviewPath=$"/native-companion/reviews/{row.ReviewID}";} + if(mappedResult.State=="complete"&&reviews!=null){var row=await scope.ServiceProvider.GetRequiredService().Save(new(){ReviewID=request.RequestId,UserID=author,BookID=request.BookId,ManuscriptID=request.ManuscriptId,ChapterStart=request.ChapterStart,ChapterEnd=request.ChapterEnd,ContentHash=contentHash,ResultJson=JsonSerializer.Serialize(mappedResult),EncryptedSource=request.RetainForImport?importService?.Protect(request):null});mappedResult.SourceRetained=row.EncryptedSource!=null;mappedResult.ReviewPath=$"/native-companion/reviews/{row.ReviewID}";} return mappedResult; },request.BookId); Response.Headers.CacheControl="no-store"; diff --git a/PlotLine/Controllers/NativeWorkspaceController.cs b/PlotLine/Controllers/NativeWorkspaceController.cs index 2248915e..c8df5300 100644 --- a/PlotLine/Controllers/NativeWorkspaceController.cs +++ b/PlotLine/Controllers/NativeWorkspaceController.cs @@ -22,6 +22,12 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB 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,updated=l.Updated,expires=l.Updated.AddSeconds(45)})); } + [HttpPost("import/preview"),ValidateAntiForgeryToken] + public async Task ImportPreview(int bookId,Guid[] reviews,[FromServices] NativeImportService importer) + {try{return View(await importer.Preview(Author,bookId,reviews));}catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or System.Security.Cryptography.CryptographicException){return BadRequest(e is ArgumentException?e.Message:"Source capture unavailable. Re-analyse with the updated Companion.");}} + [HttpPost("import/commit"),ValidateAntiForgeryToken] + public async Task ImportCommit(string confirmation,bool confirm,[FromServices] NativeImportService importer) + {if(!confirm)return BadRequest("Explicit import confirmation is required.");try{return View(await importer.Commit(Author,confirmation));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return Conflict(e.Message);}catch(Microsoft.Data.SqlClient.SqlException){return Conflict("Import could not commit. Review decisions are preserved. Preview again; existing story data has not been replaced.");}} [HttpGet("status")] public async Task Status() { diff --git a/PlotLine/Data/NativeImportRepository.cs b/PlotLine/Data/NativeImportRepository.cs new file mode 100644 index 00000000..31f22cb3 --- /dev/null +++ b/PlotLine/Data/NativeImportRepository.cs @@ -0,0 +1,24 @@ +using System.Data; +using System.Text.Json; +using Dapper; +using PlotLine.Services.NativeCompanion; +namespace PlotLine.Data; +public sealed class NativeImportedChapter {public string ChapterKey{get;set;}="";public string ContentHash{get;set;}="";public int ReviewVersion{get;set;}} +public interface INativeImportRepository +{ + Task> List(int user,int book); + Task Result(int user,Guid operation); + Task Commit(int user,Guid operation,NativeImportPlan plan); +} +public sealed class NativeImportRepository(ISqlConnectionFactory factory):INativeImportRepository +{ + public async Task> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync("dbo.NativeReviewImport",new{Action="List",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();} + public async Task Result(int user,Guid operation){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync("dbo.NativeReviewImport",new{Action="Result",UserID=user,OperationID=operation},commandType:CommandType.StoredProcedure);} + public async Task Commit(int user,Guid operation,NativeImportPlan plan) + { + using var db=factory.CreateConnection();using var sets=await db.QueryMultipleAsync("dbo.NativeReviewImport",new{Action="Commit",UserID=user,OperationID=operation,BookID=plan.BookID,DocumentGuid=plan.ManuscriptID,ItemsJson=JsonSerializer.Serialize(plan.Items)},commandType:CommandType.StoredProcedure,commandTimeout:120); + // The canonical build emits its four established sets. Consume through the final + // post-commit result so a later source-save failure cannot masquerade as success. + await sets.ReadAsync();await sets.ReadAsync();await sets.ReadAsync();await sets.ReadAsync();return await sets.ReadSingleAsync(); + } +} diff --git a/PlotLine/Data/NativeReviewRepository.cs b/PlotLine/Data/NativeReviewRepository.cs index b340facd..3f6a76c8 100644 --- a/PlotLine/Data/NativeReviewRepository.cs +++ b/PlotLine/Data/NativeReviewRepository.cs @@ -3,7 +3,7 @@ using Dapper; namespace PlotLine.Data; public sealed class NativeReview { - public Guid ReviewID {get;set;}public int UserID {get;set;}public int BookID {get;set;}public Guid ManuscriptID {get;set;}public int ChapterStart {get;set;}public int ChapterEnd {get;set;}public string ContentHash {get;set;}="";public string ResultJson {get;set;}="";public string? DecisionsJson {get;set;}public int Version {get;set;}public DateTime CreatedUtc {get;set;} + public string? EncryptedSource{get;set;}public Guid ReviewID {get;set;}public int UserID {get;set;}public int BookID {get;set;}public Guid ManuscriptID {get;set;}public int ChapterStart {get;set;}public int ChapterEnd {get;set;}public string ContentHash {get;set;}="";public string ResultJson {get;set;}="";public string? DecisionsJson {get;set;}public int Version {get;set;}public DateTime CreatedUtc {get;set;} } public interface INativeReviewRepository { @@ -19,6 +19,6 @@ public sealed class NativeReviewRepository(ISqlConnectionFactory factory):INativ public Task Find(int user,int book,Guid manuscript,string hash)=>Read(new{Action="Find",UserID=user,BookID=book,ManuscriptID=manuscript,ContentHash=hash}); public Task Get(int user,Guid id)=>Read(new{Action="Get",UserID=user,ReviewID=id}); public async Task> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync("dbo.NativeChapterReview_Access",new{Action="List",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();} - public async Task Save(NativeReview r)=>await Read(new{Action="Save",r.UserID,r.BookID,r.ReviewID,r.ManuscriptID,r.ChapterStart,r.ChapterEnd,r.ContentHash,r.ResultJson})??throw new InvalidOperationException("Review was not saved."); + public async Task Save(NativeReview r){var saved=await Read(new{Action="Save",r.UserID,r.BookID,r.ReviewID,r.ManuscriptID,r.ChapterStart,r.ChapterEnd,r.ContentHash,r.ResultJson})??throw new InvalidOperationException("Review was not saved.");if(!string.IsNullOrEmpty(r.EncryptedSource)){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.NativeReviewSource_Save",new{r.UserID,ReviewID=saved.ReviewID,r.EncryptedSource},commandType:CommandType.StoredProcedure);saved.EncryptedSource??=r.EncryptedSource;}return saved;} public async Task Decide(int user,Guid id,int version,string json){using var db=factory.CreateConnection();return await db.ExecuteScalarAsync("dbo.NativeChapterReview_Access",new{Action="Decide",UserID=user,ReviewID=id,Version=version,DecisionsJson=json},commandType:CommandType.StoredProcedure)==1;} } diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index e5b49899..6a91e50f 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -97,6 +97,8 @@ public class Program builder.Services.AddSingleton(); builder.Services.AddAuthentication().AddScheme(PlotLine.Services.NativeCompanion.DesktopPairing.Scheme, _ => { }); builder.Services.AddSingleton(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/PlotLine/Services/NativeCompanion/NativeImportService.cs b/PlotLine/Services/NativeCompanion/NativeImportService.cs new file mode 100644 index 00000000..d51128dd --- /dev/null +++ b/PlotLine/Services/NativeCompanion/NativeImportService.cs @@ -0,0 +1,55 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Microsoft.AspNetCore.DataProtection; +using PlotDirector.Companion.Protocol; +using PlotLine.Data; +namespace PlotLine.Services.NativeCompanion; +public sealed record NativeImportItem(Guid ReviewID,int Version,string Key,string Hash,string Title,int Start,int End,NativeImportScene[] Scenes); +public sealed record NativeImportScene(string Key,string Title,string Summary,string Text,int StartParagraph,int EndParagraph,int Words); +public sealed record NativeImportPlan(int BookID,Guid ManuscriptID,NativeImportItem[] Items,string[] Conflicts,int Skipped,string Ticket); +public sealed record NativeImportTicket(int User,int Book,Guid[] Reviews,int[] Versions,DateTime Expires,Guid Operation); +public sealed class NativeImportResult {public int BuildID{get;set;}public int ChaptersCreated{get;set;}public int ScenesCreated{get;set;}public bool AlreadyBuilt{get;set;}public string Message{get;set;}="";} +public sealed class NativeImportService(INativeReviewRepository reviews,IWordCompanionRepository access,INativeImportRepository imports,IDataProtectionProvider protection,ISubscriptionService subscriptions) +{ + private readonly IDataProtector ticket=protection.CreateProtector("NativeImport.Confirmation.v1"); + private readonly IDataProtector source=protection.CreateProtector("NativeImport.Source.v1"); + public string Protect(AiChapterRequest request)=>source.Protect(JsonSerializer.Serialize(request)); + public async Task Preview(int user,int book,Guid[] ids,Guid? operation=null) + { + if(!(await subscriptions.CanUseFeatureAsync(user,Models.SubscriptionFeature.Import)).Allowed)throw new UnauthorizedAccessException("Import is not available on this account."); + var structure=await access.GetBookStructureAsync(book,user)??throw new UnauthorizedAccessException("Book access denied."); + if(ids.Length is <1 or >100||ids.Distinct().Count()!=ids.Length)throw new ArgumentException("Select up to 100 different chapter reviews."); + var items=new List();var conflicts=new List();var skipped=0;Guid manuscript=Guid.Empty;var versions=new List(); + foreach(var id in ids){var row=await reviews.Get(user,id)??throw new ArgumentException("A review expired or is unavailable.");if(row.BookID!=book)throw new UnauthorizedAccessException("Reviews must belong to this book.");versions.Add(row.Version); + if(manuscript==Guid.Empty)manuscript=row.ManuscriptID;if(manuscript!=row.ManuscriptID)throw new ArgumentException("Select chapters from one manuscript."); + var result=JsonSerializer.Deserialize(row.ResultJson)!;var decisions=string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize(row.DecisionsJson)!; + var approved=decisions.Where(d=>d.State=="approved").OrderBy(d=>d.Index).ToArray();skipped+=result.Scenes.Length-approved.Length; + if(approved.Length==0){conflicts.Add($"{result.ChapterTitle}: no approved scenes. Save review decisions first.");continue;} + if(string.IsNullOrEmpty(row.EncryptedSource)){conflicts.Add($"{result.ChapterTitle}: source prose was not retained. Use the updated Companion and explicitly retain this chapter for import.");continue;} + var capture=JsonSerializer.Deserialize(source.Unprotect(row.EncryptedSource))!;NativeChapterMapping.Build(capture); + if(Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{capture.ChapterStart,capture.ChapterEnd,capture.Paragraphs})))!=row.ContentHash)throw new ArgumentException("Source content no longer matches this review."); + if(capture.ManuscriptId!=row.ManuscriptID||capture.BookId!=book||capture.ChapterStart!=row.ChapterStart||capture.ChapterEnd!=row.ChapterEnd)throw new ArgumentException("Source identity mismatch."); + var title=string.IsNullOrWhiteSpace(result.ChapterTitle)?"Chapter":result.ChapterTitle;var key="native:"+manuscript.ToString("N")+":"+row.ChapterStart; + var scenes=new List();foreach(var choice in approved){if(choice.Index<0||choice.Index>=result.Scenes.Length)throw new ArgumentException("Review boundaries are invalid.");var scene=result.Scenes[choice.Index];var paragraphs=capture.Paragraphs.Where(p=>p.Start>=scene.Start&&p.End<=scene.End&&!p.IsHeading).ToArray();if(paragraphs.Length==0)throw new ArgumentException("A scene has no source paragraphs.");var text=string.Join("",paragraphs.Select(p=>p.Text));scenes.Add(new(key+":"+scene.Start,choice.Title,choice.Summary,text,paragraphs[0].Index,paragraphs[^1].Index,Count(text)));} + items.Add(new(row.ReviewID,row.Version,key,row.ContentHash,title,row.ChapterStart,row.ChapterEnd,scenes.ToArray())); + } + var imported=await imports.List(user,book);var pending=new List();foreach(var item in items.OrderBy(i=>i.Start)){ + var prior=imported.FirstOrDefault(p=>p.ChapterKey==item.Key);if(prior!=null){if(prior.ContentHash==item.Hash&&prior.ReviewVersion==item.Version){skipped+=item.Scenes.Length;continue;}conflicts.Add(item.Title+": already imported with different content/decisions; existing scenes will not be overwritten.");continue;} + if(structure.Chapters.Any(c=>string.Equals(c.Title.Trim(),item.Title.Trim(),StringComparison.OrdinalIgnoreCase)))conflicts.Add(item.Title+": an existing chapter has this title. Resolve the match before importing; no replacement is performed."); + if(pending.Any(p=>p.Start Commit(int user,string confirmation) + { + NativeImportTicket saved;try{saved=JsonSerializer.Deserialize(ticket.Unprotect(confirmation))!;}catch(Exception e)when(e is CryptographicException or JsonException or ArgumentException){throw new ArgumentException("Invalid import confirmation.");} + if(saved.User!=user||saved.Expires0)throw new ArgumentException(string.Join(" ",plan.Conflicts));if(plan.Items.Length==0)return new(){AlreadyBuilt=true,Message="All selected approved chapters already match an import. Nothing changed."}; + return await imports.Commit(user,saved.Operation,plan); + } + private static int Count(string text)=>text.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length; +} diff --git a/PlotLine/Sql/232_NativeApprovedImport.sql b/PlotLine/Sql/232_NativeApprovedImport.sql new file mode 100644 index 00000000..f806673e --- /dev/null +++ b/PlotLine/Sql/232_NativeApprovedImport.sql @@ -0,0 +1,88 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +IF COL_LENGTH(N'dbo.NativeChapterReviews',N'EncryptedSource') IS NULL ALTER TABLE dbo.NativeChapterReviews ADD EncryptedSource nvarchar(max) NULL; +IF OBJECT_ID(N'dbo.NativeImportOperations',N'U') IS NULL + CREATE TABLE dbo.NativeImportOperations(OperationID uniqueidentifier PRIMARY KEY,UserID int NOT NULL,BookID int NOT NULL,BuildID int NOT NULL,ChaptersCreated int NOT NULL,ScenesCreated int NOT NULL,CreatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME()); +IF OBJECT_ID(N'dbo.NativeReviewImports',N'U') IS NULL + CREATE TABLE dbo.NativeReviewImports(BookID int NOT NULL,ChapterKey nvarchar(80) NOT NULL,ContentHash varchar(64) NOT NULL,ReviewID uniqueidentifier NOT NULL,ReviewVersion int NOT NULL,ChapterID int NOT NULL,BuildID int NOT NULL,PRIMARY KEY(BookID,ChapterKey)); +-- Independent provenance, without FKs that block existing book/project deletion and restore. +GO +CREATE OR ALTER PROCEDURE dbo.NativeReviewSource_Save @UserID int,@ReviewID uniqueidentifier,@EncryptedSource nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; + IF DATALENGTH(@EncryptedSource)>8388608 THROW 51000,'Source capture too large',1; + UPDATE dbo.NativeChapterReviews SET EncryptedSource=@EncryptedSource WHERE ReviewID=@ReviewID AND UserID=@UserID AND EncryptedSource IS NULL; +END; +GO +CREATE OR ALTER PROCEDURE dbo.NativeReviewImport @Action varchar(12),@UserID int,@BookID int=0,@OperationID uniqueidentifier=NULL,@DocumentGuid uniqueidentifier=NULL,@ItemsJson nvarchar(max)=NULL +AS +BEGIN + SET NOCOUNT ON;SET XACT_ABORT ON; + IF @Action='Result' + BEGIN + SELECT BuildID,ChaptersCreated,ScenesCreated,CAST(1 AS bit) AlreadyBuilt,N'Approved import already committed. Nothing duplicated.' Message FROM dbo.NativeImportOperations WHERE OperationID=@OperationID AND UserID=@UserID;RETURN; + END; + IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE b.BookID=@BookID AND b.IsArchived=0 AND a.UserID=@UserID AND a.IsActive=1) THROW 51000,'Book access denied',1; + IF @Action='List' BEGIN SELECT ChapterKey,ContentHash,ReviewVersion FROM dbo.NativeReviewImports WHERE BookID=@BookID;RETURN;END; + IF @Action<>'Commit' OR @OperationID IS NULL OR @DocumentGuid IS NULL OR ISJSON(@ItemsJson)<>1 THROW 51000,'Invalid native import',1; + BEGIN TRANSACTION; + BEGIN TRY + DECLARE @LockResult int,@LockName nvarchar(255)=CONCAT('NativeImport:',@BookID); + EXEC @LockResult=sys.sp_getapplock @Resource=@LockName,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000; + IF @LockResult<0 THROW 51000,'Book import busy. Retry the same confirmation.',1; + IF EXISTS(SELECT 1 FROM dbo.NativeImportOperations WHERE OperationID=@OperationID AND UserID=@UserID) + BEGIN + EXEC dbo.Onboarding_ManuscriptBuild_GetByPreview @UserID=@UserID,@PreviewID=@OperationID; + SELECT BuildID,ChaptersCreated,ScenesCreated,CAST(1 AS bit) AlreadyBuilt,N'Import already committed.' Message FROM dbo.NativeImportOperations WHERE OperationID=@OperationID AND UserID=@UserID; + COMMIT;RETURN; + END; + DECLARE @ProjectID int,@MaxSort int,@MaxNumber decimal(9,2); + SELECT @ProjectID=ProjectID FROM dbo.Books WITH(XLOCK,HOLDLOCK) WHERE BookID=@BookID AND IsArchived=0; + IF @ProjectID IS NULL THROW 51000,'Book unavailable',1; + IF EXISTS(SELECT 1 FROM dbo.ManuscriptDocuments WHERE BookID=@BookID AND IsActive=1 AND DocumentGuid<>@DocumentGuid) THROW 51000,'Book is bound to another manuscript',1; + DECLARE @Items table(ReviewID uniqueidentifier,Version int,[Key] nvarchar(80),Hash varchar(64),Title nvarchar(200),[Start] int,[End] int,Scenes nvarchar(max)); + INSERT @Items SELECT ReviewID,Version,[Key],Hash,Title,[Start],[End],Scenes FROM OPENJSON(@ItemsJson) WITH(ReviewID uniqueidentifier,Version int,[Key] nvarchar(80),Hash varchar(64),Title nvarchar(200),[Start] int,[End] int,Scenes nvarchar(max) AS JSON); + IF (SELECT COUNT(*) FROM @Items) NOT BETWEEN 1 AND 100 THROW 51000,'Select a bounded chapter batch',1; + IF EXISTS(SELECT [Key] FROM @Items GROUP BY [Key] HAVING COUNT(*)>1) THROW 51000,'Competing chapters',1; + IF EXISTS(SELECT 1 FROM @Items i LEFT JOIN dbo.NativeChapterReviews r WITH(UPDLOCK,HOLDLOCK) ON r.ReviewID=i.ReviewID AND r.UserID=@UserID AND r.BookID=@BookID WHERE r.ReviewID IS NULL OR r.Version<>i.Version OR r.ContentHash<>i.Hash OR r.EncryptedSource IS NULL OR r.CreatedUtc<=DATEADD(day,-30,SYSUTCDATETIME())) THROW 51000,'Reviews changed or expired. Preview again.',1; + IF EXISTS(SELECT 1 FROM @Items i JOIN dbo.NativeReviewImports n ON n.BookID=@BookID AND n.ChapterKey=i.[Key]) THROW 51000,'A chapter was imported meanwhile. Preview again.',1; + IF EXISTS(SELECT 1 FROM @Items i JOIN dbo.Chapters c ON c.BookID=@BookID AND c.IsArchived=0 AND UPPER(LTRIM(RTRIM(c.ChapterTitle)))=UPPER(LTRIM(RTRIM(i.Title)))) THROW 51000,'An existing chapter has this title. No replacement performed.',1; + SELECT @MaxSort=COALESCE(MAX(SortOrder),0),@MaxNumber=COALESCE(MAX(ChapterNumber),0) FROM dbo.Chapters WHERE BookID=@BookID AND IsArchived=0; + DECLARE @Chapters nvarchar(max)=(SELECT [Key] TemporaryChapterKey,Title,@MaxSort+10*ROW_NUMBER() OVER(ORDER BY [Start]) SortOrder,0 WordCount FROM @Items ORDER BY [Start] FOR JSON PATH); + DECLARE @Scenes table(TemporarySceneKey nvarchar(80),TemporaryChapterKey nvarchar(80),Title nvarchar(200),Summary nvarchar(max),SourceText nvarchar(max),StartParagraph int,EndParagraph int,Words int,SortOrder int); + INSERT @Scenes SELECT s.[Key],i.[Key],s.Title,s.Summary,s.[Text],s.StartParagraph,s.EndParagraph,s.Words,10*TRY_CONVERT(int,j.[key])+10 FROM @Items i CROSS APPLY OPENJSON(i.Scenes) j CROSS APPLY OPENJSON(j.value) WITH([Key] nvarchar(80),Title nvarchar(200),Summary nvarchar(max),[Text] nvarchar(max),StartParagraph int,EndParagraph int,Words int) s; + IF EXISTS(SELECT 1 FROM @Items i WHERE NOT EXISTS(SELECT 1 FROM @Scenes s WHERE s.TemporaryChapterKey=i.[Key])) THROW 51000,'Every imported chapter requires approved scenes',1; + DECLARE @ScenesJson nvarchar(max)=(SELECT TemporarySceneKey,TemporaryChapterKey,Title,SortOrder,Words WordCount FROM @Scenes FOR JSON PATH); + SET @Chapters=(SELECT i.[Key] TemporaryChapterKey,i.Title,@MaxSort+10*ROW_NUMBER() OVER(ORDER BY i.[Start]) SortOrder,(SELECT SUM(s.Words) FROM @Scenes s WHERE s.TemporaryChapterKey=i.[Key]) WordCount FROM @Items i ORDER BY i.[Start] FOR JSON PATH); + -- Reuse the established import builder, including manuscript binding and maps. + -- Its nested COMMIT does not commit this outer transaction. + EXEC dbo.Onboarding_ManuscriptBuild_Create @UserID=@UserID,@PreviewID=@OperationID,@ProjectID=@ProjectID,@BookID=@BookID,@DocumentGuid=@DocumentGuid,@ChaptersJson=@Chapters,@ScenesJson=@ScenesJson,@CharactersJson=N'[]'; + DECLARE @BuildID int=(SELECT OnboardingManuscriptBuildID FROM dbo.OnboardingManuscriptBuilds WHERE PreviewID=@OperationID AND UserID=@UserID); + IF @BuildID IS NULL THROW 51000,'Established import builder rejected the structure',1; + ;WITH NewNumbers AS(SELECT m.ChapterID,@MaxNumber+ROW_NUMBER() OVER(ORDER BY i.[Start]) Number FROM dbo.OnboardingManuscriptBuildChapterMap m JOIN @Items i ON i.[Key]=m.TemporaryChapterKey WHERE m.OnboardingManuscriptBuildID=@BuildID) + UPDATE c SET ChapterNumber=n.Number FROM dbo.Chapters c JOIN NewNumbers n ON n.ChapterID=c.ChapterID; + UPDATE s SET SceneTitleSource=N'Author' FROM dbo.Scenes s JOIN dbo.OnboardingManuscriptBuildSceneMap m ON m.SceneID=s.SceneID AND m.OnboardingManuscriptBuildID=@BuildID; + DECLARE @SceneID int,@ChapterID int,@Text nvarchar(max),@Summary nvarchar(max),@Words int,@Start int,@End int; + DECLARE Sources CURSOR LOCAL FAST_FORWARD FOR SELECT m.SceneID,c.ChapterID,s.SourceText,s.Summary,s.Words,s.StartParagraph,s.EndParagraph FROM @Scenes s JOIN dbo.OnboardingManuscriptBuildSceneMap m ON m.OnboardingManuscriptBuildID=@BuildID AND m.TemporarySceneKey=s.TemporarySceneKey JOIN dbo.Scenes c ON c.SceneID=m.SceneID; + OPEN Sources;FETCH NEXT FROM Sources INTO @SceneID,@ChapterID,@Text,@Summary,@Words,@Start,@End; + WHILE @@FETCH_STATUS=0 + BEGIN + DECLARE @Characters int=LEN(@Text); + EXEC dbo.SceneManuscriptSource_Save @SceneID=@SceneID,@ProjectID=@ProjectID,@BookID=@BookID,@ChapterID=@ChapterID,@SourceText=@Text,@SourceWordCount=@Words,@SourceCharacterCount=@Characters,@SourceStartParagraph=@Start,@SourceEndParagraph=@End,@WordStartParagraphIndex=@Start,@WordEndParagraphIndex=@End,@SourceKind=N'NativeApprovedImport'; + EXEC dbo.SceneStructuralSummary_Save @SceneID=@SceneID,@StructuralSummary=@Summary; + FETCH NEXT FROM Sources INTO @SceneID,@ChapterID,@Text,@Summary,@Words,@Start,@End; + END;CLOSE Sources;DEALLOCATE Sources; + INSERT dbo.NativeReviewImports(BookID,ChapterKey,ContentHash,ReviewID,ReviewVersion,ChapterID,BuildID) SELECT @BookID,i.[Key],i.Hash,i.ReviewID,i.Version,m.ChapterID,@BuildID FROM @Items i JOIN dbo.OnboardingManuscriptBuildChapterMap m ON m.OnboardingManuscriptBuildID=@BuildID AND m.TemporaryChapterKey=i.[Key]; + INSERT dbo.NativeImportOperations(OperationID,UserID,BookID,BuildID,ChaptersCreated,ScenesCreated) SELECT @OperationID,@UserID,@BookID,@BuildID,COUNT(*),(SELECT COUNT(*) FROM @Scenes) FROM @Items; + UPDATE dbo.OnboardingManuscriptBuilds SET Status=N'Complete',MarkerStatus=N'NotRequestedNative' WHERE OnboardingManuscriptBuildID=@BuildID; + COMMIT; + SELECT BuildID,ChaptersCreated,ScenesCreated,CAST(0 AS bit) AlreadyBuilt,N'Approved chapters, scenes, summaries and prose imported. Existing content and Word are unchanged.' Message FROM dbo.NativeImportOperations WHERE OperationID=@OperationID AND UserID=@UserID; + END TRY + BEGIN CATCH + IF @@TRANCOUNT>0 ROLLBACK; + THROW; + END CATCH; +END; +GO diff --git a/PlotLine/Views/NativeWorkspace/ImportCommit.cshtml b/PlotLine/Views/NativeWorkspace/ImportCommit.cshtml new file mode 100644 index 00000000..bc8daa2d --- /dev/null +++ b/PlotLine/Views/NativeWorkspace/ImportCommit.cshtml @@ -0,0 +1,3 @@ +@model PlotLine.Services.NativeCompanion.NativeImportResult +@{ViewData["Title"]="Import result";} +

Approved import result

@Model.Message

New chapters: @Model.ChaptersCreated · New scenes: @Model.ScenesCreated · Existing content overwritten: 0

Word prose and markers are unchanged. Saved PlotDirector scenes are now available in the book workspace. Automatic Word marker linkage is a separate action.

Return to PlotDirector
diff --git a/PlotLine/Views/NativeWorkspace/ImportPreview.cshtml b/PlotLine/Views/NativeWorkspace/ImportPreview.cshtml new file mode 100644 index 00000000..0737a420 --- /dev/null +++ b/PlotLine/Views/NativeWorkspace/ImportPreview.cshtml @@ -0,0 +1,8 @@ +@model PlotLine.Services.NativeCompanion.NativeImportPlan +@{ViewData["Title"]="Preview approved import";} +

Preview approved import

Creates @Model.Items.Length new chapters and @Model.Items.Sum(i=>i.Scenes.Length) scenes. @Model.Skipped rejected, pending or already imported scenes are skipped. Word remains unchanged.

+

New chapters append in manuscript order. Existing chapters, relationships, plot lines and author metadata are preserved. Matching imported captures are skipped; competing changes require reconciliation.

+@if(Model.Conflicts.Length>0){

Resolve before importing

    @foreach(var conflict in Model.Conflicts){
  • @conflict
  • }
} +@foreach(var chapter in Model.Items){

Create chapter: @chapter.Title

    @foreach(var scene in chapter.Scenes){
  • Create scene: @scene.Title

    @scene.Summary

    @scene.Words words
  • }
} +@if(Model.Conflicts.Length==0&&Model.Items.Length>0){
@Html.AntiForgeryToken()
} +Cancel / return to reviews
diff --git a/PlotLine/Views/NativeWorkspace/Review.cshtml b/PlotLine/Views/NativeWorkspace/Review.cshtml index d4d3664d..9cb89b36 100644 --- a/PlotLine/Views/NativeWorkspace/Review.cshtml +++ b/PlotLine/Views/NativeWorkspace/Review.cshtml @@ -21,5 +21,5 @@

Requires the exact live manuscript and observed revision. Navigation is explicit and never triggered by following.

} -

Import remains a separate, explicit operation through the established manuscript import. These decisions are retained as suggestions; this page does not yet transfer them into an import build.

+

After saving decisions, return to the Companion workspace, select the reviewed chapters and preview the approved import. Only approved scenes are included. No import occurs until you confirm the preview. Older captures require the updated Companion to retain source prose explicitly.

diff --git a/PlotLine/Views/NativeWorkspace/Workspace.cshtml b/PlotLine/Views/NativeWorkspace/Workspace.cshtml index 486ddf98..02ec29c7 100644 --- a/PlotLine/Views/NativeWorkspace/Workspace.cshtml +++ b/PlotLine/Views/NativeWorkspace/Workspace.cshtml @@ -12,6 +12,6 @@

AI chapter suggestions

Generated by PlotDirector’s existing chapter-analysis service. Review titles and summaries before any import. Successful chapters remain available for 30 days.

@if(Model.Reviews.Count==0){
No saved AI suggestions yet. Detect Heading 1 chapters in the tray Companion, select chapters and explicitly confirm analysis.
} - else {} + else {
@Html.AntiForgeryToken()
}