Prepare Context Intent text preview and deterministic matching

This commit is contained in:
Atlas Development Worker 2026-12-01 13:38:48 +00:00
parent 6b02f7fb9a
commit 5bee47e637
4 changed files with 262 additions and 0 deletions

View File

@ -0,0 +1,112 @@
# Context Intent task 67: preparation and schema release prerequisite
Status: partial implementation, not ready for acceptance. No migration, database
change or deployment has been performed. The task remains incomplete.
## Implemented preparation
`PlotLine/Services/Context/ContextIntentText.cs` is a pure shared server utility:
- Paste preparation accepts ordinary lines, bullets, numbered lists and checked or
unchecked Markdown checkboxes. It preserves order and repeated objectives, rejects
oversized input without truncation, and returns editable-preview data. A pasted
check is a requested manual state for preview, never persisted completion.
- Palette preparation merges appearances by supplied identity key, unions names,
aliases and provenance, and keeps different identities with the same label apart.
- Matching examines only the supplied changed passage, uses exact case-insensitive
names/aliases with Unicode word boundaries, prefers the longest overlapping
phrase and returns all identities for shared spellings. It neither confirms a
candidate nor creates facts, knowledge, relationships, events or completion.
- Offsets describe the exact supplied passage in UTF-16; they are not Word positions.
Callers must supply authorised identities and encode text when rendering.
The regression harness includes `ContextIntentTextTests`, also available with
`dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --context-intent-text`.
The existing `NameTextMatcher` is a different, normalised manuscript-wide name
verification search: it does not preserve exact original passage offsets or select
longest overlapping multi-entity matches. Intent preparation does not invoke that
paid verification workflow or change its contracts.
There is no Context endpoint, palette data loader, UI or persistence wired to this
utility yet. Passing these tests does not establish feature acceptance.
## Concrete storage proposal for the remaining implementation
Keep `ChapterGoals` and existing scene purpose/outcome fields authoritative. Keep
the existing `SceneChecklistItems` identities for scene objectives; do not copy them
into an independent Intent document. Extend that checklist to support chapter items:
| Concern | Proposed contract |
| --- | --- |
| Scope | Nullable `SceneID` plus nullable `ChapterID`, exactly one populated. Existing scene rows remain unchanged. Chapter rows reference the canonical chapter. |
| Text/order/completion | Reuse `ItemText` (300 characters), `SortOrder`, `IsCompleted` and the existing item identity. Preserve author order across completion changes. |
| Change/notes | Add an explicit changed flag and optional author notes. Changing an item never silently completes it. |
| Entity links | Separate child rows keyed by item, entity kind and canonical/candidate identity, with explicit covered state. Link and covered are distinct from item completion. Validate each identity in the authorised project/book at save time. |
| Passage evidence | Separate child rows containing source book/chapter/scene, accepted revision/paragraph identity when available and the quoted passage. Retain evidence as author evidence if a later manuscript revision changes it; do not reinterpret it as a fact. |
| Concurrency | Atomic stored-procedure saves with a scope/row fingerprint that also detects changes by existing Writer and scene editors. Stale saves retain the local draft and require reconciliation. |
| Permissions | Reuse book/project access and `ContextEditPolicy`; independently validate scope and edit permission in stored procedures. All mutations require antiforgery. |
| Lifecycle | Item children delete with the item. Chapter/book/project deletion and restore explicitly include chapter items; no orphaned metadata. Entity archival/merge must retain meaningful author evidence and resolve current identity through canonical references. |
This is a proposed schema contract, not an approved or qualified SQL migration.
Recheck the next migration number when implementing (339 was the latest numeric
prefix at discovery). Never edit existing numbered scripts.
Required source integration before qualification:
- Update checklist read/write projections and preserve compatibility with existing
`SceneChecklist_ListByScene`, `SceneChecklist_Save` and scene/Writer callers.
- Extend `ProjectBackupStoredFieldContract.Schema.cs` and
`ProjectBackupGraphValidation.cs`. Current backups require a scene link for every
checklist row; merely making `SceneID` nullable would lose chapter items.
- Add forward-only replacements for affected backup/export/restore and scoped
deletion procedures. Current explicit checklist export projection is visible in
migration 215; graph restore evolves through 229, 236 and 241. Trace the effective
procedures rather than replaying those historical scripts. Include entity link
and evidence remapping in portable backups and book recovery.
- Qualify existing scene checklist compatibility, chapter-only scope, project
isolation, stale concurrent saves, archival/deletion and backup/restore round trips
with synthetic data in disposable databases. Existing author records must survive.
## Remaining application and acceptance work
Implement one shared partial/component in the Context tool registry and docked
Writer sidebar, using the same saved data. Default to chapter scope; optional scene
scope must work without prose or Word. Reuse existing goal editors. Add paste preview,
manual add/edit/check/change/notes, drag and keyboard reorder, explicit entity
link/covered actions, and evidence drop contracts for future project 12 integration.
Do not implement a native editor or a separate Intent window.
Build the palette from authorised canonical references and persisted candidates
only; do not reconstruct raw Scene Intelligence JSON or trigger analysis. Use typed
identity keys, canonical aliases and provenance; default to current chapter/scene
associations with wider story search. Include characters, locations, assets, threads
and relevant plotlines. Matching remains reference suggestions only.
Register the component with the existing Context lifecycle, dirty/busy refresh
guards and saved-data invalidation. Extend the invalidation category map for all
palette categories. Refresh newly captured entities while held without retargeting
the held chapter/scene; preserve focus and drafts across panes/windows. Handle
accepted Word manuscript updates through the existing accepted-source contract.
Use theme controls, collapsible/resizable palette and `PlotDirector.toast`.
Run the solution build, regression harness, focused UI/concurrency tests and schema
qualification. After a reviewed schema release to Development, verify the full
deployed commit and use the registered ordinary browser fixture for real manual
checklist/entity-link/evidence persistence after reload and fresh login, held-scope
SignalR refresh, chapter-only/no-prose use and cleanup. Record receipts, feature URL,
actual outcomes and limitations in CYJ. Production is excluded.
## Deployment gate requiring operator assistance
`Docs/Codex/Deployment.md`, “SQL changes and recovery”, requires an explicit reviewed
plan qualified against Development's schema. The installed unattended route invokes
the routine code-only publisher. `Tools/Deployment/development_release.py` explicitly
rejects any `PlotLine/Sql` changes relative to its approved baseline with:
“Schema changes require a separately reviewed/qualified migration plan”.
The worker must not bypass that guard, invoke sudo, access signing material, manually
apply SQL or change the baseline. An operator must identify/provision the authorised
schema qualification and activation route for this task. This is a deployment
prerequisite, not a request to reopen the agreed Intent product design. Resume from
the committed preparation and this contract once that route is supplied; do not
claim Development readiness or mark task 67 complete in the meantime.

View File

@ -0,0 +1,43 @@
using PlotLine.Services.Context;
using static PlotLine.Services.Context.ContextIntentText;
internal static class ContextIntentTextTests
{
public static void Run()
{
static void Check(bool condition, string message) { if (!condition) throw new Exception(message); }
static void Reject(Action action) { try { action(); } catch (ArgumentException) { return; } throw new Exception("Expected bounded-input rejection."); }
var parsed = Parse("- [ ] Introduce the disagreement\r\n* [x] Keep the promise\n\n1. Reveal a clue\n• Keep the promise\nUnbulleted objective\n- [ ] ");
Check(parsed.Count == 5, "Blank lines and empty checklist entries are omitted.");
Check(parsed[1].RequestedCompleted && !parsed[0].RequestedCompleted, "Pasted checks remain explicit preview choices.");
Check(parsed[1].Text == parsed[3].Text, "Repeated author objectives are preserved.");
Check(Parse("- [X] A\r+ B\n2) C\n– D").Select(x => x.Text).SequenceEqual(new[] { "A", "B", "C", "D" }), "Common bullet and newline formats.");
Check(Parse("<script>alert('text')</script>")[0].Text.StartsWith("<script>"), "Parser returns plain text; rendering must encode it.");
Reject(() => Parse(new string('a', 301)));
Reject(() => Parse(string.Join('\n', Enumerable.Repeat("- a", 201))));
Reject(() => Parse(new string(' ', 64_001)));
Entity[] library = [
new("character:1", "Mira Vale", ["Mira", "Captain"], ["Recorded scene appearance"]),
new("character:1", "Mira Vale", ["M. Vale"], ["Author plan"]),
new("candidate:2", "Captain", [], ["Pending candidate; not confirmed"]),
new("location:1", "Vale", [], ["Recorded location"]),
new("asset:1", "Key", [], ["Existing asset"])
];
var palette = Deduplicate(library);
Check(palette.Count == 4 && palette[0].Provenance.Count == 2, "Deduplicate identities and retain provenance.");
var mentions = Match("MIRA VALE met the Captain. Mira had the key, not a keyboard or a monkey. M. Vale left.", library);
Check(mentions.Count == 5, "Case insensitive, whole word/phrase and aliases only.");
Check(mentions[0].Text == "MIRA VALE" && mentions[0].EntityKeys.SequenceEqual(new[] { "character:1" }), "Longest phrase suppresses nested names.");
Check(mentions[1].Ambiguous && mentions[1].EntityKeys.SequenceEqual(new[] { "candidate:2", "character:1" }), "Shared canonical/candidate labels remain ambiguous.");
Check(mentions[^1].Text == "M. Vale", "Punctuation within an exact alias is literal.");
Check(Match("Key_Key Key2 2Key Key\u0301 Key", library).Count == 1, "Unicode marks, numbers and connectors form word boundaries.");
Check(Match("\U00010400Key Key\U00010400 (Key)", library).Count == 1, "Supplementary Unicode letters cannot be mistaken for boundaries.");
Check(Match("Mira! Mira?", library).Count == 2, "Repeated occurrences retain independent passage offsets.");
Check(Match("", library).Count == 0 && Match("Mira", []).Count == 0, "Empty accepted text/reference libraries produce no suggestions.");
Check(Match("Someone keeps an unspoken promise.", library).Count == 0, "No semantic inference.");
Reject(() => Match(new string('a', MaximumPassageLength + 1), library));
Reject(() => Deduplicate([new("", "Name", [], [])]));
Check(library[0].Provenance.Count == 1 && library[0].Aliases.Count == 2, "Preparation never mutates canonical input.");
}
}

View File

@ -17,6 +17,7 @@ using PlotLine.ViewModels;
if(args.Contains("--scene-creation")){await SceneCreationTests.Run();return;}
if(args.Contains("--help-visibility")){HelpVisibilityTests.Run();return;}
if(args.Contains("--context-intent-text")){ContextIntentTextTests.Run();Console.WriteLine("PASS Context Intent paste preview, identity deduplication and deterministic passage matching");return;}
if(args.Contains("--application-domain")){ApplicationDomainBoundaryTests.Run();return;}
if(args.Contains("--spatial-context-database")){await SpatialContextDatabaseTests.Run(args.Last());return;}
if(args.Contains("--location-taxonomy-fixture")){await LocationsWorkspaceDatabaseTests.ExportTaxonomy(args[^2],args[^1]);return;}
@ -239,6 +240,7 @@ var tests = new (string Name, Action Test)[]
("Context Names Library query parity and bounded identities",()=>ContextNamesTests.Run().GetAwaiter().GetResult()),
("Context relationship state and focused editing",()=>ContextRelationshipTests.Run().GetAwaiter().GetResult()),
("Context character narrative projection and focused editing",()=>ContextCharacterTests.Run().GetAwaiter().GetResult()),
("Context Intent deterministic text preparation",ContextIntentTextTests.Run),
("Context My Windows routing and lifecycle",ContextWindowsTests.Run),
("Context committed-save notifications and scope",()=>ContextSavedDataTests.Run().GetAwaiter().GetResult()),
("Context main-page navigation safety and delegated link coverage",ContextWorkspaceNavigationTests.Run),

View File

@ -0,0 +1,105 @@
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;
}