PlotDirector/PlotLine.Tests/WritingContextDevelopmentFixture.cs

52 lines
6.3 KiB
C#

using System.Diagnostics;
using System.Text.Json;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using PlotDirector.Companion.Protocol.Manuscript;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services.Manuscript;
internal static class WritingContextDevelopmentFixture
{
public sealed class Scope
{
public int User {get;set;}public int Project {get;set;}public int Book {get;set;}
public int[] Chapters {get;set;}=[];public int[] Scenes {get;set;}=[];
public Guid Instance {get;set;}public Guid Session {get;set;}public Guid Manuscript {get;set;}
public int[] SceneStarts {get;set;}=[];
}
public static async Task Run(string[] args)
{
if(!OperatingSystem.IsLinux()||args.Length!=3||!args[1].StartsWith("/tmp/pd-dev-browser-",StringComparison.Ordinal)||!args[2].StartsWith("/tmp/pd-context-",StringComparison.Ordinal))throw new Exception("Explicit private Development fixture files required");
if((File.GetUnixFileMode(args[1])&(UnixFileMode.GroupRead|UnixFileMode.OtherRead))!=0)throw new Exception("Identity file must be private");
using var identity=JsonDocument.Parse(await File.ReadAllTextAsync(args[1]));var who=identity.RootElement;
var scope=JsonSerializer.Deserialize<Scope>(await File.ReadAllTextAsync(args[2]))!;
var email=who.GetProperty("Email").GetString()!;
if(who.GetProperty("Database").GetString()!="PlotDirector_Development"||who.GetProperty("UserID").GetInt32()!=scope.User||!email.StartsWith("pwa-browser-")||!email.EndsWith("@example.invalid")||scope.Book<=0||scope.Project<=0||scope.Session==Guid.Empty||scope.Manuscript==Guid.Empty)throw new Exception("Fixture identity mismatch");
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 environment=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new Exception("Development configuration inaccessible");
var connectionString=environment.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');
if(new SqlConnectionStringBuilder(connectionString).InitialCatalog!="PlotDirector_Development")throw new Exception("Unexpected database");
var factory=new SqlConnectionFactory(new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",connectionString}}).Build());
var user=await new UserRepository(factory).GetByEmailAsync(email);var project=await new ProjectRepository(factory).GetForUserAsync(scope.Project,scope.User);var book=await new BookRepository(factory).GetAsync(scope.Book);
if(user?.UserID!=scope.User||project?.IsOwner!=true||book?.ProjectID!=scope.Project)throw new Exception("Synthetic project ownership mismatch");
var snapshots=new ParagraphManuscriptRepository(factory);if(await snapshots.Get(scope.User,scope.Book)!=null)throw new Exception("Refusing to overwrite an existing paragraph snapshot");
var chapters=new ChapterRepository(factory);var scenes=new SceneRepository(factory);var lookup=await new LookupRepository(factory).GetAllAsync();
for(int i=0;i<2;i++){
if(scope.Chapters.Length<=i){var created=await chapters.SaveAsync(new(){BookID=scope.Book,ChapterNumber=i+1,ChapterTitle="Context fixture chapter "+(i+1),RevisionStatusID=lookup.RevisionStatuses.First().RevisionStatusID,SortOrder=i+1});scope.Chapters=[..scope.Chapters,created];await File.WriteAllTextAsync(args[2],JsonSerializer.Serialize(scope));}
var chapter=await chapters.GetAsync(scope.Chapters[i]);if(chapter?.BookID!=scope.Book)throw new Exception("Foreign fixture chapter");
if(scope.Scenes.Length<=i){var created=await scenes.SaveAsync(new(){ChapterID=scope.Chapters[i],SceneNumber=1,SceneTitle="Context fixture scene "+(i+1),RevisionStatusID=lookup.RevisionStatuses.First().RevisionStatusID,TimeModeID=lookup.TimeModes.First().TimeModeID,TimeConfidenceID=lookup.TimeConfidences.First().TimeConfidenceID,SortOrder=1});scope.Scenes=[..scope.Scenes,created];await File.WriteAllTextAsync(args[2],JsonSerializer.Serialize(scope));}
if((await scenes.GetAsync(scope.Scenes[i]))?.ChapterID!=scope.Chapters[i])throw new Exception("Foreign fixture scene");
}
var structure=await new WordCompanionRepository(factory).GetBookStructureAsync(scope.Book,scope.User);
if(structure?.Chapters.Count!=2||!structure.Chapters.SelectMany(c=>c.Scenes).Select(s=>s.SceneId).SequenceEqual(scope.Scenes))throw new Exception("Unexpected fixture structure; refusing adoption");
var rows=new List<ParagraphOccurrence>();int position=0;foreach(var text in new[]{"Chapter one\r","First exact synthetic paragraph.\r","More first-scene evidence.\r","Chapter two\r","Second exact synthetic paragraph.\r","More second-scene evidence.\r"}){var outline=rows.Count%3==0?1:10;rows.Add(new(){Ordinal=rows.Count,Start=position,End=position+text.Length,Text=text,Outline=outline});position+=text.Length;}
var state=ParagraphManuscriptEngine.Bootstrap(scope.Book,scope.Project,scope.Manuscript,rows,[new(){ChapterId=scope.Chapters[0],SceneId=scope.Scenes[0],Start=2,End=3,Title="Context fixture scene 1"},new(){ChapterId=scope.Chapters[1],SceneId=scope.Scenes[1],Start=5,End=6,Title="Context fixture scene 2"}]);
state.SessionId=scope.Session;state.WordRevision=1;state.DocumentName="Synthetic context manuscript.docx";state.Mode="Manual";state.SnapshotHash=ParagraphManuscriptEngine.Hash(state.Paragraphs.Select(p=>p.Occurrence).ToArray());
var saved=await snapshots.Save(scope.User,state,-1,Guid.NewGuid());
if(saved.Paragraphs.Count!=6||saved.Scenes.Count!=2||saved.Paragraphs.Any(p=>p.Story&&!p.PositionVerified))throw new Exception("Fixture snapshot verification failed");
scope.SceneStarts=[saved.Paragraphs[1].Occurrence.Start,saved.Paragraphs[4].Occurrence.Start];await File.WriteAllTextAsync(args[2],JsonSerializer.Serialize(scope));
Console.WriteLine($"PASS guarded Development fixture: book {scope.Book}, two canonical chapters/scenes, six exact paragraphs; no AI, import job or author data changed");
}
}