using System.Text.Json; using PlotLine.Models.Investigations; using PlotLine.Services.Investigations; internal static class InvestigationDiagnosticTests { static void Check(bool ok,string message){if(!ok)throw new Exception(message);} static List Follow(Catalogue c,string concern,string target,ISet caps) { var answers=new List(); for(int n=0;n<=c.MaxAnswers;n++){ var e=InvestigationEngine.Evaluate(c,concern,answers,caps);if(e.NextQuestion==null)return answers; Check(nq.Id==e.NextQuestion); var targets=target=="competing"?new[]{"motivation","change"}:new[]{target}; var o=q.Options.OrderByDescending(o=>o.Contributions.Sum(v=>targets.Contains(v.Hypothesis)?v.Weight*20:-Math.Max(0,v.Weight))+(o.Interpretation=="different-aspects"?1:0)).ThenBy(o=>o.Id,StringComparer.Ordinal).First(); Check(!answers.Any(a=>a.Question==q.Id),"question repeated");answers.Add(new(q.Id,o.Id)); } throw new Exception("loop"); } public static void Run() { var old=CatalogueValidator.Parse(File.ReadAllText("Docs/Writer/Investigations/synthetic-catalogue.json")); var c=CatalogueValidator.Parse(File.ReadAllText("Docs/Writer/Investigations/synthetic-catalogue-v2.json"));var caps=c.Capabilities.Select(d=>d.Id).ToHashSet(); Check(old.EngineVersion==0&&c.EngineVersion==2&&old.Version!=c.Version,"version compatibility"); Check(old.MinAnswers==c.MinAnswers&&old.MaxAnswers==c.MaxAnswers,"bounds unchanged"); Check(JsonSerializer.Serialize(old.Hypotheses)==JsonSerializer.Serialize(c.Hypotheses),"thresholds and mappings unchanged"); foreach(var q in old.Questions)Check(JsonSerializer.Serialize(q.Options.Select(o=>new{o.Id,o.Uncertain,o.Interpretation,o.Contributions}))==JsonSerializer.Serialize(c.Questions.Single(x=>x.Id==q.Id).Options.Select(o=>new{o.Id,o.Uncertain,o.Interpretation,o.Contributions})),"stable option/evidence semantics "+q.Id); using(var input=File.OpenRead("Docs/Writer/Writer3/Evidence/Phase3D1A/baseline-traces.json.gz")) using(var gzip=new System.IO.Compression.GZipStream(input,System.IO.Compression.CompressionMode.Decompress)) using(var baseline=JsonDocument.Parse(gzip)){ foreach(var baselinePath in baseline.RootElement.GetProperty("paths").EnumerateArray())foreach(var step in baselinePath.GetProperty("trace").EnumerateArray()){ var a=step.GetProperty("answers").Deserialize>(CatalogueValidator.Json)!;var recorded=step.GetProperty("evaluation").Deserialize(CatalogueValidator.Json)!; var replay=InvestigationEngine.Evaluate(old,baselinePath.GetProperty("concern").GetString()!,a,recorded.AvailableCapabilities.ToHashSet()); Check(JsonSerializer.Serialize(recorded,CatalogueValidator.Json)==JsonSerializer.Serialize(replay,CatalogueValidator.Json),"exact legacy evaluation replay: "+baselinePath.GetProperty("target").GetString()+" / "+a.Count); } } var outcomes=new HashSet(); foreach(var concern in c.Concerns)foreach(var h in c.Hypotheses){var a=Follow(c,concern.Id,h.Id,caps);var e=InvestigationEngine.Evaluate(c,concern.Id,a,caps);Check(e.Recommendations.Contains(h.Id),"valid reachable path "+concern.Id+"/"+h.Id);Check(InvestigationConclusion.From(c,e).Kind=="supported","author supported projection");Check(e.AnswerCount>=c.MinAnswers,"no premature confidence");outcomes.Add(string.Join(",",e.Recommendations));} Check(outcomes.Count==5,"five distinct recommendations"); var competing=Follow(c,"story","competing",caps);Check(InvestigationEngine.Evaluate(c,"story",competing,caps).Recommendations.Count==2,"two actually selected supported explanations"); var beforeChallenge=InvestigationEngine.Evaluate(c,"story",competing.Take(8),caps);Check(beforeChallenge.NextQuestion!=null&&beforeChallenge.Recommendations.Count==0&&beforeChallenge.Hypotheses.Any(h=>h.Supported),"useful rival question precedes terminal recommendation"); var start=InvestigationEngine.Evaluate(c,"character",[],caps);Check(start.NextQuestion=="motivation-1","discovery before challenge/preference"); var yes=InvestigationEngine.Evaluate(c,"story",[new("motivation-1","yes")],caps);var no=InvestigationEngine.Evaluate(c,"story",[new("motivation-1","no")],caps);Check(yes.NextQuestion!=no.NextQuestion,"adaptive evidence-based selection"); var unknown=new List();for(int n=0;nq.Id==e.NextQuestion);unknown.Add(new(q.Id,q.Options.First(o=>o.Uncertain).Id));} var weak=InvestigationEngine.Evaluate(c,"story",unknown,caps);Check(weak.Recommendations.Count==0&&InvestigationConclusion.From(c,weak).Kind=="insufficient","uncertainty has no confidence"); var conflict=InvestigationEngine.Evaluate(c,"character",[new("motivation-1","yes"),new("motivation-4","yes")],caps);Check(conflict.NextQuestion=="motivation-clarify","material challenge conflict can clarify without redundant second question");Check(conflict.Recommendations.Count==0,"conflict no confidence"); var redundant=InvestigationEngine.Evaluate(c,"character",[new("motivation-1","yes"),new("motivation-2","yes")],caps).Hypotheses.Single(h=>h.Id=="motivation");Check(redundant.Support==3&&redundant.Dimensions==1&&!redundant.Supported,"correlated not independent"); var path=Follow(c,"story","motivation",caps);var supported=InvestigationEngine.Evaluate(c,"story",path,caps);var unavailable=InvestigationEngine.Evaluate(c,"story",path,new HashSet());Check(unavailable.Recommendations.Count==0&&InvestigationConclusion.From(c,unavailable).Kind=="unavailable","unavailable not usable");Check(supported.Hypotheses.Select(h=>(h.Id,h.Score,h.Supported)).SequenceEqual(unavailable.Hypotheses.Select(h=>(h.Id,h.Score,h.Supported))),"availability never rescores"); var row=new Investigation{ID=Guid.NewGuid(),UserID=4,ProjectID=7,BookID=12,CatalogueVersion=c.Version,Concern="story",Answers=path,Presented=path.Select(a=>a.Question).ToList()}; var repo=new InvestigationMemoryRepository();repo.Publish(JsonSerializer.Serialize(c,CatalogueValidator.Json),"test").GetAwaiter().GetResult();repo.Save(row,0,"save",supported).GetAwaiter().GetResult();var resumed=repo.Read(4,12,row.ID).GetAwaiter().GetResult()!; Check(JsonSerializer.Serialize(InvestigationService.Evaluate(c,resumed))==JsonSerializer.Serialize(supported),"resume same semantics");Check(repo.Read(5,12,row.ID).Result==null&&repo.Read(4,13,row.ID).Result==null,"private scope"); InvestigationService.Answer(resumed,c,"motivation-4","yes", "reconsidered");Check(!InvestigationService.Evaluate(c,resumed).Recommendations.Contains("motivation"),"revision changes conclusion"); Check(repo.Catalogue(old.Version).Result!.EngineVersion==0,"old catalogue remains readable"); var exhausted=CatalogueValidator.Parse(JsonSerializer.Serialize(c,CatalogueValidator.Json));foreach(var q in exhausted.Questions)q.Retired=true; var end=InvestigationEngine.Evaluate(exhausted,"story",[],caps);Check(end.NextQuestion==null&&end.Recommendations.Count==0,"safe question exhaustion"); Console.WriteLine("PASS diagnostic acceptance: 20 actual selected recommendation witnesses; stable v1 semantics; unchanged evidence/thresholds; adaptive, contradiction, revision, persistence, isolation, uncertainty, exhaustion and author outcomes"); } public static void Export(string catalogue, string output) { var c=CatalogueValidator.Parse(File.ReadAllText(catalogue));var available=c.Capabilities.Where(d=>d.Available).Select(d=>d.Id).ToHashSet();var paths=new List(); foreach(var concern in c.Concerns)foreach(var target in c.Hypotheses.Select(h=>h.Id).Concat(["all-yes","all-no","uncertain","alternating","moderate","weak","competing","correlated","unavailable"])) { var a=new List();var trace=new List();var caps=target=="unavailable"?new HashSet():available;var desired=target=="unavailable"?"motivation":target; for(int n=0;n<=c.MaxAnswers;n++) { var state=InvestigationEngine.Evaluate(c,concern.Id,a,caps);trace.Add(InvestigationDiagnostics.Trace(c,concern.Id,a,caps));if(state.NextQuestion==null)break; if(n==c.MaxAnswers)throw new Exception("Loop");var q=c.Questions.Single(q=>q.Id==state.NextQuestion);AnswerOption o; if(target=="uncertain" || target=="weak"&&n>1 || target=="correlated"&&!q.Id.StartsWith("motivation-"))o=q.Options.First(x=>x.Uncertain); else if(target=="all-yes")o=q.Options.First();else if(target=="all-no")o=q.Options[1];else if(target=="alternating")o=q.Options[n%q.Options.Count]; else {var targets=target=="competing"?new[]{"motivation","change"}:new[]{target is "moderate" or "weak" or "correlated"?"motivation":desired}; o=q.Options.OrderByDescending(o=>o.Contributions.Sum(v=>targets.Contains(v.Hypothesis)?v.Weight*20:-Math.Max(0,v.Weight))+(o.Interpretation=="different-aspects"?1:0)).ThenBy(o=>o.Id,StringComparer.Ordinal).First(); if(target=="moderate"&&q.Purpose=="Discovery")o=q.Options.First(x=>x.Uncertain); if(target=="correlated"&&q.Purpose!="Discovery"&&q.Purpose!="Corroboration")o=q.Options.First(x=>x.Uncertain); } a.Add(new(q.Id,o.Id)); } var final=InvestigationEngine.Evaluate(c,concern.Id,a,caps);paths.Add(new{concern=concern.Id,target,answers=a,final,trace}); if(c.Hypotheses.Any(h=>h.Id==target)) { var revised=a.Select(x=>x.Question.StartsWith(target+"-")&&x.Option=="yes"?x with{Option="no"}:x).ToList(); paths.Add(new{concern=concern.Id,target=target+"-revision",answers=revised,final=InvestigationEngine.Evaluate(c,concern.Id,revised,caps),trace=new[]{InvestigationDiagnostics.Trace(c,concern.Id,revised,caps)}}); } } Directory.CreateDirectory(Path.GetDirectoryName(output)!);File.WriteAllText(output,JsonSerializer.Serialize(new{catalogue=c.Version,paths},CatalogueValidator.Json)); Console.WriteLine($"PASS diagnostic export: {paths.Count} deterministic paths through actual engine ({c.Version})"); } }