PlotDirector/PlotLine.Tests/InvestigationTests.cs

62 lines
11 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Text.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using PlotLine.Models.Investigations;
using PlotLine.Services.Investigations;
internal static class InvestigationTests
{
static string Root {get{var p=new DirectoryInfo(Directory.GetCurrentDirectory());while(p!=null&&!File.Exists(Path.Combine(p.FullName,"PlotLine.slnx")))p=p.Parent;return p?.FullName??throw new Exception("Repository not found");}}
static Catalogue Load()=>CatalogueValidator.Parse(File.ReadAllText(Path.Combine(Root,"Docs/Writer/Investigations/synthetic-catalogue.json")));
static void Check(bool b,string s){if(!b)throw new Exception(s);}
static void Reject(Action a){try{a();}catch(ArgumentException){return;}throw new Exception("Invalid catalogue accepted");}
static HashSet<string> All(Catalogue c)=>c.Capabilities.Select(d=>d.Id).ToHashSet();
static Evaluation E(Catalogue c,IEnumerable<Answer> a,string concern="story",ISet<string>? caps=null)=>InvestigationEngine.Evaluate(c,concern,a,caps??All(c));
public static void Run()
{
var c=Load();var start=E(c,[]);Check(start.AnswerCount==0&&start.NextQuestion!=null&&start.Recommendations.Count==0,"starting state");Check(E(c,[],"character").Hypotheses[0].Id=="motivation","concern activates prior");
var positive=E(c,[new("motivation-1","yes")]);Check(positive.Hypotheses.Single(h=>h.Id=="motivation").Support==3,"weighted positive");var negative=E(c,[new("motivation-1","no")]);Check(negative.Hypotheses.Single(h=>h.Id=="motivation").Opposition==-3,"negative evidence");
var duplicate=E(c,[new("motivation-1","yes"),new("motivation-2","yes")]);Check(duplicate.Hypotheses.Single(h=>h.Id=="motivation").Support==3&&duplicate.RedundantContributions==1,"redundancy capped");Check(!duplicate.Hypotheses.Single(h=>h.Id=="motivation").Supported,"same dimension not confident");
var corroboration=E(c,[new("motivation-1","yes"),new("motivation-3","yes")]);Check(corroboration.Hypotheses.Single(h=>h.Id=="motivation").Groups==2&&!corroboration.Hypotheses.Single(h=>h.Id=="motivation").Supported,"challenge and competitor required");
var a=new List<Answer>{new("motivation-1","yes"),new("motivation-2","no"),new("motivation-3","yes"),new("motivation-4","no"),new("change-1","no")};var conflict=E(c,a);Check(conflict.Hypotheses.Single(h=>h.Id=="motivation").Conflicts.Length==1,"genuine same-aspect conflict");Check(conflict.NextQuestion=="motivation-clarify","clarification selected");
a.Add(new("motivation-clarify","aspects"));Check(E(c,a).Hypotheses.Single(h=>h.Id=="motivation").Conflicts.Length==0,"explicit distinct aspects");
var revised=E(c,[new("motivation-1","yes"),new("motivation-1","no")]);Check(revised.Hypotheses.Single(h=>h.Id=="motivation").Support==0&&revised.Hypotheses.Single(h=>h.Id=="motivation").Opposition==-3,"superseded evidence removed");
Check(JsonSerializer.Serialize(E(c,a))==JsonSerializer.Serialize(E(c,a)),"deterministic replay");Check(E(c,[]).Candidates.All(q=>!q.Id.EndsWith("clarify")),"prerequisites exclude clarification");
var uncertain=c.Questions.Where(q=>q.Purpose!="Clarification").Take(12).Select(q=>new Answer(q.Id,"unsure")).ToArray();Check(E(c,uncertain).Recommendations.Count==0&&E(c,uncertain).NextQuestion==null,"bounded insufficient evidence");
Check(E(c,[new("motivation-1","yes")]).Recommendations.Count==0,"not early threshold");Check(DestinationRegistry.Resolve(c.Capabilities[0],1,2,false,new Dictionary<string,Answer>())==null,"unauthorised destination denied");Check(DestinationRegistry.Resolve(c.Capabilities[0],1,0,true,new Dictionary<string,Answer>())==null,"missing book denied");var dest=DestinationRegistry.Resolve(c.Capabilities[0],1,2,true,new Dictionary<string,Answer>());Check(dest?.Controller=="Characters","authenticated resolver");
var invalid=Load();invalid.Questions[0].Id=invalid.Questions[1].Id;Reject(()=>CatalogueValidator.Validate(invalid));invalid=Load();invalid.Questions[0].Options[0].Contributions[0].Weight=4;Reject(()=>CatalogueValidator.Validate(invalid));invalid=Load();invalid.Capabilities[0].Resolver="https://public.example";Reject(()=>CatalogueValidator.Validate(invalid));invalid=Load();invalid.Questions[0].Eligibility.AllAnswers[invalid.Questions[0].Id]=["yes"];Reject(()=>CatalogueValidator.Validate(invalid));invalid=Load();invalid.Hypotheses[0].Capabilities=["missing"];Reject(()=>CatalogueValidator.Validate(invalid));invalid=Load();invalid.SchemaVersion=2;Reject(()=>CatalogueValidator.Validate(invalid));Reject(()=>CatalogueValidator.Parse("{\"Questions\":null}"));
var i=new Investigation{Concern="story",Presented=["motivation-1"],Answers=[new("motivation-1","yes")]};InvestigationService.Answer(i,c,"motivation-1","no","Changed my understanding");Check(i.Answers.Count==1&&i.Answers[0].Option=="no","in-place answer revision");Reject(()=>InvestigationService.Answer(i,c,"change-1","yes",null));var round=JsonSerializer.Deserialize<Investigation>(JsonSerializer.Serialize(i,CatalogueValidator.Json),CatalogueValidator.Json)!;Check(round.Answers.SequenceEqual(i.Answers),"persistence round trip");
var supportedAnswers=new List<Answer>{new("motivation-1","yes"),new("motivation-2","yes"),new("motivation-3","yes"),new("motivation-4","no"),new("change-1","no"),new("change-2","no"),new("connections-1","no"),new("organisation-1","no")};
Check(E(c,supportedAnswers).Recommendations.Contains("motivation"),"independent corroboration + challenge permits recommendation");Check(E(c,supportedAnswers,caps:new HashSet<string>()).Outcome=="No suitable destination currently available","destination becoming unavailable is explicit");
var withTool=E(c,supportedAnswers);var withoutTool=E(c,supportedAnswers,caps:new HashSet<string>());Check(withTool.Hypotheses.Select(h=>(h.Id,h.Support,h.Opposition,h.Score,h.Dimensions,h.Groups,h.Challenged,h.Supported)).SequenceEqual(withoutTool.Hypotheses.Select(h=>(h.Id,h.Support,h.Opposition,h.Score,h.Dimensions,h.Groups,h.Challenged,h.Supported))),"missing prerequisites do not change diagnostic evidence");
var continued=InvestigationEngine.Evaluate(c,"story",supportedAnswers,All(c),10);Check(continued.NextQuestion!=null&&continued.Recommendations.Count==0,"author requests further investigation");
supportedAnswers.RemoveAll(a=>a.Question.StartsWith("motivation-"));supportedAnswers.AddRange(new Answer[]{new("motivation-1","no"),new("motivation-2","no"),new("motivation-3","no"),new("motivation-4","yes")});Check(!E(c,supportedAnswers).Recommendations.Contains("motivation"),"revision changes recommendation");
var ambiguous=new List<Answer>{new("motivation-1","yes"),new("motivation-3","yes"),new("motivation-4","no"),new("change-1","yes"),new("change-3","yes"),new("change-4","no"),new("connections-1","no"),new("organisation-1","no")};Check(E(c,ambiguous,"next").Recommendations.Count==2,"two supported plausible explanations");
invalid=Load();invalid.Questions[0].Eligibility.AllAnswers[invalid.Questions[1].Id]=["yes"];invalid.Questions[1].Eligibility.AllAnswers[invalid.Questions[0].Id]=["yes"];Reject(()=>CatalogueValidator.Validate(invalid));
var env=new TestEnvironment{EnvironmentName="Production"};Check(!new InvestigationAccess(env,new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"WriterInvestigations:Enabled","true"}}).Build()).Enabled,"Production cannot enable synthetic experience");env.EnvironmentName="Development";Check(new InvestigationAccess(env,new ConfigurationBuilder().Build()).Enabled,"Development preview enabled");
var report=Simulate();Check(report.UnreachableHypotheses.Length==0&&report.UnreachableDestinations.Length==0,"all hypotheses/destinations reachable");
}
sealed class TestEnvironment:Microsoft.AspNetCore.Hosting.IWebHostEnvironment {public string EnvironmentName{get;set;}="";public string ApplicationName{get;set;}="";public string WebRootPath{get;set;}="";public IFileProvider WebRootFileProvider{get;set;}=new NullFileProvider();public string ContentRootPath{get;set;}="";public IFileProvider ContentRootFileProvider{get;set;}=new NullFileProvider();}
public sealed record Coverage(int SchemaVersion,int Paths,int Steps,string[] Hypotheses,string[] Destinations,string[] UnreachableHypotheses,string[] UnreachableDestinations,int RepeatedQuestions,int Loops,int PrematureRecommendations,int InvalidDestinations,int NonDeterministic,List<object> RepresentativePaths);
public static Coverage Simulate(string? output=null)
{
var c=Load();var hypotheses=new HashSet<string>();var destinations=new HashSet<string>();var paths=new List<object>();int total=0,steps=0,repeats=0,loops=0,premature=0,invalid=0,nondeterministic=0;var random=new Random(31701);
// Every concern × target plus seeded adversarial/random/uncertain paths. No network/database/AI.
foreach(var concern in c.Concerns)foreach(var target in c.Hypotheses.Select(h=>h.Id).Concat(["uncertain","alternating","random"]))for(int seed=0;seed<(target=="random"?50:1);seed++)
{
total++;var answers=new List<Answer>();var seen=new HashSet<string>();Evaluation state=E(c,answers,concern.Id);var trace=new List<string>();
for(int n=0;n<=c.MaxAnswers;n++){
if(JsonSerializer.Serialize(state)!=JsonSerializer.Serialize(E(c,answers,concern.Id)))nondeterministic++;
if(state.NextQuestion==null)break;if(n==c.MaxAnswers){loops++;break;}if(!seen.Add(state.NextQuestion)){repeats++;break;}
var q=c.Questions.Single(q=>q.Id==state.NextQuestion);AnswerOption option;
if(target=="uncertain")option=q.Options.First(o=>o.Uncertain);else if(target=="alternating")option=q.Options[n%q.Options.Count];else if(target=="random")option=q.Options[random.Next(q.Options.Count)];else option=q.Options.OrderByDescending(o=>o.Contributions.Sum(e=>e.Hypothesis==target?e.Weight*20:-Math.Max(0,e.Weight))+(o.Interpretation=="different-aspects"?1:0)).ThenBy(o=>o.Id,StringComparer.Ordinal).First();
answers.Add(new(q.Id,option.Id));trace.Add(q.Id+"="+option.Id);steps++;state=E(c,answers,concern.Id);
if(state.Recommendations.Count>0&&answers.Count<c.MinAnswers)premature++;
}
foreach(var h in state.Recommendations){hypotheses.Add(h);foreach(var cap in c.Hypotheses.Single(x=>x.Id==h).Capabilities){var d=c.Capabilities.Single(x=>x.Id==cap);if(DestinationRegistry.Resolve(d,1,2,true,answers.ToDictionary(a=>a.Question))==null)invalid++;else destinations.Add(cap);}}
if(target!="random")paths.Add(new{concern=concern.Id,target,answers=trace,outcome=state.Outcome,recommendations=state.Recommendations,eligibility=state.Hypotheses});
}
var report=new Coverage(1,total,steps,hypotheses.Order().ToArray(),destinations.Order().ToArray(),c.Hypotheses.Select(h=>h.Id).Except(hypotheses).ToArray(),c.Capabilities.Select(d=>d.Id).Except(destinations).ToArray(),repeats,loops,premature,invalid,nondeterministic,paths);
if(output!=null)File.WriteAllText(output,JsonSerializer.Serialize(report,CatalogueValidator.Json));Check(repeats+loops+premature+invalid+nondeterministic==0,"simulation safety invariant");return report;
}
}