using System.Security.Cryptography; using System.Text; using System.Xml; namespace PlotDirector.Companion.Protocol.Manuscript; public sealed class ParagraphOccurrence { public Guid Id {get;set;} public string NativeId {get;set;}=""; public string Fingerprint {get;set;}=""; public string Text {get;set;}=""; public string PreviousText {get;set;}=""; public int Ordinal {get;set;} public int Start {get;set;} public int End {get;set;} public int Outline {get;set;}=10; public Guid? PreviousId {get;set;} public Guid? NextId {get;set;} public string Change {get;set;}="Inserted"; public bool WasMoved {get;set;} public string Resolution {get;set;}="New"; } public sealed class ParagraphComparison { public ParagraphOccurrence[] Current {get;set;}=Array.Empty(); public ParagraphOccurrence[] Removed {get;set;}=Array.Empty(); public int Ambiguous {get;set;} } // Word w14:paraId is a document-part hint, not PlotDirector identity or proof of permanence. public static class WordParagraphIdentity { public static string Read(string xml) { if(string.IsNullOrEmpty(xml)||xml.Length>256*1024)return ""; try{using var input=new StringReader(xml);using var reader=XmlReader.Create(input,new XmlReaderSettings{DtdProcessing=DtdProcessing.Prohibit,XmlResolver=null,MaxCharactersInDocument=256*1024}); bool package=false,main=false;int partDepth=-1; while(reader.Read()) { if(reader.NodeType==XmlNodeType.Element&&reader.LocalName=="package"&&reader.NamespaceURI=="http://schemas.microsoft.com/office/2006/xmlPackage")package=true; if(reader.NodeType==XmlNodeType.Element&&reader.LocalName=="part"&&reader.NamespaceURI=="http://schemas.microsoft.com/office/2006/xmlPackage"){partDepth=reader.Depth;main=reader.GetAttribute("name","http://schemas.microsoft.com/office/2006/xmlPackage")=="/word/document.xml";} if(reader.NodeType==XmlNodeType.EndElement&&reader.Depth==partDepth){main=false;partDepth=-1;} if((!package||main)&&reader.NodeType==XmlNodeType.Element&&reader.LocalName=="p"&&reader.NamespaceURI=="http://schemas.openxmlformats.org/wordprocessingml/2006/main")return Normalise(reader.GetAttribute("paraId","http://schemas.microsoft.com/office/word/2010/wordml")); } }catch(XmlException){}return ""; } public static string Normalise(string? id)=>id!=null&&id.Length==8&&uint.TryParse(id,System.Globalization.NumberStyles.HexNumber,System.Globalization.CultureInfo.InvariantCulture,out var n)&&n>0&&n<0x80000000?id.ToUpperInvariant():""; } public static class ParagraphReconciliation { public static string Fingerprint(string text){using var hash=SHA256.Create();return BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-","");} public static string SnapshotFingerprint(IReadOnlyList rows){var buffer=new StringBuilder();foreach(var row in rows)buffer.Append(row.NativeId.Length).Append(':').Append(row.NativeId).Append(':').Append(row.Outline).Append(':').Append(row.End-row.Start).Append(':').Append(row.Text.Length).Append(':').Append(row.Text);return Fingerprint(buffer.ToString());} public static ParagraphComparison Compare(IReadOnlyList previous,IReadOnlyList incoming) { if(previous.Count>100000||incoming.Count>100000)throw new ArgumentException("Paragraph limit exceeded."); if(previous.Any(p=>p.Id==Guid.Empty)||previous.Select(p=>p.Id).Distinct().Count()!=previous.Count)throw new ArgumentException("Invalid prior occurrence identities."); var old=previous.ToArray();var next=incoming.Select((p,i)=>new ParagraphOccurrence{NativeId=WordParagraphIdentity.Normalise(p.NativeId),Text=p.Text,Fingerprint=Fingerprint(p.Text),Ordinal=i,Start=p.Start,End=p.End,Outline=p.Outline}).ToArray(); if(next.Sum(p=>(long)p.Text.Length)>16*1024*1024)throw new ArgumentException("Manuscript text exceeds limit."); var used=new HashSet();var pairs=new Dictionary(); void Match(int a,int b,string resolution){if(!used.Contains(a)&&!pairs.ContainsKey(b)){used.Add(a);pairs[b]=a;next[b].Id=old[a].Id;next[b].Resolution=resolution;}} // An unchanged sequence is sufficient to preserve occurrences even when Word regenerates its XML hints. var oldNativePositions=old.Select((p,i)=>(Id:WordParagraphIdentity.Normalise(p.NativeId),Index:i)).Where(p=>p.Id!="").GroupBy(p=>p.Id).Where(g=>g.Count()==1).ToDictionary(g=>g.Key,g=>g.Single().Index); var nativeContradiction=next.Select((p,i)=>(p.NativeId,i)).Any(p=>p.NativeId!=""&&oldNativePositions.TryGetValue(p.NativeId,out var at)&&at!=p.i); if(!nativeContradiction&&old.Length==next.Length&&old.Select(p=>p.Text).SequenceEqual(next.Select(p=>p.Text))){for(var i=0;i(p,i)).Where(x=>WordParagraphIdentity.Normalise(x.p.NativeId)!="").GroupBy(x=>WordParagraphIdentity.Normalise(x.p.NativeId)).ToDictionary(g=>g.Key,g=>g.Select(x=>x.i).ToArray()); var newNative=next.Select((p,i)=>(p,i)).Where(x=>x.p.NativeId!="").GroupBy(x=>x.p.NativeId).ToDictionary(g=>g.Key,g=>g.Select(x=>x.i).ToArray()); foreach(var entry in newNative)if(entry.Value.Length==1&&oldNative.TryGetValue(entry.Key,out var prior)&&prior.Length==1)Match(prior[0],entry.Value[0],"Native identifier"); var oldHashes=old.Select((p,i)=>(Hash:Fingerprint(p.Text),Index:i)).GroupBy(x=>x.Hash).ToDictionary(g=>g.Key,g=>g.Select(x=>x.Index).ToArray()); var newHashes=next.Select((p,i)=>(Hash:p.Fingerprint,Index:i)).GroupBy(x=>x.Hash).ToDictionary(g=>g.Key,g=>g.Select(x=>x.Index).ToArray()); // Independently unique adjacent content can establish a context pair if Word hints disappeared. foreach(var entry in newHashes){if(entry.Value.Length!=1||!oldHashes.TryGetValue(entry.Key,out var prior)||prior.Length!=1)continue;int a=prior[0],b=entry.Value[0];if(used.Contains(a)||pairs.ContainsKey(b))continue; bool SameNeighbour(int x,int y)=>x>=0&&x=0&&y0&&a>0&&pairs.TryGetValue(b-1,out var left)&&left==a-1)||(b+1(prior);var candidates=new Dictionary>(); foreach(var b in entry.Value.Where(b=>!pairs.ContainsKey(b))){var adjacent=new HashSet(); if(b>0&&pairs.TryGetValue(b-1,out var left)&&priorSet.Contains(left+1)&&!used.Contains(left+1))adjacent.Add(left+1); if(b+1();if(values.Count<2)values.Add(b); } foreach(var candidate in candidates.Where(c=>c.Value.Count==1))Match(candidate.Key,candidate.Value[0],"Duplicate resolved by neighbour"); } // A single rewritten paragraph between two independently recognised neighbours is a reviewable occurrence, // provided its old text has not moved elsewhere. Splits/merges and competing copies remain unresolved. for(int b=1;b+1(oldHashes.Where(entry=>entry.Value.All(used.Contains)).Select(entry=>entry.Key)); foreach(var p in next.Where(p=>p.Id==Guid.Empty))if(oldHashes.ContainsKey(p.Fingerprint)||(p.NativeId!=""&&oldNative.ContainsKey(p.NativeId)))p.Resolution=copiedHashes.Contains(p.Fingerprint)?"New copy":"Ambiguous"; } // Longest increasing subsequence distinguishes moves from index shifts caused by insertion/deletion. var matched=pairs.OrderBy(p=>p.Key).ToArray();var tails=new List();var tailEntries=new List();var links=new int[matched.Length]; for(int i=0;i0?tailEntries[lo-1]:-1;if(lo==tails.Count){tails.Add(matched[i].Value);tailEntries.Add(i);}else{tails[lo]=matched[i].Value;tailEntries[lo]=i;}} var stable=new HashSet();for(int i=tailEntries.Count==0?-1:tailEntries[tailEntries.Count-1];i>=0;i=links[i])stable.Add(matched[i].Key); var oldIds=new HashSet(old.Select(p=>p.Id));var proposedCounts=incoming.Where(p=>p.Id!=Guid.Empty).GroupBy(p=>p.Id).ToDictionary(g=>g.Key,g=>g.Count()); for(int i=0;i0?next[i-1].Id:(Guid?)null; } for(int i=0;i+1!used.Contains(i)).ToArray(),Ambiguous=next.Count(p=>p.Resolution=="Ambiguous")}; } // Reassemble exactly the existing bounded stream; no paragraph text matching or prose rewriting. public static ParagraphOccurrence[] Assemble(ParagraphFragment[] fragments,int documentEnd) { var rows=new List();var text=new StringBuilder();int position=0,index=1,start=0,outline=10;string native=""; foreach(var f in fragments){if(f.Text==null||f.Start!=position||f.End<=f.Start||f.End>documentEnd||f.Text.Length>ProtocolVersion.MaxParagraphCharacters||f.ParagraphIndex!=index)throw new ArgumentException("Incomplete paragraph stream."); if(text.Length==0){start=f.Start;outline=f.OutlineLevel;native=WordParagraphIdentity.Normalise(f.NativeParagraphId);} else if(f.NativeParagraphId!=""&&WordParagraphIdentity.Normalise(f.NativeParagraphId)!=native)throw new ArgumentException("Paragraph identifier changed within a batch."); text.Append(f.Text);position=f.End;if(f.CompletesParagraph){rows.Add(new(){Ordinal=rows.Count,Start=start,End=position,Outline=outline,NativeId=native,Text=text.ToString()});text.Clear();index++;} if(rows.Count>100000||position>16*1024*1024)throw new ArgumentException("Paragraph stream exceeds limit."); } if(position!=documentEnd||text.Length!=0)throw new ArgumentException("Incomplete paragraph stream.");return rows.ToArray(); } }