using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.AspNetCore.Authorization; using PlotLine.Data; using PlotLine.Models.WritingSolver; namespace PlotLine.Services; // An observer only: prefix outcomes are always supplied by the unchanged engine. public sealed class WritingSolverReview(IWebHostEnvironment environment, IAuthorizationService authorization, WritingSolverResults results, IHelpService? help=null) { public const string Cookie="pd-solver-review"; public static readonly string[] Categories=["Question feels wrong here","My answer isn't available","Wording feels awkward","Journey is too long","Result feels wrong","Start Here feels wrong","Look for guidance feels wrong","Other"]; public async Task Authorized(HttpContext context)=>environment.IsDevelopment() && (await authorization.AuthorizeAsync(context.User,null,"AdminOnly")).Succeeded; public async Task Enabled(HttpContext context)=>context.Request.Cookies[Cookie]=="on" && await Authorized(context); public static string Hash(SolverGraph graph)=>Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(graph,WritingSolverRepository.JsonOptions)))); public SolverReviewSnapshot Capture(SolverGraph graph,IEnumerable history) { var outcome=WritingSolverEngine.Evaluate(graph,history); var steps=new List(); var sources=new Dictionary>(); var accumulated=new Dictionary(); for(var i=0;in.Id==answer.Node); var selected=node.Choices.Where(c=>answer.Choices.Contains(c.Id)).ToArray(); foreach(var choice in selected)foreach(var weight in choice.Weights) { accumulated[weight.Key]=accumulated.GetValueOrDefault(weight.Key)+weight.Value; if(!sources.ContainsKey(weight.Key))sources[weight.Key]=[]; sources[weight.Key].Add(new(node.Id,node.Title,choice.Id,choice.Text,weight.Value)); } var prefix=outcome.Answers.Take(i+1).ToList(); var after=WritingSolverEngine.Evaluate(graph,prefix); var routes=node.Routes.Where(r=>prefix.Count>=r.FromAnswers&&(r.BeforeAnswers==0||prefix.Count=r.Minimum)) .Select(r=>new{Route=r,Node=graph.Nodes.Single(n=>n.Id==r.Target)}) .Where(x=>x.Node.Active&&!prefix.Any(a=>a.Node==x.Node.Id)) .Select(x=>new{x.Route,x.Node,Rank=x.Route.Priority+x.Node.Affinity.Sum(w=>accumulated.GetValueOrDefault(w.Key)*w.Value)}) .OrderByDescending(x=>x.Rank).ThenBy(x=>x.Node.Order).ThenBy(x=>x.Node.Id,StringComparer.Ordinal).ToArray(); string Describe(SolverRoute r)=>$"{(r.Choice is null ? "no choice restriction" : "choice "+r.Choice)}; {(r.Signal is null ? "no signal threshold" : r.Signal+" ≥ "+r.Minimum)}; answers ≥ {r.FromAnswers}"+(r.BeforeAnswers>0?$" and < {r.BeforeAnswers}":""); var winner=routes.FirstOrDefault(); var reason=after.Reassurance is not null?"Neutral endpoint / reassurance choice; no next question.":winner is null?"No eligible unvisited route.":$"Selected {winner.Node.Id}: {Describe(winner.Route)}. Priority {winner.Route.Priority} + target affinity = {winner.Rank}; ties use target order then ID."; if(selected.Any(c=>c.Fallback))reason="Fallback answer selected. "+reason; if(after.Next is null&&after.Reassurance is null)reason+=" Engine stopped: "+Stop(graph,after)+". Any selected route was not asked."; steps.Add(new(node.Id,node.Title,selected.Select(c=>c.Id).ToArray(),selected.Select(c=>c.Text).ToArray(),after.Next?.Id,reason,routes.Select(x=>$"{x.Node.Id}: {Describe(x.Route)}; rank {x.Rank}; target order {x.Node.Order}").ToArray())); } var ranked=graph.Solutions.Where(s=>s.Active).Select(s=>new{Solution=s,Score=s.Signals.Sum(w=>outcome.Scores.GetValueOrDefault(w.Key)*w.Value)}) .OrderByDescending(x=>x.Score).ThenBy(x=>x.Solution.Order).ThenBy(x=>x.Solution.Id,StringComparer.Ordinal).ToArray(); var returned=outcome.Solutions.Select(s=>s.Id).ToHashSet(); var near=ranked.Where(x=>!returned.Contains(x.Solution.Id)&&x.Score>0).Take(5).Select(x=>x.Solution.Id).ToHashSet(); var diagnoses=ranked.Where(x=>returned.Contains(x.Solution.Id)||near.Contains(x.Solution.Id)).Select(x=>new SolverReviewDiagnosis(x.Solution.Id,x.Solution.Title,x.Score,x.Solution.Threshold,returned.Contains(x.Solution.Id), x.Solution.Signals.Where(w=>outcome.Scores.GetValueOrDefault(w.Key)!=0).Select(w=>$"{w.Key}: {outcome.Scores.GetValueOrDefault(w.Key)} × {w.Value} = {outcome.Scores.GetValueOrDefault(w.Key)*w.Value}").ToArray(), x.Solution.RequiredSignals.Where(w=>outcome.Scores.GetValueOrDefault(w.Key)$"{w.Key}: needs {w.Value}, has {outcome.Scores.GetValueOrDefault(w.Key)}").ToArray())).ToList(); var primary=outcome.Solutions.FirstOrDefault();var recommendation=primary is null?null:results.Catalog.Results.FirstOrDefault(r=>r.Solution==primary.Id); string? Capability(string? id)=>id is null?null:results.Capability(id).Name+" ("+id+")"; return new(graph.Version,Hash(graph),DateTimeOffset.UtcNow,outcome.Answers.Count,outcome.Next?.Id,outcome.Next?.Title,Stop(graph,outcome),steps, outcome.Scores.OrderBy(x=>x.Key).Select(x=>new SolverReviewSignal(x.Key,x.Value,sources.GetValueOrDefault(x.Key)??[])).ToList(),diagnoses, Capability(recommendation?.Capability),Capability(recommendation?.Secondary),Article(recommendation?.ArticleKey),outcome.Answers.ToList(),outcome.Reassurance?.Title); } private string? Article(string? key) { if(key is null)return null;var article=help?.GetByContextKey(key); return article is null?key:article.Title+" ("+key+", /help/"+article.CategorySlug+"/"+article.Slug+")"; } private static string Stop(SolverGraph graph,SolverOutcome outcome)=>outcome.Next is not null?$"Continuing: next question selected; {outcome.Answers.Count}/{graph.MinAnswers} minimum answers, next question requires answer: {outcome.Next.RequireAnswer}":outcome.Reassurance is not null?"Neutral endpoint":outcome.Answers.Count>=graph.MaxAnswers?"Question limit reached"+(outcome.Solutions.Count>0?"; diagnosis qualified":"; insufficient evidence"):outcome.Solutions.Count>0?"Diagnosis qualified":"Insufficient evidence; no eligible next question"; } // One atomic JSON record per feedback item, in persistent, non-public App_Data. No database or workspace data. public sealed class WritingSolverReviewStore(IWebHostEnvironment environment) { private readonly SemaphoreSlim gate=new(1,1); private string DirectoryPath { get { if(!environment.IsDevelopment())throw new InvalidOperationException("Review storage is Development only.");return Path.Combine(environment.ContentRootPath,"App_Data","WritingSolverReview"); } } public async Task> List() { var dir=DirectoryPath;if(!Directory.Exists(dir))return []; var records=new List(); foreach(var path in Directory.EnumerateFiles(dir,"*.json"))records.Add(JsonSerializer.Deserialize(await File.ReadAllTextAsync(path))??throw new InvalidDataException("Invalid review feedback.")); return records.OrderByDescending(x=>x.Captured.CapturedUtc).ToArray(); } public async Task Find(Guid id) {var path=Path.Combine(DirectoryPath,id+".json");return File.Exists(path)?JsonSerializer.Deserialize(await File.ReadAllTextAsync(path)):null;} public async Task Save(SolverReviewFeedback item) { await gate.WaitAsync();try{await Write(item);}finally{gate.Release();} } private async Task Write(SolverReviewFeedback item) { var dir=DirectoryPath;Directory.CreateDirectory(dir);if(!OperatingSystem.IsWindows())File.SetUnixFileMode(dir,UnixFileMode.UserRead|UnixFileMode.UserWrite|UnixFileMode.UserExecute);var path=Path.Combine(dir,item.Id+".json");var tmp=path+".tmp"; await File.WriteAllTextAsync(tmp,JsonSerializer.Serialize(item));if(!OperatingSystem.IsWindows())File.SetUnixFileMode(tmp,UnixFileMode.UserRead|UnixFileMode.UserWrite);File.Move(tmp,path,true); } public async Task Resolve(Guid id,bool resolved) {await gate.WaitAsync();try{var item=await Find(id);if(item is null)return false;await Write(item with{Resolved=resolved});return true;}finally{gate.Release();}} } public static class WritingSolverReviewBoundary { public static void UseWritingSolverReviewBoundary(this WebApplication app) { if(!app.Environment.IsDevelopment())app.Use(async(context,next)=> { if(context.Request.Path.StartsWithSegments("/admin/writing-solver-review",StringComparison.OrdinalIgnoreCase)){context.Response.StatusCode=404;return;} await next(); }); } }