117 lines
12 KiB
C#
117 lines
12 KiB
C#
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<ParagraphOccurrence>();
|
|
public ParagraphOccurrence[] Removed {get;set;}=Array.Empty<ParagraphOccurrence>();
|
|
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<ParagraphOccurrence> 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<ParagraphOccurrence> previous,IReadOnlyList<ParagraphOccurrence> 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<int>();var pairs=new Dictionary<int,int>();
|
|
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<next.Length;i++)Match(i,i,"Unchanged sequence");}
|
|
else{
|
|
var oldNative=old.Select((p,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<old.Length&&y>=0&&y<next.Length&&old[x].Text==next[y].Text&&oldHashes[Fingerprint(old[x].Text)].Length==1&&newHashes[next[y].Fingerprint].Length==1;
|
|
if(SameNeighbour(a-1,b-1)||SameNeighbour(a+1,b+1))Match(a,b,"Unique contextual pair");}
|
|
// Exact text is only a candidate. A recognised neighbour must confirm the occurrence.
|
|
for(var pass=0;pass<2;pass++)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;
|
|
if((b>0&&a>0&&pairs.TryGetValue(b-1,out var left)&&left==a-1)||(b+1<next.Length&&a+1<old.Length&&pairs.TryGetValue(b+1,out var right)&&right==a+1))Match(a,b,"Fingerprint and neighbour");}
|
|
// Duplicate native IDs/content (copy/paste): preserve only a single context-confirmed original.
|
|
foreach(var entry in newHashes){if(!oldHashes.TryGetValue(entry.Key,out var prior))continue;
|
|
var priorSet=new HashSet<int>(prior);var candidates=new Dictionary<int,List<int>>();
|
|
foreach(var b in entry.Value.Where(b=>!pairs.ContainsKey(b))){var adjacent=new HashSet<int>();
|
|
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<next.Length&&pairs.TryGetValue(b+1,out var right)&&priorSet.Contains(right-1)&&!used.Contains(right-1))adjacent.Add(right-1);
|
|
if(adjacent.Count!=1)continue;var original=adjacent.Single();if(!candidates.TryGetValue(original,out var values))candidates[original]=values=new List<int>();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<next.Length;b++)if(next[b].Id==Guid.Empty&&pairs.TryGetValue(b-1,out var l)&&pairs.TryGetValue(b+1,out var r)&&r==l+2&&!used.Contains(l+1)&&!newHashes.ContainsKey(Fingerprint(old[l+1].Text)))Match(l+1,b,"Contextual rewrite; review");
|
|
var copiedHashes=new HashSet<string>(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<int>();var tailEntries=new List<int>();var links=new int[matched.Length];
|
|
for(int i=0;i<matched.Length;i++){int lo=0,hi=tails.Count;while(lo<hi){int m=(lo+hi)/2;if(tails[m]<matched[i].Value)lo=m+1;else hi=m;}links[i]=lo>0?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<int>();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<Guid>(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;i<next.Length;i++){
|
|
var p=next[i];if(p.Id==Guid.Empty){var proposed=incoming[i].Id;p.Id=proposed!=Guid.Empty&&!oldIds.Contains(proposed)&&proposedCounts[proposed]==1?proposed:Guid.NewGuid();p.Change=p.Resolution=="Ambiguous"?"Ambiguous":"Inserted";}
|
|
else{var prior=old[pairs[i]];p.PreviousText=prior.Text;p.WasMoved=!stable.Contains(i);p.Change=prior.Text!=p.Text?"Modified":p.WasMoved?"Moved":"Unchanged";}
|
|
p.PreviousId=i>0?next[i-1].Id:(Guid?)null;
|
|
}
|
|
for(int i=0;i+1<next.Length;i++)next[i].NextId=next[i+1].Id;
|
|
return new(){Current=next,Removed=old.Where((_,i)=>!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<ParagraphOccurrence>();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();
|
|
}
|
|
}
|