using System.Diagnostics; using System.Text.Json; using PlotDirector.Companion.Protocol.Manuscript; using PlotLine.Models; using PlotLine.Services; using PlotLine.Services.Manuscript; internal static class ParagraphManuscriptTests { private static int count; private static void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);count++;} private static ParagraphOccurrence[] Rows(params string[] texts){int start=0;return texts.Select((text,i)=>{var p=new ParagraphOccurrence{Text=text,Ordinal=i,NativeId=(i+1).ToString("X8"),Start=start,End=start+text.Length,Outline=10};start=p.End;return p;}).ToArray();} private static ParagraphManuscript Initial()=>ParagraphManuscriptEngine.Bootstrap(4,2,Guid.NewGuid(),Rows("Arrival.\r","The keeper handed Mira the sealed letter.\r","No.\r","The train departed.\r","No.\r","Dusk.\r"),[new(){SceneId=41,ChapterId=11,Title="Arrival",Start=1,End=3},new(){SceneId=42,ChapterId=11,Title="Departure",Start=4,End=6}]); public static void Run() { var capture=new PlotDirector.Companion.Protocol.ManuscriptCapture{ParagraphTracking=true,End=8,Paragraphs=[new(){Start=0,End=8,Text="Heading\r",ParagraphIndex=1,OutlineLevel=1,CompletesParagraph=true,NativeParagraphId="00000011"}]}; var preview=PlotLine.Services.NativeCompanion.NativeManuscriptCapture.Build(capture,7,4,2,3,"Synthetic document"); Check(preview.ParagraphTracking&&preview.NativeParagraphs?.Single().Id!=Guid.Empty&&preview.NativeParagraphs?.Single().Text=="Heading\r","Opted-in import capture retains raw paragraph text and opaque occurrence identity"); var state=Initial();var ids=state.Paragraphs.Select(p=>p.Occurrence.Id).ToArray(); Check(ids.Distinct().Count()==6&&ids.All(id=>id!=Guid.Empty),"Opaque occurrence IDs, including separate identical dialogue"); var saved=ParagraphManuscriptEngine.Clone(state);ParagraphManuscriptEngine.Reconcile(saved,state.Paragraphs.Select(p=>p.Occurrence).ToArray()); Check(saved.Paragraphs.Select(p=>p.Occurrence.Id).SequenceEqual(ids),"Saved snapshot and process reconstruction retain occurrence identities"); var evidence=ParagraphManuscriptEngine.Anchor(state,"Knowledge",91,true,1,1,null,null);var original=evidence.OriginalText; var current=state.Paragraphs.Select(p=>p.Occurrence).ToList();var moved=current[1];current.RemoveAt(1);current.Insert(4,moved);ParagraphManuscriptEngine.Reconcile(state,current); Check(evidence.State=="Verified"&&evidence.DerivedSceneId==42&&state.Evidence.Count==1,"Reliable paragraph move updates derived event scene without copying event"); var copy=new ParagraphOccurrence{Text=moved.Text,NativeId=moved.NativeId,Outline=10};current=state.Paragraphs.Select(p=>p.Occurrence).ToList();current.Add(copy);ParagraphManuscriptEngine.Reconcile(state,current); Check(state.Paragraphs.Last().Occurrence.Id!=moved.Id&&state.Evidence.Count==1,"Copied paragraph has a distinct identity and no duplicated story event"); state=Initial();evidence=ParagraphManuscriptEngine.Anchor(state,"Relationship",92,true,1,1,null,null);current=state.Paragraphs.Select(p=>p.Occurrence).ToList();current[1]=new(){Text="Mira refused the letter.\r",NativeId=current[1].NativeId,Outline=10};ParagraphManuscriptEngine.Reconcile(state,current); Check(evidence.State=="Needs review"&&evidence.OriginalText==original&&evidence.CurrentText.Contains("refused")&&evidence.DerivedSceneId==null,"Rewritten evidence retains original passage and withholds unconfirmed derived facts"); ParagraphManuscriptEngine.Confirm(state,evidence.Id);Check(evidence.State=="Verified","Author confirmation verifies changed evidence"); current=state.Paragraphs.Select(p=>p.Occurrence).ToList();current.RemoveAt(1);ParagraphManuscriptEngine.Reconcile(state,current); Check(evidence.State=="Missing"&&state.Evidence.Single().EventId==92&&evidence.OriginalText==original,"Deleting evidence preserves the event and before text"); state=Initial();var raw=string.Concat(state.Paragraphs.Select(p=>p.Occurrence.Text));var first=state.Scenes[0].Id;var second=state.Scenes[1].Id; ParagraphManuscriptEngine.Split(state,state.Paragraphs[1].Occurrence.Id,"The letter"); Check(state.Scenes.Count(s=>!s.Retired)==3&&string.Concat(state.Paragraphs.Select(p=>p.Occurrence.Text))==raw,"Scene split preserves every raw Word character"); ParagraphManuscriptEngine.Undo(state);Check(state.Paragraphs[1].SceneId==first&&state.Scenes.Count(s=>!s.Retired)==2,"Undo restores grouping and opaque scene identity"); ParagraphManuscriptEngine.MoveBoundary(state,second,state.Paragraphs[2].Occurrence.Id); Check(state.Paragraphs[2].SceneId==second,"Boundary moves between adjacent paragraphs"); ParagraphManuscriptEngine.Merge(state,first,second);Check(state.Paragraphs.All(p=>p.SceneId==first)&&state.Scenes.Single(s=>s.Id==second).Retired&&string.Concat(state.Paragraphs.Select(p=>p.Occurrence.Text))==raw,"Adjacent merge retains text and retires, rather than destroys, scene identity"); ParagraphManuscriptEngine.Undo(state);Check(state.Paragraphs[2].SceneId==second&&!state.Scenes.Single(s=>s.Id==second).Retired,"Merge undo restores original scene and prior boundary"); var unresolved=Initial();foreach(var row in unresolved.Paragraphs.Take(3))row.PositionVerified=false;unresolved.Scenes[0].NeedsRefinement=true; ParagraphManuscriptEngine.ConfirmGrouping(unresolved,unresolved.Scenes[0].Id); Check(unresolved.Paragraphs.Take(3).All(p=>p.PositionVerified)&&!unresolved.Scenes[0].NeedsRefinement,"Author can explicitly confirm a proposed scene grouping without editing Word prose"); ParagraphManuscriptEngine.Undo(unresolved);Check(unresolved.Paragraphs.Take(3).All(p=>!p.PositionVerified),"Grouping confirmation can be undone without discarding the Word snapshot"); var excluded=Initial();excluded.Chapters.Add(new(){CanonicalId=0,HeadingId=excluded.Paragraphs[3].Occurrence.Id,Title="Explicitly excluded section"});foreach(var row in excluded.Paragraphs.Skip(3)){row.Story=false;row.SceneId=null;row.PositionVerified=false;} ParagraphManuscriptEngine.Reconcile(excluded,excluded.Paragraphs.Select(p=>p.Occurrence).ToArray()); Check(excluded.Paragraphs.Count(p=>p.Story)==3&&excluded.Paragraphs.Count==6,"Previously excluded import sections remain captured without silently importing their prose on sync"); bool uncertain=false;try{ParagraphManuscriptEngine.Reconcile(excluded,excluded.Paragraphs.Where((p,i)=>i!=3).Select(p=>p.Occurrence).ToArray());}catch(InvalidOperationException){uncertain=true;} Check(uncertain&&excluded.Paragraphs.Count==6,"An unresolvable excluded-section boundary refuses mutation instead of guessing where that book's prose starts"); var before=ParagraphReconciliation.Compare([],Rows("Before.\r","Same.\r","Same.\r","After.\r")).Current; var changes=Rows("Before.\r","Same.\r","New.\r","Same.\r","After.\r");changes[3].NativeId=before[2].NativeId;changes[4].NativeId=before[3].NativeId;changes[2].NativeId="00000030"; var reconciled=ParagraphReconciliation.Compare(before,changes).Current; Check(reconciled[1].Id==before[1].Id&&reconciled[3].Id==before[2].Id,"Identical short dialogue remains associated with its individual native occurrence"); var delta=ParagraphDeltaCodec.Create(3,before,reconciled);var end=reconciled.Sum(p=>p.End-p.Start);var restored=ParagraphDeltaCodec.Expand(delta,before,end); Check(restored.Select(p=>p.Id).SequenceEqual(reconciled.Select(p=>p.Id))&&restored.Select(p=>p.Text).SequenceEqual(reconciled.Select(p=>p.Text))&&delta.Changes.Count(p=>p.Text!=null)==1,"Delta sends only changed prose and retains occurrence order"); var priorRewrite=Rows("Opening.\r","She entered.\r","Original revelation.\r","He waited.\r","Closing.\r");foreach(var row in priorRewrite)row.NativeId="";var priorIdentity=ParagraphReconciliation.Compare([],priorRewrite).Current; var revised=Rows("Opening.\r","She entered.\r","Rewritten revelation.\r","He waited.\r","Closing.\r");foreach(var row in revised)row.NativeId="";var rewrite=ParagraphReconciliation.Compare(priorIdentity,revised); Check(rewrite.Current[2].Id==priorIdentity[2].Id&&rewrite.Current[2].Change=="Modified"&&rewrite.Current[2].Resolution.Contains("review"),"Lost native hints can reconcile a single rewrite between recognised neighbours without matching a moved/copy candidate"); var split=Rows("Before.\r","Same part one.\r","part two.\r","Same.\r","After.\r");split[2].NativeId="00000031";split[3].NativeId=before[2].NativeId;split[4].NativeId=before[3].NativeId; var splitResult=ParagraphReconciliation.Compare(before,split);Check(splitResult.Current[1].Id==before[1].Id&&splitResult.Current[2].Id!=before[1].Id,"Paragraph split retains only the surviving occurrence identity"); var xml=""; Check(WordParagraphIdentity.Read(xml)=="00000022"&&WordParagraphIdentity.Read("]>&x;")=="","Word XML hint is restricted to main document part and forbids external entities"); using var schema=JsonDocument.Parse(JsonSerializer.Serialize(ChapterStructureIntegerContract.ForParagraphCount(97).Schema)); Check(schema.RootElement.GetProperty("properties").GetProperty("sceneBoundaries").GetProperty("items").GetProperty("properties").GetProperty("endParagraph").GetProperty("maximum").GetInt32()==97,"Provider schema is bounded by the actual 97 submitted paragraphs, never the raw source count 99"); var request=JsonSerializer.Serialize(new ManuscriptStructureAnalysisRequest());Check(!request.Contains("ConfidenceContractVersion"),"Legacy request serialization omits new contract field, preserving checkpoint hashes"); var validator=new ChapterStructureValidator();ChapterStructureModel Model(string schema,decimal confidence)=>new(){SchemaVersion=schema,ChapterSummary="Summary",SceneBoundaries=[new(){SceneNumber=1,StartParagraph=1,EndParagraph=1,Confidence=confidence,Reason="Single continuous scene",StructuralSummary="The manuscript contains one continuous narrative scene."}]}; Check(validator.Validate(Model("1.0",.9m),1).IsValid&&validator.Validate(Model("2.0",90),1).IsValid&&!validator.Validate(Model("2.0",.9m),1).IsValid&&!validator.Validate(Model("2.0",101),1).IsValid,"Versioned integer confidence validation preserves legacy decimals and rejects new fractional scores"); var large=Enumerable.Range(1,25000).Select(n=>new ParagraphOccurrence{Text=$"Paragraph {n}: one two three four five six seven eight nine.\r",NativeId=n.ToString("X8"),Start=n*65,End=n*65+65}).ToArray(); var timer=Stopwatch.StartNew();var initial=ParagraphReconciliation.Compare([],large).Current;var repeat=ParagraphReconciliation.Compare(initial,large);timer.Stop(); Check(repeat.Current.Select(p=>p.Id).SequenceEqual(initial.Select(p=>p.Id))&&timer.Elapsed{{41,0}},41); Check(facts.Count==1&&facts[0].CharacterID==3,"Missing primary evidence is excluded from verified story facts while unanchored scene events remain compatible"); Console.WriteLine($"{count} paragraph manuscript assertions passed."); } }