17 KiB
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, uniqueversion,changeNote,isDemo,entryNode,minAnswersandmaxAnswers(1–6).nodes: stableid,type(areaorquestion), title/help,active,multiple,order, signalaffinity,choices, androutes.- Choices: ID unique within their node, natural-language
text, help/icon, order, active,fallback, andweights(signal ID → signed nonzero integer −100…100). - Routes: target node ID, optional choice ID and/or signal/minimum condition, priority, and explicit
allowCyclemetadata. Multiple alternatives may match. - Solutions: ID, stable slug, H1
title,pageTitle, description, summary, plain-text editorialcontent(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.
Explicit neutral outcomes (Curated V2 engineering gate)
A schema-v1 question can now declare neutralEndpoint: true (default false). The declaration means after answering this question, the conversation ends with reassurance rather than a diagnosis. It is generic; runtime code does not recognise adoption node or choice IDs.
A neutral endpoint must have no routes, routing affinity, multi-select mode or diagnostic choice weights. It must supply a node-level reassurance fallback. A choice may override that reassurance with its own reassurance object. Other nodes cannot carry reassurance without the explicit declaration. Existing undeclared evidence-free dead ends remain invalid. Invalid/missing fields or inactive/missing feature references fail normal import validation.
{
"neutralEndpoint": true,
"reassurance": {
"title": "Use only what helps.",
"summary": "You can leave with this reassurance, or return another time.",
"advice": ["One useful next step is enough."]
}
}
reassurance requires a nonempty title and summary, permits up to three plain-text advice paragraphs and one optional feature ID. The feature is linked through its existing active public record; there are no arbitrary outcome URLs. The selected choice's content takes precedence over the fallback. All copy is encoded Razor text.
The engine retains previously accumulated signals, adds none at the neutral endpoint, returns no diagnostic solutions and records the selected reassurance in SolverOutcome. Replay and revision recompute that outcome from protected answer history. The existing UI renders it server-side with Back/Restart and an optional single capability, without the diagnostic library. Ordinary insufficient-evidence endings retain their existing neutral advice/reading links and are distinct from authored reassurance.
Old/demo graphs omit these properties and keep their previous behaviour. Additive JSON properties require deploying the updated parser before publishing a graph containing them. Database storage and procedures need no migration because publication remains a validated, immutable JSON snapshot.
WritingSolver:EnableIndexing defaults true for existing public behaviour. Set it false in the Development service environment to force all solver/feature responses to noindex, follow (including an HTTP robots header) and exclude solver URLs from the sitemap. Development activation is not editorial/Production indexing approval.
Before development graph publication, Tools/WritingSolver backup development takes a unique COPY_ONLY/CHECKSUM backup and verifies mapped-file existence/size. It refuses any configured database other than PlotDirector_Development. Then publish FILE uses the normal repository validation and dbo.WritingSolver_Publish transaction. This is not a restore test.
Curated V2's reconciled semantic expectations live in its acceptance-paths.json. The original literal baseline is retained under Docs/WritingSolver/CuratedV2/DevelopmentGate/. The owner explicitly approved eight known secondary-result exceptions for Development only; regression checks permit exactly those known supports, prohibit new exceptions, and continue to require all 60 correct primaries and all literal prefixes. The strict semantic report remains 52/60, rather than being relabelled green. These acceptance exceptions are test/review metadata, not production scoring overrides.
Stage 1 corroboration and intention (November 2026)
Additive schema-v1 fields retain their defaults for earlier snapshots:
SolverSolution.requiredSignals: positive evidence minima, default empty. These determine eligibility in addition to the unchanged weighted score/threshold. They do not contribute points. Early symptom scores can therefore represent hypotheses without publishing a conclusion.SolverNode.requireAnswer: default false. A selected follow-up marked true cannot be skipped merely because a hypothesis crosses threshold; the existing maximum-answer limit still applies.SolverNode.maxChoices: default zero/unlimited. A positive value is valid only on a multi-select question (2–12). The engine enforces the limit with or without JavaScript; the renderer and enhancement script explain it. Stage 1 asks for at most two broad tracking concerns to establish a useful focus.SolverNode.allowNeutralChoices: default false. On a single-choice diagnostic question, explicitly authored choice reassurance can end the conversation without a solution. Such choices must have no weights or applicable onward route. This allows “the choice is deliberate and working” to end immediately, rather than adding another reassurance question. Existing node-level neutral endpoints retain their stricter requirements and previous behaviour.
A current Stage 1 diagnosis requires an observed consequence and a stated concern. Creative diagnoses additionally require an actual intention answer: a management concern elsewhere (for example, remembering several books) cannot establish that a slow relationship is unwanted. Explicit, specific management complaints can establish the concern before the follow-up, so the solver need not repeat an intention question after corroboration. Deliberate-but-hard-to-manage is distinct from deliberate-and-working.
WritingSolverTraversal evaluates and deduplicates semantic states before enqueuing them. The identity remains visited node sequence + complete signal totals + next node. The 100,000 distinct-state limit is unchanged; duplicate pending answers with identical evidence no longer consume extra budget. No scores or reachable outcomes are discarded. The original V2 still explores 11,325 states. Explicit tests separately cover choice-specific reassurance because that existing semantic traversal identity merges neutral presentation variants.
The original curated-v2 graph and 60-case expectations remain historical regression fixtures. Stage 1 is a separate immutable publication version in Candidates/curated-v2-stage1. Its authored expanded paths and semantic expectations are frozen in its own acceptance-paths.json. --writing-solver-stage1 audits that file; --write-paths is an explicit authoring operation, not part of normal regressions. Production publication is not authorised by the Development gate.
Authored diagnostic result presentation
Content/WritingSolver/Presentation/results-v1.json is a separate, deterministic presentation catalogue. It does not alter or republish the Stage 1 graph. Each result has one primary capability, diagnosis-specific inference/relevance/look-for copy, an optional useful principle, at most one secondary capability and at most one existing Help article key.
Evidence copy is explicitly bound to exact accepted node/choice pairs. Only matched rules for the returned diagnosis are rendered; up to three authored observations/intention clauses form the explanation. This supports materially different paths to one diagnosis without runtime text generation. A score or unaccepted/stale history cannot supply evidence copy. Exhaustive tests require a matched corroborating observation for every returned result in all Stage 1 states. No signals, scores or diagnosis identifiers are exposed in the presentation.
Result.cshtml is used only for completed diagnostic conversations. Solution.cshtml/Page.cshtml retain the existing direct advice/SEO article content. Supporting diagnoses stay visible as compact expandable evidence summaries. Reassurance retains its own template; insufficient evidence has no diagnosis confirmation or recommendation panel. The indiscriminate article catalogue is removed from every conversation state without deleting any article.
Capabilities declare an audited existing application route, public tour anchor, screenshot requirement and end-user preview caption. Until a safe, existing /images/writing-solver/*.webp|png capture is configured, the visual component explicitly renders a Development placeholder. A configured but missing file also retains the placeholder. Capture requirements are kept out of product-facing captions. The later application-theme work will supply genuine screenshots; none are fabricated here.
Visitors receive a public tour CTA. Signed-in authors enter an authenticated project selector; project membership is resolved using existing user-scoped repositories, and character-specific views additionally validate that the selected character belongs to that project. Missing project/character context gives a usable selection/empty state rather than a broken route. Redirects use fixed audited local templates and validated numeric IDs. No new database queries, procedures, migrations or production configuration changes are required.