PlotDirector/PlotLine/Services/Investigations/InvestigationEngine.cs

87 lines
9.7 KiB
C#

using PlotLine.Models.Investigations;
namespace PlotLine.Services.Investigations;
// Pure deterministic function: no repository, HTTP, manuscript, clock, random source or AI dependency.
public static class InvestigationEngine
{
public static bool Allows(Rule r,IReadOnlyDictionary<string,Answer> a)=>a.Count>=r.MinAnswers&&r.AllAnswers.All(x=>a.TryGetValue(x.Key,out var answer)&&x.Value.Contains(answer.Option))&&!r.ExcludeAnswered.Any(a.ContainsKey);
public static Evaluation Evaluate(Catalogue c,string concern,IEnumerable<Answer> history,ISet<string> available,int continueUntil=0)
{
var seed=c.Concerns.SingleOrDefault(x=>x.Id==concern)??throw new ArgumentException("Choose a starting concern.");
// Last answer wins. Callers keep revision events separately, never obsolete scoring contributions.
var answers=history.GroupBy(x=>x.Question).ToDictionary(x=>x.Key,x=>x.Last());
var result=new Evaluation{AnswerCount=answers.Count,AvailableCapabilities=available.Order(StringComparer.Ordinal).ToList()};
foreach(var a in answers.Values){var q=c.Questions.Single(x=>x.Id==a.Question);var option=q.Options.Single(x=>x.Id==a.Option);result.Evidence.AddRange(option.Contributions.Select(e=>new Evidence(q.Id,option.Id,e.Hypothesis,e.Dimension,q.Group,e.Aspect,e.Weight,option.Uncertain)));}
foreach(var h in c.Hypotheses)
{
var rows=result.Evidence.Where(e=>e.Hypothesis==h.Id&&!e.Uncertain).ToArray();
// A dimension/group contributes its strongest support and strongest opposition once.
var independent=rows.GroupBy(e=>(e.Dimension,e.Group)).Select(g=>new{g.Key.Dimension,Positive=g.Max(e=>Math.Max(0,e.Raw)),Negative=g.Min(e=>Math.Min(0,e.Raw))}).ToArray();
var support=independent.GroupBy(x=>x.Dimension).Sum(g=>Math.Min(3,g.Sum(x=>x.Positive)));
var opposition=independent.GroupBy(x=>x.Dimension).Sum(g=>Math.Max(-3,g.Sum(x=>x.Negative)));
result.RedundantContributions+=Math.Max(0,rows.Count(e=>e.Raw!=0)-independent.Length);
var conflicts=rows.GroupBy(e=>(e.Dimension,e.Aspect)).Where(g=>g.Any(e=>e.Raw>=2)&&g.Any(e=>e.Raw<=-2)).Where(g=>!answers.Values.Any(a=>{var q=c.Questions.Single(x=>x.Id==a.Question);var o=q.Options.Single(x=>x.Id==a.Option);return q.Clarifies.Contains(g.Key.Dimension)&&q.Hypotheses.Contains(h.Id)&&o.Interpretation == "different-aspects";})).Select(g=>$"{h.Id}/{g.Key.Dimension}/{g.Key.Aspect}").ToArray();
var dimensions=independent.Where(x=>x.Positive>0).Select(x=>x.Dimension).Distinct().Count();
var groups=rows.Where(e=>e.Raw>0).Select(e=>e.Group).Distinct().Count();
var challenged=answers.Values.Any(a=>{var q=c.Questions.Single(x=>x.Id==a.Question);return (q.Purpose=="Challenge"&&q.Hypotheses.Contains(h.Id)||c.Editorial!=null&&c.Editorial.Challenges.GetValueOrDefault(h.Id,[]).Contains(q.Id))&&!q.Options.Single(o=>o.Id==a.Option).Uncertain;});
var competitors=result.Evidence.Where(e=>e.Hypothesis!=h.Id&&!e.Uncertain&&e.Raw!=0).Select(e=>e.Hypothesis).Distinct().Count();
var eligible=Allows(h.Eligibility,answers)&&h.Capabilities.Any(id=>available.Contains(id)&&c.Capabilities.Any(d=>d.Id==id&&d.Available&&Allows(d.Prerequisites,answers)));
var missing=new List<string>();if(dimensions<h.MinDimensions)missing.Add("distinct dimensions");if(groups<h.MinGroups)missing.Add("independent corroboration");if(!challenged)missing.Add("challenge opportunity");if(competitors<1)missing.Add("competing explanation examined");if(conflicts.Length>0)missing.Add("material conflict clarified");if(support+opposition<h.Threshold)missing.Add("net evidence");
if(c.Editorial?.TentativeOnly.Contains(h.Id)==true)missing.Add("catalogue provides tentative guidance only");
result.Hypotheses.Add(new(h.Id,seed.Priors.GetValueOrDefault(h.Id),support,opposition,support+opposition+seed.Priors.GetValueOrDefault(h.Id),dimensions,groups,challenged,eligible,missing.Count==0,conflicts,missing.ToArray()));
}
result.Hypotheses=result.Hypotheses.OrderByDescending(h=>h.Score).ThenBy(h=>h.Id,StringComparer.Ordinal).ToList();
var plausible=result.Hypotheses.Where(h=>h.Score>0).Take(2).Select(h=>h.Id).ToHashSet();
var covered=result.Evidence.Select(e=>(e.Hypothesis,e.Dimension)).ToHashSet();
foreach(var q in c.Questions.Where(q=>!q.Retired&&!answers.ContainsKey(q.Id)&&Allows(q.Eligibility,answers)))
{
var overlap=q.Hypotheses.Count(plausible.Contains);var gaps=q.Hypotheses.Sum(h=>q.Dimensions.Count(d=>!covered.Contains((h,d))));
var conflicts=result.Hypotheses.Count(h=>q.Hypotheses.Contains(h.Id)&&h.Conflicts.Any(f=>q.Clarifies.Any(d=>f.Contains('/'+d+'/'))));
var challenge=q.Purpose=="Challenge"?result.Hypotheses.Count(h=>plausible.Contains(h.Id)&&q.Hypotheses.Contains(h.Id)&&!h.Challenged):0;
var corroboration=q.Purpose=="Corroboration"?result.Hypotheses.Count(h=>plausible.Contains(h.Id)&&q.Hypotheses.Contains(h.Id)&&h.Groups<c.Hypotheses.Single(x=>x.Id==h.Id).MinGroups):0;
var rank=q.InformationValue+overlap*3+gaps*2+conflicts*30+challenge*15+corroboration*8+(q.Purpose=="Discrimination"&&overlap>1?8:0);
result.Candidates.Add(new(q.Id,rank,$"Relevant leading explanations: {string.Join(", ",q.Hypotheses.Where(plausible.Contains))}; unexamined dimensions: {gaps}; unresolved conflicts: {conflicts}; challenge gaps: {challenge}; corroboration gaps: {corroboration}; authored information value: {q.InformationValue}."));
}
if(c.EngineVersion==2)result.Candidates=SelectQuestions(c,answers,result);
if(c.EngineVersion==3)result.Candidates=EditorialQuestionSelection.Select(c,concern,answers,result);
result.Candidates=result.Candidates.OrderByDescending(x=>x.Rank).ThenBy(x=>x.Id,StringComparer.Ordinal).ToList();
var qualified=result.Hypotheses.Where(h=>h.Supported).ToArray();var ready=answers.Count>=Math.Max(c.MinAnswers,continueUntil);
if(c.EngineVersion>=2&&qualified.Length>0){
var best=qualified.Max(h=>h.Score);
// A close, positively supported rival deserves its missing challenge/clarification before choosing a tool.
var unresolved=result.Hypotheses.Any(h=>!h.Supported&&h.Support+h.Opposition>=c.Hypotheses.Single(x=>x.Id==h.Id).Threshold-2&&result.Candidates.Any(candidate=>{var q=c.Questions.Single(x=>x.Id==candidate.Id);var possible=q.Options.Where(o=>!o.Uncertain).Select(o=>o.Contributions.Where(v=>v.Hypothesis==h.Id).Sum(v=>Math.Max(0,v.Weight))).DefaultIfEmpty().Max();return q.Hypotheses.Contains(h.Id)&&h.Score+possible>=best-2;}));
if(unresolved)ready=false;
}
if(ready&&qualified.Length>0){var usable=qualified.Where(h=>h.Eligible).ToArray();if(usable.Length==0)result.Outcome="No suitable destination currently available";else{result.Recommendations=usable.Where(h=>h.Score>=usable[0].Score-2).Take(2).Select(h=>h.Id).ToList();result.Outcome=result.Recommendations.Count==2?"Two plausible explanations":"Supported recommendation";}}
if(result.Outcome=="Investigating"&&(answers.Count>=c.MaxAnswers||result.Candidates.Count==0))result.Outcome=result.Hypotheses.Count(h=>h.Support>0)>=2?"Two plausible explanations":"More information needed";
if(c.EngineVersion>=2&&result.Outcome!="Investigating"&&result.Recommendations.Count==0&&result.Outcome!="No suitable destination currently available")
result.Outcome=result.Hypotheses.Any(h=>h.Conflicts.Length>0)?"Conflicting evidence":result.Hypotheses.Count(h=>h.Support+h.Opposition>0)>=2?"Two plausible explanations":result.Hypotheses.Any(h=>h.Support+h.Opposition>0)?"Tentative conclusion":"More information needed";
// Ambiguous terminal outcomes do not invent qualified recommendations.
if(result.Outcome=="Investigating")result.NextQuestion=result.Candidates.FirstOrDefault()?.Id;
return result;
}
// Versioned selection preserves exact legacy evaluation/replay while correcting synthetic preview ordering.
static List<CandidateQuestion> SelectQuestions(Catalogue c, Dictionary<string,Answer> answers, Evaluation e)
{
var leaders=e.Hypotheses.Where(h=>h.Score>0).Take(2).Select(h=>h.Id).ToHashSet();
var covered=e.Evidence.Where(v=>!v.Uncertain&&v.Raw!=0).Select(v=>(v.Hypothesis,v.Dimension)).ToHashSet();
var candidates=new List<CandidateQuestion>();
foreach(var q in c.Questions.Where(q=>!q.Retired&&!answers.ContainsKey(q.Id)&&Allows(q.Eligibility,answers)))
{
var conflicts=e.Hypotheses.Count(h=>q.Hypotheses.Contains(h.Id)&&h.Conflicts.Any(f=>q.Clarifies.Any(d=>f.Contains('/'+d+'/'))));
if(q.Purpose=="Clarification"&&conflicts==0)continue;
var effects=q.Options.Where(o=>!o.Uncertain).SelectMany(o=>o.Contributions).Where(v=>v.Weight!=0).Select(v=>(v.Hypothesis,v.Dimension)).Distinct().ToArray();
// Non-evidence preference questions cannot buy priority by declaring many hypotheses/dimensions.
var overlap=effects.Select(v=>v.Hypothesis).Distinct().Count(leaders.Contains);
var gaps=effects.Count(v=>!covered.Contains(v));
var discovery=q.Purpose=="Discovery"?q.Hypotheses.Count(h=>!e.Evidence.Any(v=>v.Hypothesis==h&&!v.Uncertain&&v.Raw!=0))*5:0;
var challenge=q.Purpose=="Challenge"?e.Hypotheses.Count(h=>leaders.Contains(h.Id)&&q.Hypotheses.Contains(h.Id)&&h.Support>0&&h.Dimensions>=c.Hypotheses.Single(x=>x.Id==h.Id).MinDimensions&&!h.Challenged):0;
var corroboration=q.Purpose=="Corroboration"?e.Hypotheses.Count(h=>leaders.Contains(h.Id)&&q.Hypotheses.Contains(h.Id)&&h.Support>0&&h.Groups<c.Hypotheses.Single(x=>x.Id==h.Id).MinGroups&&effects.Any(v=>v.Hypothesis==h.Id&&!covered.Contains(v))):0;
var rank=q.InformationValue+overlap*3+gaps*2+discovery+conflicts*100+challenge*20+corroboration*8+(q.Purpose=="Discrimination"&&overlap>1?8:0);
candidates.Add(new(q.Id,rank,$"Leading explanations: {string.Join(", ",effects.Select(v=>v.Hypothesis).Distinct().Where(leaders.Contains))}; substantive dimension gaps: {gaps}; discovery: {discovery}; conflicts: {conflicts}; challenge gaps: {challenge}; independent corroboration gaps: {corroboration}; information value: {q.InformationValue}."));
}
return candidates;
}
}