using System.Diagnostics; using System.Data; using System.Security.Cryptography; using System.Text; using Dapper; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services.Manuscript; using PlotLine.Services.Writer; internal static class WriterPhase21DatabaseTests { public static async Task Run() { var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true};foreach(var part in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(part);using var process=Process.Start(start)!;var env=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new Exception("Configuration unavailable"); var raw=env.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');var connection=new SqlConnectionStringBuilder(raw);if(connection.InitialCatalog!="PlotDirector_Development")throw new Exception("Unexpected configured database");connection.InitialCatalog="PlotDirector_WriterPhase21_20261118"; using var db=new SqlConnection(connection.ConnectionString);await db.OpenAsync();if(await db.ExecuteScalarAsync("SELECT DB_NAME()")!=connection.InitialCatalog)throw new Exception("Wrong disposable target"); void Check(bool ok,string text){if(!ok)throw new Exception(text);Console.WriteLine("PASS Phase21 "+text);} async Task Reject(Func action,string text){try{await action();}catch(Exception e)when(e is SqlException or ArgumentException or KeyNotFoundException or AuthoringConflictException){Check(true,text);return;}throw new Exception(text);} var factory=new SqlConnectionFactory(new ConfigurationBuilder().AddInMemoryCollection(new Dictionary{{"ConnectionStrings:DefaultConnection",connection.ConnectionString}}).Build()); var rows=await db.QuerySingleAsync<(int UserID,int Other,int ProjectID,int BookID,int ForeignBook,int ChapterID,int EmptyChapter,int SceneID)>(""" DECLARE @u int,@o int,@p int,@b int,@f int,@c int,@empty int,@s int,@l int,@revision int=(SELECT TOP(1) RevisionStatusID FROM dbo.RevisionStatuses ORDER BY SortOrder); INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+'@work.invalid','Synthetic work author','not-a-credential');SET @u=SCOPE_IDENTITY(); INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+'@work.invalid','Synthetic other','not-a-credential');SET @o=SCOPE_IDENTITY(); INSERT dbo.SubscriptionLevel(Name,DisplayName,MaxBooks,MaxChaptersPerBook,MaxScenesPerBook,MaxCharactersPerProject,MaxStorageMB,MaxCollaborators,SortOrder,RequiresStripeSubscription) VALUES(CONVERT(nvarchar(36),NEWID()),'Work fixture',10,100,100,100,100,0,0,0);SET @l=SCOPE_IDENTITY(); INSERT dbo.UserSubscription(UserID,SubscriptionLevelID,IsActive,IsTrial,TrialExpiryDateUTC) VALUES(@u,@l,1,1,'2030-01-01'); INSERT dbo.Projects(ProjectName) VALUES('Synthetic intelligent Writer');SET @p=SCOPE_IDENTITY(); INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@p,@u,'Owner',1); INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@p,'Synthetic Writer',1,1);SET @b=SCOPE_IDENTITY(); INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@p,'Foreign target',2,2);SET @f=SCOPE_IDENTITY(); INSERT dbo.Chapters(BookID,ChapterTitle,ChapterNumber,SortOrder,RevisionStatusID) VALUES(@b,'Synthetic chapter',1,1,@revision);SET @c=SCOPE_IDENTITY(); INSERT dbo.Chapters(BookID,ChapterTitle,ChapterNumber,SortOrder,RevisionStatusID) VALUES(@b,'Chapter without a scene',2,2,@revision);SET @empty=SCOPE_IDENTITY(); INSERT dbo.Scenes(ChapterID,SceneTitle,SceneNumber,SortOrder,RevisionStatusID,TimeModeID,TimeConfidenceID) VALUES(@c,'Synthetic scene',1,1,@revision,(SELECT TOP(1) TimeModeID FROM dbo.TimeModes ORDER BY SortOrder),(SELECT TOP(1) TimeConfidenceID FROM dbo.TimeConfidences ORDER BY SortOrder));SET @s=SCOPE_IDENTITY(); SELECT @u UserID,@o Other,@p ProjectID,@b BookID,@f ForeignBook,@c ChapterID,@empty EmptyChapter,@s SceneID; """); var user=rows.UserID;var book=rows.BookID;var planner=new WriterActivityRepository(factory);var id=Guid.NewGuid(); var create=new{Action="save",UserID=user,BookID=book,ID=id,Title="Revise arrival",Kind="Editing",EntityKind="Scene",EntityID=rows.SceneID,Notes="Keep the change clear",Status="Next"}; await planner.Execute(create);await planner.Execute(create);Check((await planner.Read(user,book)).Count==1,"idempotent create preserves a single activity"); await Reject(()=>planner.Execute(new{Action="save",UserID=user,BookID=rows.ForeignBook,ID=Guid.NewGuid(),Title="Wrong scope",Kind="Writing",EntityKind="Scene",EntityID=rows.SceneID}),"cross-book scene reference refused"); await Reject(async()=>{await planner.Read(rows.Other,book);},"unrelated author cannot read planner"); await db.ExecuteAsync("INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@ProjectID,@Other,'Collaborator',1)",new{rows.ProjectID,rows.Other}); Check((await planner.Read(rows.Other,book)).Count==0,"shared project authors do not see each other's private intentions"); await Reject(()=>planner.Execute(new{Action="status",UserID=rows.Other,BookID=book,ID=id,Version=1,Status="Completed"}),"shared project author cannot mutate another activity"); var second=Guid.NewGuid();await planner.Execute(new{Action="save",UserID=user,BookID=book,ID=second,Title="Review chapter",Kind="Review",TargetDate=DateTime.Today.AddDays(1)}); foreach(var state in new[]{"In progress","Completed","Next","Deferred"}){var row=(await planner.Read(user,book)).Single(x=>x.ID==id);await planner.Execute(new{Action="status",UserID=user,BookID=book,ID=id,row.Version,Status=state});Check((await planner.Read(user,book)).Single(x=>x.ID==id).Status==state,"planned activity transitions to "+state);} var current=(await planner.Read(user,book)).Single(x=>x.ID==second);await planner.Execute(new{Action="move",UserID=user,BookID=book,ID=second,current.Version,Direction=-1});Check((await planner.Read(user,book))[0].ID==second,"accessible reorder persists across reads"); await Reject(()=>planner.Execute(new{Action="status",UserID=user,BookID=book,ID=second,current.Version,Status="Completed"}),"stale activity mutation is refused"); current=(await planner.Read(user,book)).Single(x=>x.ID==second);await planner.Execute(new{Action="archive",UserID=user,BookID=book,ID=second,current.Version});current=(await planner.Read(user,book)).Single(x=>x.ID==second);Check(current.IsArchived,"archive retains activity history");await planner.Execute(new{Action="restore",UserID=user,BookID=book,ID=second,current.Version});Check(!(await planner.Read(user,book)).Single(x=>x.ID==second).IsArchived,"archive can be restored"); Check((await planner.Read(user,book)).Any(x=>x.TargetDate==null)&&(await planner.Read(user,book)).Any(x=>x.TargetDate.HasValue),"dated and undated activities share one collection"); Check(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.WriterWorkSessions WHERE UserID=@user",new{user})==0,"planning mutations never fabricate sessions"); var investigations=new InvestigationRepository(factory);var catalogue=await investigations.Catalogue("guided-investigation-production-v0.1")??throw new Exception("Published author catalogue missing"); var bookAccess=NativeWorkflowTests.Proxy((name,args)=>name=="CanAccessEntityAsync"?Task.FromResult((int)args![1]! ==book):throw new Exception(name)); var investigationService=new PlotLine.Services.Investigations.InvestigationService(investigations,new BookRepository(factory),bookAccess,TimeProvider.System,new ConfigurationBuilder().Build());var startID=Guid.NewGuid(); var started=await investigationService.Start(user,book,catalogue.Concerns.First().Id,catalogue.Version,startID);var retried=await investigationService.Start(user,book,catalogue.Concerns.First().Id,catalogue.Version,startID); Check(started.ID==retried.ID&&(await investigations.Replay(user,book,startID)).Length==1,"real investigation missing-ID lookup permits an idempotent start without duplicate history"); await Reject(()=>investigationService.Start(rows.Other,book,catalogue.Concerns.First().Id,catalogue.Version,startID),"another author cannot adopt a start request ID"); var paragraphs=new ParagraphManuscriptRepository(factory);var paragraph=Guid.NewGuid();var stableScene=Guid.NewGuid();var text="A quiet arrival changed the traveller's plan.\r"; var source=new ParagraphManuscript{BookId=book,ProjectId=rows.ProjectID,ManuscriptId=Guid.NewGuid(),SnapshotHash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))),Scenes=[new(){Id=stableScene,CanonicalId=rows.SceneID,ChapterId=rows.ChapterID}],Paragraphs=[new(){Story=true,PositionVerified=true,ChapterId=rows.ChapterID,SceneId=stableScene,Occurrence=new(){Id=paragraph,Ordinal=0,Start=0,End=text.Length,Text=text}}]}; await paragraphs.Save(user,source,-1,Guid.NewGuid());var reader=new ManuscriptReaderService(paragraphs,new BookRepository(factory),new ChapterRepository(factory));var accepted=await reader.Read(user,book,rows.ChapterID);var review=new WriterReviewService(factory,reader,new WriterAuthoringFixture()); foreach(var scope in new[]{"Chapter","Scene","Passage"}){ var request=new ReviewSave{BookID=book,ChapterID=rows.ChapterID,ID=Guid.NewGuid(),ContentVersion=accepted!.ContentVersion,Scope=scope,SceneID=scope=="Scene"?rows.SceneID:null,Observation="Editorial "+scope,Classification="Continuity"};if(scope=="Passage"){request.StartParagraph=paragraph;request.EndParagraph=paragraph;request.StartOffset=2;request.EndOffset=12;} var row=await review.Save(user,request);Check(row.EffectiveScope==scope&&row.EffectiveClassification=="Continuity","annotation persists explicit "+scope+" scope and classification"); var retry=await review.Save(user,request);Check(row.ID==retry.ID,"annotation create retry is idempotent");request.Version=row.Version;request.Classification="Revision needed";request.Status="Dismissed";request.Observation="Reconsidered";var updated=await review.Save(user,request);Check(updated.Status=="Dismissed"&&updated.EffectiveClassification=="Revision needed"&&updated.StartParagraph==row.StartParagraph,"classification/status editing preserves accepted anchor"); await Reject(()=>review.Save(rows.Other,new(){BookID=book,ChapterID=rows.ChapterID,ID=row.ID,Version=updated.Version,Observation="Foreign write",Classification="Plot"}),"another author cannot modify annotations"); } await Reject(()=>review.Save(user,new(){BookID=book,ChapterID=rows.ChapterID,ID=Guid.NewGuid(),ContentVersion=accepted!.ContentVersion,Scope="Scene",SceneID=999999,Observation="Invented scene"}),"unverified scene association refused"); await Reject(()=>review.Save(user,new(){BookID=book,ChapterID=rows.ChapterID,ID=Guid.NewGuid(),ContentVersion=accepted!.ContentVersion,Scope="Passage",StartParagraph=Guid.NewGuid(),EndParagraph=Guid.NewGuid(),StartOffset=0,EndOffset=1,Observation="Foreign anchor"}),"unknown paragraph anchor refused"); var after=await paragraphs.Get(user,book);Check(after!.Revision==accepted!.Revision&&after.Paragraphs.Single().Occurrence.Id==paragraph&&after.Paragraphs.Single().Occurrence.Text==text,"planner and annotations preserve canonical text, revision, paragraph and scene identity"); } }