8.5 KiB
Raw Blame History

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.