using System.Text.Json; using PlotLine.Data; using PlotLine.Models.WritingSolver; using PlotLine.Services; // Validation-only: no connection factory, publication API or live database is used. internal static class WritingSolverCuratedV2Tests { private static readonly JsonSerializerOptions Json = WritingSolverRepository.JsonOptions; public sealed record PrefixExpectation(int AfterAnswers, string? ExpectedNext, string[] ExpectedResults); public sealed record AcceptanceCase(int Id, string Complaint, SolverAnswer[] Answers, PrefixExpectation[] PrefixExpectations, string? ExpectedPrimary, string[] AcceptableSupporting, string[] RequiredSupporting, string[] ForbiddenResults, string Notes); public sealed record AcceptanceFile(string Version, AcceptanceCase[] Cases); public sealed record Score(string Id, int Value, int Threshold, bool Qualified); public sealed record Step(SolverAnswer Answer, string? Next, Dictionary Signals, Score[] Scores, string[] Results); public sealed record CaseResult(int Id, string Complaint, SolverAnswer[] RequestedPath, SolverAnswer[] AcceptedPath, string? ExpectedPrimary, string[] AcceptableSupporting, string[] RequiredSupporting, string[] ForbiddenResults, Step[] Prefixes, Dictionary Signals, Score[] Scores, string? Primary, string[] Supporting, string? Next, bool Pass, string[] Errors, string[] Warnings); public sealed record Exploration(int StateCount, long Attempts, int PeakQueue, bool Complete, Dictionary Nodes, Dictionary Solutions, string[] PrimarySolutions, int TerminalStates, int NeutralTerminalStates, int MaximumAnswers, string[] Errors); public static string Root() { var directory=new DirectoryInfo(AppContext.BaseDirectory); while(directory is not null && !File.Exists(Path.Combine(directory.FullName,"PlotLine.slnx"))) directory=directory.Parent; return directory?.FullName ?? throw new InvalidOperationException("Repository root missing."); } public static string DirectoryPath => Path.Combine(Root(),"PlotLine/Content/WritingSolver/Candidates/curated-v2"); public static SolverGraph Graph() => JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(DirectoryPath,"writing-solver-curated-v2.json")),Json) ?? throw new InvalidDataException("Empty graph."); private static AcceptanceCase[] Cases() => JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(DirectoryPath,"acceptance-paths.json")),Json)!.Cases; private static void Require(bool condition,string message) { if(!condition) throw new Exception(message); } private static Score[] Scores(SolverGraph graph,SolverOutcome outcome) => graph.Solutions.Where(s=>s.Active) .Select(s=>new Score(s.Id,s.Signals.Sum(w=>outcome.Scores.GetValueOrDefault(w.Key)*w.Value),s.Threshold,false)) .Select(s=>s with {Qualified=s.Value>=s.Threshold}).OrderByDescending(s=>s.Value) .ThenBy(s=>graph.Solutions.Single(d=>d.Id==s.Id).Order).ThenBy(s=>s.Id,StringComparer.Ordinal).ToArray(); public static CaseResult[] Replay(SolverGraph graph) { var cases=Cases(); Require(cases.Length==60 && cases.Select(c=>c.Id).Order().SequenceEqual(Enumerable.Range(1,60)),"Exactly the supplied 60 case IDs must be tested."); return cases.Select(test=> { var errors=new List(); var warnings=new List(); var steps=new List(); var history=new List(); var outcome=WritingSolverEngine.Evaluate(graph,history); if(test.PrefixExpectations.Length!=test.Answers.Length || !test.PrefixExpectations.Select(p=>p.AfterAnswers).Order().SequenceEqual(Enumerable.Range(1,test.Answers.Length))) errors.Add("Every submitted answer needs exactly one prefix expectation."); foreach(var answer in test.Answers) { if(outcome.Next?.Id!=answer.Node) { errors.Add($"After {history.Count} answers: expected question {answer.Node}, actual {outcome.Next?.Id ?? "terminal"}."); break; } history.Add(answer); outcome=WritingSolverEngine.Evaluate(graph,history); if(outcome.Answers.Count!=history.Count) {errors.Add("The engine rejected this choice combination.");break;} var ids=outcome.Solutions.Select(s=>s.Id).ToArray(); steps.Add(new(answer,outcome.Next?.Id,new(outcome.Scores),Scores(graph,outcome),ids)); var expected=test.PrefixExpectations.SingleOrDefault(p=>p.AfterAnswers==history.Count); if(expected is not null) { if(expected.ExpectedNext!=outcome.Next?.Id) errors.Add($"Prefix {history.Count}: next expected {expected.ExpectedNext ?? "terminal"}, actual {outcome.Next?.Id ?? "terminal"}."); if(!expected.ExpectedResults.SequenceEqual(ids)) errors.Add($"Prefix {history.Count}: results expected [{string.Join(",",expected.ExpectedResults)}], actual [{string.Join(",",ids)}]."); } foreach(var forbidden in ids.Intersect(test.ForbiddenResults)) errors.Add($"Prefix {history.Count}: forbidden result {forbidden} was returned."); } var primary=outcome.Solutions.FirstOrDefault()?.Id; var supporting=outcome.Solutions.Skip(1).Select(s=>s.Id).ToArray(); if(primary!=test.ExpectedPrimary) errors.Add($"Expected primary {test.ExpectedPrimary ?? "none"}, actual {primary ?? "none"}."); foreach(var required in test.RequiredSupporting.Except(supporting)) errors.Add($"Required supporting result missing: {required}."); foreach(var id in supporting.Except(test.AcceptableSupporting)) warnings.Add($"Supporting result {id} is present in the explicit prefix expectation but absent from acceptableSupporting; reconcile the supplied metadata."); foreach(var conflict in test.AcceptableSupporting.Intersect(test.ForbiddenResults)) warnings.Add($"{conflict} is both acceptable and forbidden in the supplied metadata; the explicit forbidden rule takes precedence."); return new CaseResult(test.Id,test.Complaint,test.Answers,outcome.Answers.ToArray(),test.ExpectedPrimary,test.AcceptableSupporting,test.RequiredSupporting,test.ForbiddenResults, steps.ToArray(),new(outcome.Scores),Scores(graph,outcome),primary,supporting,outcome.Next?.Id,errors.Count==0,errors.ToArray(),warnings.ToArray()); }).ToArray(); } // Faithful instrumentation of the existing validator traversal, including its exact // history/score key and seen+pending ceiling. This intentionally does not replace it. public static Exploration Explore(SolverGraph graph) { var pending=new Queue();pending.Enqueue([]); var seen=new HashSet();var nodes=new Dictionary();var solutions=new Dictionary(); var primary=new HashSet();var errors=new List();long attempts=0;var peak=1;var terminals=0;var neutral=0;var maximum=0;var complete=true; while(pending.TryDequeue(out var history)) { attempts++; 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) {errors.Add("The real validator's seen+pending ceiling was exceeded.");complete=false;break;} maximum=Math.Max(maximum,outcome.Answers.Count); foreach(var solution in outcome.Solutions) solutions.TryAdd(solution.Id,outcome.Answers.ToArray()); if(outcome.Solutions.FirstOrDefault() is { } winner) primary.Add(winner.Id); if(outcome.Next is not { } node) {terminals++;if(outcome.Solutions.Count==0) neutral++;continue;} nodes.TryAdd(node.Id,outcome.Answers.ToArray()); foreach(var choice in node.Choices.Where(c=>c.Active)) pending.Enqueue([..history,new(node.Id,[choice.Id])]); if(node.Multiple) { var substantive=node.Choices.Where(c=>c.Active && !c.Fallback).ToArray(); Require(substantive.Length<=12,$"Too many multi-select choices at {node.Id}."); for(var mask=1;mask<(1<(mask & (1<c.Id).ToArray(); pending.Enqueue([..history,new(node.Id,ids)]); } } peak=Math.Max(peak,pending.Count); } errors.AddRange(graph.Nodes.Where(n=>n.Active && !nodes.ContainsKey(n.Id)).Select(n=>$"Unreachable active node: {n.Id}")); errors.AddRange(graph.Solutions.Where(s=>s.Active && !solutions.ContainsKey(s.Id)).Select(s=>$"Unreachable active solution: {s.Id}")); return new(seen.Count,attempts,peak,complete,nodes,solutions,primary.Order(StringComparer.Ordinal).ToArray(),terminals,neutral,maximum,errors.ToArray()); } public static void Acceptance() { var results=Replay(Graph()); Require(results.All(r=>r.Pass),string.Join("; ",results.Where(r=>!r.Pass).Select(r=>$"Case {r.Id}: {string.Join(" ",r.Errors)}"))); } public static void ReachabilityAndRevision() { var graph=Graph();var exploration=Explore(graph); Require(exploration.Complete && exploration.Errors.Length==0,string.Join("; ",exploration.Errors)); Require(exploration.StateCount==11325,$"Expected the supplied 11,325 states, actual {exploration.StateCount}."); Require(exploration.Nodes.Count==44 && exploration.Solutions.Count==52,"Reachability differs from the supplied assembly report."); foreach(var test in Cases()) { foreach(var prefix in Enumerable.Range(0,test.Answers.Length+1)) { var history=test.Answers.Take(prefix).ToArray();var outcome=WritingSolverEngine.Evaluate(graph,history); Require(outcome.Answers.Count==history.Length,$"Case {test.Id} prefix {prefix} was rejected."); Require(outcome.Answers.Select(a=>a.Node).Distinct().Count()==history.Length,"Question repeated."); var replay=WritingSolverEngine.Evaluate(graph,history); Require(outcome.Next?.Id==replay.Next?.Id && outcome.Scores.OrderBy(s=>s.Key).SequenceEqual(replay.Scores.OrderBy(s=>s.Key)),"Replay/Forward changed the outcome."); } } var original=Cases().Single(c=>c.Id==20).Answers; var revised=original.ToArray();revised[0]=new("entry",["feels-wrong"]); var after=WritingSolverEngine.Evaluate(graph,revised); Require(after.Answers.Count==1 && after.Next?.Id=="feel-where" && !after.Scores.ContainsKey("knowledge"),"Revision retained stale answers or knowledge scores."); foreach(var multi in graph.Nodes.Where(n=>n.Multiple)) { var path=exploration.Nodes[multi.Id]; foreach(var fallback in multi.Choices.Where(c=>c.Active && c.Fallback)) { var one=multi.Choices.First(c=>c.Active && !c.Fallback); var invalid=WritingSolverEngine.Evaluate(graph,[..path,new(multi.Id,[one.Id,fallback.Id])]); Require(invalid.Answers.Count==path.Length,"Fallback was combined with another answer."); var single=WritingSolverEngine.Evaluate(graph,[..path,new(multi.Id,[one.Id])]); var duplicate=WritingSolverEngine.Evaluate(graph,[..path,new(multi.Id,[one.Id,one.Id])]); Require(single.Scores.OrderBy(s=>s.Key).SequenceEqual(duplicate.Scores.OrderBy(s=>s.Key)),"Duplicate selections amplified weights."); } } } private sealed class NoDatabaseConnection : ISqlConnectionFactory { public int Calls { get; private set; } public System.Data.IDbConnection CreateConnection() { Calls++; throw new InvalidOperationException("Validation-only test must never open a database connection."); } } public static void ExistingValidatorBoundary() { var errors=WritingSolverValidator.Validate(Graph()); Require(errors.SequenceEqual(new[]{"Dead end without diagnostic evidence: existing-barrier"}),"The known neutral adoption endpoint blocker changed: "+string.Join("; ",errors)); var connections=new NoDatabaseConnection(); try { new WritingSolverRepository(connections).PublishAsync(File.ReadAllText(Path.Combine(DirectoryPath,"writing-solver-curated-v2.json")),"validation-only").GetAwaiter().GetResult(); throw new Exception("The current publication guard accepted a rejected graph."); } catch(InvalidDataException exception) { Require(exception.Message.Contains("existing-barrier") && connections.Calls==0,"Publication did not reject before opening a database connection."); } } public static void Run(string[] args) { var graph=Graph();var validation=WritingSolverValidator.Validate(graph);var exploration=Explore(graph);var results=Replay(graph); var reportIndex=Array.IndexOf(args,"--report"); var report=reportIndex<0 ? Path.Combine(Root(),"Docs/WritingSolver/CuratedV2/results.json") : args[reportIndex+1]; var lengths=results.Select(r=>r.AcceptedPath.Length).Order().ToArray(); var signals=graph.Nodes.SelectMany(n=>n.Choices).SelectMany(c=>c.Weights.Keys).Distinct().Order().ToArray(); var witness=exploration.Nodes.GetValueOrDefault("existing-barrier") ?? []; var neutral=graph.Nodes.Single(n=>n.Id=="existing-barrier").Choices.Where(c=>c.Active).Select(choice=> { var outcome=WritingSolverEngine.Evaluate(graph,[..witness,new("existing-barrier",[choice.Id])]); return new {Choice=choice.Id,Path=outcome.Answers,Signals=outcome.Scores,Scores=Scores(graph,outcome),Next=outcome.Next?.Id,Results=outcome.Solutions.Select(s=>s.Id).ToArray()}; }).ToArray(); Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(report))!); File.WriteAllText(report,JsonSerializer.Serialize(new {graph.Version,Counts=new {Signals=signals.Length,Nodes=graph.Nodes.Count,Solutions=graph.Solutions.Count,Features=graph.Features.Count}, ValidationPassed=validation.Count==0,ValidationErrors=validation,Exploration=exploration,Passed=results.Count(r=>r.Pass),Total=results.Length, JourneyLengths=new {Min=lengths.Min(),Median=(lengths[29]+lengths[30])/2.0,Mean=lengths.Average(),Max=lengths.Max(),ContinuingCases=results.Where(r=>r.Next is not null).Select(r=>r.Id).ToArray()}, NeutralAdoptionWitnesses=neutral,Results=results},Json)+"\n"); Console.WriteLine($"Actual validator: {(validation.Count==0 ? "PASS" : "FAIL")}; {string.Join("; ",validation)}"); Console.WriteLine($"Exploration: {exploration.StateCount} states, {exploration.Nodes.Count}/44 nodes, {exploration.Solutions.Count}/52 solutions, complete={exploration.Complete}."); Console.WriteLine($"Acceptance: {results.Count(r=>r.Pass)}/60. Lengths {lengths.Min()}–{lengths.Max()}, median {(lengths[29]+lengths[30])/2.0}, mean {lengths.Average():F2}."); foreach(var result in results.Where(r=>!r.Pass)) Console.WriteLine($"Case {result.Id}: {string.Join(" ",result.Errors)}"); if(validation.Count>0 || !exploration.Complete || exploration.Errors.Length>0 || results.Any(r=>!r.Pass)) Environment.ExitCode=1; } }