PlotDirector/PlotLine/Services/Context/ContextIntentText.cs
2026-12-01 13:38:48 +00:00

106 lines
6.2 KiB
C#

using System.Globalization;
using System.Text.RegularExpressions;
namespace PlotLine.Services.Context;
// Pure preparation for an editable preview. This type has no persistence, inference,
// manuscript navigation, candidate acceptance or completion side effects.
public static partial class ContextIntentText
{
public const int MaximumItems = 200;
public const int MaximumItemLength = 300; // Existing SceneChecklistItems.ItemText contract.
public const int MaximumPassageLength = 32_000;
public sealed record PreviewItem(string Text, bool RequestedCompleted);
public sealed record Entity(string Key, string Name, IReadOnlyList<string> Aliases,
IReadOnlyList<string> Provenance);
public sealed record Mention(int Start, int Length, string Text, IReadOnlyList<string> EntityKeys)
{
public bool Ambiguous => EntityKeys.Count > 1;
}
[GeneratedRegex(@"^\s*(?:(?:[-*+•‣–—]|\d+[.)])\s+)?(?:\[(?<check>[ xX])\]\s*)?(?<text>.*?)\s*$")]
private static partial Regex Bullet();
public static IReadOnlyList<PreviewItem> Parse(string input)
{
ArgumentNullException.ThrowIfNull(input);
if (input.Length > 64_000) throw new ArgumentException("Paste 64,000 characters or fewer.");
var result = new List<PreviewItem>();
foreach (var line in input.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'))
{
if (string.IsNullOrWhiteSpace(line)) continue;
var match = Bullet().Match(line);
var text = match.Groups["text"].Value;
if (text.Length == 0) continue;
if (text.Length > MaximumItemLength)
throw new ArgumentException("Each item must contain 300 characters or fewer. Edit the pasted list and preview again.");
if (result.Count == MaximumItems) throw new ArgumentException("Preview at most 200 items at a time.");
result.Add(new(text, match.Groups["check"].Value.Equals("x", StringComparison.OrdinalIgnoreCase)));
}
return result;
}
// Keys are supplied from authorised canonical identities or persisted candidate IDs.
// Equal labels never merge identities. Repeated appearances of one identity do.
public static IReadOnlyList<Entity> Deduplicate(IEnumerable<Entity> entities)
{
var rows = entities.Take(5_001).ToList();
if (rows.Count > 5_000) throw new ArgumentException("Narrow the Story Elements search.");
if (rows.Any(e => string.IsNullOrWhiteSpace(e.Key) || string.IsNullOrWhiteSpace(e.Name) ||
e.Key.Length > 200 || e.Name.Length > 300 || e.Aliases.Count > 100 ||
e.Aliases.Any(a => a.Length > 300))) throw new ArgumentException("Invalid Story Element identity or alias.");
return rows.GroupBy(e => e.Key, StringComparer.Ordinal).Select(g => new Entity(g.Key, g.First().Name.Trim(),
g.SelectMany(e => e.Aliases.Prepend(e.Name)).Where(a => !string.IsNullOrWhiteSpace(a)).Select(a => a.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase).ToArray(),
g.SelectMany(e => e.Provenance).Distinct(StringComparer.Ordinal).ToArray())).ToArray();
}
// Only the caller's current accepted changed passage is searched. A mention is
// a reference suggestion, including every ambiguous identity, never a story fact.
// Offsets refer to UTF-16 positions in that exact passage, not Word caret offsets.
public static IReadOnlyList<Mention> Match(string passage, IEnumerable<Entity> entities)
{
ArgumentNullException.ThrowIfNull(passage);
if (passage.Length > MaximumPassageLength) throw new ArgumentException("Match one changed passage of at most 32,000 characters.");
var spellings = Deduplicate(entities).SelectMany(e => e.Aliases.Select(a => (Name: a, e.Key)))
.GroupBy(x => x.Name, StringComparer.OrdinalIgnoreCase).Take(10_001).ToList();
if (spellings.Count > 10_000) throw new ArgumentException("Narrow the Story Elements search before matching.");
var found = new List<Mention>();
foreach (var spelling in spellings)
{
var name = spelling.Key;
var keys = spelling.Select(x => x.Key).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();
for (var offset = 0; offset <= passage.Length - name.Length;)
{
var start = passage.IndexOf(name, offset, StringComparison.OrdinalIgnoreCase);
if (start < 0) break;
var end = start + name.Length;
if ((start == 0 || !WordAt(passage, PreviousScalar(passage, start))) &&
(end == passage.Length || !WordAt(passage, end)))
{
if (found.Count == 2_000) throw new ArgumentException("Choose a shorter changed passage before matching.");
found.Add(new(start, name.Length, passage.Substring(start, name.Length), keys));
}
offset = start + Math.Max(1, name.Length);
}
}
// Prefer the longest whole phrase when names/aliases overlap. This does
// not resolve shared spellings: their complete key set remains visible.
var selected = new List<Mention>();
foreach (var mention in found.OrderByDescending(m => m.Length).ThenBy(m => m.Start))
if (!selected.Any(m => mention.Start < m.Start + m.Length && m.Start < mention.Start + mention.Length))
selected.Add(mention);
return selected.OrderBy(m => m.Start).ToArray();
}
private static int PreviousScalar(string text, int index) =>
index > 1 && char.IsLowSurrogate(text[index - 1]) && char.IsHighSurrogate(text[index - 2]) ? index - 2 : index - 1;
private static bool WordAt(string text, int index) => char.GetUnicodeCategory(text, index) is
UnicodeCategory.UppercaseLetter or UnicodeCategory.LowercaseLetter or UnicodeCategory.TitlecaseLetter or
UnicodeCategory.ModifierLetter or UnicodeCategory.OtherLetter or UnicodeCategory.DecimalDigitNumber or
UnicodeCategory.LetterNumber or UnicodeCategory.OtherNumber or UnicodeCategory.NonSpacingMark or
UnicodeCategory.SpacingCombiningMark or UnicodeCategory.EnclosingMark or UnicodeCategory.ConnectorPunctuation;
}