138 lines
18 KiB
C#
138 lines
18 KiB
C#
using System.Text.Json;
|
|
using PlotDirector.Companion.Protocol.Manuscript;
|
|
using PlotLine.Models;
|
|
namespace PlotLine.Services.Manuscript;
|
|
// One reconciliation engine; the existing capture transport supplies value snapshots, never COM objects.
|
|
public static class ParagraphManuscriptEngine
|
|
{
|
|
public static ParagraphManuscript Bootstrap(int book,int project,Guid manuscript,IReadOnlyList<ParagraphOccurrence> rows,IReadOnlyList<ParagraphBootstrapScene> scenes)
|
|
{
|
|
if(manuscript==Guid.Empty||book<=0)throw new ArgumentException("A persistent manuscript and book are required.");
|
|
var state=new ParagraphManuscript{BookId=book,ProjectId=project,ManuscriptId=manuscript};
|
|
state.Scenes=scenes.Select(s=>new ParagraphScene{CanonicalId=s.SceneId,ChapterId=s.ChapterId,Title=s.Title,NeedsRefinement=s.NeedsRefinement}).ToList();
|
|
var comparison=ParagraphReconciliation.Compare([],rows);
|
|
if(rows.All(p=>p.Id!=Guid.Empty)&&rows.Select(p=>p.Id).Distinct().Count()==rows.Count)for(int i=0;i<rows.Count;i++)comparison.Current[i].Id=rows[i].Id;
|
|
foreach(var p in comparison.Current){var source=scenes.LastOrDefault(s=>p.Ordinal+1>=s.Start&&p.Ordinal+1<=s.End);var scene=source==null?null:state.Scenes.First(s=>s.CanonicalId==source.SceneId);
|
|
state.Paragraphs.Add(new(){Occurrence=p,ChapterId=scene?.ChapterId,SceneId=p.Outline==1?null:scene?.Id,Story=scene!=null&&p.Outline!=1,PositionVerified=scene!=null});}
|
|
foreach(var chapter in scenes.GroupBy(s=>s.ChapterId)){
|
|
var first=chapter.Min(s=>s.Start)-1;var heading=state.Paragraphs.LastOrDefault(p=>p.Occurrence.Ordinal<=first&&p.Occurrence.Outline==1);
|
|
state.Chapters.Add(new(){CanonicalId=chapter.Key,HeadingId=heading?.Occurrence.Id??Guid.Empty,Title=heading?.Occurrence.Text.Trim()??"Chapter"});
|
|
}
|
|
foreach(var p in state.Paragraphs.Where(p=>p.Occurrence.Outline==1)){var chapter=state.Chapters.FirstOrDefault(c=>c.HeadingId==p.Occurrence.Id);p.ChapterId=chapter?.CanonicalId;p.PositionVerified=p.ChapterId>0;}
|
|
state.SnapshotHash=Hash(rows);state.UpdatedUtc=DateTime.UtcNow;Validate(state);return state;
|
|
}
|
|
public static string Hash(IReadOnlyList<ParagraphOccurrence> rows)=>ParagraphReconciliation.SnapshotFingerprint(rows);
|
|
public static ParagraphManuscript Clone(ParagraphManuscript state)=>JsonSerializer.Deserialize<ParagraphManuscript>(JsonSerializer.Serialize(state))!;
|
|
public static void Reconcile(ParagraphManuscript state,IReadOnlyList<ParagraphOccurrence> rows)
|
|
{
|
|
var comparison=ParagraphReconciliation.Compare(state.Paragraphs.Select(p=>p.Occurrence).ToArray(),rows);var old=state.Paragraphs.ToDictionary(p=>p.Occurrence.Id);var next=comparison.Current;
|
|
var index=next.Select((p,i)=>(p.Id,i)).ToDictionary(p=>p.Id,p=>p.i);
|
|
var chapterHeadings=state.Chapters.Where(c=>index.ContainsKey(c.HeadingId)).ToDictionary(c=>c.HeadingId);
|
|
if(state.Chapters.Any(c=>c.CanonicalId==0&&c.HeadingId!=Guid.Empty&&!index.ContainsKey(c.HeadingId)))throw new InvalidOperationException("An excluded manuscript section boundary cannot be reliably identified. Review the Word structure before synchronising; no saved manuscript was changed.");
|
|
var excludedAt=new bool[next.Length];bool excluded=false;
|
|
var chapterAt=new int?[next.Length];int? currentChapter=state.Chapters.FirstOrDefault(c=>c.HeadingId==Guid.Empty)?.CanonicalId;
|
|
for(int n=0;n<next.Length;n++){if(chapterHeadings.TryGetValue(next[n].Id,out var binding)){excluded=binding.CanonicalId==0;currentChapter=excluded?null:binding.CanonicalId;}else if(next[n].Outline==1){currentChapter=null;excluded=false;}chapterAt[n]=currentChapter;excludedAt[n]=excluded;}
|
|
var oldGroups=state.Paragraphs.Where(p=>p.SceneId.HasValue).GroupBy(p=>p.SceneId!.Value).ToDictionary(g=>g.Key,g=>g.ToArray());
|
|
var starts=new List<(int At,ParagraphScene Scene,bool Verified)>();
|
|
foreach(var scene in state.Scenes.Where(s=>!s.Retired)){
|
|
var prior=oldGroups.GetValueOrDefault(scene.Id)??[];if(prior.Length==0)continue;
|
|
if(index.TryGetValue(prior[0].Occurrence.Id,out var at)){
|
|
// A moved scene-start paragraph alone is not proof that the whole scene moved.
|
|
var positions=prior.Where(p=>index.ContainsKey(p.Occurrence.Id)).Select(p=>index[p.Occurrence.Id]).Order().ToArray();
|
|
var complete=positions.Length==prior.Length&&positions[^1]-positions[0]+1==positions.Length;
|
|
if(complete&&chapterAt[positions[0]].HasValue&&positions.All(pos=>chapterAt[pos]==chapterAt[positions[0]]))scene.ChapterId=chapterAt[positions[0]]!.Value;
|
|
var verified=at==positions[0]&&(prior.Length==1||complete||!next[at].WasMoved);
|
|
if(!verified&&!complete){var remaining=positions.Where(pos=>!next[pos].WasMoved).ToArray();if(remaining.Length>0)at=remaining[0];scene.NeedsRefinement=true;}
|
|
starts.Add((at,scene,verified));
|
|
}else{
|
|
var surviving=prior.Where(p=>index.ContainsKey(p.Occurrence.Id)).Select(p=>index[p.Occurrence.Id]).Order().ToArray();
|
|
if(surviving.Length>0){starts.Add((surviving[0],scene,false));scene.NeedsRefinement=true;}
|
|
}
|
|
}
|
|
starts=starts.OrderBy(s=>s.At).ToList();var current=new List<StoryParagraph>();int boundaryIndex=-1;
|
|
foreach(var p in next){while(boundaryIndex+1<starts.Count&&starts[boundaryIndex+1].At<=p.Ordinal)boundaryIndex++;var boundary=boundaryIndex>=0?starts[boundaryIndex]:default;var before=old.GetValueOrDefault(p.Id);var scene=boundary.Scene;
|
|
// Heading 1 is structure, not prose. Front matter before an imported boundary stays outside the story.
|
|
if(scene==null&&p.Outline!=1&&chapterAt[p.Ordinal].HasValue){var first=starts.FirstOrDefault(s=>s.Scene.ChapterId==chapterAt[p.Ordinal]);if(first.Scene!=null){scene=first.Scene;scene.NeedsRefinement=true;}}
|
|
var story=!excludedAt[p.Ordinal]&&p.Outline!=1&&scene!=null;
|
|
current.Add(new(){Occurrence=p,Story=story,SceneId=story?scene!.Id:null,ChapterId=chapterAt[p.Ordinal],PositionVerified=(p.Outline==1&&chapterAt[p.Ordinal]>0)||(story&&boundary.Scene!=null&&boundary.Scene.Id==scene?.Id&&boundary.Verified&&p.Resolution!="Ambiguous"&&chapterAt[p.Ordinal]==scene?.ChapterId)});
|
|
}
|
|
// If a boundary disappeared, preserve that scene's surviving paragraph grouping as unresolved.
|
|
foreach(var p in current.Where(p=>p.SceneId==null&&p.Occurrence.Outline!=1&&!excludedAt[p.Occurrence.Ordinal]))if(old.TryGetValue(p.Occurrence.Id,out var prior)&&prior.Story){p.Story=true;p.SceneId=prior.SceneId;p.ChapterId=prior.ChapterId;p.PositionVerified=false;}
|
|
foreach(var scene in state.Scenes.Where(s=>!s.Retired))if(current.Any(p=>p.SceneId==scene.Id&&!p.PositionVerified))scene.NeedsRefinement=true;
|
|
state.Paragraphs=current;var hash=Hash(rows);if(hash!=state.SnapshotHash)state.Undo.Clear();state.SnapshotHash=hash;state.UpdatedUtc=DateTime.UtcNow;RefreshEvidence(state);Validate(state);
|
|
}
|
|
private static ParagraphLayout Layout(ParagraphManuscript state)=>new(){Chapters=state.Chapters.Select(c=>new ParagraphChapter{CanonicalId=c.CanonicalId,HeadingId=c.HeadingId,Title=c.Title}).ToList(),SnapshotHash=state.SnapshotHash,EventPositions=state.EventPositions.Select(e=>new ManuscriptEventOption{Kind=e.Kind,Id=e.Id,SceneId=e.SceneId,Description=e.Description}).ToList(),Scenes=state.Scenes.Select(s=>new ParagraphScene{Id=s.Id,CanonicalId=s.CanonicalId,ChapterId=s.ChapterId,Title=s.Title,Retired=s.Retired,MergedInto=s.MergedInto,NeedsRefinement=s.NeedsRefinement}).ToList(),Assignments=state.Paragraphs.Select(p=>new ParagraphAssignment{ParagraphId=p.Occurrence.Id,ChapterId=p.ChapterId,SceneId=p.SceneId,PositionVerified=p.PositionVerified}).ToList()};
|
|
private static void Remember(ParagraphManuscript state){var limit=Math.Clamp(100000/Math.Max(1,state.Paragraphs.Count),1,12);while(state.Undo.Count>=limit)state.Undo.RemoveAt(0);state.Undo.Add(Layout(state));}
|
|
public static void ConfirmGrouping(ParagraphManuscript state,Guid sceneId)
|
|
{
|
|
var scene=state.Scenes.Single(s=>s.Id==sceneId&&!s.Retired);var rows=state.Paragraphs.Where(p=>p.SceneId==sceneId&&p.Story).ToArray();if(rows.Length==0)throw new ArgumentException("No surviving scene paragraphs to confirm.");
|
|
Remember(state);foreach(var p in rows){p.PositionVerified=true;p.ChapterId=scene.ChapterId;}scene.NeedsRefinement=false;
|
|
foreach(var heading in state.Paragraphs.Where(p=>p.Occurrence.Outline==1&&p.Occurrence.Ordinal>=rows[0].Occurrence.Ordinal-1&&p.Occurrence.Ordinal<=rows[^1].Occurrence.Ordinal&&state.Chapters.All(c=>c.HeadingId!=p.Occurrence.Id)))state.Chapters.Add(new(){CanonicalId=scene.ChapterId,HeadingId=heading.Occurrence.Id,Title=heading.Occurrence.Text.Trim()});
|
|
RefreshEvidence(state);Validate(state);
|
|
}
|
|
public static void Split(ParagraphManuscript state,Guid paragraph,string title)
|
|
{
|
|
var p=state.Paragraphs.SingleOrDefault(p=>p.Occurrence.Id==paragraph&&p.Story)??throw new ArgumentException("Choose a story paragraph.");var source=state.Scenes.Single(s=>s.Id==p.SceneId&&!s.Retired);
|
|
var group=state.Paragraphs.Where(x=>x.SceneId==source.Id).ToArray();if(group[0]==p)throw new ArgumentException("The paragraph already begins a scene.");if(string.IsNullOrWhiteSpace(title)||title.Length>200)throw new ArgumentException("Enter a scene title of up to 200 characters.");
|
|
Remember(state);var created=new ParagraphScene{ChapterId=source.ChapterId,Title=title.Trim()};state.Scenes.Add(created);foreach(var row in group.Where(x=>x.Occurrence.Ordinal>=p.Occurrence.Ordinal)){row.SceneId=created.Id;row.PositionVerified=true;}source.NeedsRefinement=false;RefreshEvidence(state);Validate(state);
|
|
}
|
|
public static void MoveBoundary(ParagraphManuscript state,Guid rightScene,Guid firstParagraph)
|
|
{
|
|
var right=state.Scenes.SingleOrDefault(s=>s.Id==rightScene&&!s.Retired)??throw new ArgumentException("Scene no longer exists.");
|
|
var ordered=state.Paragraphs.Where(p=>p.Story).GroupBy(p=>p.SceneId).ToArray();var i=Array.FindIndex(ordered,g=>g.Key==rightScene);if(i<=0)throw new ArgumentException("Choose an adjacent scene boundary.");
|
|
var left=state.Scenes.Single(s=>s.Id==ordered[i-1].Key);if(left.ChapterId!=right.ChapterId)throw new ArgumentException("A boundary cannot cross chapters.");
|
|
var rows=ordered[i-1].Concat(ordered[i]).OrderBy(p=>p.Occurrence.Ordinal).ToArray();var cut=Array.FindIndex(rows,p=>p.Occurrence.Id==firstParagraph);if(cut<=0||cut>=rows.Length)throw new ArgumentException("Keep at least one paragraph in each scene.");
|
|
Remember(state);for(int n=0;n<rows.Length;n++){rows[n].SceneId=n<cut?left.Id:right.Id;rows[n].PositionVerified=true;}left.NeedsRefinement=right.NeedsRefinement=false;RefreshEvidence(state);Validate(state);
|
|
}
|
|
public static void Merge(ParagraphManuscript state,Guid leftScene,Guid rightScene)
|
|
{
|
|
var groups=state.Paragraphs.Where(p=>p.Story).GroupBy(p=>p.SceneId).ToArray();var i=Array.FindIndex(groups,g=>g.Key==leftScene);if(i<0||i+1>=groups.Length||groups[i+1].Key!=rightScene)throw new ArgumentException("Only adjacent scenes can be merged.");
|
|
var left=state.Scenes.Single(s=>s.Id==leftScene&&!s.Retired);var right=state.Scenes.Single(s=>s.Id==rightScene&&!s.Retired);if(left.ChapterId!=right.ChapterId)throw new ArgumentException("Scenes belong to different chapters.");
|
|
Remember(state);foreach(var p in state.Paragraphs.Where(p=>p.SceneId==rightScene)){p.SceneId=leftScene;p.PositionVerified=true;}right.Retired=true;right.MergedInto=left.Id;foreach(var e in state.EventPositions.Where(e=>e.SceneId==right.CanonicalId))e.SceneId=left.CanonicalId;left.NeedsRefinement=false;RefreshEvidence(state);Validate(state);
|
|
}
|
|
public static void Undo(ParagraphManuscript state)
|
|
{
|
|
if(state.Undo.Count==0)throw new InvalidOperationException("No structure change to undo.");var previous=state.Undo[^1];if(previous.SnapshotHash!=state.SnapshotHash)throw new InvalidOperationException("Word changed. This earlier layout cannot safely be restored.");
|
|
state.Undo.RemoveAt(state.Undo.Count-1);foreach(var extra in state.Scenes.Where(s=>previous.Scenes.All(p=>p.Id!=s.Id))){extra.Retired=true;previous.Scenes.Add(extra);}state.Scenes=previous.Scenes;state.Chapters=previous.Chapters;state.EventPositions=previous.EventPositions;var assignments=previous.Assignments.ToDictionary(p=>p.ParagraphId);foreach(var p in state.Paragraphs){var a=assignments[p.Occurrence.Id];p.SceneId=a.SceneId;p.ChapterId=a.ChapterId;p.PositionVerified=a.PositionVerified;}RefreshEvidence(state);Validate(state);
|
|
}
|
|
public static StoryEvidence Anchor(ParagraphManuscript state,string kind,int eventId,bool primary,int from,int to,int? startOffset,int? endOffset)
|
|
{
|
|
if(kind is not ("Knowledge" or "Relationship")||eventId<=0)throw new ArgumentException("Choose a saved event.");var rows=state.Paragraphs.Where(p=>p.Occurrence.Ordinal>=from&&p.Occurrence.Ordinal<=to).ToArray();
|
|
if(rows.Length==0||to<from||rows.Length!=to-from+1||rows.Any(p=>!p.Story||!p.PositionVerified))throw new ArgumentException("Choose a reliably mapped story passage.");
|
|
var evidence=new StoryEvidence{EventKind=kind,EventId=eventId,Primary=primary,StartParagraph=rows[0].Occurrence.Id,EndParagraph=rows[^1].Occurrence.Id,StartOffset=startOffset,EndOffset=endOffset};
|
|
evidence.CurrentText=Text(state,evidence)??throw new ArgumentException("Passage offsets are outside the selected text.");if(evidence.CurrentText.Length==0||evidence.CurrentText.Length>100000)throw new ArgumentException("Choose a passage of up to 100,000 characters.");
|
|
evidence.OriginalText=evidence.ConfirmedText=evidence.CurrentText;if(primary)foreach(var old in state.Evidence.Where(e=>e.EventKind==kind&&e.EventId==eventId))old.Primary=false;
|
|
state.Evidence.Add(evidence);state.Undo.Clear();RefreshEvidence(state);evidence.OriginalPosition=evidence.CurrentPosition;return evidence;
|
|
}
|
|
public static void Confirm(ParagraphManuscript state,Guid evidence)
|
|
{
|
|
var item=state.Evidence.Single(e=>e.Id==evidence);var text=Text(state,item)??throw new ArgumentException("Relink missing evidence first.");
|
|
var start=state.Paragraphs.Single(p=>p.Occurrence.Id==item.StartParagraph);if(!start.PositionVerified)throw new ArgumentException("Resolve the scene boundary before confirming evidence.");item.ConfirmedText=text;state.Undo.Clear();RefreshEvidence(state);
|
|
}
|
|
public static string? Text(ParagraphManuscript state,StoryEvidence anchor,IReadOnlyDictionary<Guid,int>? positions=null)
|
|
{
|
|
int a=positions==null?state.Paragraphs.FindIndex(p=>p.Occurrence.Id==anchor.StartParagraph):positions.GetValueOrDefault(anchor.StartParagraph,-1),b=positions==null?state.Paragraphs.FindIndex(p=>p.Occurrence.Id==anchor.EndParagraph):positions.GetValueOrDefault(anchor.EndParagraph,-1);if(a<0||b<a)return null;
|
|
var rows=state.Paragraphs.Skip(a).Take(b-a+1).ToArray();int start=anchor.StartOffset??0,end=anchor.EndOffset??rows[^1].Occurrence.Text.Length;
|
|
if(start<0||start>rows[0].Occurrence.Text.Length||end<0||end>rows[^1].Occurrence.Text.Length||(rows.Length==1&&end<start))return null;
|
|
return rows.Length==1?rows[0].Occurrence.Text.Substring(start,end-start):rows[0].Occurrence.Text[start..]+string.Concat(rows.Skip(1).Take(rows.Length-2).Select(p=>p.Occurrence.Text))+rows[^1].Occurrence.Text[..end];
|
|
}
|
|
public static void RefreshEvidence(ParagraphManuscript state)
|
|
{
|
|
var positions=state.Paragraphs.Select((p,i)=>(p.Occurrence.Id,i)).ToDictionary(p=>p.Id,p=>p.i);var byId=state.Paragraphs.ToDictionary(p=>p.Occurrence.Id);var scenes=state.Scenes.ToDictionary(s=>s.Id);
|
|
foreach(var e in state.Evidence){var current=Text(state,e,positions);var paragraph=byId.GetValueOrDefault(e.StartParagraph);if(e.CurrentScene!=paragraph?.SceneId){e.PreviousScene=e.CurrentScene;e.PreviousPosition=e.CurrentPosition;}
|
|
e.CurrentText=current??"";e.CurrentScene=paragraph?.SceneId;e.CurrentPosition=paragraph==null?"Paragraph missing":$"Paragraph {paragraph.Occurrence.Ordinal+1} · { (paragraph.SceneId.HasValue&&scenes.TryGetValue(paragraph.SceneId.Value,out var scene)?scene.Title:"Scene needs review") }";
|
|
e.State=current==null?"Missing":current!=e.ConfirmedText||paragraph?.PositionVerified!=true||!RangeVerified(state,e,positions)?"Needs review":"Verified";
|
|
e.DerivedSceneId=e.State=="Verified"&&e.CurrentScene.HasValue?scenes[e.CurrentScene.Value].CanonicalId:null;
|
|
}
|
|
}
|
|
private static bool RangeVerified(ParagraphManuscript state,StoryEvidence evidence,IReadOnlyDictionary<Guid,int> positions){int a=positions.GetValueOrDefault(evidence.StartParagraph,-1),b=positions.GetValueOrDefault(evidence.EndParagraph,-1);return a>=0&&b>=a&&state.Paragraphs.Skip(a).Take(b-a+1).All(p=>p.PositionVerified);}
|
|
public static void Validate(ParagraphManuscript state)
|
|
{
|
|
if(state.Paragraphs.Count>100000||state.Evidence.Count>10000||state.Scenes.Count>10000||state.Evidence.Sum(e=>(long)e.OriginalText.Length+e.ConfirmedText.Length+e.CurrentText.Length)>8*1024*1024)throw new ArgumentException("Manuscript structure exceeds limits.");
|
|
if(state.Evidence.Any(e=>e.Id==Guid.Empty)||state.Evidence.Select(e=>e.Id).Distinct().Count()!=state.Evidence.Count)throw new ArgumentException("Duplicate or empty evidence identities.");
|
|
if(state.Paragraphs.Any(p=>p.Occurrence.Id==Guid.Empty)||state.Scenes.Any(s=>s.Id==Guid.Empty)||state.Paragraphs.Select(p=>p.Occurrence.Id).Distinct().Count()!=state.Paragraphs.Count||state.Scenes.Select(s=>s.Id).Distinct().Count()!=state.Scenes.Count)throw new ArgumentException("Duplicate manuscript identities.");
|
|
var scenes=state.Scenes.Where(s=>!s.Retired).ToDictionary(s=>s.Id);if(state.Paragraphs.Any(p=>p.Story&&(!p.SceneId.HasValue||!scenes.ContainsKey(p.SceneId.Value))))throw new ArgumentException("Every story paragraph must belong to one current scene.");
|
|
var completed=new HashSet<Guid>();Guid? last=null;foreach(var p in state.Paragraphs.Where(p=>p.Story)){if(p.SceneId!=last){if(p.SceneId.HasValue&&completed.Contains(p.SceneId.Value))throw new ArgumentException("Scene groups must be contiguous.");if(last.HasValue)completed.Add(last.Value);last=p.SceneId;}}
|
|
}
|
|
}
|