129 lines
12 KiB
C#
129 lines
12 KiB
C#
using System.Text.Json;
|
|
using PlotLine.Data;
|
|
using PlotLine.Models.WritingSolver;
|
|
using PlotLine.Services;
|
|
|
|
internal static class WritingSolverDeadEndTests
|
|
{
|
|
private static readonly JsonSerializerOptions Json=WritingSolverRepository.JsonOptions;
|
|
private static string Root=>WritingSolverCuratedV2Tests.Root();
|
|
public static string DirectoryPath=>Path.Combine(Root,"PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1-repair");
|
|
public static SolverGraph Graph()=>WritingSolverRepository.Parse(File.ReadAllText(Path.Combine(DirectoryPath,"writing-solver-curated-v2-stage1-repair.json")));
|
|
private static void Check(bool condition,string message){if(!condition)throw new Exception(message);}
|
|
public static void Run(string[] args)
|
|
{
|
|
var graph=JsonSerializer.Deserialize<SolverGraph>(File.ReadAllText(Path.Combine(DirectoryPath,"writing-solver-curated-v2-stage1-repair.json")),Json)!;
|
|
var before=Audit(WritingSolverStage1Tests.Graph());var after=Audit(graph);
|
|
var folder=Path.Combine(Root,"Docs/WritingSolver/CuratedV2/DeadEndRepair");Directory.CreateDirectory(folder);
|
|
var validation=WritingSolverValidator.Validate(graph);
|
|
File.WriteAllText(Path.Combine(folder,"audit.json"),JsonSerializer.Serialize(new{Before=before,After=after,Validation=validation},Json));
|
|
Console.WriteLine($"Before: {JsonSerializer.Serialize(before.Counts)}");Console.WriteLine($"After: {JsonSerializer.Serialize(after.Counts)}");
|
|
Console.WriteLine($"Traversal {after.Exploration.StateCount}, nodes {after.Exploration.Nodes.Count}/{graph.Nodes.Count}, solutions {after.Exploration.Solutions.Count}/52, primary {after.Exploration.PrimarySolutions.Length}; {string.Join("; ",validation)}");
|
|
if(args.Contains("--write-unused"))
|
|
{
|
|
var path=Path.Combine(folder,"unused-variants.json");var previous=File.Exists(path)?JsonSerializer.Deserialize<string[]>(File.ReadAllText(path),Json)!:[];
|
|
File.WriteAllText(path,JsonSerializer.Serialize(previous.Concat(graph.Nodes.Where(n=>!after.Exploration.Nodes.ContainsKey(n.Id)).Select(n=>n.Id)).Distinct().Order().ToArray(),Json));
|
|
}
|
|
if(args.Contains("--write-paths"))WritePaths(graph);
|
|
if(File.Exists(Path.Combine(DirectoryPath,"acceptance-paths.json")))
|
|
{
|
|
var replay=WritingSolverCuratedV2Tests.Replay(graph,Path.Combine(DirectoryPath,"acceptance-paths.json"));
|
|
Console.WriteLine($"Acceptance {replay.Count(c=>c.Pass && c.Warnings.Length==0)}/60; prefixes {WritingSolverCuratedV2Tests.MatchedPrefixes(replay,Path.Combine(DirectoryPath,"acceptance-paths.json"))}/{replay.Sum(c=>c.RequestedPath.Length)}");
|
|
foreach(var c in replay.Where(c=>!c.Pass||c.Warnings.Length>0))Console.WriteLine($"Case {c.Id}: {string.Join("; ",c.Errors.Concat(c.Warnings))}");
|
|
File.WriteAllText(Path.Combine(folder,"cases.json"),JsonSerializer.Serialize(replay,Json));
|
|
if(replay.Any(c=>!c.Pass||c.Warnings.Length>0))Environment.ExitCode=1;
|
|
}
|
|
if(validation.Count>0 || !after.Exploration.Complete || after.Counts.GetValueOrDefault("corroborated-without-result")>0 || after.Counts.GetValueOrDefault("budget-before-corroboration-question")>0 || after.Counts.GetValueOrDefault("unexplained-empty")>0)Environment.ExitCode=1;
|
|
}
|
|
public sealed record AuditReport(Dictionary<string,int> Counts,Dictionary<string,SolverAnswer[][]> Witnesses,WritingSolverCuratedV2Tests.Exploration Exploration);
|
|
public static AuditReport Audit(SolverGraph graph,Action<SolverOutcome>? inspect=null)
|
|
{
|
|
var counts=new Dictionary<string,int>();var witnesses=new Dictionary<string,List<SolverAnswer[]>>();
|
|
var traversal=WritingSolverCuratedV2Tests.Explore(graph,o=>
|
|
{
|
|
inspect?.Invoke(o);
|
|
if(o.Next is not null)return;
|
|
string kind;
|
|
if(o.Reassurance is not null)kind="authored-neutral";
|
|
else if(o.Solutions.Count>0)kind="diagnostic";
|
|
else
|
|
{
|
|
var corroborated=graph.Solutions.Any(s=>s.RequiredSignals.All(w=>o.Scores.GetValueOrDefault(w.Key)>=w.Value));
|
|
if(corroborated)kind="corroborated-without-result";
|
|
else if(o.Answers.Count==graph.MaxAnswers && !o.Answers.Any(a=>a.Node.StartsWith("check-")||a.Node.StartsWith("final-")))kind="budget-before-corroboration-question";
|
|
else if(o.Answers.LastOrDefault() is {} last && graph.Nodes.Single(n=>n.Id==last.Node).Choices.Any(c=>last.Choices.Contains(c.Id) && c.Id=="unsure"))kind="explicit-uncertainty";
|
|
else
|
|
{
|
|
var lastAnswer=o.Answers.LastOrDefault();
|
|
var explicitFallback=lastAnswer is not null && graph.Nodes.Single(n=>n.Id==lastAnswer.Node).Choices.Any(c=>lastAnswer.Choices.Contains(c.Id) && c.Fallback && c.Weights.Count==0);
|
|
kind=explicitFallback?"other-insufficient":"unexplained-empty";
|
|
}
|
|
}
|
|
counts[kind]=counts.GetValueOrDefault(kind)+1;
|
|
if(!witnesses.TryGetValue(kind,out var list))witnesses[kind]=list=[];
|
|
if(list.Count<8)list.Add(o.Answers.ToArray());
|
|
});
|
|
return new(counts,witnesses.ToDictionary(p=>p.Key,p=>p.Value.ToArray()),traversal);
|
|
}
|
|
public static void Regression()
|
|
{
|
|
var graph=Graph();var presentation=WritingSolverResultTests.Content();
|
|
var audit=Audit(graph,o=>
|
|
{
|
|
if(o.Scores.GetValueOrDefault("series")==0)Check(!o.Solutions.Any(s=>s.Id is "d50" or "d51"),"A cross-book result escaped without book evidence.");
|
|
if(o.Solutions.Count==0)return;
|
|
Check(o.Answers.Count>=4,"A diagnosis was reached before four meaningful answers.");
|
|
foreach(var solution in o.Solutions)Check(presentation.Evidence(o,solution.Id).Count>0 && presentation.Catalog.Evidence.Any(e=>e.Priority==100 && e.Solutions.Contains(solution.Id) && o.Answers.Any(a=>a.Node==e.Node && a.Choices.Contains(e.Choice))),"Repaired result lost its actual evidence explanation.");
|
|
});
|
|
Check(audit.Exploration.Complete && audit.Exploration.Errors.Length==0 && audit.Exploration.PrimarySolutions.Length==52,"Repair lost reachability or exceeded the ceiling.");
|
|
Check(audit.Counts.GetValueOrDefault("corroborated-without-result")==0,"A fully corroborated concern still ends without a result.");
|
|
Check(audit.Counts.GetValueOrDefault("budget-before-corroboration-question")==0,"Navigation exhausted the budget before offering a corroborating question.");
|
|
Check(audit.Counts.GetValueOrDefault("unexplained-empty")==0,"A substantive answer still silently ends without a diagnosis or authored neutral outcome.");
|
|
var original=WritingSolverStage1Tests.Graph();
|
|
foreach(var s in graph.Solutions){var old=original.Solutions.Single(p=>p.Id==s.Id);Check(s.Threshold==old.Threshold && s.Signals.OrderBy(p=>p.Key).SequenceEqual(old.Signals.OrderBy(p=>p.Key)) && s.RequiredSignals.OrderBy(p=>p.Key).SequenceEqual(old.RequiredSignals.OrderBy(p=>p.Key)),"Diagnosis coefficients, thresholds or evidence gates were weakened.");}
|
|
var cases=WritingSolverCuratedV2Tests.Replay(graph,Path.Combine(DirectoryPath,"acceptance-paths.json"));Check(cases.Length==60 && cases.All(c=>c.Pass && c.Warnings.Length==0),"Repaired canonical paths regressed.");
|
|
var tooMany=Follow(graph,"story-not-working","too-many","lost","unwanted");Check(tooMany.Solutions.FirstOrDefault()?.Id=="d01","Reported four-answer storyline memory complaint still has no result.");
|
|
var changedHypothesis=Follow(graph,"story-not-working","dont-connect","gap","unwanted");Check(changedHypothesis.Solutions.FirstOrDefault()?.Id=="d02","A corroborated alternative hypothesis still has no scoring evidence.");
|
|
var knowledge=Follow(graph,"losing-track","knowledge","checking","source");Check(knowledge.Solutions.FirstOrDefault()?.Id=="d22","Locating an existing learning event still has no result.");
|
|
var finalVoice=Follow(graph,"unsure","reread-cant-see","story-hangs-together","takes-over","voice","voice");Check(finalVoice.Solutions.FirstOrDefault()?.Id=="d12" && finalVoice.Answers.Count==6,"Final-slot corroboration did not collect the POV concern.");
|
|
var finalMain=Follow(graph,"unsure","reread-cant-see","story-hangs-together","takes-over","gaps","disappears");Check(finalMain.Solutions.FirstOrDefault()?.Id=="d02" && finalMain.Answers.Count==6,"An intended main plot still runs out of room to identify its supporting-thread problem.");
|
|
var longCast=Follow(graph,"unsure","reread-cant-see","characters-consistent","who-they-are","same-job","unwanted");Check(longCast.Solutions.FirstOrDefault()?.Id=="d09" && longCast.Answers.Count==6,"Long rescue navigation still displaces confirmation.");
|
|
var route=graph.Nodes.SelectMany(n=>n.Routes).First();var from=route.FromAnswers;var before=route.BeforeAnswers;
|
|
route.FromAnswers=4;route.BeforeAnswers=4;
|
|
Check(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("Invalid route answer range")),"Contradictory navigation ranges must be rejected.");
|
|
route.FromAnswers=from;route.BeforeAnswers=before;
|
|
Check(graph.RequireCorroboratedResults,"Repaired publication must enforce corroborated outcomes.");
|
|
var lost=graph.Nodes.Single(n=>n.Id=="check-threads-lost-apart").Choices.Single(c=>c.Id=="lost");
|
|
var saved=lost.Weights;lost.Weights=lost.Weights.Where(w=>w.Key.StartsWith("observed-")).ToDictionary(w=>w.Key,w=>w.Value);
|
|
Check(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("corroborated journey ends without a result")),"Actual publication validation must reject reintroduction of the reported scored-evidence omission.");lost.Weights=saved;
|
|
|
|
}
|
|
public static SolverOutcome Follow(SolverGraph graph,params string[] choices)
|
|
{
|
|
var history=new List<SolverAnswer>();var outcome=WritingSolverEngine.Evaluate(graph,history);
|
|
foreach(var choice in choices){Check(outcome.Next is not null,"Journey ended before its authored answer.");Check(outcome.Next!.Choices.Any(c=>c.Id==choice),$"Missing choice {choice} at {outcome.Next.Id}");history.Add(new(outcome.Next.Id,[choice]));outcome=WritingSolverEngine.Evaluate(graph,history);}
|
|
return outcome;
|
|
}
|
|
private static void WritePaths(SolverGraph graph)
|
|
{
|
|
var old=JsonSerializer.Deserialize<WritingSolverCuratedV2Tests.AcceptanceFile>(File.ReadAllText(Path.Combine(WritingSolverStage1Tests.DirectoryPath,"acceptance-paths.json")),Json)!;
|
|
var cases=old.Cases.Select(test=>
|
|
{
|
|
var history=new List<SolverAnswer>();var prefixes=new List<WritingSolverCuratedV2Tests.PrefixExpectation>();var outcome=WritingSolverEngine.Evaluate(graph,history);
|
|
while(outcome.Next is {} node)
|
|
{
|
|
var source=node.Id.StartsWith("final-")?"check-"+node.Id[6..]:node.Id;
|
|
var answer=test.Answers.FirstOrDefault(a=>a.Node==source);
|
|
// A reserved-tail family question can replace a redundant old detail question.
|
|
answer??=test.Answers.FirstOrDefault(a=>a.Node.StartsWith("check-"+source.Split('-')[1]) && a.Choices.All(id=>node.Choices.Any(c=>c.Id==id)));
|
|
Check(answer is not null,$"Case {test.Id}: no authored answer for {node.Id}.");
|
|
history.Add(new(node.Id,answer!.Choices));outcome=WritingSolverEngine.Evaluate(graph,history);
|
|
var expected=test.ExpectedPrimary is null?Array.Empty<string>():new[]{test.ExpectedPrimary}.Concat(test.RequiredSupporting).ToArray();
|
|
prefixes.Add(new(history.Count,outcome.Next?.Id,outcome.Next is null?expected:[]));
|
|
}
|
|
return test with{Answers=history.ToArray(),PrefixExpectations=prefixes.ToArray()};
|
|
}).ToArray();
|
|
File.WriteAllText(Path.Combine(DirectoryPath,"acceptance-paths.json"),JsonSerializer.Serialize(new WritingSolverCuratedV2Tests.AcceptanceFile(graph.Version,cases),Json));
|
|
}
|
|
}
|