PlotDirector/PlotLine.Tests/ChapterSynchronisationTests.cs

88 lines
16 KiB
C#

using System.Diagnostics;
using System.Text.Json;
using PlotDirector.Companion.Protocol.Manuscript;
using PlotLine.Models;
using PlotLine.Services.Manuscript;
internal static class ChapterSynchronisationTests
{
public static void Run()
{
ChapterStructuralContentTests.Run();
void Check(bool condition,string message){if(!condition)throw new Exception(message);Console.WriteLine("PASS "+message);}
void Refused(Action work,string message){try{work();throw new Exception("Unsafe chapter evidence accepted: "+message);}catch(Exception e)when(e is ArgumentException or InvalidOperationException){Console.WriteLine("PASS "+message);}}
Check(ChapterFingerprint.Content(["a\r","b\r"])!=ChapterFingerprint.Content(["a\rb\r"]),"Fingerprint preserves paragraph splitting/merging");
Check(ChapterFingerprint.Content(["a\r","b\r"])!=ChapterFingerprint.Content(["b\r","a\r"]),"Fingerprint preserves paragraph order");
Check(ChapterFingerprint.Content(["é\r"])!=ChapterFingerprint.Content(["e\u0301\r"]),"Fingerprint preserves Unicode composition differences");
Check(ChapterFingerprint.Content(["a\r"])!=ChapterFingerprint.Content(["a\r\n"]),"Fingerprint preserves line endings and Word control characters");
Check(ChapterFingerprint.Content(["\ud800\r"])!=ChapterFingerprint.Content(["\ufffd\r"]),"Fingerprint preserves isolated UTF-16 code units without replacement collisions");
var rows=new List<ParagraphOccurrence>();var start=0;
foreach(var text in new[]{"Chapter one\r","First passage.\r","More first prose.\r","Chapter two\r","Second passage.\r","More second prose.\r"}){rows.Add(new(){Id=Guid.NewGuid(),NativeId=(rows.Count+1).ToString("X8"),Ordinal=rows.Count,Start=start,End=start+text.Length,Outline=rows.Count%3==0?1:10,Text=text});start+=text.Length;}
var state=ParagraphManuscriptEngine.Bootstrap(12,7,Guid.NewGuid(),rows.ToArray(),[new(){ChapterId=10,SceneId=22,Start=2,End=3,Title="First"},new(){ChapterId=11,SceneId=23,Start=5,End=6,Title="Second"}]);state.Revision=3;state.SessionId=Guid.NewGuid();state.WordRevision=1;
state.Chapters=[new(){CanonicalId=10,HeadingId=state.Paragraphs[0].Occurrence.Id,Title="Chapter one"},new(){CanonicalId=11,HeadingId=state.Paragraphs[3].Occurrence.Id,Title="Chapter two"}];
foreach(var p in state.Paragraphs.Where(p=>p.Occurrence.Outline==1)){p.ChapterId=p.Occurrence.Ordinal==0?10:11;p.PositionVerified=true;}
ChapterObservation Proof(int id=10){var part=ChapterCheckpointEngine.Parts(state).Single(p=>p.Chapter.CanonicalId==id);var evidence=part.Rows.Select(p=>new ChapterParagraph{NativeId=p.Occurrence.NativeId,Text=p.Occurrence.Text,Length=p.Occurrence.Text.Length,Outline=p.Occurrence.Outline}).ToArray();return new(){ChapterId=id,RequestId=Guid.NewGuid(),InstanceId=Guid.NewGuid(),SessionId=Guid.NewGuid(),ManuscriptId=state.ManuscriptId,WordRevision=0,BaseRevision=state.Revision,Start=500,End=500+evidence.Sum(p=>p.Length),ContentHash=ChapterFingerprint.Content(evidence.Select(p=>p.Text!)),IdentityHash=ChapterFingerprint.Identity(evidence),Paragraphs=evidence,NextHeadingId=id==10?state.Paragraphs[3].Occurrence.NativeId:""};}
var before=JsonSerializer.Serialize(state);var proof=Proof();var accepted=ChapterCheckpointEngine.Validate(state,proof,DateTime.UtcNow);
Check(accepted.Positions.First().Start==500&&accepted.Positions.Where(p=>p.SceneId.HasValue).All(p=>p.SceneId==22),"Unchanged reopened chapter accepts new physical positions without changing scene identity");
Check(JsonSerializer.Serialize(state)==before,"Validation proposals do not mutate accepted paragraphs, scenes, evidence or session identity");
var stale=Proof();stale.BaseRevision--;Refused(()=>ChapterCheckpointEngine.Validate(state,stale,DateTime.UtcNow),"Stale accepted-snapshot lineage is refused");
var duplicate=Proof();duplicate.Paragraphs[1].NativeId=duplicate.Paragraphs[0].NativeId;Refused(()=>ChapterCheckpointEngine.Validate(state,duplicate,DateTime.UtcNow),"Duplicate native paragraph identities cannot produce a green checkpoint");
var changed=Proof();changed.Reconcile=true;changed.Paragraphs[1].Text="Edited first passage.\r";changed.Paragraphs[1].Length=changed.Paragraphs[1].Text!.Length;changed.ContentHash=ChapterFingerprint.Content(changed.Paragraphs.Select(p=>p.Text!));changed.IdentityHash=ChapterFingerprint.Identity(changed.Paragraphs);changed.End=changed.Start+changed.Paragraphs.Sum(p=>p.Length);
Refused(()=>ChapterCheckpointEngine.Validate(state,changed,DateTime.UtcNow),"Changed hash is not accepted as synchronised");
var merged=ChapterCheckpointEngine.MergeChapter(state,changed);Check(merged.Skip(3).Select(p=>p.Id).SequenceEqual(state.Paragraphs.Skip(3).Select(p=>p.Occurrence.Id)),"Selective chapter merge preserves unrelated paragraph GUIDs");
Check(merged[3].Start-state.Paragraphs[3].Occurrence.Start==changed.Paragraphs[1].Length-state.Paragraphs[1].Occurrence.Text.Length,"Logical positions in later chapters account for changed text length");
var copy=JsonSerializer.Deserialize<ParagraphManuscript>(before)!;ParagraphManuscriptEngine.Reconcile(copy,merged);Check(copy.Scenes.Select(p=>p.Id).SequenceEqual(state.Scenes.Select(p=>p.Id))&&copy.Paragraphs.Where(p=>p.ChapterId==11).All(p=>p.SceneId==null||p.SceneId==state.Scenes.Single(s=>s.ChapterId==11).Id),"Existing reconciliation preserves canonical scene GUIDs and hard chapter membership");
var crossing=Proof();crossing.Reconcile=true;crossing.NextHeadingId="000000FF";Refused(()=>ChapterCheckpointEngine.MergeChapter(state,crossing),"Changed or moved chapter boundary requires review instead of cross-chapter reassignment");
var movedLast=Proof(11);movedLast.NextHeadingId="00000001";Check(ChapterCheckpointEngine.Validate(state,movedLast,DateTime.UtcNow).Checkpoint.Status=="Needs review","A formerly last chapter moved before another heading cannot report unchanged global structure");
var legacy=JsonSerializer.Deserialize<ParagraphManuscript>(before)!;foreach(var p in legacy.Paragraphs)p.Occurrence.NativeId="";var adoption=Proof();adoption.Reconcile=true;
var adopted=ChapterCheckpointEngine.Validate(legacy,adoption,DateTime.UtcNow);Check(adopted.Bindings.Length==3&&legacy.Paragraphs.All(p=>p.Occurrence.NativeId==""),"Explicit legacy repair proposes native bindings while preserving every original PlotDirector GUID");
adoption.Reconcile=false;Refused(()=>ChapterCheckpointEngine.Validate(legacy,adoption,DateTime.UtcNow),"Passive hash checks cannot silently adopt missing legacy identities");
var renamed=Proof();renamed.Reconcile=true;renamed.Paragraphs[0].Text="A renamed chapter\r";renamed.Paragraphs[0].Length=renamed.Paragraphs[0].Text!.Length;renamed.ContentHash=ChapterFingerprint.Content(renamed.Paragraphs.Select(p=>p.Text!));renamed.IdentityHash=ChapterFingerprint.Identity(renamed.Paragraphs);renamed.End=renamed.Start+renamed.Paragraphs.Sum(p=>p.Length);
var renamedState=JsonSerializer.Deserialize<ParagraphManuscript>(before)!;ParagraphManuscriptEngine.Reconcile(renamedState,ChapterCheckpointEngine.MergeChapter(state,renamed));Check(renamedState.Chapters[0].CanonicalId==10&&renamedState.Chapters[0].HeadingId==state.Chapters[0].HeadingId,"Renamed heading preserves canonical chapter and paragraph identities");
foreach(var kind in new[]{"insert","delete","split","merge"}){
var mutation=Proof();mutation.Reconcile=true;var altered=mutation.Paragraphs.ToList();
if(kind=="insert")altered.Insert(2,new(){NativeId="000000FF",Text="Inserted paragraph.\r",Length=20});
if(kind=="delete")altered.RemoveAt(2);
if(kind=="split"){altered[1].Text="First\r";altered[1].Length=6;altered.Insert(2,new(){NativeId="000000FF",Text=" passage.\r",Length=10});}
if(kind=="merge"){altered[1].Text+=altered[2].Text;altered[1].Length=altered[1].Text!.Length;altered.RemoveAt(2);}
foreach(var row in altered)row.Length=row.Text!.Length;
mutation.Paragraphs=altered.ToArray();mutation.ContentHash=ChapterFingerprint.Content(altered.Select(p=>p.Text!));mutation.IdentityHash=ChapterFingerprint.Identity(altered);mutation.End=mutation.Start+altered.Sum(p=>p.Length);
var candidate=JsonSerializer.Deserialize<ParagraphManuscript>(before)!;ParagraphManuscriptEngine.Reconcile(candidate,ChapterCheckpointEngine.MergeChapter(state,mutation));
Check(candidate.Paragraphs.Where(p=>p.ChapterId==11).Select(p=>p.Occurrence.Id).SequenceEqual(state.Paragraphs.Where(p=>p.ChapterId==11).Select(p=>p.Occurrence.Id))&&candidate.Scenes.Select(s=>s.Id).SequenceEqual(state.Scenes.Select(s=>s.Id)),"Chapter "+kind+" preserves unrelated paragraph and scene identities");
}
var insertedHeading=Proof();insertedHeading.Reconcile=true;insertedHeading.Paragraphs[1].Outline=1;insertedHeading.IdentityHash=ChapterFingerprint.Identity(insertedHeading.Paragraphs);Refused(()=>ChapterCheckpointEngine.MergeChapter(state,insertedHeading),"Inserted chapter headings require review instead of silently splitting canonical chapters");
state.ChapterCheckpoints=ChapterCheckpointEngine.Build(state,state.Revision).ToList();state.ChapterCheckpoints[0]=accepted.Checkpoint;
var graph=new ProjectBackupExport{FormatVersion="1.5",Project=new(){ProjectID=7},Data=new(){Books=[new(){BookID=12,ProjectID=7}],Chapters=[new(){ChapterID=10,BookID=12},new(){ChapterID=11,BookID=12}],Scenes=[new(){SceneID=22,ChapterID=10},new(){SceneID=23,ChapterID=11}]},Recovery=new(){ParagraphManuscripts=[state]}};
ParagraphRecovery.Validate(graph);var portable=PlotLine.Services.BookBackupGraph.Clone(graph);portable.Project!.ProjectID=107;ParagraphRecovery.Remap(portable,(kind,id)=>id+100);var restored=portable.Recovery.ParagraphManuscripts!.Single();
Check(restored.ChapterCheckpoints[0].ChapterId==110&&restored.ChapterCheckpoints[0].HeadingId==state.Chapters[0].HeadingId&&restored.ChapterCheckpoints[0].ContentHash==state.ChapterCheckpoints[0].ContentHash&&restored.ChapterCheckpoints[0].Status=="Not yet checked"&&restored.SessionId==Guid.Empty,"Backup remaps canonical checkpoint IDs, preserves content/GUID evidence and detaches live trust");
var xml="<w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:w14='http://schemas.microsoft.com/office/word/2010/wordml'><w:body><w:p w14:paraId='00000001'><w:pPr><w:outlineLvl w:val='0'/></w:pPr><w:r><w:t>Chapter one</w:t></w:r></w:p><w:p w14:paraId='00000002'><w:r><w:t>Exact</w:t><w:tab/><w:t>text</w:t></w:r></w:p></w:body></w:document>";
Check(ChapterFingerprint.ReadXml(xml,"Chapter one\rExact\ttext\r").Length==2,"Portable chapter XML identity enumeration matches exact Word range text");
Check(ChapterFingerprint.ReadXml(xml.Replace("<w:body>","<w:body><w:sdt><w:sdtContent>").Replace("</w:body>","</w:sdtContent></w:sdt></w:body>"),"Chapter one\rExact\ttext\r").Length==2,"Existing block content-control markers preserve exact paragraph order without Word edits");
const string exactText = "Chapter one\rExact\ttext\r";
var originalRows = ChapterFingerprint.ReadXml(xml, exactText);
var withoutIds = System.Text.RegularExpressions.Regex.Replace(xml, " w14:paraId=\"[0-9A-Fa-f]{8}\"", "");
var liveIds = string.Concat(originalRows.Select(row => row.NativeId + row.Length.ToString("X8")));
var liveRows = ChapterFingerprint.ReadXml(withoutIds, exactText, liveIds);
Check(ChapterFingerprint.Identity(liveRows) == ChapterFingerprint.Identity(originalRows), "Live Word IDs and spans restore the exact identity digest when range XML omits IDs");
Refused(() => ChapterFingerprint.ReadXml(withoutIds, exactText, liveIds.Substring(0, 16)), "Incomplete live identity frames are refused");
Refused(() => ChapterFingerprint.ReadXml(withoutIds, exactText, liveIds.Substring(0, 8) + "00000001" + liveIds.Substring(16)), "Mismatched live paragraph span is refused");
Refused(() => ChapterFingerprint.ReadXml(withoutIds, exactText, liveIds.Substring(0, 16) + liveIds.Substring(0, 8) + liveIds.Substring(24)), "Duplicate live Word IDs are refused");
Refused(() => ChapterFingerprint.ReadXml(xml, exactText, "7FFFFFFF" + liveIds.Substring(8)), "Live Word IDs cannot overwrite contradictory XML IDs");
var pageBreakXml = xml.Replace("<w:t>Exact</w:t>", "<w:t>Exact</w:t><w:br w:type='page'/>");
Check(ChapterFingerprint.ReadXml(pageBreakXml, "Chapter one\rExact\f\ttext\r").Length == 2, "Explicit page break uses the exact live Word form-feed position");
Refused(() => ChapterFingerprint.ReadXml(pageBreakXml, exactText), "Page break cannot be ignored when the live Word text disagrees");
Refused(()=>ChapterFingerprint.ReadXml(xml,"Different\r"),"XML/range disagreement is refused rather than inventing paragraph offsets");
Refused(()=>ChapterFingerprint.ReadXml(xml.Replace("<w:body>","<w:body><w:tbl/>"),"Chapter one\rExact\ttext\r"),"Complex Word tables require safe bounded fallback");
var pictureXml=xml.Replace("<w:t>Exact</w:t>","<w:t>Exact</w:t><w:drawing/>");
var pictureText="Chapter one\rExact\u0001\ttext\r";
var pictureIds=originalRows[0].NativeId+originalRows[0].Length.ToString("X8")+originalRows[1].NativeId+(pictureText.Length-originalRows[0].Length).ToString("X8");
Check(ChapterFingerprint.ReadXml(pictureXml,pictureText,pictureIds,true)[1].Text=="Exact\u0001\ttext\r","Picture evidence uses measured native paragraph text without projecting object characters");
Check(ChapterFingerprint.ReadXml(pictureXml,exactText,liveIds,true)[1].Text==originalRows[1].Text,"Anchored picture evidence preserves the exact native text when no object character is present");
Refused(()=>ChapterFingerprint.ReadXml(pictureXml,pictureText,pictureIds),"Older native-ID-only evidence cannot certify picture paragraph text");
Refused(()=>ChapterFingerprint.ReadXml(pictureXml,pictureText,pictureIds.Substring(0,24)+"00000001",true),"Picture native spans must cover the whole chapter");
Refused(()=>ChapterFingerprint.ReadXml(pictureXml.Replace("<w:drawing/>","<w:drawing/><w:fldChar/>"),pictureText,pictureIds,true),"Native picture fallback does not relax unsafe field handling");
var presence=new PlotLine.Services.NativeCompanion.NativePresenceStore(TimeProvider.System);var instance=Guid.NewGuid();var session=Guid.NewGuid();presence.Put(7,"grant",DateTimeOffset.UtcNow.AddHours(1),instance,session,new(){BookId=12,ManuscriptId=state.ManuscriptId,CanChapterSync=true,CanCapture=true,CanParagraphSync=true,WordAvailable=true,WordSaved=true,Sequence=1,Revision=1});var lease=presence.Read(7,12).Single();presence.RecordChapterProgress(7,12,instance,session,1,new(){State="Synchronised",Total=2,Matching=2});var operation=Guid.NewGuid();Check(presence.RequestChapterRepair(7,lease,operation)&&presence.ChapterTransfer(7,12,instance,session)?.State=="pending","A repeated repair cannot inherit a previous green completion before fresh acceptance");
Check(presence.CanRepairChapter(7,lease,operation)&&!presence.CanRepairChapter(7,lease with{Grant="different-installation"},operation),"Explicit repair authority is scoped to its approved installation grant and live revision");presence.CancelChapterRepairs(7,12);Check(!presence.CanRepairChapter(7,lease,operation)&&presence.ChapterTransfer(7,12,instance,session)?.State=="needs-review","Cancellation revokes transfer permission while retaining accepted checkpoints");
var watch=Stopwatch.StartNew();for(int i=0;i<48;i++)ChapterFingerprint.Content(Enumerable.Range(0,180).Select(n=>"Synthetic paragraph "+n+new string('x',100)+"\r"));watch.Stop();Console.WriteLine($"MEASURE portable exact SHA-256: 48 synthetic chapters / 8640 paragraphs in {watch.Elapsed.TotalMilliseconds:F1}ms. No Word COM or UI measurement.");
}
}