Add data-driven Writing Problem Solver and warm public site styling

This commit is contained in:
Nick Beckley 2026-11-01 14:33:03 +00:00
parent f2d15b9db3
commit b01fdae8ed
29 changed files with 1486 additions and 6 deletions

View File

@ -0,0 +1,47 @@
# Development review: Writing Problem Solver
Implemented 1 November 2026. Development only; no production database or host was changed.
## Review routes
- https://dev.plotdirector.com/writing-problems
- https://dev.plotdirector.com/writing-problems/managing-interweaving-plot-lines
- https://dev.plotdirector.com/writing-problems/finding-a-clearer-view-of-your-novel
- https://dev.plotdirector.com/features/plot-lines
- https://dev.plotdirector.com/features/scenes
- https://dev.plotdirector.com/features/characters
- https://dev.plotdirector.com/admin/writing-solver (administrator required)
- https://dev.plotdirector.com/sitemap.xml
Try The story itself → several threads + characters move between them → seeing where each thread appears. Revise an answer using Back. Try People → None of these → not sure for the broader advice route. This is deliberately only a small demonstration, not the final question collection. Demo editorial pages are noindex; curated active/indexable pages enter the sitemap automatically.
## Implementation inventory
- `PlotLine/Models/WritingSolver/SolverGraph.cs`: typed graph, signal vectors, conditional routes, page/editorial metadata and many-to-many primary/supporting feature mappings.
- `PlotLine/Services/WritingSolverEngine.cs`: deterministic scoring, question selection and complete answer recalculation.
- `PlotLine/Services/WritingSolverValidator.cs`: structural checks and bounded exhaustive reachable-state validation.
- `PlotLine/Data/WritingSolverRepository.cs`: Dapper/stored-procedure access, strict JSON import and validated snapshot caching.
- `PlotLine/Sql/206_WritingProblemSolver.sql`: versioned graph table and atomic publication/read procedures. No existing migration changed.
- `PlotLine/Content/WritingSolver/demo.json`: four nodes, two demonstration diagnoses and three features; six entry areas with a clearly explained demo fallback.
- `PlotLine/Controllers/WritingProblemsController.cs`: anonymous, expiring signed history; server-rendered journey, solution and feature routes.
- `PlotLine/Controllers/WritingSolverAdminController.cs` and `Views/WritingProblems/Admin.cshtml`: authorised inspection tables, full JSON, validation reports and version publication.
- `PlotLine/Views/WritingProblems/{Index,Page,Solution,Icon}.cshtml`: accessible, responsive public presentation and practical advice before product capabilities.
- `PlotLine/wwwroot/css/writing-solver.css`: public-only palette refinement, responsive layouts and decorative edge-image fade. Existing public home/tour content and application themes retained.
- `PlotLine/wwwroot/js/writing-solver.js`: small progressive enhancement for fallback exclusivity and empty selections. The journey remains functional without JavaScript.
- `PlotLine/wwwroot/images/public/writing-solver-desk.png`: generated decorative imagery; prompt and provenance in Framework.md.
- `PlotLine/Controllers/SitemapController.cs`, `Views/Shared/_PublicLayout.cshtml`, `Program.cs`: existing SEO/navigation/layout/DI integration.
- `Tools/WritingSolver/{Program.cs,WritingSolver.csproj}` and `PlotLine.slnx`: developer validation/import, development database guards and migration helper.
- `PlotLine.Tests/WritingSolverTests.cs`, `Program.cs`, `ToolbarBrowserHost.cs`, `Browser/writing-solver.cjs`, `Browser/public-site.cjs`: engine/import/state/browser regressions and updated shared public palette expectations.
## Verification
- `dotnet build PlotLine.slnx`: passed; two existing nullable warnings in the regression harness.
- `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj --no-build`: 378 PASS results, no failures.
- `node PlotLine.Tests/Browser/writing-solver.cjs`: passed real MVC/Razor journeys at 390px and 1440px, browser Back/revision, multi-select/fallback, three-feature results, no-JS forms/direct pages, canonical/social/JSON-LD, indexable sitemap inclusion and noindex exclusion, invalid state, overflow and layout-shift checks.
- `node PlotLine.Tests/Browser/public-site.cjs`: passed all six application themes, browser/PWA contexts, signed-in/out, authentication palette/form validation, responsive layouts, assets/navigation/SEO.
- Strict import validation and development database verification passed. Schema table and both procedures confirmed; demo-1 published atomically.
- Development backup before successful migration: `/var/opt/mssql/backup/PlotDirector_Development_solver_20261101_143004.bak` (225,603,584 bytes). BACKUP WITH COPY_ONLY/CHECKSUM completed and mapped file existence/size verified. This is not a restore test.
## Import contract and limits
See [Framework.md](Framework.md) for the structured JSON contract, CLI commands, administration, scoring/tie-break rules, publication/rollback process and asset prompt. Versioned document storage publishes the graph atomically. The public journey visits a node once and is capped at six answers. Import validation rejects graphs exceeding 100,000 queued/visited scoring states or multi-select questions with more than 12 substantive choices; it never silently skips unvalidated routes. These are explicit complexity safeguards. Review editorial quality and representative journeys when the curated collection arrives.

View File

@ -0,0 +1,56 @@
# Writing Problem Solver
## Runtime and storage
Public MVC routes use Dapper and `dbo.WritingSolver_Get`. Migration `206_WritingProblemSolver.sql` creates immutable `WritingSolverVersions` snapshots (JSON checked by SQL Server, unique version, UTC publication/editor metadata and a unique active version). Every publication validates the entire typed graph before calling `dbo.WritingSolver_Publish`, which serialises writers, deactivates the previous version and inserts the replacement in one transaction. Earlier snapshots are retained. No author data is stored.
The graph is deliberately a versioned document rather than a mutable collection of rows: a node, its weighted choices, conditional edges, editorial pages and feature mappings must be published together. Stable IDs, explicit properties and a checked importer support a large curated artifact without partially updated references. For SQL inspection use `OPENJSON(GraphJson,'$.nodes')`, `$.solutions`, or `$.features` against the active snapshot. Do not update snapshots directly. The application only accesses stored procedures.
`SolverGraph.cs` is the schema contract. `Content/WritingSolver/demo.json` is a complete worked example and import template. Schema v1 has:
- `schemaVersion`, unique `version`, `changeNote`, `isDemo`, `entryNode`, `minAnswers` and `maxAnswers` (1–6).
- `nodes`: stable `id`, `type` (`area` or `question`), title/help, `active`, `multiple`, `order`, signal `affinity`, `choices`, and `routes`.
- Choices: ID unique within their node, natural-language `text`, help/icon, order, active, `fallback`, and `weights` (signal ID → signed nonzero integer −100…100).
- Routes: target node ID, optional choice ID and/or signal/minimum condition, priority, and explicit `allowCycle` metadata. Multiple alternatives may match.
- Solutions: ID, stable slug, H1 `title`, `pageTitle`, description, summary, plain-text editorial `content` (paragraphs separated by two newlines), principle, related questions, internal search intents, active/index flags, order, optional social image; signal coefficients and positive threshold; related solution IDs; many-to-many feature links with primary flag and explanation.
- Features: the same editorial/SEO fields, plus optional local screenshot path. Features receive relevance through solution mappings; shared signals can affect many diagnoses and hence many features.
Unknown JSON properties are rejected. IDs/slugs are lowercase letters/digits with hyphens. Do not add manuscript recognition to runtime logic. Content is rendered as encoded text, never editorial HTML.
## Deterministic conversation
The engine replays valid answers from the entry node, adding every selected choice's signal vector. Duplicate selections never amplify a weight. Fallback choices are exclusive. The next eligible, unvisited target is chosen by descending route priority plus target affinity dot accumulated signals, then display order and ordinal ID. Conditions can inspect both the preceding choice and accumulated signals. Later answers can change the leading diagnosis. Solutions are ranked by their coefficient dot signal vector, threshold, order and ID; up to three can be shown. Stop at the maximum, or after the minimum when a qualifying solution exists, or when no eligible target remains. Insufficient evidence gives neutral practical advice and crawlable reading links.
Explicitly permitted cycles are accepted as graph metadata, but the public journey visits each node at most once. Authors cannot be trapped in a loop. Publication validation identifies structural cycles and conservative signal impossibility, then explores all distinct reachable score/visited-node states to prove active node and solution reachability under the actual routing engine. Validation rejects rather than silently truncates graphs exceeding 100,000 distinct states or multi-select nodes with more than 12 substantive choices. It is not a proof of editorial quality or that every answer combination produces a diagnosis. Review representative journeys when publishing a curated matrix. Inactive nodes are retained for editorial maintenance but active edges cannot target them.
History contains only graph version and choice IDs, protected by ASP.NET Data Protection with a two-hour expiry and an isolated purpose. POSTs require antiforgery tokens and redirect to GET. GET state URLs support browser Back/Forward and explicit Back. Revisions replay the prefix and discard stale successors. Graph publication invalidates old journeys gracefully. No personal information, cookies for diagnostic tracking, local storage or database session is needed. State pages send `no-store` and `no-referrer`.
## Import and inspection
Admin route: `/admin/writing-solver` (existing `AdminOnly` policy). Inspect the full graph JSON, validate without saving, then publish a new version. Import errors are displayed; invalid artifacts are never partially applied. Use a fresh version even for corrections. Validation covers duplicate IDs/slugs, unknown properties, missing/inactive references, feature mappings, malformed weights, orphan nodes, structurally unreachable solutions, impossible signal thresholds, unpermitted cycles, and dead ends without evidence. Low feature coverage is reported as a warning. Explicitly permitted cycles still terminate at runtime.
Developer dry run (no database access):
```
dotnet run --project Tools/WritingSolver -- validate PlotLine/Content/WritingSolver/demo.json
```
Development publication after taking/verifying the required backup:
```
sudo -n dotnet Tools/WritingSolver/bin/Debug/net10.0/WritingSolver.dll publish /absolute/path/to/matrix.json
```
The helper reads the protected environment as data, checks the configured database and `DB_NAME()` are `PlotDirector_Development`, and refuses any other target. Its `migrate SQLFILE` operation takes a unique COPY_ONLY/CHECKSUM backup and verifies the mapped backup file exists and is nonempty before applying only that file (this is not a restore test). It never restores or resets data. CLI `inspect development` lists retained versions. A rollback is a new version of the previous artifact, preserving audit history. Follow `Docs/Codex/Database.md` for live changes.
## Pages, discoverability and design
`/writing-problems`, `/writing-problems/{solution-slug}`, `/features/{feature-slug}` are server rendered and work without JavaScript. Shared public navigation and reading links make pages crawlable. Existing `PublicSeo`, canonical origin, social metadata, JSON-LD and sitemap generation are reused. Page slugs determine canonical URLs; state query strings do not. Keep slugs stable once indexed. `index` defaults false, so previews cannot accidentally enter search. Curated active pages with `index:true` enter the sitemap and render index/follow. Search intents are internal metadata, not keyword blocks. No FAQ schema is emitted without visible question/answer content.
`writing-solver.css` scopes the shared warm cream/plum/sage refinement to `html[data-site-theme=public]`. It retains current home/tour structure and the existing ordinary-browser/PWA public identity boundary. Public auth uses the same stylesheet; PWA auth keeps its existing application-theme switch. No authenticated theme is changed. Decorative image is not needed to understand or operate the page. Choices are full-width on mobile, native radios/checkboxes, and have visible focus. JavaScript only improves fallback exclusivity and empty-selection errors; no animated stage replacement or height transition is used.
The decorative asset `wwwroot/images/public/writing-solver-desk.png` was generated with the built-in image tool. Prompt: wide photorealistic warm writer's desk, old books and leaves at far left, steaming speckled tea cup and notebook/pen at far right, empty cream middle 70%, soft honey light, sage/brown/plum details, no text/logo/interface. CSS adds a clean central fade.
## Verification
Run `dotnet build PlotLine.slnx`, then `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj` serially. Engine/import regressions are in `WritingSolverTests.cs`. For real MVC/Razor browser tests, start the isolated `--toolbar-browser-host` from the repository root, then run `node PlotLine.Tests/Browser/writing-solver.cjs` and `node PlotLine.Tests/Browser/public-site.cjs`. These use seed fixtures and never touch the database. The solver suite covers desktop/mobile, browser Back, fallback revision, native no-JS forms, multi-feature results, anonymous invalid-state recovery, direct pages, canonical/social/structured data, demo sitemap exclusion, overflow and cumulative layout shift.

View File

@ -24,9 +24,9 @@ const themes = ['warm-light', 'warm-dark', 'modern-light', 'modern-dark', 'rose-
assert.equal(await page.locator('html').getAttribute('data-site-theme'), 'public');
assert.equal(await page.locator('html').getAttribute('data-app-theme'), null);
assert.equal(await page.locator('html').getAttribute('data-bs-theme'), 'light');
assert.equal(await page.locator('.public-links a').allTextContents().then(a => a.join('|')), 'Home|Tour|Pricing|Help');
assert.equal(await page.locator('.public-links a').allTextContents().then(a => a.join('|')), 'Home|Tour|Writing Solver|Pricing|Help');
assert.equal(await page.locator('[data-ribbon-shell]').count(), 0);
assert.equal(await page.locator('body').evaluate(el => getComputedStyle(el).backgroundColor), 'rgb(248, 245, 238)');
assert.equal(await page.locator('body').evaluate(el => getComputedStyle(el).backgroundColor), 'rgb(252, 243, 229)');
assert.equal(await page.locator('.public-account').innerText().then(s => s.includes('Your workspace')), !anonymous);
}
}

View File

@ -0,0 +1,87 @@
// Real MVC/Razor routes on the isolated --toolbar-browser-host; no database writes.
const { chromium } = require('playwright');
const assert = require('node:assert/strict');
const base = process.env.SOLVER_BASE_URL || 'http://127.0.0.1:5238';
(async () => {
const browser = await chromium.launch();
try {
for (const width of [390, 1440]) {
const context = await browser.newContext({ viewport: {width,height:1000} });
await context.addInitScript(() => {
localStorage.setItem('plotdirector.applicationTheme','rose-pink');
window.__shifts = [];
new PerformanceObserver(list => list.getEntries().forEach(e => { if (!e.hadRecentInput) window.__shifts.push(e.value); })).observe({type:'layout-shift',buffered:true});
});
const page = await context.newPage();
const errors=[]; page.on('pageerror',e=>errors.push(e.message));
const noOverflow = async () => assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),`Overflow at ${width}`);
assert.equal((await page.goto(base+'/writing-problems')).status(),200);
await noOverflow();
assert.equal(await page.locator('html').getAttribute('data-site-theme'),'public');
assert.equal(await page.locator('html').getAttribute('data-app-theme'),null);
await page.locator('button[type=submit]').click();
assert(await page.locator('.solver-selection-error').isVisible());
await page.locator('input[value=story]').check();
await page.locator('button[type=submit]').click();
await page.locator('input[value=threads]').check();
await page.locator('input[value=crossing]').check();
await noOverflow();
await page.screenshot({path:`/tmp/writing-solver-plot-${width}.png`,fullPage:true});
await page.locator('button[type=submit]').click();
assert.match(await page.locator('legend').innerText(),/next writing session/);
await page.goBack();
await page.locator('input[value=other]').check();
assert.equal(await page.locator('input[value=threads]').isChecked(),false);
await page.locator('input[value=threads]').check();
assert.equal(await page.locator('input[value=other]').isChecked(),false);
await page.locator('input[value=crossing]').check();
await page.locator('button[type=submit]').click();
await page.locator('input[value=weave]').check();
await page.locator('button[type=submit]').click();
assert.match(await page.locator('.solver-result h1').first().innerText(),/interweaving plot lines/);
assert.equal(await page.locator('.solver-features h3').count(),3);
await noOverflow();
await page.screenshot({path:`/tmp/writing-solver-result-${width}.png`,fullPage:true});
assert((await page.evaluate(()=>window.__shifts.reduce((a,b)=>a+b,0)))<.1,'Unexpected layout movement');
await page.getByRole('link',{name:'Start again',exact:true}).click();
await page.locator('input[value=people]').check();
await page.locator('button[type=submit]').click();
assert.match(await page.locator('legend').innerText(),/step back/);
await page.locator('input[value=other]').check();
await page.locator('button[type=submit]').click();
await page.locator('input[value=other]').check();
await page.locator('button[type=submit]').click();
assert.match(await page.locator('.solver-result h1').innerText(),/breathing room/);
assert.equal(errors.length,0,errors.join('\n'));
await context.close();
}
const context=await browser.newContext({javaScriptEnabled:false,viewport:{width:390,height:900}});
const page=await context.newPage();
await page.goto(base+'/writing-problems');
await page.locator('input[value=story]').check(); await page.locator('button[type=submit]').click();
assert.match(await page.locator('legend').innerText(),/tangled/);
const response=await page.goto(base+'/writing-problems/managing-interweaving-plot-lines');
assert.equal(response.status(),200);
assert(await page.locator('h1').innerText().then(t=>t.includes('interweaving')));
assert.equal(await page.locator('link[rel=canonical]').getAttribute('href'),'https://plotdirector.com/writing-problems/managing-interweaving-plot-lines');
assert.equal(await page.locator('meta[name=robots]').getAttribute('content'),'noindex, follow');
assert(await page.locator('meta[property="og:description"]').getAttribute('content'));
assert(await page.locator('script[type="application/ld+json"]').count());
assert.equal((await page.goto(base+'/features/plot-lines')).status(),200);
assert.equal((await page.goto(base+'/writing-problems/unknown-diagnosis')).status(),404);
const sitemap=await (await page.request.get(base+'/sitemap.xml')).text();
assert(sitemap.includes('https://plotdirector.com/writing-problems</loc>'));
assert(!sitemap.includes('managing-interweaving-plot-lines'),'Noindex demo leaked into sitemap');
if (!process.env.SOLVER_BASE_URL) {
const curatedSitemap=await (await page.request.get(base+'/sitemap.xml?curated=true')).text();
assert(curatedSitemap.includes('/writing-problems/managing-interweaving-plot-lines</loc>'));
assert(curatedSitemap.includes('/features/plot-lines</loc>'));
await page.goto(base+'/writing-problems/managing-interweaving-plot-lines?curated=true');
assert.equal(await page.locator('meta[name=robots]').getAttribute('content'),'index, follow');
}
await page.goto(base+'/writing-problems?state=invalid');
assert.match(await page.locator('[role=status]').innerText(),/expired or changed/);
await context.close();
console.log('PASS Writing Solver: desktop/mobile, revision, fallback, multi-feature results, no-JS, canonical/social/JSON-LD, sitemap, invalid anonymous state, no overflow/CLS');
} finally { await browser.close(); }
})().catch(error=>{console.error(error);process.exit(1);});

View File

@ -52,6 +52,9 @@ if (args.Contains("--plot-lines"))
var tests = new (string Name, Action Test)[]
{
("Writing Solver anonymous state is protected, expires and rejects stale versions", WritingSolverTests.AnonymousState),
("Writing Solver scoring, multi-select, revision, fallback and graph routes", WritingSolverTests.RoutingAndRevision),
("Writing Solver import rejects invalid graphs and editorial identities", WritingSolverTests.Validation),
("Ribbon operation identity and semantic icons stay consistent", RibbonPresentationTests.SemanticMetadata),
("Subscription entitlement evaluates trials, paid access, overrides and real plan limits", SubscriptionEntitlementTests.EffectiveStateAndLimits),
("Subscription enforcement is concurrent, audited and admin-authorised", SubscriptionEntitlementTests.EnforcementAndAdminSecurity),

View File

@ -75,6 +75,7 @@ internal static class ToolbarBrowserHost
builder.Services.AddSingleton<IAppearanceRepository, AppearanceMemoryPreferences>();
builder.Services.AddScoped<ApplicationNavigation>(_ => new ApplicationNavigation(null!, null!, null!));
builder.Services.AddSingleton<IHelpService, HelpService>();
builder.Services.AddSingleton<IWritingSolverRepository, WritingSolverFixtureRepository>();
builder.Services.AddSingleton<IHelpMarkdownRenderer, HelpMarkdownRenderer>();
builder.Services.AddScoped<ICurrentUserService>(services => new ToolbarTestUser(int.Parse(services.GetRequiredService<IHttpContextAccessor>().HttpContext!.User.FindFirstValue(ClaimTypes.NameIdentifier)!)));
var app = builder.Build();
@ -334,3 +335,18 @@ internal static class ToolbarBrowserHost
await app.RunAsync();
}
}
internal sealed class WritingSolverFixtureRepository(IHttpContextAccessor accessor) : IWritingSolverRepository
{
public Task<PlotLine.Models.WritingSolver.SolverGraph> GetAsync()
{
var graph = WritingSolverRepository.Parse(File.ReadAllText("PlotLine/Content/WritingSolver/demo.json"));
if (accessor.HttpContext?.Request.Query["curated"].ToString() == "true")
{
graph.IsDemo = false;
foreach(var page in graph.Solutions.Cast<PlotLine.Models.WritingSolver.SolverPage>().Concat(graph.Features)) page.Index = true;
}
return Task.FromResult(graph);
}
public Task PublishAsync(string json,string editor) => throw new NotSupportedException("Read-only fixture");
}

View File

@ -0,0 +1,96 @@
using PlotLine.Data;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using PlotLine.Controllers;
using PlotLine.Models.WritingSolver;
using PlotLine.Services;
internal static class WritingSolverTests
{
private static string Root()
{
var directory=new DirectoryInfo(AppContext.BaseDirectory);
while(directory is not null && !File.Exists(Path.Combine(directory.FullName,"PlotLine.slnx"))) directory=directory.Parent;
return directory?.FullName ?? throw new Exception("Repository unavailable.");
}
private static SolverGraph Graph() => WritingSolverRepository.Parse(File.ReadAllText(Path.Combine(Root(),"PlotLine/Content/WritingSolver/demo.json")));
private static void Require(bool ok,string message) { if(!ok) throw new Exception(message); }
public static void RoutingAndRevision()
{
var graph=Graph();
var history=new[]{new SolverAnswer("welcome",["story"]),new SolverAnswer("plot",["threads","crossing"]),new SolverAnswer("focus",["weave"])};
var result=WritingSolverEngine.Evaluate(graph,history);
Require(result.Next is null && result.Solutions[0].Id=="interweaving","Plot diagnosis missing.");
Require(result.Scores["plot"]==6 && result.Scores["people"]==2,"Multi-select weights are incorrect.");
Require(result.Solutions[0].Features.Count==3 && result.Solutions[0].Features.Count(f=>f.Primary)==1,"Feature roles missing.");
var revised=WritingSolverEngine.Evaluate(graph,[new("welcome",["people"]),history[1],history[2]]);
Require(revised.Next?.Id=="broaden" && revised.Answers.Count==1 && revised.Scores.Count==0,"Revision kept stale answers/scores.");
var fallback=WritingSolverEngine.Evaluate(graph,[new("welcome",["story"]),new("plot",["other"]),new("broaden",["other"]),new("focus",["other"])]);
Require(fallback.Solutions.Any(s=>s.Id=="overview"),"Fallback did not broaden into useful advice.");
var invalid=WritingSolverEngine.Evaluate(graph,[history[0],new("plot",["threads","other"])]);
Require(invalid.Answers.Count==1,"Fallback must be exclusive.");
var repeated=WritingSolverEngine.Evaluate(graph,[history[0],new("plot",["threads","threads"])]);
Require(repeated.Scores["plot"]==3,"Duplicate selections amplified weights.");
graph.Solutions[1].Signals=new(){["plot"]=1};
Require(WritingSolverEngine.Evaluate(graph,history).Solutions.Count==2,"Multiple diagnoses were lost.");
graph=Graph();
graph.Nodes.Single(n=>n.Id=="welcome").Routes.Add(new(){Target="focus",Signal="plot",Minimum=1,Priority=100});
Require(WritingSolverEngine.Evaluate(graph,[history[0]]).Next?.Id=="focus","Signal-conditioned alternative route was ignored.");
}
private sealed class MemoryGraph(SolverGraph graph) : IWritingSolverRepository
{
public Task<SolverGraph> GetAsync() => Task.FromResult(graph);
public Task PublishAsync(string json,string editor) => throw new NotSupportedException();
}
public static void AnonymousState()
{
var provider = new EphemeralDataProtectionProvider();
var protector = provider.CreateProtector("WritingSolver.history.v1").ToTimeLimitedDataProtector();
var controller = new WritingProblemsController(new MemoryGraph(Graph()),provider,new ConfigurationBuilder().Build())
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
var valid = protector.Protect("{\"Version\":\"demo-1\",\"Answers\":[{\"Node\":\"welcome\",\"Choices\":[\"story\"]}]}",TimeSpan.FromHours(2));
var view = (ViewResult)controller.Index(valid).GetAwaiter().GetResult();
var journey = (SolverJourney)view.Model!;
Require(journey.Error is null && journey.Outcome.Next?.Id=="plot","Anonymous protected history did not resume.");
Require(controller.Response.Headers.CacheControl.ToString().Contains("no-store"),"Diagnostic state must not be cached.");
foreach(var token in new[]{valid+"tampered",protector.Protect("{}",DateTimeOffset.UtcNow.AddMinutes(-1)),protector.Protect("{\"Version\":\"obsolete\",\"Answers\":[]}",TimeSpan.FromHours(2))})
{
view=(ViewResult)controller.Index(token).GetAwaiter().GetResult();
journey=(SolverJourney)view.Model!;
Require(journey.Error is not null && journey.Outcome.Answers.Count==0,"Expired/tampered/stale-version history must restart gracefully.");
}
}
public static void Validation()
{
var graph=Graph();
Require(WritingSolverValidator.Validate(graph).Count==0,"Demo must validate.");
graph.Solutions[1].Slug=graph.Solutions[0].Slug;
Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("Duplicate solution slug")),"Duplicate slug accepted.");
graph=Graph(); graph.Nodes[0].Routes.Add(new(){Target="missing"});
Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("target")),"Missing reference accepted.");
graph=Graph(); graph.Nodes.Single(n=>n.Id=="focus").Routes.Add(new(){Target="welcome"});
Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("cycle")),"Cycle accepted.");
graph=Graph(); graph.Solutions[0].Threshold=10000;
Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("Unreachable solution")),"Impossible diagnosis accepted.");
graph=Graph(); graph.Nodes.Add(new(){Id="orphan",Title="Orphan",Choices=[new(){Id="other",Text="Other",Fallback=true}]});
var errors=WritingSolverValidator.Validate(graph);
Require(errors.Any(e=>e.Contains("Unreachable node")) && errors.Any(e=>e.Contains("Dead end")),"Orphan/dead end accepted.");
graph=Graph(); graph.Nodes[0].Choices[0].Weights["plot"]=101;
Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("Malformed weights")),"Malformed weights accepted.");
graph=Graph();
graph.Nodes[0].Routes.Single(r=>r.Choice=="story").Signal="plot";
graph.Nodes[0].Routes.Single(r=>r.Choice=="story").Minimum=99;
Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("Impossible signal route")),"Impossible conditional route accepted.");
graph=Graph();
graph.Nodes[0].Routes.Single(r=>r.Choice=="story").Priority=-100;
Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("Unreachable node under")),"Structurally connected but shadowed route accepted.");
graph=Graph(); graph.Solutions[0].Features[0].Feature="missing";
Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("feature mapping")),"Invalid feature accepted.");
}
}

View File

@ -1,4 +1,7 @@
<Solution>
<Project Path="PlotLine/PlotLine.csproj" />
<Folder Name="/Tools/">
<Project Path="Tools/WritingSolver/WritingSolver.csproj" />
</Folder>
<Project Path="PlotLine.Tests/PlotLine.Tests.csproj" />
</Solution>

View File

@ -0,0 +1,348 @@
{
"schemaVersion": 1,
"version": "demo-1",
"changeNote": "Framework demonstration only; replace with the curated diagnostic matrix.",
"isDemo": true,
"minAnswers": 3,
"maxAnswers": 6,
"entryNode": "welcome",
"nodes": [
{
"id": "welcome",
"type": "area",
"title": "What’s becoming difficult to keep track of?",
"help": "Pick the area that’s causing you the most grief right now.",
"choices": [
{
"id": "story",
"text": "The story itself",
"weights": {
"plot": 1
},
"help": "Plots, subplots and how everything fits together",
"icon": "layers",
"order": 0
},
{
"id": "people",
"text": "People",
"weights": {},
"help": "Characters, relationships and what they know",
"icon": "people",
"order": 1
},
{
"id": "time",
"text": "Time",
"weights": {},
"help": "Dates, chronology, flashbacks and continuity",
"icon": "clock",
"order": 2
},
{
"id": "places",
"text": "Places & things",
"weights": {},
"help": "Locations, important objects, clues and possessions",
"icon": "pin",
"order": 3
},
{
"id": "structure",
"text": "Structure",
"weights": {},
"help": "Scenes, chapters, ordering and pacing",
"icon": "book",
"order": 4
},
{
"id": "project",
"text": "The whole project",
"weights": {},
"help": "Large novels, series and general overwhelm",
"icon": "shelf",
"order": 5
},
{
"id": "other",
"text": "None of these quite fit",
"weights": {},
"fallback": true,
"order": 7
}
],
"routes": [
{
"target": "plot",
"choice": "story",
"priority": 10
},
{
"target": "broaden"
}
]
},
{
"id": "plot",
"title": "What’s tangled about your plot?",
"help": "Choose all that apply. It’s quite normal for more than one to fit.",
"multiple": true,
"choices": [
{
"id": "threads",
"text": "I’ve got several plot lines or story threads",
"weights": {
"plot": 2
},
"order": 0
},
{
"id": "crossing",
"text": "Characters move between them",
"weights": {
"plot": 1,
"people": 2
},
"order": 1
},
{
"id": "disappearing",
"text": "A subplot keeps disappearing (and I’m not sure when)",
"weights": {
"plot": 2,
"gaps": 2
},
"order": 2
},
{
"id": "connections",
"text": "I can’t see how everything connects",
"weights": {
"plot": 2,
"people": 1
},
"order": 3
},
{
"id": "scenes",
"text": "I’m not sure which scenes advance which plot",
"weights": {
"plot": 1,
"scenes": 2
},
"order": 4
},
{
"id": "other",
"text": "Something else",
"weights": {},
"fallback": true,
"order": 5
}
],
"routes": [
{
"target": "broaden",
"choice": "other",
"priority": 20
},
{
"target": "focus"
}
]
},
{
"id": "broaden",
"title": "Let’s take a step back.",
"help": "The full question collection is still being curated. For this preview, we can explore story threads, or give you a useful place to start.",
"choices": [
{
"id": "threads",
"text": "There are several threads to keep in view",
"weights": {
"plot": 2
},
"order": 0
},
{
"id": "overview",
"text": "I need a clearer view of the story as a whole",
"weights": {
"overview": 3
},
"order": 1
},
{
"id": "other",
"text": "None of these quite fit — show me a useful starting point",
"weights": {
"overview": 3
},
"fallback": true,
"order": 2
}
],
"routes": [
{
"target": "focus"
}
]
},
{
"id": "focus",
"title": "What would make your next writing session easier?",
"help": "Choose the change you’d most like to see.",
"choices": [
{
"id": "weave",
"text": "Seeing where each story thread appears",
"weights": {
"plot": 2,
"gaps": 1
},
"order": 0
},
{
"id": "cast",
"text": "Following characters between story threads",
"weights": {
"plot": 1,
"people": 2
},
"order": 1
},
{
"id": "scene",
"text": "Knowing what each scene contributes",
"weights": {
"plot": 1,
"scenes": 2
},
"order": 2
},
{
"id": "other",
"text": "I’m still not sure — help me find a starting point",
"weights": {
"overview": 3
},
"fallback": true,
"order": 3
}
],
"routes": []
}
],
"solutions": [
{
"id": "interweaving",
"slug": "managing-interweaving-plot-lines",
"title": "You’re managing multiple, interweaving plot lines.",
"pageTitle": "Managing multiple, interweaving plot lines",
"description": "Keep overlapping story threads clear by mapping each plot line to the scenes and characters that carry it.",
"summary": "You’ve got more than one story thread running through your novel, and it’s becoming hard to see where each one appears, how they interact and whether they’re all getting the attention they need.",
"content": "Start by naming each thread and writing one sentence about the change it follows. List the scenes that advance it, then look for long gaps. A quiet thread is not automatically a problem: ask whether the reader still has enough reason to remember and care about it.\n\nNext, mark scenes that belong to more than one thread. These are useful places to check that the characters’ actions and knowledge make sense across both stories. You can do this on paper, in a spreadsheet, or in a connected scene view.",
"principle": "See your plots, scenes and characters together, so you can follow each thread and the points where they intersect.",
"signals": {
"plot": 1
},
"threshold": 4,
"features": [
{
"feature": "plot-lines",
"primary": true,
"reason": "Track each plot line across scenes, see overlaps and spot long gaps."
},
{
"feature": "scenes",
"reason": "Check which scenes advance each thread and what changes in them."
},
{
"feature": "characters",
"reason": "Follow the characters who carry events between threads."
}
],
"related": [
"overview"
],
"questions": [
"How do I keep track of several plot lines?",
"What can I do when a subplot disappears?"
],
"searchIntents": [
"manage interweaving plots",
"track subplots in a novel"
],
"index": false
},
{
"id": "overview",
"slug": "finding-a-clearer-view-of-your-novel",
"title": "Let’s give your story a little breathing room.",
"pageTitle": "Finding a clearer view of your novel",
"description": "A practical starting point when your novel feels difficult to organise: identify one small question and review the scenes around it.",
"summary": "When everything feels tangled, you don’t need to reorganise your whole novel at once. Start with one small question about what happens next.",
"content": "Write a one-line summary of three adjacent scenes. For each, note who wants something, what changes, and what question carries the reader forward. Look at this small sequence before attempting to solve the whole book.\n\nIf the difficulty is about dates, places or another area outside this demonstration, keep a short list of the uncertainties. The full diagnostic collection will cover those areas when it is ready.",
"principle": "Make one part of the story visible before trying to hold the whole novel in your head.",
"signals": {
"overview": 1
},
"threshold": 3,
"features": [
{
"feature": "scenes",
"primary": true,
"reason": "Build a manageable view of a short sequence of scenes."
}
],
"related": [
"interweaving"
],
"questions": [
"Where do I start when my novel feels overwhelming?"
],
"index": false
}
],
"features": [
{
"id": "plot-lines",
"slug": "plot-lines",
"title": "Plot Lines",
"pageTitle": "Plot Lines for novel planning",
"description": "Follow each story thread across the scenes in your novel.",
"summary": "Follow each story thread across the scenes in your novel.",
"content": "Give each thread a clear purpose, then link it to the scenes that move it forward. The Plot Lines workspace helps you see shared scenes, gaps and the weave of your story.",
"screenshot": "/images/public/plot-lines.jpg",
"index": false,
"questions": [],
"searchIntents": []
},
{
"id": "scenes",
"slug": "scenes",
"title": "Scenes",
"pageTitle": "Scenes for novel planning",
"description": "See what each scene contributes to the story.",
"summary": "See what each scene contributes to the story.",
"content": "A scene earns its place through the change it brings. Keep a short note of its purpose, connect it to the relevant story threads, and review its position in the wider sequence.",
"screenshot": "/images/public/scene.jpg",
"index": false,
"questions": [],
"searchIntents": []
},
{
"id": "characters",
"slug": "characters",
"title": "Characters",
"pageTitle": "Characters for novel planning",
"description": "Keep the people in your story connected to the events that shape them.",
"summary": "Keep the people in your story connected to the events that shape them.",
"content": "Keep character notes alongside your scene planning. When a character crosses between plot lines, review what they want, what they know and what changes for them.",
"screenshot": "/images/public/characters.jpg",
"index": false,
"questions": [],
"searchIntents": []
}
]
}

View File

@ -8,10 +8,10 @@ using PlotLine.Services;
namespace PlotLine.Controllers;
[AllowAnonymous]
public sealed class SitemapController(IHelpService help, IConfiguration configuration) : Controller
public sealed class SitemapController(IHelpService help, IConfiguration configuration, PlotLine.Data.IWritingSolverRepository solver) : Controller
{
[HttpGet("/sitemap.xml")]
public IActionResult Index()
public async Task<IActionResult> Index()
{
var urls = new List<SitemapUrl>
{
@ -25,6 +25,11 @@ public sealed class SitemapController(IHelpService help, IConfiguration configur
new("/terms", "yearly", "0.3")
};
var graph = await solver.GetAsync();
urls.Add(new("/writing-problems", "monthly", "0.8"));
urls.AddRange(graph.Solutions.Where(p => p.Active && p.Index).Select(p => new SitemapUrl($"/writing-problems/{p.Slug}", "monthly", "0.7")));
urls.AddRange(graph.Features.Where(p => p.Active && p.Index).Select(p => new SitemapUrl($"/features/{p.Slug}", "monthly", "0.7")));
var articles = help.GetAllArticles();
urls.AddRange(articles
.Where(article => !string.IsNullOrWhiteSpace(article.CategorySlug))

View File

@ -0,0 +1,80 @@
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Data;
using PlotLine.Models.WritingSolver;
using PlotLine.Services;
namespace PlotLine.Controllers;
[AllowAnonymous]
public sealed class WritingProblemsController(IWritingSolverRepository repository, IDataProtectionProvider protection, IConfiguration configuration) : Controller
{
private readonly ITimeLimitedDataProtector protector = protection.CreateProtector("WritingSolver.history.v1").ToTimeLimitedDataProtector();
private sealed record History(string Version, List<SolverAnswer> Answers);
private string Encode(SolverGraph graph, IEnumerable<SolverAnswer> answers) => protector.Protect(JsonSerializer.Serialize(new History(graph.Version, answers.ToList())), TimeSpan.FromHours(2));
private List<SolverAnswer> Decode(SolverGraph graph, string? state)
{
if (string.IsNullOrEmpty(state)) return [];
if (state.Length > 16000) throw new InvalidDataException("History too large.");
var history = JsonSerializer.Deserialize<History>(protector.Unprotect(state, out _));
if (history is null || history.Version != graph.Version) throw new InvalidDataException("The question collection has changed. Please begin again.");
return history.Answers;
}
[HttpGet("/writing-problems")]
public async Task<IActionResult> Index(string? state = null, bool choose = false)
{
Response.Headers.CacheControl = "no-store";
Response.Headers["Referrer-Policy"] = "no-referrer";
var graph = await repository.GetAsync();
List<SolverAnswer> history = [];
string? error = choose ? "Choose an answer to continue. Use Something else on its own if the other answers don’t fit." : null;
try { history = Decode(graph,state); }
catch (Exception ex) when (ex is CryptographicException or JsonException or InvalidDataException)
{ error = "Your previous conversation has expired or changed. Let’s start afresh."; }
var outcome = WritingSolverEngine.Evaluate(graph,history);
SetSeo("The Writing Problem Solver", "Tell us what’s making your novel complicated and find a practical way to untangle it.", "/writing-problems", state is null);
ViewData["BackState"] = outcome.Answers.Count > 0 ? Encode(graph,outcome.Answers.Take(outcome.Answers.Count-1)) : null;
return View(new SolverJourney(graph,outcome,Encode(graph,outcome.Answers),error));
}
[HttpPost("/writing-problems/answer")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Answer(string state, string node, string[] choices)
{
var graph = await repository.GetAsync();
try
{
var history = Decode(graph,state);
var before = WritingSolverEngine.Evaluate(graph,history);
if (before.Next?.Id != node) return BadRequest("That question is no longer current. Go back and try again.");
history.Add(new(node, choices));
var after = WritingSolverEngine.Evaluate(graph,history);
if (after.Answers.Count != history.Count) return RedirectToAction(nameof(Index), new { state, choose = true });
return RedirectToAction(nameof(Index), new { state = Encode(graph, after.Answers) });
}
catch (Exception ex) when (ex is CryptographicException or JsonException or InvalidDataException)
{ return RedirectToAction(nameof(Index)); }
}
[HttpGet("/writing-problems/{slug}")]
public async Task<IActionResult> Solution(string slug) => await Page(slug,false);
[HttpGet("/features/{slug}")]
public async Task<IActionResult> Feature(string slug) => await Page(slug,true);
private async Task<IActionResult> Page(string slug,bool feature)
{
var graph = await repository.GetAsync();
SolverPage? page = feature ? graph.Features.FirstOrDefault(p => p.Active && p.Slug == slug) : graph.Solutions.FirstOrDefault(p => p.Active && p.Slug == slug);
if (page is null) return NotFound();
SetSeo(page.PageTitle,page.Description,$"/{(feature ? "features" : "writing-problems")}/{page.Slug}",page.Index,page.SocialImage);
return View("Page",new SolverPageView(graph,page,feature));
}
private void SetSeo(string title,string description,string path,bool index,string? image=null)
{
ViewData["Robots"] = index ? "index, follow" : "noindex, follow";
PublicSeo.Apply(ViewData,configuration,new SeoMetadata
{
Title=title, Description=description, CanonicalPath=path, OgImage=image,
JsonLd=[PublicSeo.WebPageJsonLd(configuration,"WebPage",title,path,description)]
});
}
}

View File

@ -0,0 +1,42 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Data;
using PlotLine.Services;
namespace PlotLine.Controllers;
[Authorize(Policy="AdminOnly")]
public sealed class WritingSolverAdminController(IWritingSolverRepository repository) : Controller
{
[HttpGet("/admin/writing-solver")]
public async Task<IActionResult> Index()
{
var graph = await repository.GetAsync();
ViewData["Graph"] = graph;
ViewData["Report"] = WritingSolverValidator.Warnings(graph);
return View("~/Views/WritingProblems/Admin.cshtml",System.Text.Json.JsonSerializer.Serialize(graph,WritingSolverRepository.JsonOptions));
}
[HttpPost("/admin/writing-solver")]
[ValidateAntiForgeryToken]
[RequestSizeLimit(2_000_000)]
public async Task<IActionResult> Import(string json,string operation)
{
try
{
var graph = WritingSolverRepository.Parse(json);
ViewData["Graph"] = graph;
var report = WritingSolverValidator.Warnings(graph);
if (operation == "publish")
{
await repository.PublishAsync(json,User.Identity?.Name ?? "administrator");
report.Insert(0,$"Published {graph.Version}. Previous versions retained.");
}
else report.Insert(0,"Validation passed. Nothing has been written. Use a new version before publishing.");
ViewData["Report"] = report;
}
catch (Microsoft.Data.SqlClient.SqlException ex) when (ex.Number == 50003)
{ ViewData["Report"] = new[]{"This version already exists. Nothing has been written. Give the artifact a new version before publishing."}; }
catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidDataException or ArgumentException or NullReferenceException)
{ ViewData["Report"] = new[]{"Validation failed. Nothing has been written.",ex.Message}; }
return View("~/Views/WritingProblems/Admin.cshtml",json);
}
}

View File

@ -0,0 +1,50 @@
using System.Data;
using System.Text.Json;
using System.Text.Json.Serialization;
using Dapper;
using PlotLine.Models.WritingSolver;
using PlotLine.Services;
namespace PlotLine.Data;
public interface IWritingSolverRepository
{
Task<SolverGraph> GetAsync();
Task PublishAsync(string json, string editor);
}
public sealed class WritingSolverRepository(ISqlConnectionFactory connections) : IWritingSolverRepository
{
private static readonly object CacheLock = new();
private static (string Json, SolverGraph Graph)? cached;
public static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
{
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
RespectNullableAnnotations = true,
WriteIndented = true
};
public static SolverGraph Parse(string json)
{
var graph = JsonSerializer.Deserialize<SolverGraph>(json, JsonOptions) ?? throw new InvalidDataException("Empty graph.");
var errors = WritingSolverValidator.Validate(graph);
if (errors.Count > 0) throw new InvalidDataException(string.Join("\n", errors));
return graph;
}
public async Task<SolverGraph> GetAsync()
{
using var connection = connections.CreateConnection();
var json = await connection.QuerySingleAsync<string>("dbo.WritingSolver_Get", commandType: CommandType.StoredProcedure);
lock (CacheLock)
{
if (cached is { } current && current.Json == json) return current.Graph;
var graph = Parse(json);
cached = (json, graph);
return graph;
}
}
public async Task PublishAsync(string json, string editor)
{
var graph = Parse(json); // Validate the entire artifact before opening a database connection.
using var connection = connections.CreateConnection();
await connection.ExecuteAsync("dbo.WritingSolver_Publish", new { graph.Version, GraphJson = JsonSerializer.Serialize(graph, JsonOptions), Editor = editor }, commandType: CommandType.StoredProcedure);
}
}

View File

@ -0,0 +1,87 @@
namespace PlotLine.Models.WritingSolver;
// Stable string IDs make editorial imports diffable. Published versions are immutable.
public sealed class SolverGraph
{
public int SchemaVersion { get; set; } = 1;
public string Version { get; set; } = "";
public string ChangeNote { get; set; } = "";
public bool IsDemo { get; set; }
public int MinAnswers { get; set; } = 3;
public int MaxAnswers { get; set; } = 6;
public string EntryNode { get; set; } = "";
public List<SolverNode> Nodes { get; set; } = [];
public List<SolverSolution> Solutions { get; set; } = [];
public List<SolverFeature> Features { get; set; } = [];
}
public sealed class SolverNode
{
public string Id { get; set; } = "";
public string Type { get; set; } = "question";
public string Title { get; set; } = "";
public string Help { get; set; } = "";
public bool Active { get; set; } = true;
public bool Multiple { get; set; }
public int Order { get; set; }
public Dictionary<string,int> Affinity { get; set; } = [];
public List<SolverChoice> Choices { get; set; } = [];
public List<SolverRoute> Routes { get; set; } = [];
}
public sealed class SolverChoice
{
public string Id { get; set; } = "";
public string Text { get; set; } = "";
public string Help { get; set; } = "";
public string Icon { get; set; } = "book";
public bool Active { get; set; } = true;
public bool Fallback { get; set; }
public int Order { get; set; }
public Dictionary<string,int> Weights { get; set; } = [];
}
public sealed class SolverRoute
{
public string Target { get; set; } = "";
public string? Choice { get; set; }
public string? Signal { get; set; }
public int Minimum { get; set; }
public int Priority { get; set; }
public bool AllowCycle { get; set; }
}
public class SolverPage
{
public string Id { get; set; } = "";
public string Slug { get; set; } = "";
public string Title { get; set; } = "";
public string PageTitle { get; set; } = "";
public string Description { get; set; } = "";
public string Summary { get; set; } = "";
public string Content { get; set; } = "";
public List<string> Questions { get; set; } = [];
public List<string> SearchIntents { get; set; } = [];
public bool Active { get; set; } = true;
public bool Index { get; set; }
public int Order { get; set; }
public string? SocialImage { get; set; }
}
public sealed class SolverSolution : SolverPage
{
public Dictionary<string,int> Signals { get; set; } = [];
public int Threshold { get; set; } = 3;
public string Principle { get; set; } = "";
public List<SolverFeatureLink> Features { get; set; } = [];
public List<string> Related { get; set; } = [];
}
public sealed class SolverFeature : SolverPage
{
public string? Screenshot { get; set; }
}
public sealed class SolverFeatureLink
{
public string Feature { get; set; } = "";
public bool Primary { get; set; }
public string Reason { get; set; } = "";
}
public sealed record SolverAnswer(string Node, string[] Choices);
public sealed record SolverOutcome(SolverNode? Next, IReadOnlyList<SolverSolution> Solutions, IReadOnlyDictionary<string,int> Scores, IReadOnlyList<SolverAnswer> Answers);
public sealed record SolverJourney(SolverGraph Graph, SolverOutcome Outcome, string History, string? Error = null);
public sealed record SolverPageView(SolverGraph Graph, SolverPage Page, bool IsFeature);

View File

@ -113,6 +113,7 @@ public class Program
builder.Services.AddScoped<IFeatureRequestRepository, FeatureRequestRepository>();
builder.Services.AddScoped<IProjectRepository, ProjectRepository>();
builder.Services.AddScoped<ApplicationNavigation>();
builder.Services.AddScoped<IWritingSolverRepository, WritingSolverRepository>();
builder.Services.AddScoped<IToolbarPreferenceRepository, ToolbarPreferenceRepository>();
builder.Services.AddScoped<IAppearanceRepository, AppearanceRepository>();
builder.Services.AddScoped<IBookRepository, BookRepository>();

View File

@ -0,0 +1,42 @@
using PlotLine.Models.WritingSolver;
namespace PlotLine.Services;
public static class WritingSolverEngine
{
public static SolverOutcome Evaluate(SolverGraph graph, IEnumerable<SolverAnswer> history)
{
var scores = new Dictionary<string,int>(StringComparer.Ordinal);
var accepted = new List<SolverAnswer>();
var next = graph.Nodes.Single(n => n.Id == graph.EntryNode && n.Active);
foreach (var answer in history.Take(graph.MaxAnswers))
{
if (next is null || answer.Node != next.Id) break; // Discard the stale suffix after revision.
var ids = answer.Choices.Distinct(StringComparer.Ordinal).ToArray();
var choices = next.Choices.Where(c => c.Active && ids.Contains(c.Id)).ToArray();
if (ids.Length == 0 || choices.Length != ids.Length || (!next.Multiple && ids.Length != 1)
|| (choices.Any(c => c.Fallback) && ids.Length != 1)) break;
accepted.Add(new(answer.Node, ids));
foreach (var choice in choices)
foreach (var weight in choice.Weights)
scores[weight.Key] = scores.GetValueOrDefault(weight.Key) + weight.Value;
next = SelectNext(graph, next, ids, accepted, scores);
}
var solutions = graph.Solutions.Where(s => s.Active)
.Select(s => new { Solution = s, Score = s.Signals.Sum(w => scores.GetValueOrDefault(w.Key) * w.Value) })
.Where(s => s.Score >= s.Solution.Threshold)
.OrderByDescending(s => s.Score).ThenBy(s => s.Solution.Order).ThenBy(s => s.Solution.Id, StringComparer.Ordinal)
.Select(s => s.Solution).Take(3).ToArray();
if (accepted.Count >= graph.MaxAnswers || (accepted.Count >= graph.MinAnswers && solutions.Length > 0)) next = null;
return new(next, next is null ? solutions : [], scores, accepted);
}
private static SolverNode? SelectNext(SolverGraph graph, SolverNode current, string[] choices, List<SolverAnswer> answers, Dictionary<string,int> scores)
{
var routes = current.Routes.Where(r => (r.Choice is null || choices.Contains(r.Choice))
&& (r.Signal is null || scores.GetValueOrDefault(r.Signal) >= r.Minimum));
return routes.Select(r => new { Route = r, Node = graph.Nodes.Single(n => n.Id == r.Target) })
.Where(x => x.Node.Active && !answers.Any(a => a.Node == x.Node.Id))
.OrderByDescending(x => x.Route.Priority + x.Node.Affinity.Sum(w => scores.GetValueOrDefault(w.Key) * w.Value))
.ThenBy(x => x.Node.Order).ThenBy(x => x.Node.Id, StringComparer.Ordinal).Select(x => x.Node).FirstOrDefault();
}
}

View File

@ -0,0 +1,151 @@
using System.Text.RegularExpressions;
using PlotLine.Models.WritingSolver;
namespace PlotLine.Services;
public static partial class WritingSolverValidator
{
public static List<string> Validate(SolverGraph graph)
{
var errors = new List<string>();
void Check(bool condition, string message) { if (!condition) errors.Add(message); }
Check(graph.SchemaVersion == 1, "Unsupported schema version.");
Check(!string.IsNullOrWhiteSpace(graph.Version) && graph.Version.Length <= 80, "Version is required (maximum 80 characters).");
Check(graph.MinAnswers >= 1 && graph.MaxAnswers >= graph.MinAnswers && graph.MaxAnswers <= 6, "Answer limits must be between one and six.");
Check(graph.Nodes.Count is > 0 and <= 1000 && graph.Solutions.Count <= 1000 && graph.Features.Count <= 1000, "Graph size is invalid.");
void Unique(IEnumerable<string> ids, string label)
{
Check(ids.All(id => !string.IsNullOrWhiteSpace(id) && Slug().IsMatch(id)), $"Invalid {label} identifier.");
foreach (var group in ids.GroupBy(x => x, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1)) errors.Add($"Duplicate {label}: {group.Key}");
}
Unique(graph.Nodes.Select(n => n.Id), "node");
Unique(graph.Solutions.Select(n => n.Id), "solution");
Unique(graph.Features.Select(n => n.Id), "feature");
Unique(graph.Solutions.Select(n => n.Slug), "solution slug");
Unique(graph.Features.Select(n => n.Slug), "feature slug");
if (errors.Count > 0) return errors;
var nodes = graph.Nodes.ToDictionary(n => n.Id);
var features = graph.Features.ToDictionary(n => n.Id);
var solutions = graph.Solutions.ToDictionary(n => n.Id);
Check(nodes.TryGetValue(graph.EntryNode, out var entry) && entry.Active, "Missing/inactive entry node.");
var signalNames = graph.Nodes.SelectMany(n => n.Choices).SelectMany(c => c.Weights.Keys).ToHashSet();
void Weights(Dictionary<string,int> weights, string label)
{
Check(weights.All(w => Slug().IsMatch(w.Key) && w.Value is >= -100 and <= 100 && w.Value != 0), $"Malformed weights: {label}");
}
foreach (var node in graph.Nodes)
{
Check(node.Type is "area" or "question", $"Unknown node type: {node.Id}");
Check(!string.IsNullOrWhiteSpace(node.Title), $"Missing question: {node.Id}");
Unique(node.Choices.Select(c => c.Id), $"choice in {node.Id}");
Check(!node.Active || node.Choices.Any(c => c.Active && c.Fallback), $"Missing fallback choice: {node.Id}");
Weights(node.Affinity, node.Id);
Check(node.Affinity.Keys.All(signalNames.Contains), $"Unknown affinity signal: {node.Id}");
foreach (var choice in node.Choices)
{
Check(!string.IsNullOrWhiteSpace(choice.Text), $"Missing choice text: {node.Id}/{choice.Id}");
Weights(choice.Weights, $"{node.Id}/{choice.Id}");
}
foreach (var route in node.Routes)
{
Check(nodes.TryGetValue(route.Target, out var target) && (!node.Active || target.Active), $"Missing/inactive target: {node.Id} -> {route.Target}");
Check(route.Choice is null || node.Choices.Any(c => c.Active && c.Id == route.Choice), $"Invalid route choice: {node.Id}");
Check(route.Signal is null || signalNames.Contains(route.Signal), $"Unknown route signal: {node.Id}");
if (route.Signal is not null)
{
var maximum = graph.Nodes.Where(n => n.Active).Select(n => n.Choices.Where(c => c.Active).Select(c => Math.Max(0,c.Weights.GetValueOrDefault(route.Signal))).DefaultIfEmpty().Sum()).Sum();
Check(route.Minimum <= maximum, $"Impossible signal route: {node.Id} -> {route.Target}");
}
}
}
foreach (var page in graph.Solutions.Cast<SolverPage>().Concat(graph.Features))
{
Check(!string.IsNullOrWhiteSpace(page.Title) && !string.IsNullOrWhiteSpace(page.PageTitle) && !string.IsNullOrWhiteSpace(page.Description) && !string.IsNullOrWhiteSpace(page.Summary) && !string.IsNullOrWhiteSpace(page.Content), $"Missing editorial/SEO fields: {page.Id}");
var image = page.SocialImage;
Check(image is null || image.StartsWith("/images/", StringComparison.Ordinal), $"Invalid social image: {page.Id}");
}
foreach (var feature in graph.Features)
Check(feature.Screenshot is null || feature.Screenshot.StartsWith("/images/", StringComparison.Ordinal), $"Invalid screenshot: {feature.Id}");
foreach (var solution in graph.Solutions)
{
Weights(solution.Signals, solution.Id);
Check(solution.Threshold > 0 && solution.Signals.Count > 0 && solution.Signals.Keys.All(signalNames.Contains), $"Invalid diagnosis signals: {solution.Id}");
Check(solution.Features.Count > 0 && solution.Features.Any(f => f.Primary), $"Missing primary feature: {solution.Id}");
Unique(solution.Features.Select(f => f.Feature), $"feature mapping in {solution.Id}");
foreach (var link in solution.Features)
Check(features.TryGetValue(link.Feature, out var feature) && (!solution.Active || feature.Active), $"Invalid feature mapping: {solution.Id}/{link.Feature}");
foreach (var related in solution.Related)
Check(solutions.TryGetValue(related, out var other) && (!solution.Active || other.Active), $"Invalid related solution: {solution.Id}/{related}");
}
if (errors.Count > 0) return errors;
var reachable = new HashSet<string>();
var visiting = new HashSet<string>();
void Visit(string id)
{
if (!visiting.Add(id)) return;
reachable.Add(id);
foreach (var route in nodes[id].Routes)
{
if (visiting.Contains(route.Target) && !route.AllowCycle) errors.Add($"Unpermitted cycle: {id} -> {route.Target}");
else if (!reachable.Contains(route.Target)) Visit(route.Target);
}
visiting.Remove(id);
}
Visit(graph.EntryNode);
foreach (var node in graph.Nodes.Where(n => n.Active && !reachable.Contains(n.Id))) errors.Add($"Unreachable node: {node.Id}");
foreach (var solution in graph.Solutions.Where(s => s.Active))
{
var upperBound = graph.Nodes.Where(n => n.Active && reachable.Contains(n.Id)).Select(n =>
{
var values = n.Choices.Where(c => c.Active).Select(c => c.Weights.Sum(w => w.Value * solution.Signals.GetValueOrDefault(w.Key))).ToArray();
return n.Multiple ? values.Where(v => v > 0).Sum() : values.DefaultIfEmpty().Max();
}).OrderDescending().Take(graph.MaxAnswers).Sum();
Check(upperBound >= solution.Threshold, $"Unreachable solution (insufficient signals): {solution.Id}");
}
foreach (var node in graph.Nodes.Where(n => n.Active && n.Routes.Count == 0))
Check(node.Choices.Any(c => c.Weights.Keys.Any(k => graph.Solutions.Any(s => s.Active && s.Signals.ContainsKey(k)))), $"Dead end without diagnostic evidence: {node.Id}");
if (errors.Count == 0) errors.AddRange(ValidateJourneys(graph));
return errors;
}
private static List<string> ValidateJourneys(SolverGraph graph)
{
var errors = new List<string>();
if (graph.Nodes.Any(n => n.Active && n.Multiple && n.Choices.Count(c => c.Active && !c.Fallback) > 12))
return ["Split multi-select nodes with more than 12 substantive choices to keep exhaustive validation bounded."];
var pending = new Queue<SolverAnswer[]>();
pending.Enqueue([]);
var seen = new HashSet<string>();
var reached = new HashSet<string>();
var diagnosed = new HashSet<string>();
while (pending.TryDequeue(out var history))
{
var outcome = WritingSolverEngine.Evaluate(graph, history);
var key = string.Join(",", outcome.Answers.Select(a => a.Node)) + ":" + string.Join(",",outcome.Scores.OrderBy(s=>s.Key).Select(s=>$"{s.Key}={s.Value}")) + ":" + outcome.Next?.Id;
if (!seen.Add(key)) continue;
if (seen.Count + pending.Count > 100000) return ["Journey validation exceeded 100,000 distinct states. Simplify the graph or split redundant choices; no data has been published."];
foreach(var solution in outcome.Solutions) diagnosed.Add(solution.Id);
if (outcome.Next is not { } node) continue;
reached.Add(node.Id);
var choices = node.Choices.Where(c=>c.Active).ToArray();
foreach(var choice in choices) pending.Enqueue([..history,new(node.Id,[choice.Id])]);
if (node.Multiple)
{
var substantive = choices.Where(c=>!c.Fallback).ToArray();
for(var mask=1;mask<(1<<substantive.Length);mask++)
{
if ((mask & (mask-1))==0) continue;
var ids = substantive.Where((_,i)=>(mask & (1<<i))!=0).Select(c=>c.Id).ToArray();
pending.Enqueue([..history,new(node.Id,ids)]);
}
}
}
errors.AddRange(graph.Nodes.Where(n=>n.Active && !reached.Contains(n.Id)).Select(n=>$"Unreachable node under scoring/routing rules: {n.Id}"));
errors.AddRange(graph.Solutions.Where(s=>s.Active && !diagnosed.Contains(s.Id)).Select(s=>$"Unreachable solution under scoring/routing rules: {s.Id}"));
return errors;
}
public static List<string> Warnings(SolverGraph graph) => graph.Features.Where(f => f.Active)
.Where(f => graph.Solutions.Count(s => s.Active && s.Features.Any(l => l.Feature == f.Id)) < 2)
.Select(f => $"Few solution routes to feature: {f.Id}").ToList();
[GeneratedRegex("^[a-z0-9]+(?:-[a-z0-9]+)*$")]
private static partial Regex Slug();
}

View File

@ -0,0 +1,43 @@
-- Immutable, validated graph snapshots. No author/account data is stored here.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
IF OBJECT_ID('dbo.WritingSolverVersions','U') IS NULL
BEGIN
CREATE TABLE dbo.WritingSolverVersions (
VersionID int IDENTITY PRIMARY KEY,
Version nvarchar(80) NOT NULL UNIQUE,
GraphJson nvarchar(max) NOT NULL CHECK (ISJSON(GraphJson)=1),
PublishedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),
Editor nvarchar(200) NOT NULL,
Active bit NOT NULL DEFAULT 0
);
CREATE UNIQUE INDEX UX_WritingSolver_Active ON dbo.WritingSolverVersions(Active) WHERE Active=1;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WritingSolver_Get AS
BEGIN
SET NOCOUNT ON;
SELECT GraphJson FROM dbo.WritingSolverVersions WHERE Active=1;
END;
GO
CREATE OR ALTER PROCEDURE dbo.WritingSolver_Publish
@Version nvarchar(80), @GraphJson nvarchar(max), @Editor nvarchar(200)
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
IF ISJSON(@GraphJson)<>1 OR JSON_VALUE(@GraphJson,'$.version')<>@Version
THROW 50001, 'Invalid Writing Solver graph/version.', 1;
BEGIN TRANSACTION;
-- Serialise publication and preserve all prior snapshots for audit/rollback by reimport.
DECLARE @LockResult int;
EXEC @LockResult = sys.sp_getapplock @Resource='WritingSolverPublish', @LockMode='Exclusive', @LockOwner='Transaction', @LockTimeout=10000;
IF @LockResult<0 THROW 50002, 'Unable to lock graph publication.', 1;
IF EXISTS(SELECT 1 FROM dbo.WritingSolverVersions WHERE Version=@Version)
THROW 50003, 'Version already exists. Publish a new version.', 1;
UPDATE dbo.WritingSolverVersions SET Active=0 WHERE Active=1;
INSERT dbo.WritingSolverVersions(Version,GraphJson,Editor,Active) VALUES(@Version,@GraphJson,@Editor,1);
COMMIT;
END;
GO

View File

@ -38,7 +38,7 @@
{
<meta name="keywords" content="@seoKeywords" />
}
<meta name="robots" content="index, follow" />
<meta name="robots" content="@(ViewData["Robots"] as string ?? "index, follow")" />
<meta property="og:site_name" content="PlotDirector" />
<meta property="og:title" content="@ogTitle" />
@if (!string.IsNullOrWhiteSpace(ogDescription))
@ -74,6 +74,7 @@
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/public-site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/public-art-direction.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/writing-solver.css" asp-append-version="true" />
<link rel="icon" href="~/favicon.svg" type="image/svg+xml" />
<meta name="theme-color" content="#f8f5ee" />
@if (isAuthentication)
@ -97,6 +98,7 @@
<div class="public-links">
<a asp-route="@PublicRouteNames.Home">Home</a>
<a asp-route="@PublicRouteNames.Features">Tour</a>
<a href="/writing-problems">Writing Solver</a>
<a asp-route="@PublicRouteNames.Pricing">Pricing</a>
<a asp-route="@PublicRouteNames.Help">Help</a>
</div>
@ -122,7 +124,8 @@
<div class="marketing-container">
<div class="public-footer-top"><a class="public-wordmark" asp-route="@PublicRouteNames.Home">PlotDirector<span class="gold-dot">.</span></a><p>Your book. Your words.<br />A little less to keep in your head.</p></div>
<nav class="public-footer__nav" aria-label="Footer navigation">
<a asp-route="@PublicRouteNames.Features">Tour</a><a asp-route="@PublicRouteNames.Pricing">Pricing</a><a asp-route="@PublicRouteNames.Help">Help</a><a asp-route="@PublicRouteNames.About">Our story</a><a asp-route="@PublicRouteNames.Contact">Contact</a><a asp-route="@PublicRouteNames.Privacy">Privacy</a><a asp-route="@PublicRouteNames.Terms">Terms</a>
<a asp-route="@PublicRouteNames.Features">Tour</a>
<a href="/writing-problems">Writing Solver</a><a asp-route="@PublicRouteNames.Pricing">Pricing</a><a asp-route="@PublicRouteNames.Help">Help</a><a asp-route="@PublicRouteNames.About">Our story</a><a asp-route="@PublicRouteNames.Contact">Contact</a><a asp-route="@PublicRouteNames.Privacy">Privacy</a><a asp-route="@PublicRouteNames.Terms">Terms</a>
</nav>
<p class="public-colophon">© @DateTime.UtcNow.Year PlotDirector. For the stories only you can tell.</p>
</div>

View File

@ -0,0 +1,33 @@
@model string
@{ ViewData["Title"] = "Writing Solver graph"; }
<h1>Writing Solver graph</h1>
<p>Immutable graph versions. Inspect nodes, choices, conditional connections, weights, diagnoses and feature mappings below. Validation reports reachability, dead ends, invalid references and unpermitted cycles. Publication preserves earlier snapshots.</p>
@if (ViewData["Report"] is IEnumerable<string> report) { <ul role="status">@foreach(var line in report) { <li>@line</li> }</ul> }
@if(ViewData["Graph"] is PlotLine.Models.WritingSolver.SolverGraph graph)
{
<h2>Graph at a glance</h2>
<p>Version @graph.Version · @graph.ChangeNote</p>
<div class="table-responsive"><table class="table"><thead><tr><th>Node</th><th>Question / active</th><th>Connections and conditions</th><th>Choice signals</th></tr></thead><tbody>
@foreach(var node in graph.Nodes.OrderBy(n=>n.Order))
{
<tr><td>@node.Id (@node.Type)</td><td>@node.Title<br />Active: @node.Active · Multiple: @node.Multiple</td>
<td>@foreach(var route in node.Routes) { <p>→ @route.Target<br />Choice: @(route.Choice ?? "any") · Signal: @(route.Signal ?? "any") ≥ @route.Minimum · Priority: @route.Priority · Cycle allowed: @route.AllowCycle</p> }</td>
<td>@foreach(var choice in node.Choices.OrderBy(c=>c.Order)) { <p><strong>@choice.Id</strong>: @choice.Text<br />Active: @choice.Active · Fallback: @choice.Fallback<br />@string.Join(", ",choice.Weights.Select(w=>$"{w.Key}: {w.Value}"))</p> }</td></tr>
}
</tbody></table></div>
<h2>Diagnoses and capabilities</h2>
<div class="table-responsive"><table class="table"><thead><tr><th>Diagnosis / active</th><th>Signals / threshold</th><th>Feature mappings</th></tr></thead><tbody>
@foreach(var solution in graph.Solutions)
{
<tr><td><a href="/writing-problems/@solution.Slug">@solution.PageTitle</a><br />@solution.Id · Active: @solution.Active · Index: @solution.Index</td><td>@string.Join(", ",solution.Signals.Select(w=>$"{w.Key}: {w.Value}"))<br />Threshold: @solution.Threshold</td>
<td>@foreach(var link in solution.Features) { <p>@link.Feature (@(link.Primary ? "primary" : "supporting"))<br />@link.Reason</p> }</td></tr>
}
</tbody></table></div>
}
<form method="post" action="/admin/writing-solver">
@Html.AntiForgeryToken()
<label for="graph-json">Graph JSON (schema v1)</label>
<textarea id="graph-json" name="json" rows="30" class="form-control" spellcheck="false" style="font-family:monospace">@Model</textarea>
<button name="operation" value="validate" class="btn btn-secondary mt-3">Validate without saving</button>
<button name="operation" value="publish" class="btn btn-primary mt-3">Validate &amp; publish new version</button>
</form>

View File

@ -0,0 +1,10 @@
@model string
@{ var path=Model switch {
"people" => "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M16 3a4 4 0 0 1 0 8M22 21v-2a4 4 0 0 0-3-3.87M13 7a4 4 0 1 1-8 0a4 4 0 0 1 8 0",
"clock" => "M12 8v4l3 3M9 2h6M12 2v2M21 13a9 9 0 1 1-18 0a9 9 0 0 1 18 0",
"pin" => "M20 10c0 6-8 12-8 12S4 16 4 10a8 8 0 1 1 16 0M15 10a3 3 0 1 1-6 0a3 3 0 0 1 6 0",
"layers" => "m12 2 10 5-10 5L2 7l10-5M2 12l10 5 10-5M2 17l10 5 10-5",
"shelf" => "M3 3h4v18H3zM10 3h4v18h-4zM16 5l4-1 3 16-4 1z",
_ => "M3 3h7c2 0 2 2 2 2s0-2 2-2h7v17h-7c-2 0-2 1-2 1s0-1-2-1H3zM12 5v16"
}; }
<svg class="solver-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.35" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="@path" /></svg>

View File

@ -0,0 +1,80 @@
@using PlotLine.Models.WritingSolver
@model SolverJourney
@{ Layout = "_PublicLayout"; var next = Model.Outcome.Next; var beginning = Model.Outcome.Answers.Count == 0; }
<section class="solver-space @(beginning ? "solver-space--entry" : "")">
<div class="solver-content">
<p class="marketing-eyebrow">The Writing Problem Solver</p>
@if (Model.Error is not null) { <p role="status">@Model.Error</p> }
@if (beginning)
{
<h1>What’s getting in the way<br class="solver-wide" /> of <em>your</em> writing?</h1>
<p class="solver-intro">Tell us what’s making your novel more complicated than it should be,<br class="solver-wide" /> and we’ll help you find a way to get it under control.</p>
}
@if (next is not null)
{
<form method="post" action="/writing-problems/answer" class="solver-form">
@Html.AntiForgeryToken()
<input type="hidden" name="state" value="@Model.History" />
<input type="hidden" name="node" value="@next.Id" />
<fieldset>
<legend class="@(beginning ? "solver-entry-legend" : "solver-question")">@next.Title</legend>
<p class="solver-help" id="solver-help">@next.Help</p>
<div class="solver-choices @(next.Type == "area" ? "solver-choices--areas" : "")">
@foreach(var choice in next.Choices.Where(c => c.Active).OrderBy(c => c.Order))
{
<label class="solver-choice @(choice.Fallback ? "solver-choice--fallback" : "")">
<input type="@(next.Multiple ? "checkbox" : "radio")" name="choices" value="@choice.Id" aria-describedby="solver-help" />
@if (next.Type == "area" && !choice.Fallback) { <partial name="Icon" model="choice.Icon" /> }
<span><strong>@choice.Text</strong>@if(!string.IsNullOrEmpty(choice.Help)) { <span class="solver-choice-help">@choice.Help</span> }</span>
</label>
}
</div>
</fieldset>
<p class="solver-selection-error" role="alert" hidden>Please choose an answer to continue.</p>
<div class="solver-controls">
@if (ViewData["BackState"] is string back) { <a class="editorial-link" href="/writing-problems?state=@back">← Back</a> }
<button class="marketing-btn marketing-btn--primary" type="submit">@(beginning ? "Let’s find your solution" : "Continue") <span aria-hidden="true">→</span></button>
</div>
</form>
}
else
{
<p class="solver-resolution">✓ Here’s a useful way forward</p>
@if(Model.Outcome.Solutions.Count == 0)
{
<h1>Let’s give this a little breathing room.</h1>
<p>There isn’t enough evidence for a specific recommendation yet. Try naming one scene or thread that feels difficult, then ask what you need to know about it next.</p>
<p>You can explore the advice below, or restart with a different area.</p>
}
@foreach(var solution in Model.Outcome.Solutions)
{
<partial name="Solution" model="@(new SolverPageView(Model.Graph,solution,false))" />
}
<div class="solver-controls">
@if (ViewData["BackState"] is string resultBack) { <a class="editorial-link" href="/writing-problems?state=@resultBack">← Back</a> }
<a class="marketing-btn marketing-btn--secondary" href="/writing-problems">Start again</a>
</div>
}
@if(Model.Outcome.Answers.Count > 0)
{
<nav class="solver-trail" aria-label="Areas discussed">
<span>We’ve talked about:</span>
@for(var i=0; i<Model.Outcome.Answers.Count; i++)
{
var answer=Model.Outcome.Answers[i];
var node=Model.Graph.Nodes.Single(n=>n.Id==answer.Node);
<span>@string.Join(", ",node.Choices.Where(c=>answer.Choices.Contains(c.Id)).Select(c=>c.Text))</span>
}
<a href="/writing-problems">Restart</a>
</nav>
}
else { <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> }
</div>
</section>
<section class="solver-library marketing-container">
<h2>A little help, whenever you need it.</h2>
<p>You can read this advice directly, without starting the conversation.</p>
@foreach(var solution in Model.Graph.Solutions.Where(s=>s.Active).OrderBy(s=>s.Order)) { <a class="editorial-link" href="/writing-problems/@solution.Slug">@solution.PageTitle →</a> }
</section>
@section Scripts { <script src="~/js/writing-solver.js" asp-append-version="true"></script> }

View File

@ -0,0 +1,33 @@
@using PlotLine.Models.WritingSolver
@model SolverPageView
@{ Layout="_PublicLayout"; }
<div class="solver-space solver-space--article">
<div class="solver-content">
<nav class="solver-trail" aria-label="Breadcrumb"><a href="/">Home</a><span>›</span><a href="@(Model.IsFeature ? "/features" : "/writing-problems")">@(Model.IsFeature ? "Features" : "Writing Problem Solver")</a></nav>
@if(Model.Graph.IsDemo) { <p class="solver-demo">Demonstration content · The curated collection is on its way.</p> }
@if(Model.IsFeature)
{
var feature=(SolverFeature)Model.Page;
<h1>@feature.Title</h1>
<p class="solver-intro">@feature.Summary</p>
@foreach(var paragraph in feature.Content.Split("\n\n")) { <p class="solver-editorial">@paragraph</p> }
@if(feature.Screenshot is not null) { <img class="solver-screenshot" src="@feature.Screenshot" alt="@feature.Title workspace in PlotDirector" width="1200" height="750" /> }
<h2>Writing problems this can help with</h2>
@foreach(var solution in Model.Graph.Solutions.Where(s=>s.Active && s.Features.Any(f=>f.Feature==feature.Id))) { <p><a href="/writing-problems/@solution.Slug">@solution.PageTitle</a></p> }
<p><a class="marketing-btn marketing-btn--primary" href="/features">See PlotDirector in action →</a></p>
}
else
{
<partial name="Solution" model="Model" />
var solution=(SolverSolution)Model.Page;
@if(solution.Related.Count>0) { <h2>You might also find this useful</h2> }
@foreach(var id in solution.Related)
{
var related=Model.Graph.Solutions.Single(s=>s.Id==id && s.Active);
<p><a href="/writing-problems/@related.Slug">@related.PageTitle</a></p>
}
}
@if(Model.Page.Questions.Count>0) { <h2>Questions this helps answer</h2><ul>@foreach(var question in Model.Page.Questions) { <li>@question</li> }</ul> }
<a class="editorial-link" href="/writing-problems">Find a way through your writing problem →</a>
</div>
</div>

View File

@ -0,0 +1,23 @@
@using PlotLine.Models.WritingSolver
@model SolverPageView
@{ var solution = (SolverSolution)Model.Page; }
<article class="solver-result">
<h1>@solution.Title</h1>
<p class="solver-intro">@solution.Summary</p>
<aside class="solver-principle"><strong>A useful principle</strong><p>@solution.Principle</p></aside>
@foreach(var paragraph in solution.Content.Split("\n\n")) { <p class="solver-editorial">@paragraph</p> }
<h2>How PlotDirector can help</h2>
<div class="solver-features">
@foreach(var link in solution.Features.OrderByDescending(f=>f.Primary))
{
var feature=Model.Graph.Features.Single(f=>f.Id==link.Feature && f.Active);
<div>
<p class="marketing-eyebrow">@(link.Primary ? "Start here" : "Works alongside it")</p>
<h3><a href="/features/@feature.Slug">@feature.Title →</a></h3>
<p>@link.Reason</p>
@if(link.Primary && feature.Screenshot is not null) { <a href="/features/@feature.Slug"><img src="@feature.Screenshot" alt="@feature.Title workspace in PlotDirector" width="1200" height="750" loading="lazy" /></a> }
</div>
}
</div>
<p><a class="editorial-link" href="/writing-problems/@solution.Slug">Read and share this advice →</a></p>
</article>

View File

@ -0,0 +1,61 @@
/* Public-only refinement; application theme tokens never participate. */
html[data-site-theme="public"] {
--paper:#fcf3e5; --paper-deep:#f0e2cf; --ink:#30242b; --muted:#71625c;
--line:#dfcdb9; --sage:#e8eadc; --gold:#c7ac67; --gold-dark:#7c733d; --plum:#54223f;
.public-header { background:#fcf3e5f5; }
.marketing-btn--primary,.public-site a.marketing-btn--primary { background:var(--plum); border-color:var(--plum); color:#fff9f0; }
.marketing-btn--primary:hover { background:#6a3153; border-color:#6a3153; color:#fff9f0; }
.writer-problems,.story-problems { background:#f3e7d6; }
.writer-hero { background:radial-gradient(ellipse at 85% 50%,#eddfca 0,transparent 60%); }
.public-links { gap:22px; }
#publicMenu { margin-left:38px; }
.solver-space { background-color:var(--paper); background-image:linear-gradient(90deg,transparent,#fcf3e5ed 22%,#fcf3e5f7 50%,#fcf3e5ed 78%,transparent),url('/images/public/writing-solver-desk.png'); background-position:center top; background-size:cover; padding:48px 24px 32px; min-height:760px; }
.solver-content { width:min(930px,100%); margin:auto; }
.solver-space--entry .solver-content { width:min(1000px,100%); text-align:center; }
.solver-space h1 { font-size:clamp(2.4rem,4.2vw,4rem); margin:12px 0 22px; line-height:1.08; }
.solver-space h1 em { color:var(--gold-dark); }
.solver-intro { font:clamp(1.15rem,1.6vw,1.45rem)/1.5 Georgia,serif; max-width:780px; margin:0 auto 28px; }
.solver-question { float:none; width:100%; font:clamp(2rem,3.5vw,3rem)/1.15 Georgia,serif; letter-spacing:-.035em; color:var(--plum); margin:10px 0 16px; }
.solver-entry-legend { font:600 1rem/1.5 "Segoe UI",sans-serif; margin-bottom:6px; }
.solver-help { color:var(--muted); margin-bottom:22px; }
.solver-choices { display:grid; gap:10px; max-width:750px; margin:0 auto; text-align:left; }
.solver-choices--areas { grid-template-columns:repeat(3,minmax(0,1fr)); max-width:100%; gap:14px; }
.solver-choice { position:relative; display:flex; gap:14px; align-items:center; cursor:pointer; min-height:58px; padding:14px 18px; background:#fffaf2e8; border:1px solid #d9bfa9; border-radius:12px; box-shadow:0 3px 5px #613d2410; color:var(--ink); }
.solver-choice:has(input:checked) { border-color:var(--plum); background:#f2e4eb; box-shadow:0 0 0 1px var(--plum); }
.solver-choice input { width:20px; height:20px; min-width:20px; accent-color:var(--plum); margin:0; }
.solver-choice strong { font-size:1rem; font-weight:500; line-height:1.4; display:block; }
.solver-choices--areas .solver-choice { min-height:125px; padding:18px 14px; gap:12px; }
.solver-choices--areas .solver-choice strong { font:600 1.5rem/1.1 Georgia,serif; color:var(--plum); letter-spacing:-.04em; }
.solver-choices--areas input { position:absolute; top:10px; right:10px; width:15px; height:15px; min-width:15px; }
.solver-choice-help { display:block; font-size:.95rem; line-height:1.4; margin-top:5px; }
.solver-icon { width:48px; min-width:48px; height:48px; color:var(--plum); }
.solver-choice--fallback { box-shadow:none; background:transparent; }
.solver-choices--areas .solver-choice--fallback { grid-column:1/-1; min-height:42px; padding:8px 16px; justify-content:center; border:0; }
.solver-choices--areas .solver-choice--fallback input { position:static; }
.solver-choices--areas .solver-choice--fallback strong { font:400 .95rem/1.4 "Segoe UI",sans-serif; letter-spacing:0; }
.solver-controls { display:flex; justify-content:flex-end; gap:30px; align-items:center; margin:24px auto; max-width:750px; }
.solver-space--entry .solver-controls { justify-content:center; }
.solver-controls .marketing-btn { border-radius:30px; padding:15px 30px; font-size:1.05rem; cursor:pointer; }
.solver-promises { font-size:.9rem; margin:20px 0; }.solver-promises span { margin:0 20px; color:var(--gold-dark); }
.solver-demo { font-size:.8rem; color:var(--muted); margin:20px 0 0; }
.solver-trail { display:flex; flex-wrap:wrap; gap:8px 14px; font-size:.8rem; color:var(--muted); border-top:1px solid var(--line); padding-top:18px; margin:25px 0; }
.solver-trail span:not(:first-child) { max-width:360px; }
.solver-resolution { color:#536b48; margin-bottom:10px; font-size:1rem; }
.solver-principle { padding:22px 26px; background:#f0e3ed; border-left:3px solid #875979; margin:25px 0; max-width:780px; }
.solver-principle p { margin:6px 0 0; font:1.2rem/1.5 Georgia,serif; }
.solver-editorial { font-size:1.06rem; line-height:1.85; max-width:780px; }
.solver-result .solver-intro { margin-left:0; }
.solver-space h2,.solver-library h2 { font-size:clamp(1.8rem,3vw,2.6rem); margin:35px 0 22px; }
.solver-space h3 { font-size:1.8rem; margin-bottom:12px; }
.solver-features { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:25px; border-top:1px solid var(--line); padding:25px 0; }
.solver-features>div:first-child { grid-column:1/-1; }
.solver-features img,.solver-screenshot { display:block; width:100%; height:auto; border:1px solid var(--line); border-radius:6px; margin:20px 0; }
.solver-library { padding-block:30px 55px; }.solver-library>a { margin:10px 30px 10px 0; }
.solver-space--article { background-size:auto 900px; background-repeat:no-repeat; }
.solver-selection-error { color:#8b293e; }
@media(max-width:1000px) { .solver-space { background-image:linear-gradient(90deg,#fcf3e5aa,#fcf3e5f5 12%,#fcf3e5f5 88%,#fcf3e5aa),url('/images/public/writing-solver-desk.png'); }.solver-choices--areas { grid-template-columns:repeat(2,minmax(0,1fr)); }.public-links { gap:14px; } #publicMenu { margin-left:20px; } }
@media(max-width:600px) { .solver-space { padding:30px 20px; min-height:800px; background-image:linear-gradient(#fcf3e5e8,#fcf3e5 240px),url('/images/public/writing-solver-desk.png'); background-size:auto 300px; background-repeat:no-repeat; }.solver-choices--areas { grid-template-columns:1fr; gap:10px; }.solver-choices--areas .solver-choice { min-height:90px; padding:15px 35px 15px 16px; }.solver-wide { display:none; }.solver-icon { width:38px; min-width:38px; height:38px; }.solver-choices--areas .solver-choice strong { font-size:1.35rem; }.solver-help { font-size:.95rem; }.solver-controls { justify-content:space-between; gap:12px; }.solver-controls .marketing-btn { padding:13px 22px; font-size:1rem; }.solver-promises span { margin:0 6px; }.solver-features { grid-template-columns:1fr; }.solver-features>div:first-child { grid-column:auto; }.solver-content h1 { overflow-wrap:break-word; }.solver-trail span:not(:first-child) { max-width:100%; } }
@media(prefers-reduced-motion:reduce) { scroll-behavior:auto; .marketing-btn { transition:none; transform:none; } }
}
html[data-site-theme="public"] main.marketing-shell > section.solver-space { max-width:none; width:100%; }
html[data-site-theme="public"] .public-footer { background:#f0e5d4; }

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 MiB

View File

@ -0,0 +1,18 @@
(() => {
const form = document.querySelector('.solver-form');
if (!form) return;
const inputs = [...form.querySelectorAll('input[name="choices"]')];
inputs.forEach(input => input.addEventListener('change', () => {
if (input.checked) inputs.forEach(other => {
if (other !== input && (input.closest('.solver-choice--fallback') || other.closest('.solver-choice--fallback'))) other.checked = false;
});
form.querySelector('.solver-selection-error').hidden = true;
}));
form.addEventListener('submit', event => {
if (!inputs.some(input => input.checked)) {
event.preventDefault();
form.querySelector('.solver-selection-error').hidden = false;
inputs[0]?.focus();
}
});
})();

View File

@ -0,0 +1,58 @@
using System.Data;
using System.Text.RegularExpressions;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using PlotLine.Data;
using PlotLine.Services;
if (args.Length < 2) throw new ArgumentException("Usage: validate|publish FILE | migrate SQL | inspect development | query SQLFILE");
var operation = args[0];
if (operation is "validate" or "publish")
{
var graph = WritingSolverRepository.Parse(await File.ReadAllTextAsync(args[1]));
Console.WriteLine($"Valid graph {graph.Version}: {graph.Nodes.Count} nodes, {graph.Solutions.Count} solutions, {graph.Features.Count} features.");
foreach(var warning in WritingSolverValidator.Warnings(graph)) Console.WriteLine(warning);
if (operation == "validate") return;
}
// Protected development environment is parsed as data, never evaluated by a shell.
var line = File.ReadLines("/etc/plotdirector/plotdirector.env").Single(l => l.StartsWith("ConnectionStrings__DefaultConnection="));
var raw = line[(line.IndexOf('=')+1)..].Trim();
if (raw.Length > 1 && (raw[0]=='\'' || raw[0]=='"') && raw[^1]==raw[0]) raw=raw[1..^1];
var cs = new SqlConnectionStringBuilder(raw);
if (!string.Equals(cs.InitialCatalog,"PlotDirector_Development",StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("Configured database is not development.");
await using var connection = new SqlConnection(cs.ConnectionString);
await connection.OpenAsync();
if (await connection.ExecuteScalarAsync<string>("SELECT DB_NAME()") != "PlotDirector_Development") throw new InvalidOperationException("Wrong database.");
Console.WriteLine("Verified PlotDirector_Development.");
if (operation == "migrate")
{
var backup=$"/var/opt/mssql/backup/PlotDirector_Development_solver_{DateTime.UtcNow:yyyyMMdd_HHmmss}.bak";
await connection.ExecuteAsync("BACKUP DATABASE [PlotDirector_Development] TO DISK=@path WITH COPY_ONLY, INIT, CHECKSUM",new {path=backup}, commandTimeout:180);
var hostBackup = new FileInfo(backup.Replace("/var/opt/mssql/", "/sql/mssql/", StringComparison.Ordinal));
if (!hostBackup.Exists || hostBackup.Length == 0) throw new IOException("Backup command succeeded but the mapped backup file is missing/empty.");
Console.WriteLine($"Backup completed with CHECKSUM; file verified: {backup} ({hostBackup.Length} bytes). This is not a restore test.");
var sql=await File.ReadAllTextAsync(args[1]);
await connection.ExecuteAsync("SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON;");
foreach(var batch in Regex.Split(sql,@"^\s*GO\s*$",RegexOptions.Multiline|RegexOptions.IgnoreCase))
if (!string.IsNullOrWhiteSpace(batch)) await connection.ExecuteAsync(batch,commandTimeout:120);
Console.WriteLine("Migration applied.");
}
else if(operation == "publish")
{
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?> { ["ConnectionStrings:DefaultConnection"]=cs.ConnectionString }).Build();
await new WritingSolverRepository(new SqlConnectionFactory(configuration)).PublishAsync(await File.ReadAllTextAsync(args[1]),Environment.UserName);
Console.WriteLine("Graph published atomically.");
}
else if(operation == "query")
{
var sql=await File.ReadAllTextAsync(args[1]);
using var results = await connection.QueryMultipleAsync(sql);
while (!results.IsConsumed)
foreach(var row in await results.ReadAsync()) Console.WriteLine(System.Text.Json.JsonSerializer.Serialize((IDictionary<string,object>)row));
}
else if(operation == "inspect")
{
foreach(var row in await connection.QueryAsync("SELECT Version,PublishedUtc,Active FROM dbo.WritingSolverVersions")) Console.WriteLine($"{row.Version} | {row.PublishedUtc} | active={row.Active}");
}
else throw new ArgumentException("Unknown operation.");

View File

@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
<ItemGroup><ProjectReference Include="../../PlotLine/PlotLine.csproj" /></ItemGroup>
</Project>