using System.Text.Json; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using PlotLine.Data; using PlotLine.Models.Investigations; using PlotLine.Services.Investigations; internal static class InvestigationGuidanceTests { public static async Task Run() { void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS Investigation companion "+name);} var repo=new InvestigationMemoryRepository();var store=new GuidanceMemoryRepository(repo);var service=new InvestigationGuidanceService(store,repo,new MemoryCache(new MemoryCacheOptions()),new ConfigurationBuilder().Build()); var c=(await repo.Catalogue())!;var hypotheses=c.Hypotheses.Where(h=>h.Capabilities.Count>0).Take(2).ToArray(); var i=new Investigation{ID=Guid.NewGuid(),UserID=4,BookID=12,ProjectID=7,CatalogueVersion=c.Version,Concern=c.Concerns[0].Id}; var evaluation=new Evaluation{Outcome="SupportedRecommendation",Recommendations=hypotheses.Select(h=>h.Id).ToList()};await repo.Save(i,0,"fixture",evaluation); var r=(await store.Read(4,7,12,i.ID))!;var before=JsonSerializer.Serialize(await repo.Read(4,12,i.ID),CatalogueValidator.Json);var events=await repo.Replay(4,12,i.ID); var summary=service.Summary(r,c);Check(summary.Findings.Count==2,"multiple saved findings and their mapped tools"); var h=hypotheses[0];var cap=h.Capabilities[0];var route=await service.Open(4,r,c,h.Id,cap);r=(await store.Read(4,7,12))!; Check(route.Controller!="WritingProblems"&&r.IsActive,"same-window trusted authenticated destination and activation"); var s=InvestigationGuidanceService.Decode(r).State;Check(s.Progress[InvestigationGuidanceService.Key(h.Id,cap)]=="Exploring","opening starts exploration, never Done"); s.Progress[InvestigationGuidanceService.Key(h.Id,cap)]="Done";await service.Save(4,r,s,"save");r=(await store.Read(4,7,12))!;await service.Open(4,r,c,h.Id,cap);r=(await store.Read(4,7,12))!; Check(InvestigationGuidanceService.Decode(r).State.Progress[InvestigationGuidanceService.Key(h.Id,cap)]=="Done","explicit completion survives reopening and resume"); s=InvestigationGuidanceService.Decode(r).State;service.Select(r,c,s,hypotheses[1].Id,null);await service.Save(4,r,s,"save");r=(await store.Read(4,7,12))!;Check(InvestigationGuidanceService.Decode(r).State.Finding==hypotheses[1].Id,"selected finding persists"); try{service.Select(r,c,s,"invented",cap);throw new Exception("invalid selection accepted");}catch(ArgumentException){Check(true,"invalid finding rejected");} var disabled=new InvestigationGuidanceService(store,repo,new MemoryCache(new MemoryCacheOptions()),new ConfigurationBuilder().AddInMemoryCollection(new Dictionary{{"WriterInvestigations:Capabilities:"+cap+":Enabled","false"}}).Build()); try{await disabled.Open(4,r,c,h.Id,cap);throw new Exception("unavailable destination accepted");}catch(ArgumentException){Check(true,"unavailable destination retains investigation");} Check(await store.Read(5,7,12,i.ID)==null&&await store.Read(4,7,13,i.ID)==null,"private author and book boundaries"); await service.Save(4,r,s,"finish");Check(await store.Read(4,7,12)==null&&(await store.Read(4,7,12,i.ID))!.Finished,"finished journey is inactive but retained"); r=(await store.Read(4,7,12,i.ID))!;await service.Save(4,r,s,"activate");Check((await store.Read(4,7,12))!.IsActive,"finished investigation can be reactivated"); var afterEvents=await repo.Replay(4,12,i.ID);var after=await repo.Read(4,12,i.ID); Check(before==JsonSerializer.Serialize(after,CatalogueValidator.Json)&&events.SequenceEqual(afterEvents),"canonical answers, diagnostic scores and event history unchanged"); foreach(var state in new[]{"saved","partial","completed"}){ var owned=new Investigation{ID=Guid.NewGuid(),UserID=4,ProjectID=7,BookID=12,CatalogueVersion=c.Version,Concern=c.Concerns[0].Id,CurrentQuestion=state=="completed"?null:c.Questions[0].Id,Accepted=state=="completed"}; owned.Answers.Add(new(c.Questions[0].Id,c.Questions[0].Options[0].Id,"original"));await repo.Save(owned,0,state,evaluation);owned.Answers[0]=new(c.Questions[0].Id,c.Questions[0].Options.Last().Id,"revised");await repo.Save(owned,owned.Version,"revision",evaluation); foreach(var scope in new[]{(5,7,12),(4,8,12),(4,7,13)}){try{await repo.Delete(scope.Item1,scope.Item2,scope.Item3,owned.ID);throw new Exception("foreign deletion accepted");}catch(UnauthorizedAccessException){}} await repo.Delete(4,7,12,owned.ID);await repo.Delete(4,7,12,owned.ID); Check(await repo.Read(4,12,owned.ID)==null&&(await repo.List(4,12)).All(x=>x.ID!=owned.ID)&&await store.Read(4,7,12,owned.ID)==null,"delete "+state+" removes saved, resume and guidance projections; repeats are safe"); try{await repo.Save(owned,owned.Version,"stale answer",evaluation);throw new Exception("deleted update recreated record");}catch(KeyNotFoundException){} try{await repo.Save(owned,0,"replayed Begin",evaluation);throw new Exception("deleted Begin recreated record");}catch(KeyNotFoundException){} } Check(await repo.Read(4,12,i.ID)!=null,"deletion preserves unrelated investigations and their accepted tool progress"); r.InvestigationJson=JsonSerializer.Serialize(new Investigation{ID=i.ID,UserID=4,ProjectID=7,BookID=12,CatalogueVersion=c.Version,Concern=c.Concerns[0].Id},CatalogueValidator.Json);r.EvaluationJson=null;Check(service.Summary(r,c).Findings.Count==0,"old records without snapshots remain readable without invented advice"); } } // Transport-only fixture. SQL permission/concurrency tests separately exercise the actual stored procedure. internal sealed class GuidanceMemoryRepository(IInvestigationRepository investigations):IInvestigationGuidanceRepository { readonly Dictionary rows=[]; public async Task Read(int user,int? project,int? book,Guid? id=null) { if(id==null)id=rows.Where(x=>x.Value.User==user&&(book==null||x.Value.Book==book)&&x.Value.Active).Select(x=>(Guid?)x.Key).FirstOrDefault();if(id==null)return null; var scopedBook=book??(rows.TryGetValue(id.Value,out var existing)?existing.Book:12);var i=await investigations.Read(user,scopedBook,id.Value);if(i==null||project!=null&&i.ProjectID!=project)return null; rows.TryGetValue(id.Value,out var state);var events=await investigations.Replay(user,i.BookID,id.Value);using var ev=JsonDocument.Parse(events.Last()); return new(){ID=i.ID,ProjectID=i.ProjectID,BookID=i.BookID,BookTitle="Fixture book",InvestigationJson=JsonSerializer.Serialize(i,CatalogueValidator.Json),EvaluationJson=ev.RootElement.GetProperty("evaluation").GetRawText(),GuidanceJson=state.Json,GuidanceVersion=state.Version,IsActive=state.Active,Finished=state.Finished}; } // Saved-summary projection for browser save/resume qualification; mirrors the existing repository contract. public async Task> List(int user,int book) { var list=await investigations.List(user,book); return list.Select(i=>{ rows.TryGetValue(i.ID,out var state); return new SavedInvestigation(i.ID,i.BookID,i.CatalogueVersion,i.Concern,i.CurrentQuestion==null?"Results available":"In progress",i.UpdatedUtc,state.Version,state.Active,state.Finished); }).ToArray(); } public async Task Save(int user,int book,Guid id,int version,string operation,string json) { var i=await investigations.Read(user,book,id)??throw new UnauthorizedAccessException();rows.TryGetValue(id,out var old);if(old.Version!=version)throw new ArgumentException("Stale guidance"); if(operation=="activate")foreach(var other in rows.Keys.ToArray()){var x=rows[other];if(x.User==user&&x.Book==book)rows[other]=(x.User,x.Book,x.Json,x.Version,false,x.Finished);} rows[id]=(user,book,json,version+1,operation=="activate"||operation=="save"&&old.Active,operation=="finish"||operation!="activate"&&old.Finished); } }