Add Development-only owner review and reproducible solver feedback
This commit is contained in:
parent
df90d03048
commit
2858a5df95
4
.gitignore
vendored
4
.gitignore
vendored
@ -360,4 +360,6 @@ MigrationBackup/
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
FodyWeavers.xsd
|
||||
# Private Development-only solver owner feedback (never source or public content).
|
||||
/PlotLine/App_Data/WritingSolverReview/
|
||||
|
||||
1
Docs/WritingSolver/ReviewMode/Evidence/clean-urls.txt
Normal file
1
Docs/WritingSolver/ReviewMode/Evidence/clean-urls.txt
Normal file
@ -0,0 +1 @@
|
||||
PASS clean URLs: 52 direct pages; private evidence/refresh/fresh sharing; Back/Forward; revised diagnosis; 390/1440; JS/no-JS; canonical/OG/structured data; robots; sitemap Development noindex
|
||||
@ -0,0 +1 @@
|
||||
PASS Development review: admin-only opt-in; collapsed observer; signal arithmetic; result snapshot/export/replay/resolve/resume; filters; direct-entry unchanged; revision and Back/Forward; multi-select; neutral and insufficient outcomes; no-JS at 390/1440; forged cookie denied.
|
||||
1
Docs/WritingSolver/ReviewMode/Evidence/journeys.txt
Normal file
1
Docs/WritingSolver/ReviewMode/Evidence/journeys.txt
Normal file
@ -0,0 +1 @@
|
||||
PASS dead-end repair: reported four-answer route; changed hypothesis; knowledge search; six-answer rescue/POV/intended-main routes; Plot Lines, timeline/continuity, relationships, scene/chapter, series, knowledge and character arc; evidence variants; optional secondary/article; explicit missing visuals; no article dump; reassurance/insufficient evidence; no-JS; 390/1440px; Back/Forward/Restart; public theme and noindex; signed-out tour CTA; signed-in authorised project/character selector and real workspace redirects.
|
||||
@ -0,0 +1 @@
|
||||
PASS Production review endpoints 404 and no UI even with forged admin/mode cookies.
|
||||
5
Docs/WritingSolver/ReviewMode/Evidence/regressions.txt
Normal file
5
Docs/WritingSolver/ReviewMode/Evidence/regressions.txt
Normal file
@ -0,0 +1,5 @@
|
||||
Build: success, zero errors; two pre-existing nullable warnings in test code.
|
||||
Regression harness: 394 PASS, exit 0.
|
||||
New observer audit: every prefix of all 60 acceptance paths compared with the unchanged engine, including signal contribution sums, diagnosis score calculations, returned ordering, route ranking and multi-select ID/label agreement. Graph fingerprint unchanged after observation.
|
||||
Access/storage audit: anonymous forged cookie denied; opted-in Development admin allowed; Production cookie denied and storage unavailable; saved feedback survives a new store instance; resolution preserves captured timestamp; replay preserves original version/hash.
|
||||
HTTP negative checks: missing antiforgery token, unknown category, note over 2,000 characters and invalid protected history all rejected with 400.
|
||||
48
Docs/WritingSolver/ReviewMode/Report.md
Normal file
48
Docs/WritingSolver/ReviewMode/Report.md
Normal file
@ -0,0 +1,48 @@
|
||||
# Development Writing Solver Review Mode
|
||||
|
||||
## Owner workflow
|
||||
|
||||
Sign in with an account already authorised by PlotDirector's existing `AdminOnly` policy. Open **Admin → Writing Solver Review Mode**, or `/admin/writing-solver-review`. Choose **Enable Writing Solver Review Mode**. This redirects to the ordinary `/writing-problems` page. The opt-in applies to this browser for 24 hours. Disable it from the review page; it has no effect on the saved feedback.
|
||||
|
||||
Use the solver normally. A small **Review journey · Development only** disclosure sits below the ordinary journey. It stays closed by default. No debug labels, IDs or scores enter the author-facing questions/results. Fresh direct-entry permanent resources remain unchanged, including for an opted-in reviewer. Completed solver arrivals retain clean URLs and personalised evidence.
|
||||
|
||||
Expand the disclosure to inspect the accepted conversation plus current question. It shows question/answer labels and IDs (including multi-select), answer count, engine stop reason, each transition's eligible routes in ranked order, route restrictions, priority and affinity rank, accumulated signals with every question/answer contribution, and diagnosis weighted-signal terms, thresholds and missing required evidence. Returned results are explicitly labelled primary/supporting; five other highest-scoring candidates are shown for comparison. These candidates are not presented as diagnoses. Start Here, secondary capability and advice article are recorded where applicable.
|
||||
|
||||
The observer uses outcomes from the existing engine at every prefix. Route reasoning describes its existing choice/signal/count filters, priority plus affinity rank and target-order/ID tie-breaks. Selected fallback answers are labelled. Rescue targets remain identifiable by their actual node IDs; no new routing categories or behaviour are invented. A winning route can be suppressed by an engine stop; the panel says so.
|
||||
|
||||
## Feedback
|
||||
|
||||
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
|
||||
|
||||
An optional note permits up to 2,000 characters. The UI asks reviewers to omit manuscript prose. Capture records accepted answers and the current step/result; unsubmitted selections and abandoned branches are not included. After saving, the item opens for inspection. **Resume this journey** returns to the accepted path if the graph fingerprint still matches, using fresh protected state and the normal solver flow.
|
||||
|
||||
The review list defaults to unresolved items, newest first; filter by category and unresolved/resolved/all. Items can be resolved and reopened. Each item has a selectable compact reproduction summary and an authenticated JSON download.
|
||||
|
||||
## Captured data and replay
|
||||
|
||||
Each record has a GUID, category, optional note, clean page path, resolved state and immutable captured snapshot. The snapshot contains graph version/SHA-256 fingerprint, UTC timestamp, answer count, current node/question, stop reason, answered steps and transition reasoning, ranked eligible routes, signal sources/totals, returned and comparison diagnosis scores/thresholds/weighted terms/missing evidence, primary/secondary capability, article reference, neutral result title where relevant, and the accepted `SolverAnswer` sequence.
|
||||
|
||||
**Replay against current Development graph** is read-only. Captured and current outcomes appear under separate headings with their own version/fingerprint. It states how many captured answers the current engine accepted; changed/deleted routes discard a stale suffix normally. Replay never overwrites the capture or changes status. Exported `Captured.Answers` can also be used as regression-harness input. Resume refuses a changed graph and directs the reviewer to replay instead.
|
||||
|
||||
## Storage and privacy
|
||||
|
||||
Simple atomic JSON files, one per feedback item, in persistent `App_Data/WritingSolverReview/`. The existing Development deployment convention preserves `App_Data`; normal restart/redeployment does not remove feedback. This is a deliberately small file-backed review log, not a ticketing subsystem or database migration. New directory permissions are 0700 and files 0600 on Linux. Atomic temporary-file replacement and a singleton write lock protect status/capture updates. The folder is explicitly excluded from Git and is outside static web roots.
|
||||
|
||||
No manuscript prose, workspace content, project/book/character identifiers, account names, email addresses, credentials, protected history tokens or browsing history are automatically stored. Notes are plain text, escaped by Razor. Captures describe only the public solver conversation. Export/list/detail/replay/status/capture/enable actions all require existing admin authorisation and Development environment. Every mutation requires antiforgery validation. A forged opt-in cookie grants no authority. The cookie is HttpOnly, SameSite Strict and Secure on HTTPS.
|
||||
|
||||
Outside Development, review endpoints return 404 before authentication, no admin link or review panel renders, and storage refuses access. The environment gate cannot be overridden by the mode cookie or a request parameter. No Production configuration or deployment changes.
|
||||
|
||||
## Baseline preservation
|
||||
|
||||
No solver engine, graph/candidate JSON, scoring, thresholds, routes, questions, answers, diagnosis data, recommendations, permanent editorial content, theme or screenshot changes. Normal mode never builds a review snapshot. Only the two existing journey-rendering views call the gated partial; direct generic result views do not.
|
||||
|
||||
Validation and deployed runtime details are recorded in [Deployment.md](Deployment.md).
|
||||
27
PlotLine.Tests/Browser/writing-solver-review.cjs
Normal file
27
PlotLine.Tests/Browser/writing-solver-review.cjs
Normal file
@ -0,0 +1,27 @@
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
|
||||
const base='http://127.0.0.1:5238',production=process.env.REVIEW_EXPECT_PRODUCTION==='true';
|
||||
const cases=JSON.parse(fs.readFileSync('PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1-repair/acceptance-paths.json')).cases;
|
||||
(async()=>{const b=await chromium.launch();const created=[];try{
|
||||
const ordinary=await b.newContext();await ordinary.addCookies([{name:'pd-solver-review',value:'on',url:base}]);const op=await ordinary.newPage();await op.goto(base+'/writing-problems');assert.equal(await op.locator('.solver-review').count(),0);assert.equal((await ordinary.request.get(base+'/admin/writing-solver-review',{maxRedirects:0})).status(),production?404:403);await ordinary.close();
|
||||
const anon=await b.newContext();await anon.addCookies([{name:'solver-anonymous',value:'true',url:base},{name:'pd-solver-review',value:'on',url:base}]);assert.equal((await anon.request.get(base+'/admin/writing-solver-review',{maxRedirects:0})).status(),production?404:401);await anon.close();
|
||||
for(const width of [390,1440]){const c=await b.newContext({viewport:{width,height:1000},javaScriptEnabled:false});await c.addCookies([{name:'solver-reviewer',value:'true',url:base}]);const p=await c.newPage();await p.goto(base+'/writing-problems');assert.equal(await p.locator('.solver-review').count(),0);
|
||||
if(production){assert.equal((await c.request.get(base+'/admin/writing-solver-review')).status(),404);await c.addCookies([{name:'pd-solver-review',value:'on',url:base}]);await p.reload();assert.equal(await p.locator('.solver-review').count(),0);await c.close();continue;}
|
||||
await p.goto(base+'/admin/writing-solver-review');await p.getByRole('button',{name:'Enable Writing Solver Review Mode',exact:true}).click();assert.equal(new URL(p.url()).pathname,'/writing-problems');assert.equal(await p.locator('.solver-review').count(),1);assert.equal(await p.locator('.solver-review').getAttribute('open'),null);await p.locator('.solver-review > summary').click();assert((await p.locator('.solver-review').innerText()).includes('0 accepted answers'));
|
||||
async function choose(choice){await p.locator(`.solver-form input[name=choices][value="${choice}"]`).check();await p.locator('.solver-form button[type=submit]').click();}
|
||||
for(const answer of ['story-not-working','too-many'])await choose(answer);
|
||||
await p.goBack();assert.equal(await p.locator('input[name=node]').inputValue(),'story-problem');await p.goForward();
|
||||
await choose('lost');await choose('unwanted');assert(new URL(p.url()).pathname.endsWith('/too-many-storylines-to-manage'));assert((await p.locator('.solver-result-evidence').innerText()).length>40);
|
||||
await p.locator('.solver-review > summary').click();const panel=p.locator('.solver-review');assert((await panel.innerText()).includes('4 accepted answers'));assert((await panel.innerText()).includes('Primary: d01'));assert((await panel.innerText()).includes('Priority'));
|
||||
await panel.locator('select[name=category]').selectOption('Result feels wrong');await panel.locator('textarea[name=note]').fill('Review verification <script>not executed</script>');await panel.getByRole('button',{name:'Capture feedback',exact:true}).click();
|
||||
const id=new URL(p.url()).pathname.split('/').at(-1);assert.match(id,/^[0-9a-f-]{36}$/);created.push(id);assert.equal(await p.locator('h1').innerText(),'Writing Solver feedback');const response=await c.request.get(base+'/admin/writing-solver-review/'+id+'/export');const item=await response.json();assert.equal(item.Category,'Result feels wrong');assert.equal(item.Captured.AnswerCount,4);assert.equal(item.Captured.Diagnoses.filter(d=>d.Returned)[0].Id,'d01');assert(item.Captured.Signals.every(s=>s.Value===s.Sources.reduce((a,b)=>a+b.Value,0)));assert.equal(item.Page,'/writing-problems/too-many-storylines-to-manage');assert.equal(item.Resolved,false);
|
||||
await p.getByRole('button',{name:'Replay against current Development graph'}).click();assert.equal(await p.getByRole('heading',{name:'Captured result at the time'}).count(),1);assert.equal(await p.getByRole('heading',{name:'Current result when replayed'}).count(),1);assert.equal((await (await c.request.get(base+'/admin/writing-solver-review/'+id+'/export')).json()).Captured.CapturedUtc,item.Captured.CapturedUtc);
|
||||
await p.getByRole('button',{name:'Mark resolved',exact:true}).click();assert((await (await c.request.get(base+'/admin/writing-solver-review/'+id+'/export')).json()).Resolved);
|
||||
await p.getByRole('button',{name:'Resume this journey'}).click();assert(new URL(p.url()).pathname.endsWith('/too-many-storylines-to-manage'));assert((await p.locator('.solver-result-evidence').innerText()).length>40);
|
||||
await p.getByRole('link',{name:'← Back',exact:true}).click();assert.equal(await p.locator('input[name=node]').inputValue(),'intent-threads');await p.getByRole('link',{name:'← Back',exact:true}).click();await p.getByRole('link',{name:'← Back',exact:true}).click();await choose('dont-connect');await choose('gap');await choose('unwanted');assert(new URL(p.url()).pathname.endsWith('/storyline-disappears-for-too-long'));
|
||||
// Review mode must not add a panel to fresh direct-entry result resources.
|
||||
const fresh=await b.newContext();await fresh.addCookies([{name:'solver-reviewer',value:'true',url:base},{name:'pd-solver-review',value:'on',url:base}]);const fp=await fresh.newPage();await fp.goto(base+'/writing-problems/too-many-storylines-to-manage');assert.equal(await fp.locator('.solver-review').count(),0);await fresh.close();
|
||||
for(const test of [cases.find(c=>c.answers.some(a=>a.choices.length>1)),cases.find(c=>c.id===50)]){await p.goto(base+'/writing-problems');for(const a of test.answers){for(const choice of a.choices)await p.locator(`input[name=choices][value="${choice}"]`).check();await p.locator('.solver-form button[type=submit]').click();}assert.equal(await p.locator('.solver-review').count(),1);await p.locator('.solver-review > summary').click();assert.equal(await p.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);}
|
||||
await p.goto(base+'/writing-problems');for(const choice of ['unsure','reread-cant-see','using-tool-concern','draft-done','discovery'])await choose(choice);assert.equal(await p.locator('.solver-neutral').count(),1);assert.equal(await p.locator('.solver-review').count(),1);
|
||||
await p.goto(base+'/admin/writing-solver-review?status=resolved&category='+encodeURIComponent('Result feels wrong'));assert(await p.locator('a[href="/admin/writing-solver-review/'+id+'"]').count());await p.getByRole('button',{name:'Disable Writing Solver Review Mode',exact:true}).click();await p.goto(base+'/writing-problems');assert.equal(await p.locator('.solver-review').count(),0);await c.close();}
|
||||
console.log('PASS '+(production?'Production review endpoints 404 and no UI even with forged admin/mode cookies.':'Development review: admin-only opt-in; collapsed observer; signal arithmetic; result snapshot/export/replay/resolve/resume; filters; direct-entry unchanged; revision and Back/Forward; multi-select; neutral and insufficient outcomes; no-JS at 390/1440; forged cookie denied.'));
|
||||
}finally{await b.close();for(const id of created){const path='PlotLine/App_Data/WritingSolverReview/'+id+'.json';if(fs.existsSync(path))fs.unlinkSync(path);}}})().catch(e=>{console.error(e);process.exit(1)});
|
||||
@ -96,6 +96,7 @@ var tests = new (string Name, Action Test)[]
|
||||
("Curated V2 preserves 60 literal paths and enforces eight explicit Development review exceptions", WritingSolverCuratedV2Tests.Acceptance),
|
||||
("Curated V2 exhausts real-engine states and preserves revision/multi-select behaviour", WritingSolverCuratedV2Tests.ReachabilityAndRevision),
|
||||
("Curated V2 passes normal validation and invalid publication stays guarded", WritingSolverCuratedV2Tests.ExistingValidatorBoundary),
|
||||
("Development review observes every acceptance prefix without changing signals, results or graph; access and durable capture stay isolated", WritingSolverReviewTests.Audit),
|
||||
("All permanent writing problems have distinct editorial content, intent, metadata, links and real images", WritingProblemEditorialTests.Audit),
|
||||
("Clean solver completion preserves private evidence and permanent indexable URLs", WritingSolverCleanUrlTests.TransitionAndIsolation),
|
||||
("Writing Solver anonymous state is protected, expires and rejects stale versions", WritingSolverTests.AnonymousState),
|
||||
|
||||
@ -79,17 +79,23 @@ internal static class ToolbarBrowserHost
|
||||
builder.Services.AddSingleton<IWritingSolverWorkspaceContext, SolverWorkspaceFixture>();
|
||||
builder.Services.AddMemoryCache();
|
||||
builder.Services.AddSingleton<WritingSolverResultContext>();
|
||||
builder.Services.AddScoped<WritingSolverReview>();
|
||||
builder.Services.AddSingleton<WritingSolverReviewStore>();
|
||||
builder.Services.AddAuthorization(options=>options.AddPolicy("AdminOnly",policy=>policy.RequireClaim(ClaimTypes.Role,"SolverReviewer")));
|
||||
builder.Services.AddSingleton(new WritingProblemEditorial(Path.GetFullPath("PlotLine/Content/WritingSolver/Editorial/pages-v1.json")));
|
||||
builder.Services.AddSingleton(new WritingSolverResults(Path.GetFullPath("PlotLine/Content/WritingSolver/Presentation/results-v1.json")));
|
||||
builder.Services.AddSingleton<IHelpMarkdownRenderer, HelpMarkdownRenderer>();
|
||||
builder.Services.AddScoped<ICurrentUserService>(services => new ToolbarTestUser(int.Parse(services.GetRequiredService<IHttpContextAccessor>().HttpContext!.User.FindFirstValue(ClaimTypes.NameIdentifier)!)));
|
||||
builder.Services.AddAuthentication("ReviewFixture").AddCookie("ReviewFixture",options=>{options.Events.OnRedirectToLogin=c=>{c.Response.StatusCode=401;return Task.CompletedTask;};options.Events.OnRedirectToAccessDenied=c=>{c.Response.StatusCode=403;return Task.CompletedTask;};});
|
||||
var app = builder.Build();
|
||||
app.UseWritingSolverReviewBoundary();
|
||||
app.Urls.Add("http://127.0.0.1:5238");
|
||||
app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.GetFullPath("PlotLine/wwwroot")) });
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
var user = context.Request.Cookies["fixture-user"] == "5" ? "5" : "4";
|
||||
context.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user), new Claim(ClaimTypes.Name, "Fixture Author")], "Fixture"));
|
||||
if(context.Request.Cookies["solver-reviewer"]=="true") ((ClaimsIdentity)context.User.Identity!).AddClaim(new Claim(ClaimTypes.Role,"SolverReviewer"));
|
||||
if(context.Request.Cookies["solver-anonymous"]=="true") context.User=new ClaimsPrincipal(new ClaimsIdentity());
|
||||
await next();
|
||||
});
|
||||
|
||||
64
PlotLine.Tests/WritingSolverReviewTests.cs
Normal file
64
PlotLine.Tests/WritingSolverReviewTests.cs
Normal file
@ -0,0 +1,64 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models.WritingSolver;
|
||||
using PlotLine.Services;
|
||||
internal static class WritingSolverReviewTests
|
||||
{
|
||||
private sealed class EnvironmentFixture(string root,string name):IWebHostEnvironment
|
||||
{
|
||||
public string EnvironmentName{get;set;}=name;public string ApplicationName{get;set;}="PlotLine";
|
||||
public string ContentRootPath{get;set;}=root;public string WebRootPath{get;set;}=root;
|
||||
public IFileProvider ContentRootFileProvider{get;set;}=new NullFileProvider();public IFileProvider WebRootFileProvider{get;set;}=new NullFileProvider();
|
||||
}
|
||||
private sealed class Authorization:IAuthorizationService
|
||||
{
|
||||
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user,object? resource,IEnumerable<IAuthorizationRequirement> requirements)=>Task.FromResult(user.IsInRole("Admin")?AuthorizationResult.Success():AuthorizationResult.Failed());
|
||||
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user,object? resource,string policyName)=>AuthorizeAsync(user,resource,Array.Empty<IAuthorizationRequirement>());
|
||||
}
|
||||
public static void Audit()=>Run().GetAwaiter().GetResult();
|
||||
private static async Task Run()
|
||||
{
|
||||
void Check(bool ok,string reason){if(!ok)throw new Exception(reason);}
|
||||
var root=Path.Combine(Path.GetTempPath(),"solver-review-test-"+Guid.NewGuid());Directory.CreateDirectory(root);
|
||||
try
|
||||
{
|
||||
var env=new EnvironmentFixture(root,"Development");var service=new WritingSolverReview(env,new Authorization(),WritingSolverResultTests.Content());
|
||||
var graph=WritingSolverRepository.Parse(File.ReadAllText(Path.Combine(WritingSolverCuratedV2Tests.Root(),"PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1-repair/writing-solver-curated-v2-stage1-repair.json")));
|
||||
var original=WritingSolverReview.Hash(graph);
|
||||
using var paths=JsonDocument.Parse(File.ReadAllText("PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1-repair/acceptance-paths.json"));
|
||||
foreach(var path in paths.RootElement.GetProperty("cases").EnumerateArray())
|
||||
{
|
||||
var answers=path.GetProperty("answers").Deserialize<List<SolverAnswer>>(WritingSolverRepository.JsonOptions)!;
|
||||
for(var n=0;n<=answers.Count;n++)
|
||||
{
|
||||
var input=answers.Take(n).ToList();var outcome=WritingSolverEngine.Evaluate(graph,input);var snapshot=service.Capture(graph,input);
|
||||
Check(snapshot.AnswerCount==outcome.Answers.Count&&snapshot.CurrentNode==outcome.Next?.Id,"Review prefix changed current route.");
|
||||
Check(snapshot.Signals.All(s=>s.Value==outcome.Scores[s.Signal]&&s.Sources.Sum(x=>x.Value)==s.Value),"Signal contribution arithmetic differs from engine.");
|
||||
Check(snapshot.Diagnoses.Where(d=>d.Returned).Select(d=>d.Id).SequenceEqual(outcome.Solutions.Select(s=>s.Id)),"Returned diagnosis order differs from engine.");
|
||||
foreach(var d in snapshot.Diagnoses){var solution=graph.Solutions.Single(s=>s.Id==d.Id);Check(d.Score==solution.Signals.Sum(w=>outcome.Scores.GetValueOrDefault(w.Key)*w.Value),"Diagnosis score differs from engine.");}
|
||||
Check(snapshot.Steps.Count==snapshot.AnswerCount,"Missing accepted step.");
|
||||
if(outcome.Next is not null&&snapshot.Steps.Count>0)Check(snapshot.Steps[^1].Candidates[0].StartsWith(outcome.Next.Id+":"),"Route reasoning ranks a different next question from the engine.");
|
||||
foreach(var step in snapshot.Steps)for(var i=0;i<step.Answers.Length;i++)Check(graph.Nodes.Single(x=>x.Id==step.Node).Choices.Single(x=>x.Id==step.ChoiceIds[i]).Text==step.Answers[i],"Multi-select labels do not match IDs.");
|
||||
}
|
||||
}
|
||||
Check(original==WritingSolverReview.Hash(graph),"Instrumentation mutated graph.");
|
||||
var http=new DefaultHttpContext();http.Request.Headers.Cookie=WritingSolverReview.Cookie+"=on";
|
||||
Check(!await service.Enabled(http),"Anonymous review cookie bypassed authorization.");
|
||||
http.User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.Role,"Admin")],"test"));Check(await service.Enabled(http),"Development admin cannot enable review.");
|
||||
env.EnvironmentName="Production";Check(!await service.Enabled(http),"Production review was enabled.");
|
||||
try{await new WritingSolverReviewStore(env).List();throw new Exception("Production store allowed access.");}catch(InvalidOperationException){}
|
||||
env.EnvironmentName="Development";var store=new WritingSolverReviewStore(env);var captured=service.Capture(graph,[]);
|
||||
var record=new SolverReviewFeedback(Guid.NewGuid(),"Other","Test note","/writing-problems",false,captured);await store.Save(record);
|
||||
var restarted=new WritingSolverReviewStore(env);Check((await restarted.Find(record.Id))?.Captured.GraphHash==original,"Feedback not durable across service instances.");
|
||||
await restarted.Resolve(record.Id,true);Check((await restarted.Find(record.Id))!.Resolved,"Resolved state not durable.");
|
||||
Check((await restarted.Find(record.Id))!.Captured.CapturedUtc==captured.CapturedUtc,"Updating status modified captured result.");
|
||||
graph.Version+="-replay";var replay=service.Capture(graph,captured.Answers);Check(replay.Version!=record.Captured.Version&&record.Captured.GraphHash==original,"Replay overwrote capture.");
|
||||
}
|
||||
finally{Directory.Delete(root,true);}
|
||||
}
|
||||
}
|
||||
85
PlotLine/Controllers/WritingSolverReviewController.cs
Normal file
85
PlotLine/Controllers/WritingSolverReviewController.cs
Normal file
@ -0,0 +1,85 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models.WritingSolver;
|
||||
using PlotLine.Services;
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
// Run before authorization: even the review endpoints are unavailable outside Development.
|
||||
public sealed class SolverReviewDevelopmentOnlyAttribute : Attribute,IAsyncAuthorizationFilter,IOrderedFilter
|
||||
{
|
||||
public int Order=>int.MinValue;
|
||||
public Task OnAuthorizationAsync(AuthorizationFilterContext context)
|
||||
{
|
||||
if(!context.HttpContext.RequestServices.GetRequiredService<IWebHostEnvironment>().IsDevelopment())context.Result=new NotFoundResult();
|
||||
context.HttpContext.Response.Headers.CacheControl="private, no-store";
|
||||
context.HttpContext.Response.Headers["X-Robots-Tag"]="noindex, nofollow";
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
[SolverReviewDevelopmentOnly]
|
||||
[Authorize(Policy="AdminOnly")]
|
||||
[Route("admin/writing-solver-review")]
|
||||
public sealed class WritingSolverReviewController(WritingSolverReview review,WritingSolverReviewStore store,IWritingSolverRepository repository,IDataProtectionProvider protection):Controller
|
||||
{
|
||||
private sealed record History(string Version,List<SolverAnswer> Answers);
|
||||
[HttpGet("")]
|
||||
public async Task<IActionResult> Index(string? category=null,string? status="unresolved")
|
||||
{
|
||||
var items=await store.List();
|
||||
return View(new SolverReviewList(items.Where(x=>(category is null||x.Category==category)&&(status!="resolved"||x.Resolved)&&(status!="unresolved"||!x.Resolved)).ToArray(),await review.Enabled(HttpContext),category,status));
|
||||
}
|
||||
[HttpPost("mode")][ValidateAntiForgeryToken]
|
||||
public IActionResult Mode(bool enabled)
|
||||
{
|
||||
if(enabled)Response.Cookies.Append(WritingSolverReview.Cookie,"on",new CookieOptions{HttpOnly=true,Secure=Request.IsHttps,SameSite=SameSiteMode.Strict,IsEssential=true,Path="/",MaxAge=TimeSpan.FromDays(1)});
|
||||
else Response.Cookies.Delete(WritingSolverReview.Cookie,new CookieOptions{Path="/"});
|
||||
return Redirect(enabled?"/writing-problems":"/admin/writing-solver-review");
|
||||
}
|
||||
[HttpPost("feedback")][ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Feedback(string state,string category,string? note)
|
||||
{
|
||||
if(!await review.Enabled(HttpContext))return Forbid();
|
||||
if(!WritingSolverReview.Categories.Contains(category)||note?.Length>2000||state is null||state.Length>16000)return BadRequest("Choose a feedback category and use at most 2,000 characters.");
|
||||
try
|
||||
{
|
||||
var protector=protection.CreateProtector("WritingSolver.history.v1").ToTimeLimitedDataProtector();
|
||||
var history=JsonSerializer.Deserialize<History>(protector.Unprotect(state,out _));
|
||||
var graph=await repository.GetAsync();
|
||||
if(history is null||history.Version!=graph.Version)return Conflict("The graph changed. Reopen the solver before capturing feedback.");
|
||||
var captured=review.Capture(graph,history.Answers);
|
||||
if(captured.AnswerCount!=history.Answers.Count)return BadRequest("This journey is no longer valid. Reopen the solver before capturing feedback.");
|
||||
var outcome=WritingSolverEngine.Evaluate(graph,history.Answers);
|
||||
var path=outcome.Solutions.FirstOrDefault() is {} solution?"/writing-problems/"+solution.Slug:"/writing-problems";
|
||||
var item=new SolverReviewFeedback(Guid.NewGuid(),category,string.IsNullOrWhiteSpace(note)?null:note.Trim(),path,false,captured);
|
||||
await store.Save(item);
|
||||
return RedirectToAction(nameof(Detail),new{id=item.Id});
|
||||
}
|
||||
catch(Exception ex)when(ex is CryptographicException or JsonException){return BadRequest("The review journey expired. Reopen the solver before capturing feedback.");}
|
||||
}
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<IActionResult> Detail(Guid id)
|
||||
{var item=await store.Find(id);return item is null?NotFound():View(new SolverReviewDetail(item,null));}
|
||||
[HttpPost("{id:guid}/status")][ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Status(Guid id,bool resolved)
|
||||
{if(!await store.Resolve(id,resolved))return NotFound();return RedirectToAction(nameof(Detail),new{id});}
|
||||
[HttpPost("{id:guid}/replay")][ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Replay(Guid id)
|
||||
{var item=await store.Find(id);return item is null?NotFound():View("Detail",new SolverReviewDetail(item,review.Capture(await repository.GetAsync(),item.Captured.Answers)));}
|
||||
[HttpPost("{id:guid}/resume")][ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Resume(Guid id)
|
||||
{
|
||||
var item=await store.Find(id);if(item is null)return NotFound();var graph=await repository.GetAsync();
|
||||
if(WritingSolverReview.Hash(graph)!=item.Captured.GraphHash)return Conflict("The graph has changed. Replay this capture to compare it with the current conversation.");
|
||||
var protector=protection.CreateProtector("WritingSolver.history.v1").ToTimeLimitedDataProtector();
|
||||
var state=protector.Protect(JsonSerializer.Serialize(new History(graph.Version,item.Captured.Answers)),TimeSpan.FromHours(2));
|
||||
return RedirectToAction("Index","WritingProblems",new{state});
|
||||
}
|
||||
[HttpGet("{id:guid}/export")]
|
||||
public async Task<IActionResult> Export(Guid id)
|
||||
{var item=await store.Find(id);return item is null?NotFound():File(System.Text.Encoding.UTF8.GetBytes(JsonSerializer.Serialize(item,new JsonSerializerOptions{WriteIndented=true})),"application/json","solver-review-"+id+".json");}
|
||||
}
|
||||
10
PlotLine/Models/WritingSolver/SolverReview.cs
Normal file
10
PlotLine/Models/WritingSolver/SolverReview.cs
Normal file
@ -0,0 +1,10 @@
|
||||
namespace PlotLine.Models.WritingSolver;
|
||||
|
||||
public sealed record SolverReviewContribution(string Node, string Question, string Choice, string Answer, int Value);
|
||||
public sealed record SolverReviewSignal(string Signal, int Value, List<SolverReviewContribution> Sources);
|
||||
public sealed record SolverReviewStep(string Node, string Question, string[] ChoiceIds, string[] Answers, string? Next, string Reason, string[] Candidates);
|
||||
public sealed record SolverReviewDiagnosis(string Id, string Title, int Score, int Threshold, bool Returned, string[] Terms, string[] MissingRequirements);
|
||||
public sealed record SolverReviewSnapshot(string Version, string GraphHash, DateTimeOffset CapturedUtc, int AnswerCount, string? CurrentNode, string? CurrentQuestion, string StopReason, List<SolverReviewStep> Steps, List<SolverReviewSignal> Signals, List<SolverReviewDiagnosis> Diagnoses, string? PrimaryCapability, string? SecondaryCapability, string? Article, List<SolverAnswer> Answers, string? NeutralTitle=null);
|
||||
public sealed record SolverReviewFeedback(Guid Id, string Category, string? Note, string Page, bool Resolved, SolverReviewSnapshot Captured);
|
||||
public sealed record SolverReviewList(IReadOnlyList<SolverReviewFeedback> Items, bool Enabled, string? Category, string? Status);
|
||||
public sealed record SolverReviewDetail(SolverReviewFeedback Feedback, SolverReviewSnapshot? Replay);
|
||||
@ -116,6 +116,8 @@ public class Program
|
||||
builder.Services.AddScoped<IWritingSolverRepository, WritingSolverRepository>();
|
||||
builder.Services.AddScoped<IWritingSolverWorkspaceContext, WritingSolverWorkspaceContext>();
|
||||
builder.Services.AddSingleton<WritingSolverResultContext>();
|
||||
builder.Services.AddScoped<WritingSolverReview>();
|
||||
builder.Services.AddSingleton<WritingSolverReviewStore>();
|
||||
builder.Services.AddSingleton(services => new WritingProblemEditorial(Path.Combine(services.GetRequiredService<IWebHostEnvironment>().ContentRootPath,"Content/WritingSolver/Editorial/pages-v1.json")));
|
||||
builder.Services.AddSingleton(services => new WritingSolverResults(Path.Combine(services.GetRequiredService<IWebHostEnvironment>().ContentRootPath,"Content/WritingSolver/Presentation/results-v1.json")));
|
||||
builder.Services.AddScoped<IToolbarPreferenceRepository, ToolbarPreferenceRepository>();
|
||||
@ -324,6 +326,7 @@ public class Program
|
||||
FileProvider = new PhysicalFileProvider(uploadStorage.UploadsRootPath),
|
||||
RequestPath = "/uploads"
|
||||
});
|
||||
app.UseWritingSolverReviewBoundary();
|
||||
app.UseRouting();
|
||||
|
||||
app.UseSession();
|
||||
|
||||
105
PlotLine/Services/WritingSolverReview.cs
Normal file
105
PlotLine/Services/WritingSolverReview.cs
Normal file
@ -0,0 +1,105 @@
|
||||
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<bool> Authorized(HttpContext context)=>environment.IsDevelopment() && (await authorization.AuthorizeAsync(context.User,null,"AdminOnly")).Succeeded;
|
||||
public async Task<bool> 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<SolverAnswer> history)
|
||||
{
|
||||
var outcome=WritingSolverEngine.Evaluate(graph,history);
|
||||
var steps=new List<SolverReviewStep>();
|
||||
var sources=new Dictionary<string,List<SolverReviewContribution>>();
|
||||
var accumulated=new Dictionary<string,int>();
|
||||
for(var i=0;i<outcome.Answers.Count;i++)
|
||||
{
|
||||
var answer=outcome.Answers[i];var node=graph.Nodes.Single(n=>n.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.BeforeAnswers)&&(r.Choice is null||answer.Choices.Contains(r.Choice))&&(r.Signal is null||accumulated.GetValueOrDefault(r.Signal)>=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.Value).Select(w=>$"{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<IReadOnlyList<SolverReviewFeedback>> List()
|
||||
{
|
||||
var dir=DirectoryPath;if(!Directory.Exists(dir))return [];
|
||||
var records=new List<SolverReviewFeedback>();
|
||||
foreach(var path in Directory.EnumerateFiles(dir,"*.json"))records.Add(JsonSerializer.Deserialize<SolverReviewFeedback>(await File.ReadAllTextAsync(path))??throw new InvalidDataException("Invalid review feedback."));
|
||||
return records.OrderByDescending(x=>x.Captured.CapturedUtc).ToArray();
|
||||
}
|
||||
public async Task<SolverReviewFeedback?> Find(Guid id)
|
||||
{var path=Path.Combine(DirectoryPath,id+".json");return File.Exists(path)?JsonSerializer.Deserialize<SolverReviewFeedback>(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<bool> 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();
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -1,3 +1,4 @@
|
||||
@inject IWebHostEnvironment Environment
|
||||
@model AdminDashboardViewModel
|
||||
@{
|
||||
ViewData["Title"] = "Admin";
|
||||
@ -5,6 +6,7 @@
|
||||
}
|
||||
|
||||
<div class="admin-dashboard">
|
||||
@if(Environment.IsDevelopment()){<p><a href="/admin/writing-solver-review">Writing Solver Review Mode →</a></p>}
|
||||
<div class="page-heading compact admin-dashboard__heading">
|
||||
<div>
|
||||
<p class="eyebrow">Admin</p>
|
||||
|
||||
@ -80,6 +80,7 @@
|
||||
}
|
||||
else { <p><a class="editorial-link" href="/writing-problems/browse">Browse writing problems →</a></p><p class="solver-promises">A few quiet minutes <span>·</span> No sign-up required <span>·</span> Advice you can use straight away</p> }
|
||||
@if(Model.Graph.IsDemo) { <p class="solver-demo">Preview journey · This small plot-line demonstration will grow into a curated collection of writing problems.</p> }
|
||||
<partial name="Review" model="Model" />
|
||||
</div>
|
||||
</section>
|
||||
@section Scripts { <script src="~/js/writing-solver.js" asp-append-version="true"></script> }
|
||||
|
||||
@ -35,6 +35,7 @@
|
||||
<a href="/writing-problems">Restart</a>
|
||||
</nav>
|
||||
}
|
||||
@if(Model.Journey is {} reviewJourney) { <partial name="Review" model="reviewJourney" /> }
|
||||
var solution=(SolverSolution)Model.Page;
|
||||
var permanent=Editorial.Find(solution.Id);
|
||||
@if(permanent is not null)
|
||||
|
||||
18
PlotLine/Views/WritingProblems/Review.cshtml
Normal file
18
PlotLine/Views/WritingProblems/Review.cshtml
Normal file
@ -0,0 +1,18 @@
|
||||
@model PlotLine.Models.WritingSolver.SolverJourney
|
||||
@inject PlotLine.Services.WritingSolverReview Review
|
||||
@if(await Review.Enabled(Context))
|
||||
{
|
||||
<details class="solver-review" style="margin-top:24px;border:1px solid #cbbdad;border-radius:8px;padding:12px;overflow-wrap:anywhere">
|
||||
<summary>Review journey · Development only</summary>
|
||||
<partial name="~/Views/WritingSolverReview/Snapshot.cshtml" model="Review.Capture(Model.Graph,Model.Outcome.Answers)" />
|
||||
<form method="post" action="/admin/writing-solver-review/feedback" class="solver-review-feedback">
|
||||
@Html.AntiForgeryToken()
|
||||
<input type="hidden" name="state" value="@Model.History" />
|
||||
<p><label style="display:block;max-width:100%">What feels wrong? <select name="category" required style="display:block;max-width:100%">@foreach(var category in PlotLine.Services.WritingSolverReview.Categories){<option>@category</option>}</select></label></p>
|
||||
<p><label style="display:block;max-width:100%">Optional note (please omit manuscript prose)<br /><textarea name="note" rows="3" maxlength="2000" style="max-width:100%;width:32rem"></textarea></label></p>
|
||||
<button type="submit" class="marketing-btn marketing-btn--secondary">Capture feedback</button>
|
||||
<p>Your accepted answers and this step/result are saved automatically. Unsubmitted choices are not captured.</p>
|
||||
</form>
|
||||
<p><a href="/admin/writing-solver-review">Review feedback / disable Review Mode →</a></p>
|
||||
</details>
|
||||
}
|
||||
20
PlotLine/Views/WritingSolverReview/Detail.cshtml
Normal file
20
PlotLine/Views/WritingSolverReview/Detail.cshtml
Normal file
@ -0,0 +1,20 @@
|
||||
@model PlotLine.Models.WritingSolver.SolverReviewDetail
|
||||
@{Layout="_PublicLayout";ViewData["Title"]="Writing Solver feedback";var item=Model.Feedback;}
|
||||
<h1>Writing Solver feedback</h1>
|
||||
<p><a href="/admin/writing-solver-review">← All feedback</a></p>
|
||||
<p><strong>@item.Category</strong> · @(item.Resolved?"Resolved":"Unresolved") · @item.Captured.CapturedUtc.ToString("u")<br />Step/page: @item.Page</p>
|
||||
@if(item.Note is not null){<p>@item.Note</p>}
|
||||
<form method="post" action="/admin/writing-solver-review/@item.Id/status">@Html.AntiForgeryToken()<input type="hidden" name="resolved" value="@(!item.Resolved?"true":"false")" /><button class="btn btn-secondary" type="submit">Mark @(item.Resolved?"unresolved":"resolved")</button></form>
|
||||
<p><a href="/admin/writing-solver-review/@item.Id/export">Export captured reproduction JSON</a></p>
|
||||
<details><summary>Copy compact reproduction summary</summary><textarea readonly rows="10" style="width:100%" aria-label="Reproduction summary">Graph @item.Captured.Version / @item.Captured.GraphHash
|
||||
@item.Category — @item.Note
|
||||
@item.Captured.StopReason
|
||||
Answers: @System.Text.Json.JsonSerializer.Serialize(item.Captured.Answers)
|
||||
Signals: @string.Join("; ",item.Captured.Signals.Select(s=>s.Signal+"="+s.Value))
|
||||
Returned: @string.Join("; ",item.Captured.Diagnoses.Where(d=>d.Returned).Select(d=>d.Id+" "+d.Score+"/"+d.Threshold))
|
||||
Start Here: @item.Captured.PrimaryCapability</textarea><p>Select the text to copy. No manuscript or workspace data is included automatically.</p></details>
|
||||
<form method="post" action="/admin/writing-solver-review/@item.Id/resume">@Html.AntiForgeryToken()<button class="btn btn-secondary" type="submit">Resume this journey</button></form>
|
||||
<h2>Captured result at the time</h2>
|
||||
<partial name="Snapshot" model="item.Captured" />
|
||||
<form method="post" action="/admin/writing-solver-review/@item.Id/replay">@Html.AntiForgeryToken()<button class="btn btn-primary" type="submit">Replay against current Development graph</button></form>
|
||||
@if(Model.Replay is {} replay){<h2>Current result when replayed</h2><p>@replay.AnswerCount of @item.Captured.AnswerCount captured answers accepted. Removed/changed routes discard the stale suffix, just as in the solver. This does not overwrite the capture.</p><partial name="Snapshot" model="replay" />}
|
||||
9
PlotLine/Views/WritingSolverReview/Index.cshtml
Normal file
9
PlotLine/Views/WritingSolverReview/Index.cshtml
Normal file
@ -0,0 +1,9 @@
|
||||
@model PlotLine.Models.WritingSolver.SolverReviewList
|
||||
@{Layout="_PublicLayout";ViewData["Title"]="Writing Solver Review";}
|
||||
<h1>Writing Solver Review</h1>
|
||||
<p>Development only. Use the ordinary solver; expand “Review journey” only when you need it.</p>
|
||||
<form method="post" action="/admin/writing-solver-review/mode">@Html.AntiForgeryToken()<input type="hidden" name="enabled" value="@(!Model.Enabled ? "true":"false")" /><button type="submit" class="btn btn-primary">@(Model.Enabled?"Disable":"Enable") Writing Solver Review Mode</button></form>
|
||||
<p><a href="/writing-problems">Open the Writing Problem Solver →</a></p>
|
||||
<form method="get"><label>Category <select name="category"><option value="">All categories</option>@foreach(var category in PlotLine.Services.WritingSolverReview.Categories){<option value="@category" selected="@(Model.Category==category)">@category</option>}</select></label> <label>Status <select name="status"><option value="all" selected="@(Model.Status=="all")">All</option><option value="unresolved" selected="@(Model.Status=="unresolved")">Unresolved</option><option value="resolved" selected="@(Model.Status=="resolved")">Resolved</option></select></label> <button type="submit" class="btn btn-secondary">Filter</button></form>
|
||||
<p>@Model.Items.Count feedback items · newest first</p>
|
||||
<ul>@foreach(var item in Model.Items){<li><a href="/admin/writing-solver-review/@item.Id">@item.Category — @item.Captured.CapturedUtc.ToString("u")</a> · @(item.Resolved?"Resolved":"Unresolved") · @item.Captured.AnswerCount answers · @item.Captured.StopReason</li>}</ul>
|
||||
16
PlotLine/Views/WritingSolverReview/Snapshot.cshtml
Normal file
16
PlotLine/Views/WritingSolverReview/Snapshot.cshtml
Normal file
@ -0,0 +1,16 @@
|
||||
@model PlotLine.Models.WritingSolver.SolverReviewSnapshot
|
||||
@{var primaryId=Model.Diagnoses.FirstOrDefault(d=>d.Returned)?.Id;}
|
||||
<div class="solver-review-snapshot" style="overflow-wrap:anywhere">
|
||||
<p><strong>@Model.StopReason</strong><br />Graph: <code>@Model.Version</code> · @Model.AnswerCount accepted answers<br />Fingerprint: <code>@Model.GraphHash</code><br />Captured: @Model.CapturedUtc.ToString("u")</p>
|
||||
@if(Model.CurrentNode is not null){<p><strong>Current question:</strong> @Model.CurrentQuestion (<code>@Model.CurrentNode</code>)</p>}
|
||||
@if(Model.NeutralTitle is not null){<p><strong>Reassurance:</strong> @Model.NeutralTitle</p>}
|
||||
<h3>Questions, answers and route reasoning</h3>
|
||||
@if(Model.Steps.Count==0){<p>No answers yet; the graph entry question is shown.</p>}
|
||||
<ol>@foreach(var step in Model.Steps){<li><strong>@step.Question</strong> (<code>@step.Node</code>)<ul>@for(var i=0;i<step.Answers.Length;i++){<li>@step.Answers[i] (<code>@step.ChoiceIds[i]</code>)</li>}</ul><p>@step.Reason</p><details><summary>Eligible routes in selection order</summary><ul>@foreach(var route in step.Candidates){<li>@route</li>}</ul></details></li>}</ol>
|
||||
<h3>Accumulated signals and answer contributions</h3>
|
||||
<ul>@foreach(var signal in Model.Signals){<li><strong><code>@signal.Signal = @signal.Value</code></strong><ul>@foreach(var source in signal.Sources){<li>@source.Question / @source.Answer (<code>@source.Node / @source.Choice</code>): @source.Value.ToString("+0;-0;0")</li>}</ul></li>}</ul>
|
||||
<h3>Diagnosis scores</h3>
|
||||
<p>Returned diagnoses are ordered primary first, then supporting. Other entries are the five highest-scoring remaining candidates, not additional results. Score alone is insufficient: required evidence and answer/continuation gates still apply.</p>
|
||||
@foreach(var diagnosis in Model.Diagnoses){<details><summary>@(diagnosis.Returned?(diagnosis.Id==primaryId?"Primary":"Supporting"):"Other candidate"): @diagnosis.Id — @diagnosis.Title · @diagnosis.Score / threshold @diagnosis.Threshold</summary><ul>@foreach(var term in diagnosis.Terms){<li><code>@term</code></li>}</ul>@if(diagnosis.MissingRequirements.Length>0){<p>Missing required evidence: @string.Join("; ",diagnosis.MissingRequirements)</p>}else{<p>Required signal minima met. Score deficit: @Math.Max(0,diagnosis.Threshold-diagnosis.Score).</p>}</details>}
|
||||
@if(Model.PrimaryCapability is not null){<p><strong>Primary Start Here:</strong> @Model.PrimaryCapability<br /><strong>Secondary:</strong> @(Model.SecondaryCapability??"None")<br /><strong>Advice article:</strong> @(Model.Article??"None")</p>}
|
||||
</div>
|
||||
Loading…
x
Reference in New Issue
Block a user