PlotDirector/PlotLine.Tests/ChapterSyncDevelopmentTests.cs

41 lines
6.9 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.Services.Manuscript;
// Opt-in, owned synthetic Development fixture only. Never uses a fixed author book ID.
internal static class ChapterSyncDevelopmentTests
{
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 synthetic fixture required");
if((File.GetUnixFileMode(args[1])&(UnixFileMode.GroupRead|UnixFileMode.OtherRead))!=0)throw new Exception("Private identity required");
using var identity=JsonDocument.Parse(await File.ReadAllTextAsync(args[1]));var who=identity.RootElement;var scope=JsonSerializer.Deserialize<WritingContextDevelopmentFixture.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"))throw new Exception("Synthetic identity mismatch");
var processInfo=new ProcessStartInfo("sudo"){RedirectStandardOutput=true};foreach(var value in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})processInfo.ArgumentList.Add(value);using var process=Process.Start(processInfo)!;var environment=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new Exception("Configuration inaccessible");
var connection=environment.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');if(new SqlConnectionStringBuilder(connection).InitialCatalog!="PlotDirector_Development")throw new Exception("Wrong database");
var factory=new SqlConnectionFactory(new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",connection}}).Build());
if((await new UserRepository(factory).GetByEmailAsync(email))?.UserID!=scope.User||(await new ProjectRepository(factory).GetForUserAsync(scope.Project,scope.User))?.IsOwner!=true||(await new BookRepository(factory).GetAsync(scope.Book))?.ProjectID!=scope.Project)throw new Exception("Synthetic ownership mismatch");
var repository=new ParagraphManuscriptRepository(factory);var chapters=new ChapterSyncRepository(factory);var original=await repository.Get(scope.User,scope.Book)??throw new Exception("Seed missing");if(original.Paragraphs.Count!=6||original.Scenes.Count!=2||original.Chapters.Count!=2||original.ManuscriptId!=scope.Manuscript||original.Paragraphs.Any(p=>p.Occurrence.NativeId!=""))throw new Exception("Unexpected fixture; do not overwrite");
var before=JsonSerializer.Serialize(original);var session=Guid.NewGuid();var proofs=new List<ChapterObservation>();
foreach(var part in ChapterCheckpointEngine.Parts(original)){
var evidence=part.Rows.Select(p=>new ChapterParagraph{NativeId=(p.Occurrence.Ordinal+1).ToString("X8"),Length=p.Occurrence.Text.Length,Outline=p.Occurrence.Outline}).ToArray();
var proof=new ChapterObservation{InstanceId=scope.Instance,SessionId=session,ManuscriptId=scope.Manuscript,WordRevision=0,BaseRevision=original.Revision,ChapterId=part.Chapter.CanonicalId,Start=1000+part.Rows[0].Occurrence.Start,End=1000+part.Rows[^1].Occurrence.End,ContentHash=ChapterFingerprint.Content(part.Rows.Select(p=>p.Occurrence.Text)),IdentityHash=ChapterFingerprint.Identity(evidence),Paragraphs=evidence,Reconcile=true,NextHeadingId=part.End<original.Paragraphs.Count?(part.End+1).ToString("X8"):""};
var source=await repository.Get(scope.User,scope.Book)??throw new Exception();var result=ChapterCheckpointEngine.Validate(source,proof,DateTime.UtcNow);await chapters.Accept(scope.User,scope.Book,proof,result);await chapters.Accept(scope.User,scope.Book,proof,result);proofs.Add(proof);
var scenePosition=result.Positions.First(p=>p.SceneId.HasValue);var cursor=await chapters.Position(scope.User,scope.Book,scope.Manuscript,session,0,scenePosition.Start);Check(cursor?.ChapterID==part.Chapter.CanonicalId&&cursor.SceneID==scenePosition.SceneId,"Committed chapter position resolves its own canonical scene");
Check((await chapters.Position(scope.User,scope.Book,scope.Manuscript,Guid.NewGuid(),0,scenePosition.Start))?.SceneID==null,"Another Word session cannot reuse live absolute positions");
var saved=await repository.Get(scope.User,scope.Book)??throw new Exception();var payload=JsonSerializer.Serialize(saved);
var stale=new ChapterObservation{RequestId=Guid.NewGuid(),SessionId=session,ManuscriptId=scope.Manuscript,WordRevision=0,BaseRevision=source.Revision-1,ChapterId=proof.ChapterId};bool denied=false;try{await chapters.Accept(scope.User,scope.Book,stale,result);}catch(SqlException){denied=true;}Check(denied&&JsonSerializer.Serialize(await repository.Get(scope.User,scope.Book))==payload,"Stale CAS refuses without partially changing checkpoint or canonical snapshot");
}
var accepted=await repository.Get(scope.User,scope.Book)??throw new Exception();Check(accepted.Revision==original.Revision&&accepted.Paragraphs.Select(p=>(p.Occurrence.Id,p.Occurrence.Text,p.SceneId,p.ChapterId)).SequenceEqual(original.Paragraphs.Select(p=>(p.Occurrence.Id,p.Occurrence.Text,p.SceneId,p.ChapterId)))&&accepted.Scenes.Select(s=>s.Id).SequenceEqual(original.Scenes.Select(s=>s.Id)),"Legacy adoption preserves every paragraph GUID, exact prose, scene GUID/assignment and coherent snapshot revision");
Check(accepted.SnapshotHash==ParagraphManuscriptEngine.Hash(accepted.Paragraphs.Select(p=>p.Occurrence).ToArray()),"Legacy native-ID adoption keeps the existing full-snapshot digest coherent");
Check(accepted.ChapterCheckpoints.Count==2&&(await chapters.List(scope.User,scope.Book,session,0)).Count==2,"Independent accepted chapters survive interrupted processing and same-request retry");
var unauthorised=false;try{await chapters.List(0,scope.Book,session,0);}catch(SqlException){unauthorised=true;}Check(unauthorised,"Unauthorised account cannot access chapter checkpoint evidence");
await File.WriteAllTextAsync(args[2]+".evidence.json",JsonSerializer.Serialize(new{scope.Book,scope.Manuscript,Revision=accepted.Revision,Proofs=proofs,Paragraphs=accepted.Paragraphs}));File.SetUnixFileMode(args[2]+".evidence.json",UnixFileMode.UserRead|UnixFileMode.UserWrite);
// Metadata adoption is the only mutation in this fixture. Author data never participates.
}
private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);}
}