PlotDirector/PlotLine/Services/Context/ContextIntentChecklist.cs

219 lines
12 KiB
C#

using System.Data;
using System.Text.Json;
using Dapper;
using PlotLine.Data;
using PlotLine.Models;
namespace PlotLine.Services.Context;
public sealed record IntentChecklistLink(string Key, bool Covered, string? Name = null);
public sealed record IntentChecklistEvidence(Guid? Id, Guid Paragraph, long Revision, string Quote);
public sealed record IntentChecklistItem(int? Id, string Text, bool Completed, bool Changed, string? Notes,
IntentChecklistLink[]? Links = null, IntentChecklistEvidence[]? Evidence = null);
internal static class IntentChecklistLinks
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private static readonly IReadOnlyDictionary<string, string> Collections = new Dictionary<string, string>
{
["character"] = "Characters", ["location"] = "Locations", ["asset"] = "StoryAssets",
["plotline"] = "PlotLines", ["thread"] = "PlotThreads", ["candidate"] = "StoryIntelligenceReviewCandidates",
["narrative-candidate"] = "StoryIntelligenceNarrativeCandidates"
};
public static bool Valid(IntentChecklistLink[]? links) => links is null || links.Length <= 40
&& links.All(link => link is not null && link.Key is { Length: > 0 and <= 80 }
&& (TryIdentity(link.Key, out _, out _) || Historical(link.Key)))
&& links.Select(link => link.Key).Distinct(StringComparer.Ordinal).Count() == links.Length;
private static bool Historical(string key) => key.StartsWith("historical:", StringComparison.Ordinal)
&& Guid.TryParseExact(key[11..], "N", out _);
private static bool TryIdentity(string key, out string table, out int id)
{
table = "";
id = 0;
var delimiter = key.IndexOf(':');
if (delimiter < 1 || !Collections.TryGetValue(key[..delimiter], out var collection)
|| !int.TryParse(key[(delimiter + 1)..], System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture, out id) || id <= 0
|| key[(delimiter + 1)..] != id.ToString(System.Globalization.CultureInfo.InvariantCulture))
return false;
table = collection;
return true;
}
public static bool IsValidBackup(string? value)
{
if (value is null) return true;
try
{
var links = JsonSerializer.Deserialize<IntentChecklistLink[]>(value, Json);
return links is not null && Valid(links)
&& links.All(link => link.Name is { Length: > 0 and <= 450 });
}
catch (JsonException) { return false; }
}
public static string? Remap(string? value, Dictionary<string, Dictionary<int, int>> maps)
{
if (value is null) return null;
var links = JsonSerializer.Deserialize<IntentChecklistLink[]>(value, Json)!;
return JsonSerializer.Serialize(links.Select(link =>
{
if (!TryIdentity(link.Key, out var table, out var id)) return link;
var key = maps.TryGetValue(table, out var mapping) && mapping.TryGetValue(id, out var target)
? link.Key[..(link.Key.IndexOf(':') + 1)] + target.ToString(System.Globalization.CultureInfo.InvariantCulture)
: "historical:" + Guid.NewGuid().ToString("N");
return link with { Key = key };
}), Json);
}
}
public sealed record IntentChecklistSave(int BookID, int ChapterID, int? SceneID, string Version, IntentChecklistItem[] Items);
public sealed record IntentChecklistFrame(int ProjectID, bool CanEdit, string Version, string? Objective, string? Outcome, IntentChecklistItem[] Items);
public sealed record IntentPassageReference(Guid Paragraph, long Revision, string Text, IReadOnlyList<IntentPassageMention> Mentions, bool MatchingLimited = false);
public sealed record IntentPassageMention(string Text, IReadOnlyList<IntentChecklistLink> Elements);
public sealed class ContextIntentChecklist(ISqlConnectionFactory connections, ICurrentUserService user,
IParagraphManuscriptRepository manuscripts,
ContextWorkspaceNotifications notifications)
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private sealed record State(int ProjectID, bool CanEdit, string Version, string ItemsJson, string? Objective, string? Outcome);
private sealed record Identity(string EntityKey, string Name);
private static IEnumerable<StoryParagraph> Scoped(ParagraphManuscript state, int chapterId, int? sceneId)
{
var scenes = state.Scenes.Where(s => !s.Retired && s.CanonicalId > 0 && s.ChapterId == chapterId
&& (!sceneId.HasValue || s.CanonicalId == sceneId)).Select(s => s.Id).ToHashSet();
return state.Paragraphs.Where(p => p.Story && p.PositionVerified && p.ChapterId == chapterId
&& p.SceneId.HasValue && scenes.Contains(p.SceneId.Value));
}
public async Task<IntentPassageReference[]> Passages(int bookId, int chapterId, int? sceneId)
{
var checklist = await Load(bookId, chapterId, sceneId);
var author = user.UserId!.Value;
var manuscript = await manuscripts.Get(author, bookId);
if (manuscript?.IntentChangedParagraphs is not { Length: > 0 } changed
|| manuscript.ProjectId != checklist.ProjectID) return [];
var ids = changed.ToHashSet();
var passages = Scoped(manuscript, chapterId, sceneId)
.Where(p => ids.Contains(p.Occurrence.Id) && !string.IsNullOrWhiteSpace(p.Occurrence.Text)
&& p.Occurrence.Text.Length <= ContextIntentText.MaximumPassageLength).Take(20).ToArray();
if (passages.Length == 0) return [];
using var db = connections.CreateConnection();
using var reader = await db.QueryMultipleAsync("dbo.ContextIntent_MatchingIndex",
new { UserID = author, BookID = bookId, ChapterID = chapterId, SceneID = sceneId },
commandType: CommandType.StoredProcedure);
var names = (await reader.ReadAsync<Identity>()).ToDictionary(i => i.EntityKey, i => i.Name, StringComparer.Ordinal);
var aliases = (await reader.ReadAsync<ContextIntentPalette.AliasRow>()).ToLookup(a => a.EntityKey, a => a.Alias, StringComparer.Ordinal);
var catalog = names.Select(pair => new ContextIntentText.Entity(pair.Key, pair.Value, aliases[pair.Key].ToArray(), [])).ToArray();
return passages.Select(p =>
{
try
{
var mentions = ContextIntentText.Match(p.Occurrence.Text, catalog)
.Select(m => new IntentPassageMention(m.Text, m.EntityKeys
.Select(key => new IntentChecklistLink(key, false, names[key])).ToArray()))
.ToArray();
return new IntentPassageReference(p.Occurrence.Id, manuscript.Revision, p.Occurrence.Text, mentions);
}
catch (ArgumentException)
{
return new IntentPassageReference(p.Occurrence.Id, manuscript.Revision, p.Occurrence.Text, [], MatchingLimited: true);
}
}).ToArray();
}
internal static bool ValidEvidence(IntentChecklistEvidence[]? evidence) => evidence is null ||
evidence.Length <= ContextIntentDraft.MaximumEvidence && evidence.All(e => e is not null
&& e.Id != Guid.Empty && e.Paragraph != Guid.Empty && e.Revision >= 0
&& !string.IsNullOrWhiteSpace(e.Quote) && e.Quote.Length <= ContextIntentText.MaximumPassageLength)
&& evidence.Where(e => e.Id.HasValue).Select(e => e.Id).Distinct().Count() == evidence.Count(e => e.Id.HasValue);
internal static bool ValidBackupEvidence(string? value)
{
if (value is null) return true;
try
{
var evidence = JsonSerializer.Deserialize<IntentChecklistEvidence[]>(value, Json);
return evidence is not null && ValidEvidence(evidence) && evidence.All(e => e.Id.HasValue);
}
catch (JsonException) { return false; }
}
public async Task<IntentChecklistFrame> Load(int bookId, int chapterId, int? sceneId, IntentChecklistSave? save = null)
{
ContextIntentPalette.Validate(new(bookId, chapterId, sceneId));
var author = user.UserId ?? throw new UnauthorizedAccessException();
string? items = null;
long? manuscriptRevision = null;
if (save is not null)
{
if (save.Version is not { Length: 64 } || !save.Version.All(Uri.IsHexDigit) ||
save.Items is null || save.Items.Length > ContextIntentText.MaximumItems ||
save.Items.Any(item => item is null || item.Id <= 0 ||
string.IsNullOrWhiteSpace(item.Text) || item.Text.Length > ContextIntentText.MaximumItemLength ||
item.Notes?.Length > ContextIntentDraft.MaximumNotesLength || !IntentChecklistLinks.Valid(item.Links)
|| !ValidEvidence(item.Evidence)))
throw new ArgumentException("Review the checklist items and try again.");
var incoming = save.Items.Select(item => item with { Text = item.Text.Trim() }).ToArray();
if (incoming.Any(i => i.Evidence is { Length: > 0 }))
{
var saved = await Load(bookId, chapterId, sceneId);
if (!saved.CanEdit) throw new UnauthorizedAccessException();
if (saved.Version != save.Version) throw new InvalidOperationException("The saved checklist changed. Your draft is still here.");
var existing = saved.Items.ToDictionary(i => i.Id!.Value);
var manuscript = incoming.Any(i => i.Evidence?.Any(e => !e.Id.HasValue) == true)
? await manuscripts.Get(author, bookId) : null;
var paragraphs = manuscript is not null && manuscript.ProjectId == saved.ProjectID
? Scoped(manuscript, chapterId, sceneId).ToDictionary(p => p.Occurrence.Id, p => p.Occurrence.Text)
: [];
for (var i = 0; i < incoming.Length; i++)
{
var item = incoming[i];
if (item.Evidence is null) continue;
var original = item.Id.HasValue ? existing.GetValueOrDefault(item.Id.Value)?.Evidence : null;
var evidence = new List<IntentChecklistEvidence>();
foreach (var entry in item.Evidence)
{
if (entry.Id.HasValue)
{
evidence.Add(original?.SingleOrDefault(e => e.Id == entry.Id)
?? throw new UnauthorizedAccessException());
continue;
}
if (manuscript is null || manuscript.Revision != entry.Revision ||
!paragraphs.TryGetValue(entry.Paragraph, out var text) ||
!text.Contains(entry.Quote, StringComparison.Ordinal))
throw new ArgumentException("Choose an exact passage from the current accepted manuscript in this scope.");
manuscriptRevision = manuscript.Revision;
evidence.Add(entry with { Id = Guid.NewGuid() });
}
incoming[i] = item with { Evidence = evidence.ToArray() };
}
}
items = JsonSerializer.Serialize(incoming, Json);
}
using var db = connections.CreateConnection();
var state = await db.QuerySingleAsync<State>("dbo.ContextIntent_Checklist",
new { UserID = author, BookID = bookId, ChapterID = chapterId, SceneID = sceneId,
ExpectedVersion = save?.Version, Items = items, ManuscriptRevision = manuscriptRevision },
commandType: CommandType.StoredProcedure);
if (save is not null)
await notifications.Invalidate(author, bookId, chapterId, sceneId, state.ProjectID, kind: "intent");
return new(state.ProjectID, state.CanEdit, state.Version, state.Objective, state.Outcome,
JsonSerializer.Deserialize<IntentChecklistItem[]>(state.ItemsJson, Json)!);
}
}