PlotDirector/PlotLine.Tests/ProductionInvestigationTests.cs

77 lines
9.9 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 PlotLine.Models.Investigations;
using PlotLine.Services.Investigations;
internal static class ProductionInvestigationTests
{
public static Catalogue Load()=>CatalogueValidator.Parse(File.ReadAllText("Docs/Writer/Investigations/production-catalogue-v0.1.json"));
static void Check(bool ok,string message){if(!ok)throw new Exception(message);}
public static void Run(string? output=null)
{
var c=Load();var caps=c.Capabilities.Select(d=>d.Id).ToHashSet();
var wording=JsonDocument.Parse(File.ReadAllText("Docs/Writer/Investigations/Production-Editorial-Source-v0.1.json"));
foreach(var expected in wording.RootElement.EnumerateArray()){
var q=c.Questions.Single(q=>q.Id==expected.GetProperty("Id").GetString());Check(q.Text==expected.GetProperty("Text").GetString(),"exact editorial question "+q.Id);
foreach(var o in expected.GetProperty("Options").EnumerateArray())Check(q.Options.Single(a=>a.Id==o.GetProperty("Id").GetString()).Text==o.GetProperty("Text").GetString(),"exact editorial answer "+q.Id);
}
Check(c.Questions.Count==19&&c.Questions.Sum(q=>q.Options.Count)==88&&!c.Synthetic,"production identity/counts");
var paths=new List<object>();var reachable=new HashSet<string>();
foreach(var concern in c.Concerns)foreach(var target in c.Hypotheses.Where(h=>h.Capabilities.Count>0).Select(h=>h.Id).Concat(["healthy","uncertain","mixed","qualified"])){
var answers=new List<Answer>();bool qualifiedSignal=false;var seen=new HashSet<string>();var steps=new List<object>();
for(int n=0;n<=c.MaxAnswers;n++){
var e=InvestigationEngine.Evaluate(c,concern.Id,answers,caps);steps.Add(new{answers=answers.ToArray(),evaluation=e});if(e.NextQuestion==null)break;
Check(n<c.MaxAnswers&&seen.Add(e.NextQuestion),"bounded adaptive questions");var q=c.Questions.Single(q=>q.Id==e.NextQuestion);AnswerOption option;
if(target=="qualified"){
var goal=new Dictionary<string,string>{{"A","disconnected"},{"B","motivation"},{"C","slow"},{"D","conflict"},{"E","continuity"},{"F","motivation"}}[concern.Id];
option=(qualifiedSignal?Enumerable.Empty<AnswerOption>():q.Options.Where(o=>o.Contributions.Any(v=>v.Hypothesis==goal&&v.Weight>0))).OrderBy(o=>Math.Abs(o.Contributions.Where(v=>v.Hypothesis==goal).Sum(v=>v.Weight)-2)).ThenBy(o=>o.Id).FirstOrDefault()??q.Options.FirstOrDefault(o=>o.Uncertain)??q.Options.First();
if(q.Purpose!="Discrimination"&&option.Contributions.Any(v=>v.Hypothesis==goal&&v.Weight>0))qualifiedSignal=true;
}
else if(target=="healthy")option=q.Options.First().Contributions.All(v=>v.Weight<=0)?q.Options.First():q.Options.FirstOrDefault(o=>o.Uncertain)??q.Options.OrderBy(o=>o.Contributions.Sum(v=>Math.Max(0,v.Weight))).First();else if(target=="uncertain")option=q.Options.FirstOrDefault(o=>o.Uncertain)??q.Options.OrderBy(o=>o.Contributions.Sum(v=>Math.Max(0,v.Weight))).ThenBy(o=>o.Id).First();
else if(target=="mixed")option=q.Options[n%q.Options.Count];
else option=q.Options.OrderByDescending(o=>o.Contributions.Sum(v=>v.Hypothesis==target?v.Weight*20:-Math.Max(0,v.Weight))).ThenBy(o=>o.Id,StringComparer.Ordinal).First();
answers.Add(new(q.Id,option.Id));
}
var final=InvestigationEngine.Evaluate(c,concern.Id,answers,caps);var result=EditorialConclusion.From(c,final);
Check(final.NextQuestion==null&&result.Action.Length>20&&result.Title.Length>0,"useful completed result");
Check(JsonSerializer.Serialize(final)==JsonSerializer.Serialize(InvestigationEngine.Evaluate(c,concern.Id,answers,caps)),"deterministic production replay");
foreach(var id in final.Recommendations){Check(final.AnswerCount>=8&&final.Hypotheses.Single(h=>h.Id==id).Supported,"unchanged confidence requirements");reachable.Add(id);}
if(target=="uncertain")Check(final.Recommendations.Count==0,"uncertainty not proof");
paths.Add(new{concern=concern.Id,target,answers,final,result,steps});
}
var examples=new[]{
("A","plot-agency",new Dictionary<string,string>{{"Q02","B"},{"Q03","B"},{"Q04","B"},{"Q11","B"},{"Q12","B"}},new[]{"agency","causality","disconnected"}),
("B","character-development",new Dictionary<string,string>{{"Q05","C"},{"Q06","C"},{"Q07","C"},{"Q17","B"}},new[]{"motivation","development","relationships"}),
("C","slow-middle",new Dictionary<string,string>{{"Q08","B"},{"Q09","B"},{"Q11","B"}},new[]{"slow","conflict"}),
("D","weak-pressure",new Dictionary<string,string>{{"Q11","B"},{"Q12","B"},{"Q13","B"}},new[]{"conflict","stakes","emotion"}),
("E","earlier-change",new Dictionary<string,string>{{"Q14","A"},{"Q15","B"},{"Q16","A"}},new[]{"continuity","chronology"}),
("A","contrasting-accounts",new Dictionary<string,string>{{"Q02","A"},{"Q03","C"}},new[]{"disconnected","causality"}),
("F","unclear-to-character",new Dictionary<string,string>{{"Q17","B"},{"Q18","B"},{"Q19","B"},{"Q05","C"}},new[]{"motivation","emotion"})};
foreach(var (concern,name,choices,expected) in examples){
var a=new List<Answer>();var steps=new List<object>();Evaluation e;
while(true){e=InvestigationEngine.Evaluate(c,concern,a,caps);steps.Add(new{answers=a.ToArray(),evaluation=e});if(e.NextQuestion==null)break;Check(a.Count<12,"named example bound");var q=c.Questions.Single(q=>q.Id==e.NextQuestion);var o=choices.TryGetValue(q.Id,out var id)?q.Options.Single(o=>o.Id==id):q.Options.FirstOrDefault(o=>o.Uncertain)??q.Options.First();a.Add(new(q.Id,o.Id));}
var result=EditorialConclusion.From(c,e);Check(result.Findings.Any(r=>expected.Contains(r.Hypothesis)),"specific cross-route editorial result "+name);
paths.Add(new{concern,target=name,answers=a,final=e,result,steps});
}
foreach(var concern in c.Concerns){
var routePaths=paths.Select(x=>JsonSerializer.SerializeToElement(x)).Where(x=>x.GetProperty("concern").GetString()==concern.Id).ToArray();
Check(routePaths.Any(x=>x.GetProperty("final").GetProperty("Recommendations").GetArrayLength()>0),"supported opening route "+concern.Id);
Check(routePaths.Any(x=>x.GetProperty("result").GetProperty("Kind").GetString() is "tentative" or "ambiguous"),"qualified opening route "+concern.Id);
}
Check(c.Hypotheses.Where(h=>!c.Editorial!.TentativeOnly.Contains(h.Id)).All(h=>reachable.Contains(h.Id)),"every confidence-eligible result demonstrated");
var pref=InvestigationEngine.Evaluate(c,"F",[new("Q17","B"),new("Q18","B"),new("Q19","B")],caps).Hypotheses.Single(h=>h.Id=="motivation");Check(pref.Support==1&&pref.Dimensions==1&&pref.Groups==1&&!pref.Supported,"Q17–Q19 cannot manufacture corroboration");
var revision=new Investigation{Concern="B",Presented=["Q05"],Answers=[new("Q05","C")]};InvestigationService.Answer(revision,c,"Q05","A",null);Check(InvestigationService.Evaluate(c,revision).Hypotheses.Single(h=>h.Id=="motivation").Support==0,"revision removes obsolete production evidence");
var repo=new InvestigationMemoryRepository();repo.Publish(JsonSerializer.Serialize(c,CatalogueValidator.Json),"test").GetAwaiter().GetResult();Check(repo.Catalogue("synthetic-3d1-v1").Result!.Synthetic&&!repo.Catalogue(c.Version).Result!.Synthetic,"immutable production/synthetic coexistence");
foreach(var change in new Action<Catalogue>[] {x=>x.Questions[1].Id=x.Questions[2].Id,x=>x.Questions[1].Options[0].Id="Z",x=>x.Editorial!.FollowUps["Q02.A"].Questions=["missing"],x=>x.Questions[1].Options[0].Contributions[0].Weight=4,x=>x.Editorial!.Results.RemoveAt(0),x=>x.Capabilities[0].Resolver="public",x=>x.Questions[0].Options[0].Contributions.Add(new(){Hypothesis="motivation",Dimension="routing",Weight=3})}){
var invalid=Load();change(invalid);bool rejected=false;try{CatalogueValidator.Validate(invalid);}catch(ArgumentException){rejected=true;}Check(rejected,"invalid catalogue rejected");
}
var used=paths.Select(x=>JsonSerializer.SerializeToElement(x)).SelectMany(x=>x.GetProperty("result").GetProperty("Findings").EnumerateArray().Select(r=>r.GetProperty("Hypothesis").GetString()!)).ToHashSet();
used.Add(c.Hypotheses.Single(h=>h.Capabilities.Count==0).Id);Check(c.Editorial!.Results.All(r=>used.Contains(r.Hypothesis)),"all authored result templates exercised");
var strong=paths.Select(x=>JsonSerializer.SerializeToElement(x)).First(x=>x.GetProperty("final").GetProperty("Recommendations").GetArrayLength()>0);
var strongAnswers=strong.GetProperty("answers").Deserialize<List<Answer>>(CatalogueValidator.Json)!;var on=InvestigationEngine.Evaluate(c,strong.GetProperty("concern").GetString()!,strongAnswers,caps);var off=InvestigationEngine.Evaluate(c,strong.GetProperty("concern").GetString()!,strongAnswers,new HashSet<string>());
Check(off.Recommendations.Count==0&&EditorialConclusion.From(c,off).Kind=="unavailable"&&on.Hypotheses.Select(h=>(h.Id,h.Support,h.Opposition,h.Score,h.Supported)).SequenceEqual(off.Hypotheses.Select(h=>(h.Id,h.Support,h.Opposition,h.Score,h.Supported))),"availability remains independent of diagnosis");
var oneDisabled=InvestigationEngine.Evaluate(c,strong.GetProperty("concern").GetString()!,strongAnswers,caps.Where(id=>id!="timeline").ToHashSet());Check(!InvestigationService.CanOpen(c,oneDisabled,"timeline")&&InvestigationService.CanOpen(c,oneDisabled,"threads"),"disabled adapter cannot be opened through an otherwise eligible multi-tool hypothesis");
var saved=new Investigation{ID=Guid.NewGuid(),UserID=4,ProjectID=7,BookID=12,CatalogueVersion=c.Version,Concern=strong.GetProperty("concern").GetString()!,Answers=strongAnswers,Presented=strongAnswers.Select(a=>a.Question).ToList()};repo.Save(saved,0,"save",on).GetAwaiter().GetResult();var resumed=repo.Read(4,12,saved.ID).Result!;Check(JsonSerializer.Serialize(InvestigationService.Evaluate(c,resumed))==JsonSerializer.Serialize(on)&&repo.Read(5,12,saved.ID).Result==null&&repo.Read(4,13,saved.ID).Result==null,"production private save/resume and scope isolation");
if(output!=null)File.WriteAllText(output,JsonSerializer.Serialize(new{catalogue=c.Version,reachable,paths},CatalogueValidator.Json));
Console.WriteLine($"PASS production investigation catalogue: {paths.Count} deterministic completed paths; reachable={string.Join(',',reachable)}");
}
}