Commit the pending application, help and browser regression work. Pin the patched PKCS dependency for the production release.
184 lines
19 KiB
C#
184 lines
19 KiB
C#
using PlotLine.Models;
|
|
|
|
namespace PlotLine.Services;
|
|
|
|
/// <summary>Workspace V1 policy. A touch is any canonical event; these roles alone reset progress.</summary>
|
|
public static class PlotHealthProgressPolicy
|
|
{
|
|
public const int QuietSceneThreshold = 10;
|
|
private static readonly HashSet<string> Roles = new(StringComparer.OrdinalIgnoreCase) {
|
|
"Introduced", "Developed", "Complicated", "Clue Planted", "Question Raised", "Question Answered",
|
|
"False Lead", "Revealed", "Payoff", "Resolved", "Contradicted", "Retconned" };
|
|
public static bool IsMeaningful(string role) => Roles.Contains(role);
|
|
}
|
|
|
|
public interface IPlotHealthEvaluator
|
|
{
|
|
PlotHealthResult Evaluate(PlotHealthContext context);
|
|
}
|
|
|
|
/// <summary>Pure canonical-data evaluation; never saves status, warnings, or inferred intent.</summary>
|
|
public sealed class PlotHealthEvaluator : IPlotHealthEvaluator
|
|
{
|
|
public PlotHealthResult Evaluate(PlotHealthContext context)
|
|
{
|
|
var ordered = context.Data.AttributionScenes.DistinctBy(s => s.SceneID).OrderBy(s => s.NarrativeOrder).ToList();
|
|
var positions = ordered.Select((s, i) => (s.SceneID, Position: i + 1)).ToDictionary(x => x.SceneID, x => x.Position);
|
|
var cutoff = Math.Clamp(context.CutoffPosition ?? ordered.Count, 0, ordered.Count);
|
|
var scopeScenes = ordered.Take(cutoff).ToDictionary(s => s.SceneID);
|
|
var expected = context.ReferenceData.AttributionScenes.Where(s => !context.BookID.HasValue || s.BookID == context.BookID).Select(s => s.SceneID).ToHashSet();
|
|
var missing = expected.Except(positions.Keys).Count();
|
|
var scope = new PlotHealthScope(context.ProjectID, context.BookID, context.ScenarioID, cutoff, ordered.Count, missing == 0, missing);
|
|
var cutoffEvidence = cutoff > 0 ? SceneEvidence(ordered[cutoff - 1].SceneID, "Evaluated cutoff") : null;
|
|
var eventsByThread = context.Data.Contributions.Where(e => scopeScenes.ContainsKey(e.SceneID))
|
|
.DistinctBy(e => e.ThreadEventID).GroupBy(e => e.PlotThreadID).ToDictionary(g => g.Key, g => g.OrderBy(e => positions[e.SceneID]).ThenBy(e => e.ThreadEventID).ToList());
|
|
var selected = context.SelectedLineIDs.ToHashSet();
|
|
var targetLookup = context.ReferenceData.PlotLines.ToDictionary(l => l.PlotLineID);
|
|
var lineEvents = context.Data.Contributions.Where(e => scopeScenes.ContainsKey(e.SceneID)).ToLookup(e => e.PlotLineID);
|
|
var targetsByEvent = context.Data.Targets.ToLookup(t => t.ThreadEventID);
|
|
var lines = new List<PlotLineHealth>();
|
|
foreach (var line in context.Data.PlotLines.Where(l => selected.Contains(l.PlotLineID) && (!context.BookID.HasValue || !l.BookID.HasValue || l.BookID == context.BookID)))
|
|
{
|
|
var threads = new List<PlotThreadHealth>();
|
|
foreach (var thread in context.Data.Threads.Where(t => t.PlotLineID == line.PlotLineID))
|
|
{
|
|
var events = eventsByThread.GetValueOrDefault(thread.PlotThreadID, []);
|
|
var progress = events.Where(e => PlotHealthProgressPolicy.IsMeaningful(e.CanonicalRole)).ToList();
|
|
var introduced = events.Where(e => Role(e, "Introduced")).ToList();
|
|
var closures = events.Where(e => Role(e, "Resolved", "Payoff") || Structural(e, "Resolve", "Abandon")).ToList();
|
|
var resolutions = events.Where(e => Role(e, "Resolved") || Structural(e, "Resolve")).ToList();
|
|
var abandonments = events.Where(e => Structural(e, "Abandon")).ToList();
|
|
var first = events.FirstOrDefault();
|
|
var last = events.LastOrDefault();
|
|
var lastProgress = progress.LastOrDefault();
|
|
var actual = SceneEvidence(thread.ActualResolutionSceneID, "Actual resolution boundary");
|
|
var intro = SceneEvidence(thread.IntroducedSceneID, "Introduction boundary");
|
|
var findings = new List<PlotHealthFinding>();
|
|
PlotHealthEvidence Evidence(PlotLineWorkspaceContributionRow e) => SceneEvidence(e.SceneID,
|
|
$"{e.CanonicalRole} · {e.CanonicalStructuralType}", e.ThreadEventID)!;
|
|
void Add(string rule, PlotHealthLevel level, string title, string explanation,
|
|
IEnumerable<PlotHealthEvidence?> evidence, int? marker = null, bool absence = false,
|
|
int? silence = null, int? chapters = null)
|
|
{
|
|
if (!scope.EvidenceComplete)
|
|
{
|
|
explanation += $" Partial order: {scope.MissingSceneCount} scope scenes are omitted; no conclusion is made about their events.";
|
|
if (absence) { level = PlotHealthLevel.Information; title += " (partial evidence)"; }
|
|
}
|
|
findings.Add(new(rule, level, line.PlotLineID, thread.PlotThreadID, title, explanation,
|
|
thread.ThreadStatusName, evidence.Where(e => e is not null).Cast<PlotHealthEvidence>().Distinct().ToList(), scope,
|
|
marker ?? last?.SceneID ?? cutoffEvidence?.SceneID, silence, chapters));
|
|
}
|
|
if (events.Count == 0)
|
|
Add("H001", PlotHealthLevel.Information, "No recorded contributions", "No canonical contribution events are recorded for this thread in the evaluated scope through the cutoff. This does not mean it should already have started.", [intro, cutoffEvidence], absence: true);
|
|
|
|
// Internal silence uses intervening scenes; trailing silence includes every scene after progress through the cutoff.
|
|
var progressScenes = progress.DistinctBy(e => e.SceneID).ToList();
|
|
for (var i = 0; i < progressScenes.Count; i++)
|
|
{
|
|
var previous = progressScenes[i];
|
|
var next = i + 1 < progressScenes.Count ? progressScenes[i + 1] : null;
|
|
var end = next is null ? cutoff : positions[next.SceneID] - 1;
|
|
var start = positions[previous.SceneID];
|
|
var terminal = resolutions.Concat(abandonments).Any(e => e.SceneID == previous.SceneID);
|
|
var closedBeforeEnd = (actual is not null && actual.Position >= start && actual.Position <= end) || resolutions.Concat(abandonments).Any(e => positions[e.SceneID] >= start && positions[e.SceneID] <= end);
|
|
if (terminal || closedBeforeEnd) continue;
|
|
if (end - start < PlotHealthProgressPolicy.QuietSceneThreshold) continue;
|
|
var touch = events.LastOrDefault(e => positions[e.SceneID] >= start && positions[e.SceneID] <= end) ?? previous;
|
|
var chapterCount = Chapters(start, end);
|
|
Add("H002", PlotHealthLevel.Review, "Quiet stretch",
|
|
$"No meaningful progress across {end - start} scenes in {chapterCount} ordered chapters. Last progress: {previous.CanonicalRole}. Most recent touch in this stretch: {touch.CanonicalRole}. Review threshold: {PlotHealthProgressPolicy.QuietSceneThreshold} scenes; a quiet stretch may be intentional.",
|
|
[Evidence(previous), Evidence(touch), next is null ? cutoffEvidence : Evidence(next)], next?.SceneID ?? cutoffEvidence?.SceneID,
|
|
absence: true, silence: end - start, chapters: chapterCount);
|
|
}
|
|
if (first is not null && progress.Count == 0 && closures.Count == 0 && actual is null && cutoff - positions[first.SceneID] >= PlotHealthProgressPolicy.QuietSceneThreshold)
|
|
Add("H002", PlotHealthLevel.Review, "No recorded meaningful progress", "Only non-progress touches are recorded after activity begins. Mentioned and Note do not reset the 10-scene progress review clock; no last meaningful event can be identified.",
|
|
[Evidence(first), Evidence(last!), cutoffEvidence], absence: true,
|
|
silence: cutoff - positions[first.SceneID], chapters: Chapters(positions[first.SceneID], cutoff));
|
|
if (introduced.Count > 0 && !progress.Any(e => !Role(e, "Introduced") && positions[e.SceneID] >= positions[introduced[0].SceneID])
|
|
&& cutoff - positions[introduced[0].SceneID] >= PlotHealthProgressPolicy.QuietSceneThreshold)
|
|
Add("H003", PlotHealthLevel.Review, "No later recorded development", "Introduction is recorded, but no later meaningful contribution beyond introduction was found by the cutoff. The same 10-scene review threshold applies.", [Evidence(introduced[0]), cutoffEvidence], absence: true);
|
|
|
|
// Coarse thread-level predicates, ordered as in Continuity; these do not match individual questions or clues.
|
|
foreach (var (role, rule, title, closing) in new[] {
|
|
("Question Raised", "H004", "Open recorded question", new[] { "Question Answered" }),
|
|
("Clue Planted", "H005", "Apparent unresolved clue", new[] { "Payoff", "Question Answered", "Revealed", "Resolved" }) })
|
|
{
|
|
var unmatched = events.LastOrDefault(e => Role(e, role) && !events.Any(later => positions[later.SceneID] > positions[e.SceneID] && Role(later, closing)));
|
|
if (unmatched is null) continue;
|
|
var otherClosure = events.Where(e => positions[e.SceneID] > positions[unmatched.SceneID] && Role(e, "Revealed", "Payoff", "Resolved"));
|
|
Add(rule, PlotHealthLevel.Review, title, role == "Question Raised"
|
|
? "No later recorded answer was found in this thread. Any later reveal/payoff/resolution is shown as evidence, not assumed to answer this question."
|
|
: "No later recorded payoff/reveal/answer/resolution was found for this thread. This is a coarse role check, not a judgement of the story's payoff.",
|
|
new[] { Evidence(unmatched), cutoffEvidence }.Concat(otherClosure.Select(Evidence)), unmatched.SceneID, absence: true);
|
|
}
|
|
if (Status(thread, "Ready For Payoff") && !events.Any(e => Role(e, "Payoff", "Resolved") || Structural(e, "Resolve")))
|
|
Add("H006", PlotHealthLevel.Review, "Payoff evidence review", "Stored status is Ready For Payoff, but no recorded payoff/resolution evidence exists by this cutoff. The status has no narrative effective date; readiness remains the author's judgement.", [last is null ? null : Evidence(last), cutoffEvidence], absence: true);
|
|
|
|
var laterDevelopment = introduced.Count > 0 ? progress.FirstOrDefault(e => !Role(e, "Introduced") && positions[e.SceneID] > positions[introduced[0].SceneID]) : progress.FirstOrDefault(e => !Role(e, "Introduced"));
|
|
if ((Status(thread, "Planned") && progress.Count > 0) || (Status(thread, "Introduced") && laterDevelopment is not null))
|
|
Add("H007", PlotHealthLevel.Review, "Status review", $"Stored status is {thread.ThreadStatusName}, while canonical contributions record meaningful {(Status(thread, "Planned") ? "activity" : "later development/payoff/resolution")}. No replacement status has been inferred or saved.",
|
|
[Evidence(laterDevelopment ?? progress[0]), cutoffEvidence]);
|
|
var positionedClosures = resolutions.Concat(abandonments).Select(Evidence).Concat(actual is null ? [] : new[] { actual }).OrderBy(e => e.Position).ToList();
|
|
var afterClosure = positionedClosures.Select(c => (Closure: c, Later: progress.FirstOrDefault(e => positions[e.SceneID] > c.Position) ?? events.FirstOrDefault(e => positions[e.SceneID] > c.Position))).FirstOrDefault(pair => pair.Later is not null);
|
|
if (afterClosure.Later is not null)
|
|
{
|
|
if (Status(thread, "Resolved", "Abandoned") && PlotHealthProgressPolicy.IsMeaningful(afterClosure.Later.CanonicalRole))
|
|
Add("H007", PlotHealthLevel.Review, "Status and later activity review", $"Stored status is {thread.ThreadStatusName}, but meaningful activity occurs after a positioned closure signal. This may be intentional.", [afterClosure.Closure, Evidence(afterClosure.Later)], afterClosure.Later.SceneID);
|
|
var explicitClosure = resolutions.Concat(abandonments).Any(e => positions[e.SceneID] == afterClosure.Closure.Position);
|
|
Add("H008", explicitClosure && PlotHealthProgressPolicy.IsMeaningful(afterClosure.Later.CanonicalRole) ? PlotHealthLevel.Warning : PlotHealthLevel.Review, "Contribution after closure evidence", "A contribution occurs after recorded closure evidence. Stored status, boundary and explicit events remain separate signals; V1 does not automatically reconcile them.", [afterClosure.Closure, Evidence(afterClosure.Later)], afterClosure.Later.SceneID);
|
|
}
|
|
var resolutionPositions = resolutions.Select(e => positions[e.SceneID]).Distinct().ToList();
|
|
if ((actual is not null && resolutionPositions.Any(p => p != actual.Position)) ||
|
|
(Status(thread, "Resolved") && actual is null && resolutions.Count == 0) ||
|
|
(!Status(thread, "Resolved") && resolutions.Count > 0))
|
|
Add("H008", PlotHealthLevel.Review, "Resolution/boundary review", "Stored status, actual-resolution boundary and explicit Resolved/Resolve events do not all provide agreeing evidence in this evaluated order. Missing or different signals are shown without choosing a universal authority.",
|
|
new PlotHealthEvidence?[] { actual, cutoffEvidence }.Concat(resolutions.Select(Evidence)), absence: resolutions.Count == 0 && actual is null);
|
|
var earlyClosure = closures.FirstOrDefault(e => !Structural(e, "Abandon") && introduced.Count > 0 && positions[e.SceneID] < positions[introduced[0].SceneID]);
|
|
if (earlyClosure is not null && !Structural(earlyClosure, "Abandon"))
|
|
Add("H009", PlotHealthLevel.Warning, "Closure before introduction", "Explicit payoff/resolution evidence precedes explicit introduction in this selected order.", [Evidence(earlyClosure), Evidence(introduced[0])], earlyClosure.SceneID);
|
|
var outside = events.Where(e => (intro is not null && positions[e.SceneID] < intro.Position) || (actual is not null && positions[e.SceneID] > actual.Position)).ToList();
|
|
if (outside.Count > 0)
|
|
Add("H010", PlotHealthLevel.Review, "Contribution outside declared boundaries", $"{outside.Select(e => e.SceneID).Distinct().Count()} scene(s) contribute before the introduction boundary or after the actual-resolution boundary. This is a review observation, not invalid membership.",
|
|
new PlotHealthEvidence?[] { intro, actual }.Concat(outside.Select(Evidence)), outside[0].SceneID);
|
|
foreach (var e in events.Where(e => Structural(e, "Branch", "Split", "Merge")))
|
|
{
|
|
var targets = targetsByEvent[e.ThreadEventID].Select(t => t.TargetPlotLineID).Distinct().ToList();
|
|
if (targets.Count == 0)
|
|
Add("H011", PlotHealthLevel.Warning, "Explicit target unavailable", $"The explicit {e.CanonicalStructuralType} event has no recorded target.", [Evidence(e)], e.SceneID);
|
|
foreach (var target in targets)
|
|
{
|
|
if (!targetLookup.TryGetValue(target, out var targetLine) || targetLine.ProjectID != context.ProjectID)
|
|
Add("H011", PlotHealthLevel.Warning, "Explicit target unavailable", $"Target Plot Line {target} is missing, archived or outside the project in the active canonical read model.", [Evidence(e)], e.SceneID);
|
|
else if (!Structural(e, "Merge") && !lineEvents[target].Any(later => positions[later.SceneID] > positions[e.SceneID]))
|
|
Add("H011", PlotHealthLevel.Review, "No recorded continuation", $"{e.CanonicalStructuralType} target “{targetLine.PlotLineName}” has no later recorded contribution in this evaluated scope. Activity outside this scope is not judged.", [Evidence(e), cutoffEvidence], e.SceneID, absence: true);
|
|
}
|
|
}
|
|
if (progress.Count > 0 && closures.Count == 0 && actual is null)
|
|
Add("H012", context.BookID.HasValue && line.BookID == context.BookID ? PlotHealthLevel.Review : PlotHealthLevel.Information,
|
|
Status(thread, "Resolved", "Abandoned") ? "No positioned closure at evaluated cutoff" : context.BookID.HasValue ? "Open at end of evaluated book scope" : "Open at current project cutoff",
|
|
"Recorded activity has begun, but no positioned closure evidence is recorded by the evaluated cutoff. Stored status has no narrative effective date and is shown separately. Current scope end is not necessarily the author's intended final ending; no sequel intent is inferred.",
|
|
[Evidence(last!), cutoffEvidence], absence: true);
|
|
var signals = events.Select(e => e.CanonicalRole).Concat(events.Where(e => Structural(e, "Resolve", "Abandon")).Select(e => $"Structural {e.CanonicalStructuralType}")).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
|
|
threads.Add(new(line.PlotLineID, thread.PlotThreadID, thread.ThreadTitle, thread.ThreadStatusName,
|
|
signals, first is null ? null : Evidence(first), last is null ? null : Evidence(last), lastProgress is null ? null : Evidence(lastProgress),
|
|
first is null ? cutoff : positions[first.SceneID] - 1,
|
|
last is null ? null : cutoff - positions[last.SceneID], last is null ? null : Chapters(positions[last.SceneID], cutoff),
|
|
lastProgress is null ? null : cutoff - positions[lastProgress.SceneID], lastProgress is null ? null : Chapters(positions[lastProgress.SceneID], cutoff), findings));
|
|
}
|
|
lines.Add(new(line.PlotLineID, threads, threads.SelectMany(t => t.Findings).OrderByDescending(f => f.Level).ThenBy(f => f.RuleID).ToList()));
|
|
}
|
|
return new(scope, lines);
|
|
|
|
PlotHealthEvidence? SceneEvidence(int? sceneID, string signal, int? eventID = null) =>
|
|
sceneID.HasValue && scopeScenes.TryGetValue(sceneID.Value, out var scene)
|
|
? new(scene.SceneID, positions[scene.SceneID], scene.BookID, scene.ChapterID, scene.SceneTitle, signal, eventID) : null;
|
|
// Distinct identities in the traversed scenes, excluding the source chapter; chapter numbers never participate.
|
|
int Chapters(int from, int through) => ordered.Skip(from).Take(Math.Max(0, through - from))
|
|
.Select(s => (s.BookID, s.ChapterID)).Where(key => key != (ordered[from - 1].BookID, ordered[from - 1].ChapterID)).Distinct().Count();
|
|
}
|
|
private static bool Role(PlotLineWorkspaceContributionRow e, params string[] roles) => roles.Contains(e.CanonicalRole, StringComparer.OrdinalIgnoreCase);
|
|
private static bool Structural(PlotLineWorkspaceContributionRow e, params string[] types) => types.Contains(e.CanonicalStructuralType, StringComparer.OrdinalIgnoreCase);
|
|
private static bool Status(PlotLineWorkspaceThreadRow t, params string[] statuses) => statuses.Contains(t.ThreadStatusName, StringComparer.OrdinalIgnoreCase);
|
|
}
|