using System.Text.Json; using PlotLine.Data; using PlotLine.Models.WritingSolver; using PlotLine.Services; internal static class WritingSolverStage1Tests { 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"); public static SolverGraph Graph() => WritingSolverRepository.Parse(File.ReadAllText(Path.Combine(DirectoryPath,"writing-solver-curated-v2-stage1.json"))); private static void Require(bool condition,string message) { if(!condition) throw new Exception(message); } public static void Run(string[] args) { // Read without Parse so failed traversal still produces its evidence report. var graph=JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(DirectoryPath,"writing-solver-curated-v2-stage1.json")),Json)!; var folder=Path.Combine(Root,"Docs/WritingSolver/CuratedV2/Stage1");Directory.CreateDirectory(folder); var before=WritingSolverCuratedV2Tests.Graph(); var oldDepth=Depths(before);var newDepth=Depths(graph); var validation=WritingSolverValidator.Validate(graph); var terminalKinds=new Dictionary();var resultPresence=new Dictionary();var primaryFrequency=new Dictionary();var noSeriesD50Max=0; var exploration=WritingSolverCuratedV2Tests.Explore(graph,outcome=> { if(outcome.Scores.GetValueOrDefault("series")==0) { var d50=graph.Solutions.Single(s=>s.Id=="d50");noSeriesD50Max=Math.Max(noSeriesD50Max,d50.Signals.Sum(w=>outcome.Scores.GetValueOrDefault(w.Key)*w.Value)); Require(!outcome.Solutions.Any(s=>s.Id is "d50" or "d51"),"A cross-book diagnosis escaped without series evidence."); } if(outcome.Next is not null)return; var kind=outcome.Reassurance is not null?"authored-reassurance":outcome.Solutions.Count>0?"diagnostic":outcome.Answers.Count==graph.MaxAnswers?"insufficient-at-budget":"insufficient-before-budget"; terminalKinds[kind]=terminalKinds.GetValueOrDefault(kind)+1; foreach(var solution in outcome.Solutions)resultPresence[solution.Id]=resultPresence.GetValueOrDefault(solution.Id)+1; if(outcome.Solutions.FirstOrDefault() is {} primary)primaryFrequency[primary.Id]=primaryFrequency.GetValueOrDefault(primary.Id)+1; }); File.WriteAllText(Path.Combine(folder,"traversal.json"),JsonSerializer.Serialize(new {Validation=validation,Exploration=exploration,Before=oldDepth,After=newDepth,TerminalKinds=terminalKinds,ResultPresence=resultPresence,PrimaryFrequency=primaryFrequency,NoSeriesD50Maximum=noSeriesD50Max},Json)); Console.WriteLine($"Validation: {string.Join("; ",validation)}; states {exploration.StateCount}; nodes {exploration.Nodes.Count}/{graph.Nodes.Count}; solutions {exploration.Solutions.Count}; primary {exploration.PrimarySolutions.Length}"); var file=Path.Combine(DirectoryPath,"acceptance-paths.json"); if(args.Contains("--write-paths"))File.WriteAllText(file,JsonSerializer.Serialize(new WritingSolverCuratedV2Tests.AcceptanceFile(graph.Version,ExtendCases(graph)),Json)); var cases=JsonSerializer.Deserialize(File.ReadAllText(file),Json)!.Cases; var results=WritingSolverCuratedV2Tests.Replay(graph,file); File.WriteAllText(Path.Combine(folder,"acceptance-results.json"),JsonSerializer.Serialize(results,Json)); foreach(var result in results.Where(r=>!r.Pass || r.Warnings.Length>0))Console.WriteLine($"Case {result.Id}: {string.Join("; ",result.Errors.Concat(result.Warnings))}"); Console.WriteLine($"Acceptance {results.Count(r=>r.Pass)}/60; prefixes {WritingSolverCuratedV2Tests.MatchedPrefixes(results,file)}/{cases.Sum(c=>c.Answers.Length)}"); Require(validation.Count==0 && exploration.Complete && exploration.Errors.Length==0 && exploration.PrimarySolutions.Length==52,"Stage 1 validation/reachability gate failed."); Require(results.All(r=>r.Pass && r.Warnings.Length==0),"Stage 1 acceptance gate failed."); Require(newDepth.All(d=>d.Minimum>=4),"A diagnosis resolves before four evidence-bearing answers."); SemanticsAndRevision(graph,cases); Console.WriteLine("PASS Stage 1 full traversal, reviewed 60 paths/prefixes, intentional outcomes and revision"); } public static void Verification() { var graph=Graph(); var cases=JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(DirectoryPath,"acceptance-paths.json")),Json)!.Cases; var results=WritingSolverCuratedV2Tests.Replay(graph,Path.Combine(DirectoryPath,"acceptance-paths.json")); Require(results.Length==60 && results.All(r=>r.Pass && r.Warnings.Length==0),"Stage 1 strict 60-case/prefix/support/forbidden regression."); var traversal=WritingSolverCuratedV2Tests.Explore(graph,o=>{if(o.Scores.GetValueOrDefault("series")==0)Require(!o.Solutions.Any(s=>s.Id is "d50" or "d51"),"Cross-book diagnosis without series evidence.");}); Require(traversal.Complete && traversal.Errors.Length==0 && traversal.Nodes.Count==graph.Nodes.Count && traversal.Solutions.Count==52 && traversal.PrimarySolutions.Length==52,"Stage 1 exhaustive reachability regression."); SemanticsAndRevision(graph,cases); var endpoint=graph.Nodes.Single(n=>n.NeutralEndpoint); foreach(var choice in endpoint.Choices) { var result=WritingSolverEngine.Evaluate(graph,[..traversal.Nodes[endpoint.Id],new(endpoint.Id,[choice.Id])]); Require(result.Reassurance== (choice.Reassurance??endpoint.Reassurance) && result.Solutions.Count==0 && result.Next is null,"Adoption regression."); } Require(new[]{4,5,6}.All(depth=>cases.Any(c=>c.ExpectedPrimary is not null && c.Answers.Length==depth)),"Missing representative journey depth."); } public static void Framework() { var graph=Graph(); Require(graph.Nodes.Single(n=>n.Id=="entry").Choices.Where(c=>!c.Fallback).Select(c=>c.Icon).Distinct().Count()==6,"Opening icons must be distinct."); var prefix=new[]{new SolverAnswer("entry",["losing-track"])}; var rejected=WritingSolverEngine.Evaluate(graph,[..prefix,new("track-what",["people","time","plots"])]); Require(rejected.Answers.Count==1 && rejected.Next?.Id=="track-what","Server must reject an over-limit selection."); var pair=WritingSolverEngine.Evaluate(graph,[..prefix,new("track-what",["knowledge","objects"])]); Require(pair.Answers.Count==2 && pair.Next is not null,"Two-area selection must work."); // Removing corroboration must suppress a high-scoring hypothesis, not lower its score. var paths=JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(DirectoryPath,"acceptance-paths.json")),Json)!.Cases; var dominance=paths.Single(c=>c.Id==3).Answers; var early=WritingSolverEngine.Evaluate(graph,dominance.Take(2)); var d04=graph.Solutions.Single(s=>s.Id=="d04"); Require(d04.Signals.Sum(w=>early.Scores.GetValueOrDefault(w.Key)*w.Value)>=d04.Threshold && early.Solutions.Count==0 && early.Next?.Id=="dominance-observation","A hypothesis score must not skip the discriminator."); var confirms=graph.Nodes.Single(n=>n.Id=="dominance-intention").Choices.Single(c=>c.Id=="even"); var saved=confirms.Weights;confirms.Weights=[]; Require(WritingSolverEngine.Evaluate(graph,dominance).Solutions.Count==0,"A score without confirming evidence must not qualify.");confirms.Weights=saved; var invalid=graph.Solutions[0];invalid.RequiredSignals["unknown-evidence"]=1; Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("required diagnostic evidence")),"Unknown evidence gates must be rejected.");invalid.RequiredSignals.Remove("unknown-evidence"); var neutral=graph.Nodes.Single(n=>n.Id=="dominance-intention").Choices.Single(c=>c.Id=="deliberate");neutral.Weights["scale"]=1; Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("Neutral choice must")),"A neutral choice must not fabricate evidence.");neutral.Weights.Clear(); graph.Nodes.Single(n=>n.Id=="track-what").MaxChoices=1; Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("multi-select limit")),"Malformed choice limits must be rejected."); } public sealed record Depth(string Id,string Title,int? Minimum,double? Typical,int Count,int? PrimaryMinimum,double? PrimaryTypical); private static Depth[] Depths(SolverGraph graph) { var depths=graph.Solutions.ToDictionary(s=>s.Id,_=>new List());var primary=graph.Solutions.ToDictionary(s=>s.Id,_=>new List()); WritingSolverCuratedV2Tests.Explore(graph,o=>{if(o.Next is not null)return;foreach(var s in o.Solutions)depths[s.Id].Add(o.Answers.Count);if(o.Solutions.FirstOrDefault() is {} winner)primary[winner.Id].Add(o.Answers.Count);}); double? Median(List x){x.Sort();return x.Count==0?null:(x[(x.Count-1)/2]+x[x.Count/2])/2.0;} return graph.Solutions.Select(s=>new Depth(s.Id,s.Title,depths[s.Id].Count==0?null:depths[s.Id].Min(),Median(depths[s.Id]),depths[s.Id].Count,primary[s.Id].Count==0?null:primary[s.Id].Min(),Median(primary[s.Id]))).ToArray(); } private static WritingSolverCuratedV2Tests.AcceptanceCase[] ExtendCases(SolverGraph graph) { var old=JsonSerializer.Deserialize(File.ReadAllText(Path.Combine(WritingSolverCuratedV2Tests.DirectoryPath,"acceptance-paths.json")),Json)!; // Authored observations for each original complaint. Expectations are kept independent of actual scoring. var supporting=new Dictionary{[8]=["d08"],[12]=["d13"],[18]=["d15"],[30]=["d52"],[35]=["d28"],[36]=["d42"],[42]=["d44"],[44]=["d44"],[46]=["d37"]}; var picks=new Dictionary{[1]="apart",[2]="gap",[3]="space",[4]="nothing",[5]="reset",[6]="remember",[7]="remember",[8]="same-job",[9]="gap",[10]="share",[11]="voice",[12]="age",[13]="unsure",[14]="network",[15]="unprepared",[16]="repeat",[17]="views",[18]="ripples",[19]="no-source",[20]="source",[21]="povs",[22]="order",[23]="clues",[24]="reader",[25]="clash",[26]="elapsed",[27]="reading",[28]="parallel",[29]="fixed",[30]="volume",[31]="place",[32]="chapter",[33]="repeat",[34]="try",[35]="journey",[36]="facts",[37]="track",[38]="holder",[39]="history",[40]="nothing",[41]="uneven",[42]="tension",[43]="unchanged",[44]="late",[45]="ripples",[46]="versions",[47]="facts",[48]="thread",[49]="whole",[50]="other",[51]="order",[52]="unprepared",[53]="gap",[54]="gap",[55]="reading",[56]="gap",[57]="moving",[58]="unsure",[59]="facts",[60]="order"}; return old.Cases.Select(test=> { var history=new List();var prefixes=new List();var outcome=WritingSolverEngine.Evaluate(graph,history); while(outcome.Next is {} node) { var original=test.Answers.FirstOrDefault(a=>a.Node==node.Id); string[] ids; if(original is not null)ids=original.Choices; else if(node.Id=="dominance-intention")ids=["even"]; else if(node.Id.StartsWith("intent-"))ids=[test.Id==57?"deliberate":"unwanted"]; else if(node.Id=="flow-target")ids=["main-story"]; else if(node.Id=="time-parallel")ids=["parallel"]; else if(node.Id=="flow-relationship")ids=["see-development"]; else ids=[picks[test.Id]]; Require(ids.All(id=>node.Choices.Any(c=>c.Id==id)), $"Case {test.Id} lacks authored choice {string.Join(',',ids)} for {node.Id}"); history.Add(new(node.Id,ids));outcome=WritingSolverEngine.Evaluate(graph,history); // Explicit semantic expected results: no diagnostics before completion; reviewed primary/supports at completion. var expected=test.Id==57?Array.Empty():new[]{test.ExpectedPrimary}.Where(s=>s is not null).Cast().Concat(supporting.GetValueOrDefault(test.Id)??test.RequiredSupporting).ToArray(); prefixes.Add(new(history.Count,outcome.Next?.Id,outcome.Next is not null?[]:expected)); } var expectedPrimary=test.Id==57?null:test.ExpectedPrimary; return test with {Answers=history.ToArray(),PrefixExpectations=prefixes.ToArray(),ExpectedPrimary=expectedPrimary,AcceptableSupporting=test.AcceptableSupporting,RequiredSupporting=supporting.GetValueOrDefault(test.Id)??test.RequiredSupporting,Notes=test.Notes+" Stage 1: new observations are explicitly authored; case 57 confirms deliberate slow progress, so no stall diagnosis is claimed."}; }).ToArray(); } private static void SemanticsAndRevision(SolverGraph graph,WritingSolverCuratedV2Tests.AcceptanceCase[] cases) { foreach(var test in cases) { var outcome=WritingSolverEngine.Evaluate(graph,test.Answers); if(test.ExpectedPrimary is not null)Require(outcome.Answers.Count is >=4 and <=6,$"Premature diagnosis in case {test.Id}"); for(var i=0;ic.Id==3).Answers; var deliberate=dominance.Select(a=>a.Node=="dominance-intention"?new SolverAnswer(a.Node,["deliberate"]):a).ToArray(); Require(WritingSolverEngine.Evaluate(graph,deliberate).Reassurance is not null,"Intentional dominance must be neutral."); var revised=new[]{new SolverAnswer("entry",["losing-track"])}.Concat(dominance.Skip(1)); var replay=WritingSolverEngine.Evaluate(graph,revised);Require(replay.Answers.Count==1 && replay.Next?.Id=="track-what","Revision did not discard stale suffix."); SolverOutcome Follow(params (string Node,string Choice)[] answers) => WritingSolverEngine.Evaluate(graph,answers.Select(a=>new SolverAnswer(a.Node,[a.Choice]))); foreach(var (observation,check,choice,intent,expected) in new[]{ ("gaps","check-threads","gap","intent-threads","d02"), ("apart","check-threads","apart","intent-threads","d03"), ("turns","check-progression","late","intent-progression","d47"), ("voice","check-cast","voice","intent-cast","d12"), ("voice","check-cast","share","intent-cast","d11")}) { var branch=new List<(string,string)>{("entry","story-not-working"),("story-problem","takes-over"),("dominance-observation",observation)}; if(observation is "gaps" or "apart")branch.Add(("dominance-intention","main")); branch.Add((check,choice));branch.Add((intent,"unwanted")); var result=Follow(branch.ToArray()); Require(result.Answers.Count==branch.Count && result.Solutions.FirstOrDefault()?.Id==expected,$"Dominance discriminator {observation}/{choice} did not identify {expected}."); } var mixed=Follow(("entry","too-much"),("scale-what","series"),("series-what","threads"),("series-thread","last-left"),("check-series","both")); Require(mixed.Solutions.Select(s=>s.Id).SequenceEqual(new[]{"d51","d50"}),"Genuine cross-book thread and memory support must coexist."); var old=WritingSolverCuratedV2Tests.Graph(); foreach(var s in graph.Solutions){var prior=old.Solutions.Single(x=>x.Id==s.Id);Require(s.Threshold==prior.Threshold && s.Signals.OrderBy(w=>w.Key).SequenceEqual(prior.Signals.OrderBy(w=>w.Key)),"Stage 1 changed reviewed coefficients/thresholds.");} } }