using System.Runtime.Serialization; using System.Security.Cryptography; using System.Text; using System.Xml; using System.Xml.Linq; namespace PlotDirector.Companion.Protocol.Manuscript; [DataContract] public sealed class ChapterParagraph { [DataMember] public string NativeId {get;set;}=""; [DataMember] public int Length {get;set;} [DataMember(EmitDefaultValue=false)] public int WordLength {get;set;} [DataMember] public ChapterPictureAnchor[] Anchors {get;set;}=Array.Empty(); [DataMember] public int Outline {get;set;}=10; [DataMember] public string? Text {get;set;} } [DataContract] public sealed class ChapterObservation { [DataMember] public Guid OperationId {get;set;} [DataMember] public Guid RequestId {get;set;}=Guid.NewGuid(); [DataMember] public Guid ManuscriptId {get;set;} [DataMember] public Guid InstanceId {get;set;} [DataMember] public Guid SessionId {get;set;} [DataMember] public long WordRevision {get;set;} [DataMember] public long BaseRevision {get;set;} [DataMember] public int ChapterId {get;set;} [DataMember] public int Start {get;set;} [DataMember] public int End {get;set;} [DataMember] public string Algorithm {get;set;}=ChapterFingerprint.Version; [DataMember] public string ContentHash {get;set;}=""; [DataMember] public string IdentityHash {get;set;}=""; [DataMember] public string PositionHash {get;set;}=""; [DataMember] public string NextHeadingId {get;set;}=""; [DataMember] public bool Reconcile {get;set;} [DataMember] public ChapterParagraph[] Paragraphs {get;set;}=Array.Empty(); } public static class ChapterFingerprint { public const string Version="sha256-utf16le-paragraphs-v1"; public const int MaxCharacters=256*1024,MaxParagraphs=10000; private static string Digest(Action write) { using var bytes=new MemoryStream();using(var writer=new BinaryWriter(bytes,Encoding.UTF8,true))write(writer); using var sha=SHA256.Create();return BitConverter.ToString(sha.ComputeHash(bytes.ToArray())).Replace("-",""); } // Encoding code units explicitly preserves even isolated UTF-16 surrogates without replacement or normalisation. private static void Text(BinaryWriter writer,string text){writer.Write(text.Length);foreach(var c in text)writer.Write((ushort)c);} public static string Content(IEnumerable paragraphs) { var rows=paragraphs.ToArray();if(rows.Length>MaxParagraphs||rows.Sum(p=>(long)p.Length)>MaxCharacters)throw new ArgumentException("Chapter exceeds bounded validation size."); return Digest(w=>{Text(w,Version);w.Write(rows.Length);foreach(var row in rows)Text(w,row);}); } public static string Identity(IEnumerable paragraphs) { var rows=paragraphs.ToArray();if(rows.Length==0||rows.Length>MaxParagraphs||rows.Any(p=>p.Length<=0||WordParagraphIdentity.Normalise(p.NativeId)!=p.NativeId||p.Outline<1||p.Outline>10)||rows.Select(p=>p.NativeId).Distinct().Count()!=rows.Length)throw new ArgumentException("Complete unique native paragraph identities are required."); return Digest(w=>{Text(w,Version+"/identity");w.Write(rows.Length);foreach(var row in rows){Text(w,row.NativeId);w.Write(row.Length);w.Write(row.Outline);}}); } public static string Mapping(IEnumerable assignments)=>Content(assignments); // Exact native paragraph text/geometry, measured on the owning Word thread. // This uses the existing v1 hashes and server validation; it is not a saved-file cache. public static ChapterParagraph[] ReadLiveText(string text,string frames) { if(text.Length>MaxCharacters||frames.Length==0||frames.Length%24!=0||frames.Length/24>MaxParagraphs) throw new ArgumentException("Incomplete or oversized live chapter evidence."); var rows=new List();var offset=0; for(var i=0;i int.TryParse(frames.Substring(at,8),System.Globalization.NumberStyles.HexNumber,System.Globalization.CultureInfo.InvariantCulture,out var n)?n:-1; var length=Number(i+8);var outline=Number(i+16); if(length<=0||length>text.Length-offset)throw new ArgumentException("Live paragraph spans do not cover chapter text."); rows.Add(new ChapterParagraph{NativeId=frames.Substring(i,8),Length=length,Outline=outline,Text=text.Substring(offset,length)}); offset+=length; } if(offset!=text.Length)throw new ArgumentException("Live paragraph spans leave incomplete chapter text."); Identity(rows);return rows.ToArray(); } // Parses only the main Word part. Complex constructs require the established bounded reader rather than guessed offsets. public static ChapterParagraph[] ReadXml(string xml,string rangeText,string? liveIdentities=null,bool nativeParagraphTextVerified=false,ChapterParagraph[]? nativePositions=null) { if(nativePositions!=null) { if(liveIdentities!=null)throw new ArgumentException("Mixed native position/identity encodings are not supported."); ChapterWordPositions.ValidateRows(nativePositions); liveIdentities=string.Concat(nativePositions.Select(p=>p.NativeId+p.Length.ToString("X8",System.Globalization.CultureInfo.InvariantCulture))); nativeParagraphTextVerified=true; } if(xml.Length>8*1024*1024||rangeText.Length>MaxCharacters)throw new ArgumentException("Chapter XML exceeds the bounded reader."); using var reader=XmlReader.Create(new StringReader(xml),new XmlReaderSettings{DtdProcessing=DtdProcessing.Prohibit,XmlResolver=null,MaxCharactersInDocument=8*1024*1024}); var root=XDocument.Load(reader);XNamespace w="http://schemas.openxmlformats.org/wordprocessingml/2006/main",pkg="http://schemas.microsoft.com/office/2006/xmlPackage",w14="http://schemas.microsoft.com/office/word/2010/wordml"; var document=root.Root?.Name==w+"document"?root.Root:root.Descendants(pkg+"part").Where(p=>(string?)p.Attribute(pkg+"name")=="/word/document.xml").SelectMany(p=>p.Descendants(w+"document")).SingleOrDefault(); var body=document?.Element(w+"body")??throw new ArgumentException("Main Word document part is missing."); var unsafeNames=new HashSet(new[]{"tbl","txbxContent","fldChar","instrText","footnoteReference","endnoteReference","object","ins","del","moveFrom","moveTo","altChunk","sym"}.Select(n=>w+n)); var unsupported=body.Descendants().FirstOrDefault(e=>unsafeNames.Contains(e.Name)); if(unsupported!=null)throw new ArgumentException("Unsupported Word structure: "+unsupported.Name.LocalName+". Review this chapter in Companion diagnostics; other accepted chapters are retained."); var hasDrawings=body.Descendants(w+"drawing").Any()||body.Descendants(w+"pPr").Elements(w+"sectPr").Any(); if(hasDrawings&&(!nativeParagraphTextVerified||liveIdentities==null))throw new ArgumentException("Pictures/section breaks require exact native paragraph text and span verification; XML projection was not guessed."); var styles=root.Descendants(w+"style").Where(e=>e.Attribute(w+"styleId")!=null).GroupBy(e=>(string)e.Attribute(w+"styleId")!).ToDictionary(g=>g.Key,g=>g.First()); int Outline(XElement paragraph){ var properties=paragraph.Element(w+"pPr");var seen=new HashSet(); for(int depth=0;depth<16;depth++){ if(int.TryParse((string?)properties?.Element(w+"outlineLvl")?.Attribute(w+"val"),out var n))return n+1; var style=(string?)properties?.Element(w+"pStyle")?.Attribute(w+"val"); if(style==null||!seen.Add(style)||!styles.TryGetValue(style,out var definition))return 10; properties=definition.Element(w+"pPr"); if(properties?.Element(w+"outlineLvl")==null&&definition.Element(w+"basedOn")?.Attribute(w+"val") is {} parent)properties=new XElement(w+"pPr",new XElement(w+"pStyle",new XAttribute(w+"val",parent.Value))); }throw new ArgumentException("Cyclic Word style inheritance."); } var rows=body.Descendants(w+"p").Where(p=>!p.Ancestors(w+"p").Any()).Select(p=>{ var text=new StringBuilder();foreach(var node in p.Descendants()){ if(node.Name==w+"t")text.Append(node.Value);else if(node.Name==w+"tab")text.Append('\t');else if(node.Name==w+"br"||node.Name==w+"cr"){var type=(string?)node.Attribute(w+"type"); if(type=="page")text.Append('\f'); else if(type==null||type=="textWrapping")text.Append('\v'); else throw new ArgumentException("Unsupported break requires measured Word extraction.");} }text.Append('\r'); var outline=Outline(p); return new ChapterParagraph{NativeId=WordParagraphIdentity.Normalise((string?)p.Attribute(w14+"paraId")),Text=text.ToString(),Length=text.Length,Outline=outline}; }).ToArray(); if(!hasDrawings&&string.Concat(rows.Select(p=>p.Text))!=rangeText)throw new ArgumentException("XML paragraph text does not equal Word Range.Text; no positions were accepted."); if (liveIdentities != null) { // Each live paragraph contributes an eight-digit ID and an eight-digit UTF-16 span. if (liveIdentities.Length != rows.Length * 16) throw new ArgumentException("Live Word paragraph count differs from chapter XML."); var offset=0; var paragraphs=body.Descendants(w+"p").Where(p=>!p.Ancestors(w+"p").Any()).ToArray(); for (var i = 0; i < rows.Length; i++) { var id = WordParagraphIdentity.Normalise(liveIdentities.Substring(i * 16, 8)); if(nativeParagraphTextVerified) { if(!int.TryParse(liveIdentities.Substring(i*16+8,8),System.Globalization.NumberStyles.HexNumber,System.Globalization.CultureInfo.InvariantCulture,out var measured)||measured<=0||measured>rangeText.Length-offset) throw new ArgumentException("Native paragraph text spans do not cover the exact chapter range."); var nativeText=rangeText.Substring(offset,measured); if(!paragraphs[i].Descendants(w+"drawing").Any()&¶graphs[i].Element(w+"pPr")?.Element(w+"sectPr")==null&&rows[i].Text!=nativeText) throw new ArgumentException("Native paragraph text differs from XML outside picture content."); rows[i].Text=nativeText;rows[i].Length=measured;offset+=measured; } var span = rows[i].Length.ToString("X8", System.Globalization.CultureInfo.InvariantCulture); if (id.Length == 0 || liveIdentities.Substring(i * 16 + 8, 8) != span || (rows[i].NativeId.Length != 0 && rows[i].NativeId != id)) throw new ArgumentException("Live Word paragraph identity or span differs from chapter XML."); rows[i].NativeId = id; } if(nativeParagraphTextVerified&&offset!=rangeText.Length)throw new ArgumentException("Native paragraph text spans leave an incomplete chapter range."); } if(nativePositions!=null) { for(var i=0;ip.Text!));return rows; } } public sealed class ChapterManifest { public bool CheckpointReuseSupported{get;set;}public bool NativePositionsSupported{get;set;}public int BookId{get;set;}public Guid ManuscriptId{get;set;}public long Revision{get;set;}public string Mode{get;set;}="Manual";public ChapterManifestItem[] Chapters{get;set;}=Array.Empty(); } public sealed class ChapterManifestItem { public bool DurableAccepted{get;set;}public int Order{get;set;}public long AcceptedRevision{get;set;} public string Algorithm{get;set;}="";public string MappingHash{get;set;}="";public string PositionHash{get;set;}="";public string NextHeadingId{get;set;}=""; public int ChapterId{get;set;}public string Title{get;set;}="";public string HeadingNativeId{get;set;}="";public string ContentHash{get;set;}="";public string IdentityHash{get;set;}="";public int Start{get;set;}public int End{get;set;}public int ParagraphCount{get;set;}public string State{get;set;}="Not yet checked"; } public sealed class ChapterSyncReply { public bool Accepted{get;set;}public string State{get;set;}="Not yet checked";public string Message{get;set;}="";public int ChapterId{get;set;}public long Revision{get;set;}public bool AllowText{get;set;} } [DataContract] public sealed class ChapterSyncProgress { [DataMember] public int Total {get;set;} [DataMember] public int Checked {get;set;} [DataMember] public int Matching {get;set;} [DataMember] public int Repaired {get;set;} [DataMember] public int NeedsReview {get;set;} [DataMember] public int? CurrentChapterId {get;set;} [DataMember] public string State {get;set;}="Not yet checked"; [DataMember] public string Message {get;set;}=""; } public sealed class ChapterFinish { public Guid InstanceId{get;set;}public Guid SessionId{get;set;}public long WordRevision{get;set;}public Guid OperationId{get;set;}public bool HasIssues{get;set;}public int[] ReviewChapterIds{get;set;}=Array.Empty(); } public sealed class ChapterRepairRequested {public Guid OperationId{get;set;}public string Message{get;set;}="";} public sealed class ChapterReuseRequest { public ChapterObservation[] Chapters{get;set;}=Array.Empty(); } public sealed class ChapterReuseReply { public int[] ChapterIds{get;set;}=Array.Empty();public long Revision{get;set;} public double ReadMs{get;set;}public double ProcessingMs{get;set;}public double ValidationMs{get;set;}public double PersistenceMs{get;set;} } public static class ChapterCheckpointReuse { public static bool Matches(ChapterManifestItem c,ChapterObservation p)=>c.DurableAccepted&&c.Algorithm==ChapterFingerprint.Version&&p.Algorithm==c.Algorithm&&c.ContentHash==p.ContentHash&&c.IdentityHash==p.IdentityHash&&c.PositionHash==p.PositionHash&&c.NextHeadingId==p.NextHeadingId&&c.ParagraphCount==p.Paragraphs.Length; }