using System.Text.RegularExpressions; using PlotLine.Models.WritingSolver; namespace PlotLine.Services; public static partial class WritingSolverValidator { public static List Validate(SolverGraph graph) { var errors = new List(); 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 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 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}"); 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}"); 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(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().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.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(); var visiting = new HashSet(); 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.Choices.Any(c => c.Weights.Keys.Any(k => graph.Solutions.Any(s => s.Active && s.Signals.ContainsKey(k)))), $"Dead end without diagnostic evidence: {node.Id}"); if (errors.Count == 0) errors.AddRange(ValidateJourneys(graph)); return errors; } private static List ValidateJourneys(SolverGraph graph) { var errors = new List(); 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(); pending.Enqueue([]); var seen = new HashSet(); var reached = new HashSet(); var diagnosed = new HashSet(); while (pending.TryDequeue(out var history)) { var outcome = WritingSolverEngine.Evaluate(graph, history); var key = string.Join(",", outcome.Answers.Select(a => a.Node)) + ":" + string.Join(",",outcome.Scores.OrderBy(s=>s.Key).Select(s=>$"{s.Key}={s.Value}")) + ":" + outcome.Next?.Id; if (!seen.Add(key)) continue; if (seen.Count + pending.Count > 100000) return ["Journey validation exceeded 100,000 distinct states. Simplify the graph or split redundant choices; no data has been published."]; foreach(var solution in outcome.Solutions) diagnosed.Add(solution.Id); if (outcome.Next is not { } node) continue; reached.Add(node.Id); var choices = node.Choices.Where(c=>c.Active).ToArray(); foreach(var choice in choices) pending.Enqueue([..history,new(node.Id,[choice.Id])]); if (node.Multiple) { var substantive = choices.Where(c=>!c.Fallback).ToArray(); for(var mask=1;mask<(1<(mask & (1<c.Id).ToArray(); pending.Enqueue([..history,new(node.Id,ids)]); } } } 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 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(); }