169 lines
12 KiB
C#
169 lines
12 KiB
C#
using System.Text.RegularExpressions;
|
|
using PlotLine.Models.WritingSolver;
|
|
namespace PlotLine.Services;
|
|
|
|
public static partial class WritingSolverValidator
|
|
{
|
|
public static List<string> Validate(SolverGraph graph)
|
|
{
|
|
var errors = new List<string>();
|
|
void Check(bool condition, string message) { if (!condition) errors.Add(message); }
|
|
Check(graph.SchemaVersion == 1, "Unsupported schema version.");
|
|
Check(!string.IsNullOrWhiteSpace(graph.Version) && graph.Version.Length <= 80, "Version is required (maximum 80 characters).");
|
|
Check(graph.MinAnswers >= 1 && graph.MaxAnswers >= graph.MinAnswers && graph.MaxAnswers <= 6, "Answer limits must be between one and six.");
|
|
Check(graph.Nodes.Count is > 0 and <= 1000 && graph.Solutions.Count <= 1000 && graph.Features.Count <= 1000, "Graph size is invalid.");
|
|
void Unique(IEnumerable<string> ids, string label)
|
|
{
|
|
Check(ids.All(id => !string.IsNullOrWhiteSpace(id) && Slug().IsMatch(id)), $"Invalid {label} identifier.");
|
|
foreach (var group in ids.GroupBy(x => x, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1)) errors.Add($"Duplicate {label}: {group.Key}");
|
|
}
|
|
Unique(graph.Nodes.Select(n => n.Id), "node");
|
|
Unique(graph.Solutions.Select(n => n.Id), "solution");
|
|
Unique(graph.Features.Select(n => n.Id), "feature");
|
|
Unique(graph.Solutions.Select(n => n.Slug), "solution slug");
|
|
Unique(graph.Features.Select(n => n.Slug), "feature slug");
|
|
if (errors.Count > 0) return errors;
|
|
var nodes = graph.Nodes.ToDictionary(n => n.Id);
|
|
var features = graph.Features.ToDictionary(n => n.Id);
|
|
var solutions = graph.Solutions.ToDictionary(n => n.Id);
|
|
Check(nodes.TryGetValue(graph.EntryNode, out var entry) && entry.Active, "Missing/inactive entry node.");
|
|
var signalNames = graph.Nodes.SelectMany(n => n.Choices).SelectMany(c => c.Weights.Keys).ToHashSet();
|
|
void Weights(Dictionary<string,int> weights, string label)
|
|
{
|
|
Check(weights.All(w => Slug().IsMatch(w.Key) && w.Value is >= -100 and <= 100 && w.Value != 0), $"Malformed weights: {label}");
|
|
}
|
|
foreach (var node in graph.Nodes)
|
|
{
|
|
Check(node.Type is "area" or "question", $"Unknown node type: {node.Id}");
|
|
Check(!string.IsNullOrWhiteSpace(node.Title), $"Missing question: {node.Id}");
|
|
Check(node.MaxChoices == 0 || (node.Multiple && node.MaxChoices is >= 2 and <= 12), $"Invalid multi-select limit: {node.Id}");
|
|
Unique(node.Choices.Select(c => c.Id), $"choice in {node.Id}");
|
|
Check(!node.Active || node.Choices.Any(c => c.Active && c.Fallback), $"Missing fallback choice: {node.Id}");
|
|
void Reassurance(SolverReassurance? content, string label)
|
|
{
|
|
if (content is null) return;
|
|
Check(!string.IsNullOrWhiteSpace(content.Title) && !string.IsNullOrWhiteSpace(content.Summary), $"Missing neutral reassurance title/summary: {label}");
|
|
Check(content.Advice.Count <= 3 && content.Advice.All(a => !string.IsNullOrWhiteSpace(a)), $"Invalid neutral next steps: {label}");
|
|
Check(content.Feature is null || (features.TryGetValue(content.Feature, out var linked) && (!node.Active || linked.Active)), $"Missing/inactive neutral feature: {label}");
|
|
}
|
|
if (node.NeutralEndpoint)
|
|
{
|
|
Check(node.Routes.Count == 0 && !node.Multiple && node.Affinity.Count == 0, $"Neutral endpoint must be terminal, single-choice and have no routing affinity: {node.Id}");
|
|
Check(node.Choices.All(c => c.Weights.Count == 0), $"Neutral endpoint must not create diagnostic evidence: {node.Id}");
|
|
Check(node.Reassurance is not null, $"Missing neutral endpoint fallback reassurance: {node.Id}");
|
|
}
|
|
else Check(node.Reassurance is null && (node.AllowNeutralChoices || node.Choices.All(c => c.Reassurance is null)), $"Reassurance requires an explicit neutral endpoint: {node.Id}");
|
|
Check(!node.AllowNeutralChoices || (!node.NeutralEndpoint && !node.Multiple && node.Choices.Any(c => c.Reassurance is not null)), $"Neutral choices require a single-choice diagnostic question with explicit reassurance: {node.Id}");
|
|
foreach (var choice in node.Choices.Where(c => node.AllowNeutralChoices && c.Reassurance is not null))
|
|
Check(choice.Weights.Count == 0 && !node.Routes.Any(r => r.Choice is null || r.Choice == choice.Id), $"Neutral choice must have no evidence or onward route: {node.Id}/{choice.Id}");
|
|
Reassurance(node.Reassurance, node.Id);
|
|
foreach (var choice in node.Choices) Reassurance(choice.Reassurance, $"{node.Id}/{choice.Id}");
|
|
Weights(node.Affinity, node.Id);
|
|
Check(node.Affinity.Keys.All(signalNames.Contains), $"Unknown affinity signal: {node.Id}");
|
|
foreach (var choice in node.Choices)
|
|
{
|
|
Check(!string.IsNullOrWhiteSpace(choice.Text), $"Missing choice text: {node.Id}/{choice.Id}");
|
|
Weights(choice.Weights, $"{node.Id}/{choice.Id}");
|
|
}
|
|
foreach (var route in node.Routes)
|
|
{
|
|
Check(route.FromAnswers >= 0 && route.FromAnswers < graph.MaxAnswers && (route.BeforeAnswers == 0 || (route.BeforeAnswers > route.FromAnswers && route.BeforeAnswers <= graph.MaxAnswers)), $"Invalid route answer range: {node.Id} -> {route.Target}");
|
|
Check(nodes.TryGetValue(route.Target, out var target) && (!node.Active || target.Active), $"Missing/inactive target: {node.Id} -> {route.Target}");
|
|
Check(route.Choice is null || node.Choices.Any(c => c.Active && c.Id == route.Choice), $"Invalid route choice: {node.Id}");
|
|
Check(route.Signal is null || signalNames.Contains(route.Signal), $"Unknown route signal: {node.Id}");
|
|
if (route.Signal is not null)
|
|
{
|
|
var maximum = graph.Nodes.Where(n => n.Active).Select(n => n.Choices.Where(c => c.Active).Select(c => Math.Max(0,c.Weights.GetValueOrDefault(route.Signal))).DefaultIfEmpty().Sum()).Sum();
|
|
Check(route.Minimum <= maximum, $"Impossible signal route: {node.Id} -> {route.Target}");
|
|
}
|
|
}
|
|
}
|
|
foreach (var page in graph.Solutions.Cast<SolverPage>().Concat(graph.Features))
|
|
{
|
|
Check(!string.IsNullOrWhiteSpace(page.Title) && !string.IsNullOrWhiteSpace(page.PageTitle) && !string.IsNullOrWhiteSpace(page.Description) && !string.IsNullOrWhiteSpace(page.Summary) && !string.IsNullOrWhiteSpace(page.Content), $"Missing editorial/SEO fields: {page.Id}");
|
|
var image = page.SocialImage;
|
|
Check(image is null || image.StartsWith("/images/", StringComparison.Ordinal), $"Invalid social image: {page.Id}");
|
|
}
|
|
foreach (var feature in graph.Features)
|
|
Check(feature.Screenshot is null || feature.Screenshot.StartsWith("/images/", StringComparison.Ordinal), $"Invalid screenshot: {feature.Id}");
|
|
foreach (var solution in graph.Solutions)
|
|
{
|
|
Weights(solution.Signals, solution.Id);
|
|
Check(solution.RequiredSignals.All(w => signalNames.Contains(w.Key) && w.Value is > 0 and <= 100), $"Invalid required diagnostic evidence: {solution.Id}");
|
|
Check(solution.Threshold > 0 && solution.Signals.Count > 0 && solution.Signals.Keys.All(signalNames.Contains), $"Invalid diagnosis signals: {solution.Id}");
|
|
Check(solution.Features.Count > 0 && solution.Features.Any(f => f.Primary), $"Missing primary feature: {solution.Id}");
|
|
Unique(solution.Features.Select(f => f.Feature), $"feature mapping in {solution.Id}");
|
|
foreach (var link in solution.Features)
|
|
Check(features.TryGetValue(link.Feature, out var feature) && (!solution.Active || feature.Active), $"Invalid feature mapping: {solution.Id}/{link.Feature}");
|
|
foreach (var related in solution.Related)
|
|
Check(solutions.TryGetValue(related, out var other) && (!solution.Active || other.Active), $"Invalid related solution: {solution.Id}/{related}");
|
|
}
|
|
if (errors.Count > 0) return errors;
|
|
var reachable = new HashSet<string>();
|
|
var visiting = new HashSet<string>();
|
|
void Visit(string id)
|
|
{
|
|
if (!visiting.Add(id)) return;
|
|
reachable.Add(id);
|
|
foreach (var route in nodes[id].Routes)
|
|
{
|
|
if (visiting.Contains(route.Target) && !route.AllowCycle) errors.Add($"Unpermitted cycle: {id} -> {route.Target}");
|
|
else if (!reachable.Contains(route.Target)) Visit(route.Target);
|
|
}
|
|
visiting.Remove(id);
|
|
}
|
|
Visit(graph.EntryNode);
|
|
foreach (var node in graph.Nodes.Where(n => n.Active && !reachable.Contains(n.Id))) errors.Add($"Unreachable node: {node.Id}");
|
|
foreach (var solution in graph.Solutions.Where(s => s.Active))
|
|
{
|
|
var upperBound = graph.Nodes.Where(n => n.Active && reachable.Contains(n.Id)).Select(n =>
|
|
{
|
|
var values = n.Choices.Where(c => c.Active).Select(c => c.Weights.Sum(w => w.Value * solution.Signals.GetValueOrDefault(w.Key))).ToArray();
|
|
return n.Multiple ? values.Where(v => v > 0).Sum() : values.DefaultIfEmpty().Max();
|
|
}).OrderDescending().Take(graph.MaxAnswers).Sum();
|
|
Check(upperBound >= solution.Threshold, $"Unreachable solution (insufficient signals): {solution.Id}");
|
|
}
|
|
foreach (var node in graph.Nodes.Where(n => n.Active && n.Routes.Count == 0))
|
|
Check(node.NeutralEndpoint || node.Choices.Any(c => c.Weights.Keys.Any(k => graph.Solutions.Any(s => s.Active && (s.Signals.ContainsKey(k) || s.RequiredSignals.ContainsKey(k))))), $"Dead end without diagnostic evidence: {node.Id}");
|
|
if (errors.Count == 0) errors.AddRange(ValidateJourneys(graph));
|
|
return errors;
|
|
}
|
|
|
|
private static List<string> ValidateJourneys(SolverGraph graph)
|
|
{
|
|
var errors = new List<string>();
|
|
if (graph.Nodes.Any(n => n.Active && n.Multiple && n.Choices.Count(c => c.Active && !c.Fallback) > 12))
|
|
return ["Split multi-select nodes with more than 12 substantive choices to keep exhaustive validation bounded."];
|
|
var pending = new Queue<SolverOutcome>();
|
|
var initial = WritingSolverEngine.Evaluate(graph,[]);
|
|
pending.Enqueue(initial);
|
|
var discovered = new HashSet<string> { WritingSolverTraversal.Key(initial) };
|
|
var reached = new HashSet<string>();
|
|
var diagnosed = new HashSet<string>();
|
|
while (pending.TryDequeue(out var outcome))
|
|
{
|
|
if (graph.RequireCorroboratedResults && outcome.Next is null && outcome.Reassurance is null && outcome.Solutions.Count == 0
|
|
&& graph.Solutions.Any(s => s.Active && s.RequiredSignals.Count > 0 && s.RequiredSignals.All(w => outcome.Scores.GetValueOrDefault(w.Key) >= w.Value)))
|
|
return ["A corroborated journey ends without a result. Supply its actual scored evidence; do not weaken its evidence gates or diagnosis threshold."];
|
|
foreach(var solution in outcome.Solutions) diagnosed.Add(solution.Id);
|
|
if (outcome.Next is not { } node) continue;
|
|
reached.Add(node.Id);
|
|
foreach(var history in WritingSolverTraversal.Extensions(outcome))
|
|
{
|
|
var next = WritingSolverEngine.Evaluate(graph,history);
|
|
if (!discovered.Add(WritingSolverTraversal.Key(next))) continue;
|
|
if (discovered.Count > 100000) return ["Journey validation exceeded 100,000 distinct states. Simplify the graph or split redundant choices; no data has been published."];
|
|
pending.Enqueue(next);
|
|
}
|
|
}
|
|
errors.AddRange(graph.Nodes.Where(n=>n.Active && !reached.Contains(n.Id)).Select(n=>$"Unreachable node under scoring/routing rules: {n.Id}"));
|
|
errors.AddRange(graph.Solutions.Where(s=>s.Active && !diagnosed.Contains(s.Id)).Select(s=>$"Unreachable solution under scoring/routing rules: {s.Id}"));
|
|
return errors;
|
|
}
|
|
public static List<string> Warnings(SolverGraph graph) => graph.Features.Where(f => f.Active)
|
|
.Where(f => graph.Solutions.Count(s => s.Active && s.Features.Any(l => l.Feature == f.Id)) < 2)
|
|
.Select(f => $"Few solution routes to feature: {f.Id}").ToList();
|
|
[GeneratedRegex("^[a-z0-9]+(?:-[a-z0-9]+)*$")]
|
|
private static partial Regex Slug();
|
|
}
|