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() { 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();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(before)!;ParagraphManuscriptEngine.Reconcile(copy,merged);Check(copy.Scenes.Select(p=>p.Id).SequenceEqual(state.Scenes.Select(p=>p.Id))&©.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(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(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(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="Chapter oneExacttext"; 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("","").Replace("",""),"Chapter one\rExact\ttext\r").Length==2,"Existing block content-control markers preserve exact paragraph order without Word edits"); Refused(()=>ChapterFingerprint.ReadXml(xml,"Different\r"),"XML/range disagreement is refused rather than inventing paragraph offsets"); Refused(()=>ChapterFingerprint.ReadXml(xml.Replace("",""),"Chapter one\rExact\ttext\r"),"Complex Word tables require safe bounded fallback"); 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."); } }