Prevent corroborated solver journeys from ending without a result

This commit is contained in:
Nick Beckley 2026-11-01 21:38:51 +00:00
parent 431fe8979b
commit 127a85d730
24 changed files with 159207 additions and 2 deletions

View File

@ -0,0 +1,51 @@
# Repair: ordinary solver journeys ending without a result
Development only. Continues from `431fe89`. The reported problem is reproduced on the ordinary live UI before repair:
1. The story isn't coming together.
2. There are too many storylines.
3. I have to search back to remember which threads are still open.
4. It is getting in the way of what I want.
Despite a concrete corroboration and concern, the result was “Let’s give this a little breathing room.” D01 had only 27 points against its existing threshold of 32: the new corroborating answer supplied an eligibility flag but no scored evidence of its own.
## Root causes
- Many new corroboration choices supplied only an observation gate. They could confirm the actual explanation but still leave its score below threshold, particularly when it differed from the first hypothesis.
- Old navigation/detail branches used the six-answer budget before corroboration or intention could be collected. Reaching a diagnosis somewhere in the graph and passing 60 carefully authored cases did not detect this practical failure rate.
- Some follow-ups asked about a different domain than the selected symptom: for example, character location/presence could lead to a fact-consistency question.
- Clear non-fault observations, such as deliberate absence or a relationship actually progressing slowly, could fall through to generic insufficient evidence after another question.
## Repair
The new immutable candidate is `writing-solver-curated-v2-stage1-repair`; the original Stage 1 remains a historical regression fixture.
Corroborating answers now supply the existing core signals their actual wording establishes. This is authored positive evidence, not a threshold bypass. `evidence-decisions.json` records every changed follow-up weight with its exact wording and before/after values. All 52 diagnosis definitions, coefficients, thresholds, required evidence gates, feature records and original 44 symptom/navigation nodes' choices remain unchanged. The eight prior semantic exceptions remain resolved; no exception allowlist is added.
Optional navigation is constrained by two additive route fields: `fromAnswers` and exclusive `beforeAnswers`, both counting accepted answers. Zero defaults preserve existing graphs. After the fourth answer, a redundant navigation branch yields to a relevant corroboration question, leaving room for intention. If a dominance branch genuinely reaches its final question at six, three authored final-question variants explicitly collect the observed problem **and the concern about it** together. Deliberate-and-working and uncertainty options remain available. No firm diagnosis is inferred merely from an observation with no concern.
Three full family discriminators are restored for late focus answers, and three final-slot questions handle the remaining irreducible branches. The resulting graph has **158 reachable nodes**, including every original node. Unused generated last-slot variants are omitted as assembly scaffolding; `unused-variants.json` records them. No diagnosis is omitted or tuned to make traversal fit the ceiling.
Specific misdirected routes now lead to the relevant existing location, knowledge, cast, causal-consequence or scene-purpose question. Clear non-fault responses end in tailored reassurance with one relevant capability, not a fabricated diagnosis.
Result-presentation evidence is bound to the new exact question/choice identities. The result design and primary tool recommendations are unchanged. Rebuilding the presentation catalogue retains these bindings automatically.
## Verification
All traversal counts below are **distinct structural states, not visitor frequencies**.
| Failure guard | Original Stage 1 | Repair |
|---|---:|---:|
| Fully corroborated concern, no result | 7,034 | **0** |
| Substantive ending with no result, no reassurance and no explicit uncertainty fallback | 10,488 | **0** |
| Budget exhausted before any corroboration question | 1,869 | **0** |
| Distinct states | 85,140 | **57,599** |
| Reachable diagnoses / primary-capable diagnoses | 52 / 52 | **52 / 52** |
The repaired traversal contains 21,685 diagnostic terminals, 10,496 authored neutral terminals, 6,599 explicit uncertainty terminals and 735 “none fits” terminals. Genuine uncertainty is not relabelled as a diagnosis. Every diagnostic outcome still takes **4–6 answers**.
The 60 semantic acceptance cases preserve their primary/neutral and required supporting expectations: **60/60, 290/290 prefixes**. The one removed prefix is the redundant intention question after case 57 has already established that a relationship is progressing slowly; its honest non-diagnostic reassurance is unchanged in intent. Coefficients, thresholds and all required-signal gates are asserted equal to Stage 1. The original Stage 1 60/291 suite also remains passing as a historical fixture.
The real repository validator passes normally, below the unchanged 100,000-state limit. The repaired snapshot also opts into `requireCorroboratedResults`: actual publication validation now rejects a fully corroborated concern that has no scored result, rather than relying only on the test harness. Its false default preserves historical snapshots. A regression recreates the original scored-evidence omission and verifies that publication validation rejects it. Full executable regressions: **391 PASS**. New guards cover all states, require actual evidence copy for every returned diagnosis, preserve four-answer minimum and series-only evidence, and reject contradictory route ranges.
The browser suite tests the reported four-answer failure, a changed hypothesis, a knowledge-source search, six-answer rescue navigation, late POV and intended-main-plot routes, plus all result-presentation families, reassurance, insufficient evidence, signed-in/out CTAs, Back/Forward/Start again, no JavaScript, 390px/1440px layouts, noindex and public styling. Captured outputs accompany this report. Live activation and verification are recorded in `Deployment.md` after release.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,4 @@
Before: {"other-insufficient":1803,"explicit-uncertainty":12796,"diagnostic":18812,"corroborated-without-result":7034,"authored-neutral":8035,"unexplained-empty":10488,"budget-before-corroboration-question":1869}
After: {"other-insufficient":735,"explicit-uncertainty":6599,"diagnostic":21685,"authored-neutral":10496}
Traversal 57599, nodes 158/158, solutions 52/52, primary 52;
Acceptance 60/60; prefixes 290/290

View File

@ -0,0 +1 @@
PASS dead-end repair: reported four-answer route; changed hypothesis; knowledge search; six-answer rescue/POV/intended-main routes; Plot Lines, timeline/continuity, relationships, scene/chapter, series, knowledge and character arc; evidence variants; optional secondary/article; explicit missing visuals; no article dump; reassurance/insufficient evidence; no-JS; 390/1440px; Back/Forward/Restart; public theme and noindex; signed-out tour CTA; signed-in authorised project/character selector and real workspace redirects.

View File

@ -0,0 +1,16 @@
Determining projects to restore...
All projects are up-to-date for restore.
PlotLine -> /srv/repos/PlotDirector/PlotLine/bin/Debug/net10.0/PlotLine.dll
WritingSolver -> /srv/repos/PlotDirector/Tools/WritingSolver/bin/Debug/net10.0/WritingSolver.dll
/srv/repos/PlotDirector/PlotLine.Tests/ToolbarBrowserHost.cs(116,19): warning CS8602: Dereference of a possibly null reference. [/srv/repos/PlotDirector/PlotLine.Tests/PlotLine.Tests.csproj]
/srv/repos/PlotDirector/PlotLine.Tests/Program.cs(3694,12): warning CS8602: Dereference of a possibly null reference. [/srv/repos/PlotDirector/PlotLine.Tests/PlotLine.Tests.csproj]
PlotLine.Tests -> /srv/repos/PlotDirector/PlotLine.Tests/bin/Debug/net10.0/PlotLine.Tests.dll
Build succeeded.
/srv/repos/PlotDirector/PlotLine.Tests/ToolbarBrowserHost.cs(116,19): warning CS8602: Dereference of a possibly null reference. [/srv/repos/PlotDirector/PlotLine.Tests/PlotLine.Tests.csproj]
/srv/repos/PlotDirector/PlotLine.Tests/Program.cs(3694,12): warning CS8602: Dereference of a possibly null reference. [/srv/repos/PlotDirector/PlotLine.Tests/PlotLine.Tests.csproj]
2 Warning(s)
0 Error(s)
Time Elapsed 00:00:32.98

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,391 @@
PASS Solver never discards a corroborated concern or exhausts navigation before verification
PASS Solver result evidence covers all reachable diagnoses without changing Stage 1 semantics
PASS Solver result copy follows actual answers, intention, variants and revision
PASS Solver workspace CTAs resolve authorised project/character context and real routes
PASS Stage 1 preserves all 60 strict conversations, corroboration, intent, reachability and adoption
PASS Stage 1 evidence gates, required follow-ups, bounded multi-select and neutral choices are enforced
PASS Neutral endpoints require explicit valid terminal declarations
PASS Neutral reassurance follows selected concerns without evidence and survives revision
PASS Scene navigation does not invent purpose evidence; genuine D05 witnesses survive
PASS D50 requires actual series evidence and preserves D50/D51 witnesses
PASS Curated V2 preserves 60 literal paths and enforces eight explicit Development review exceptions
PASS Curated V2 exhausts real-engine states and preserves revision/multi-select behaviour
PASS Curated V2 passes normal validation and invalid publication stays guarded
PASS Writing Solver anonymous state is protected, expires and rejects stale versions
PASS Writing Solver scoring, multi-select, revision, fallback and graph routes
PASS Writing Solver import rejects invalid graphs and editorial identities
PASS Ribbon operation identity and semantic icons stay consistent
PASS Subscription entitlement evaluates trials, paid access, overrides and real plan limits
PASS Subscription enforcement is concurrent, audited and admin-authorised
PASS Plot Health stays scene-based with 12,000 contributions
PASS Plot Health preserves Discovery planning and boundary contradictions
PASS Plot Health separates stored status and meaningful-progress clocks
PASS Plot Health explains question, payoff, closure and boundary evidence
PASS Plot Health evaluates explicit targets and scoped line rollups
PASS Plot Health respects scenario coverage and ordered chapter identities
PASS Plot Lines Focus and Weave preserve gaps and shared-scene identity
PASS Plot Lines thread, enrichment and Timeline inspector contracts hold
PASS Plot Lines composition remains bounded with a large generated weave
PASS Exception review uses evidence, identity, consequence and directional conflicts
PASS Exception assessment preserves author decisions and scene history
PASS Character card widths reflect displayed text without changing character data
PASS Relationships workspace large cast, temporal states and canonical edits
PASS Scene relationship proposals preserve direction and validate acceptance
PASS Location and asset merges require confirmation and distinct records
PASS Location persisted analysis preserves contextual bedrooms and setting provenance
PASS Location consequence outranks capped recurrence
PASS Location scene significance is attributed only to actual settings
PASS Location significance preserves hierarchy and independent uncertainty
PASS Character profile age uses canonical reference chronology
PASS Character detail and date-only save retain canonical DOB
PASS Story Point presence, previous appearances and age cross book boundaries
PASS Story Point knowledge stops at selected narrative position
PASS Story Point relationships and independent asset state are historical
PASS Story Point threads and continuity warnings respect future evidence
PASS Story Point ownership, AJAX and bounded batch loading require no AI
PASS Story Point narrative tie breakers match canonical order
PASS Malformed confidence 0. is repaired to 0.0
PASS Markdown fences are stripped
PASS Unescaped backslash in evidence is repaired
PASS Truncated JSON is rejected
PASS Repaired JSON deserialises into SceneIntelligenceScene
PASS Chapter Structure confidence 0. repairs and deserialises
PASS Chapter Structure confidence 0. 8 repairs and deserialises
PASS Chapter Structure confidence 7 .5 repairs when unambiguous
PASS JSON repair leaves decimal-looking prose unchanged
PASS Chapter Structure semantic validation still rejects out-of-range repaired confidence
PASS Structural scene detection parser failure uses friendly diagnostics and retry
PASS Chapter Structure boundary normaliser repairs gaps and overlaps
PASS Chapter Structure boundary normaliser preserves valid coverage
PASS Chapter Structure boundary normaliser handles terminal ghost paragraph
PASS Chapter Structure boundary normaliser discards multiple terminal ghost paragraphs
PASS Chapter Structure boundary normaliser replays full book terminal empty failure
PASS Chapter Structure boundary normaliser keeps meaningful end overflow repair
PASS Chapter Structure boundary normaliser preserves genuine inverted ranges for validation
PASS Structural Word mapping uses paragraph map as authoritative text
PASS Structural Word mapping includes filtered Word paragraphs in source coverage
PASS Structural Word mapping fails precisely when map metadata is incomplete
PASS Structural Word mapping keeps trailing empty normalisation mapped
PASS Shared parser reports raw chapter output on unrecoverable JSON
PASS Character filtering rejects generic groups
PASS Character filtering preserves titled names
PASS Location filtering rejects merged phrases
PASS Location filtering preserves story locations
PASS Location canonical keys merge trivial variants
PASS Location contextual names use POV and structural setting
PASS Location canonical keys merge punctuation and safe plurals
PASS Location candidate consolidation handles generic review variants
PASS Location candidate identity is parent-aware for generic sub-locations
PASS Locations page uses hierarchical sort order
PASS Location review UX supports large candidate sets
PASS Story Intelligence auto resolves exact known locations before review
PASS Story Intelligence location review uses single identity decision
PASS Asset filtering rejects generic objects
PASS Asset filtering preserves story assets
PASS Asset canonical keys merge trivial variants
PASS Asset canonical keys merge contextual vehicle variants
PASS Asset canonical keys keep unrelated owned cars distinct
PASS Asset candidate keys attach unique unowned variants
PASS Asset filtering rejects relationship facts
PASS Asset contextual names resolve POV ownership
PASS Asset structural phrases trim neighbouring nouns
PASS Asset significance is generic and not fixture-specific
PASS Story Intelligence asset review applies current identity rules
PASS Relationship review requires pair evidence and distinguishes social types
PASS Relationship signals map to broad lookup types
PASS Relationship signals infer friendship without romance
PASS Relationship events preserve chronological story order
PASS Relationship progression keeps chronological state
PASS Relationship observations do not create event spam
PASS Relationship review orders by first story appearance
PASS Relationship evidence priority preserves explicit semantics
PASS Relationship evidence handles retained hostile and incidental examples
PASS Knowledge signals map to existing knowledge states
PASS Knowledge recipient resolves narrator through POV
PASS Knowledge identity reveal preserves subjective timing
PASS Knowledge duplicate statements share canonical keys
PASS Knowledge suspicion and certainty remain distinct
PASS Illustration prompt builder separates spec and prompt
PASS Illustration prompt builder uses realistic image direction
PASS Illustration specification validation catches missing typed fields
PASS Illustration category validation rejects unknown values
PASS Illustration status transitions protect approval flow
PASS Illustration status transitions support archive flow
PASS Illustration metadata flags fallback location labels
PASS Illustration location matching rejects vehicle living room reuse
PASS Illustration automatic generation policy blocks vague fallbacks
PASS Story Memory import image generation defaults are safe
PASS Illustration storage codes are normalised safely
PASS Illustration starter batch has required category counts
PASS Illustration starter generation plan skips successful items
PASS Story Intelligence visualisation archive is preserved
PASS Story Intelligence visualisation runtime is removed
PASS Story Intelligence does not retry exhausted billing quota
PASS Illustration bulk retry result reports counts
PASS Illustration bulk retry skips blocking duplicate stable codes
PASS Illustration provider reports missing image model
PASS Illustration provider omits GPT image response format
PASS Illustration matching rejects adult masculine unknown art for Beth
PASS Illustration matching treats Mrs title as hard feminine evidence
PASS Illustration matching infers mother and aunt as mature feminine
PASS Illustration matching rejects duplicate named portrait allocation
PASS Illustration semantic types prevent bathroom office and ambulance car mismatches
PASS Illustration demand archetypes stay broad and use active template
PASS Story Intelligence evidence extraction prevents observed attribute leakage
PASS Story Intelligence scene call uses strict structured output
PASS Story Intelligence scene schema constrains confidence numbers
PASS Story Intelligence scene schema constrains evidence strings
PASS Story Intelligence temporal resolves chapter anchor and afternoon
PASS Story Intelligence temporal rolls over after midnight
PASS Story Intelligence temporal resolves following morning
PASS Story Intelligence temporal resolves exact day offsets
PASS Story Intelligence temporal resolves following weekday
PASS Story Intelligence temporal resolves evening clock time
PASS Story Intelligence temporal rejects unanchored clock time
PASS Story Intelligence temporal preserves yearless calendar date clues
PASS Story Intelligence temporal resolves yearless calendar dates from context
PASS Story Intelligence temporal inherits previous morning when extraction is empty
PASS Story Intelligence temporal inherits previous evening when extraction is empty
PASS Story Intelligence temporal inherits previous night when extraction is empty
PASS Story Intelligence temporal inherits after midnight advancement
PASS Story Intelligence temporal inherits chapter anchor when extraction is empty
PASS Story Intelligence temporal stays unknown without context or extraction
PASS Story Intelligence temporal explicit date overrides previous context
PASS Story Intelligence temporal preserves vague few days
PASS Core import applies structural chronology to canonical scenes
PASS Story Intelligence temporal importer preserves manual chronology
PASS Story Intelligence temporal materialisation saves canonical chronology
PASS Story Intelligence temporal malformed values are discarded
PASS Story Calendar places dated scenes on Monday-first month grid
PASS Story Calendar separates unplaced scenes without guessing
PASS Story Calendar book filter and all books scope work
PASS Story Calendar month navigation uses story dates across years
PASS Story Calendar month dropdown follows displayed month
PASS Story Calendar handles no dated scenes
PASS Story Calendar day details endpoint returns partial
PASS Story Calendar day details endpoint respects book filter
PASS Story Calendar day details endpoint handles empty story date
PASS Story Calendar day details endpoint rejects invalid project
PASS Story Calendar index returns surface partial for AJAX
PASS Story Calendar day selection uses progressive AJAX hooks
PASS Story Intelligence structured metric values validate and import
PASS Story Intelligence structured schema covers complete response model
PASS Story Intelligence structured schema remains fixture agnostic
PASS Illustration assignment repair enforces explicit evidence groups and strict subtypes
PASS Lean import removes replay links while retaining progress
PASS Story Intelligence progress does not prematurely report safe close
PASS Structural import creates scenes before Word sync
PASS Structural import creates first scene without placeholder
PASS Structural import persists paragraph mapping and source text
PASS Structural import persists canonical scene source text
PASS Structural import adds summaries without extra scene AI calls
PASS Core import scan stage defers scenes and characters
PASS Core import basic location detector is conservative
PASS Core import basic location detector consolidates and skips existing matches
PASS Core import basic location detector supports pending parent candidates
PASS Core import character discovery protects accepted locations
PASS Core import gates characters behind basic location review
PASS Core import hides exact existing character names from review
PASS Core import hides exact existing character aliases from review
PASS Core import keeps suspected unknown aliases in review
PASS Core import keeps ambiguous existing character matches in review
PASS Core import keeps new characters in review
PASS Core import auto resolved character evidence is preserved
PASS Core import character evidence is candidate specific
PASS Core import deterministically maps known characters
PASS Core import wizard orders scenes before characters
PASS Core import remaps characters after review
PASS Scan review separates known matches from unresolved names
PASS Story Intelligence uses persisted scene source after restart
PASS Story Intelligence canonical mode bypasses duplicate boundary analysis
PASS Story Intelligence progress uses canonical scene summaries
PASS Story Intelligence downstream imports prefer canonical SceneIDs
PASS Story Intelligence scene prompt no longer asks for duplicate factual summary
PASS Story Intelligence review uses canonical structural summaries and counts
PASS Story Intelligence review centre completion is category scoped
PASS Word sync requires save acknowledgement
PASS Word sync retry resumes existing structure
PASS Story Intelligence enriches existing structural scenes
PASS Core import scene titles ride existing structural AI call
PASS Core import scene title preference is review scoped
PASS Core import scene title preference moved to Detect Scenes
PASS Core import Review Chapters is compact and chapter only
PASS Core import Detect Scenes is compact and owns title option
PASS Book context is canonical import metadata
PASS Names defaults from selected book context
PASS Story Intelligence starts from core import complete
PASS Generated scene titles persist with provenance
PASS Scene title display keeps scene numbers visible
PASS Manuscript text statistics handles pure prose
PASS Manuscript text statistics handles pure dialogue
PASS Manuscript text statistics splits narrative before dialogue
PASS Manuscript text statistics splits dialogue before narrative
PASS Manuscript text statistics handles multiple dialogue passages
PASS Manuscript text statistics supports smart quotes
PASS Manuscript text statistics supports straight quotes
PASS Manuscript text statistics carries multi-paragraph dialogue
PASS Manuscript text statistics returns to prose after continued dialogue
PASS Manuscript text statistics ignores empty paragraphs
PASS Manuscript text statistics reconciles scene totals
PASS Manuscript text statistics aggregates chapter scenes
PASS Manuscript text statistics recalculates existing scene sources
PASS Manuscript text statistics does not invoke AI
PASS Phase 21T repairs durable character understanding
PASS Phase 21U extracts mandatory character appearance fixtures
PASS Character sex hints are conservative and reviewable
PASS Character discovery does not truncate scan review candidates
PASS Character discovery rejects sentence-start words
PASS Character discovery rejects fragments and location names
PASS Manuscript scan preview keeps only auto-selected character candidates
PASS Word Companion scan completion uses chunked transport
PASS Word Companion scan chunks assemble full novel payloads
PASS Word Companion scan chunks reject partial and conflicting payloads
PASS Onboarding wizard keeps character pages inside one main step
PASS Scan review aliases feed Story Intelligence known character context
PASS Name Intelligence package contract is present
PASS Name Intelligence reference data is copied on publish
PASS Name Intelligence repository uses stored procedures
PASS Name Intelligence review warning is wired
PASS Name Intelligence library defaults to all locales
PASS Story Intelligence new-format context uses canonical characters
PASS Story Intelligence character defaults link proposed existing matches
PASS Story Intelligence character defaults ignore generic references
PASS Story Intelligence character defaults keep descriptive identities
PASS Story Intelligence character review uses single identity decision
PASS Story Intelligence auto resolves exact known identities before review
PASS Story Intelligence character matching keeps ambiguous known names visible
PASS Story Intelligence descriptive references consolidate articles
PASS Story Intelligence review omits character metrics dashboard
PASS Story Intelligence resumed chapters use canonical labels
PASS Story Intelligence character review posts selected existing match
PASS Story Intelligence character default changes preserve persisted results
PASS Structural POV rides existing chapter analysis
PASS Structural POV persists through import resolution
PASS Chapter POV derives from canonical scenes
PASS Permanent Analyse My Book starts from saved book
PASS Story Intelligence canonical context carries provenance
PASS Scene prompt protects canonical scene context
PASS Structural setting rides existing chapter analysis
PASS Explicit narrator labels detect deterministic POV
PASS AI POV JSON parses into structural models
PASS Post character review resolves persisted structural POV
PASS Normal scene and chapter saves persist POV
PASS Character merge is a reusable stored procedure workflow
PASS Story Intelligence character review suppresses resolved narrator POV
PASS Story Intelligence character review reuses structured appearance aliases
PASS Entity preferred names are peer aliases
PASS Story Intelligence review evidence includes chapter scene labels
PASS Story Intelligence import enables project metric defaults before save
PASS Project metrics add defaults backfills scene values
PASS Story Intelligence scene prompt uses configured metrics
PASS Story Intelligence scene prompt uses scene characters terminology
PASS Story Intelligence downstream imports support canonical scene results
PASS Story Intelligence runner supplies metrics and Plot Lines
PASS Story Intelligence metric persistence uses configured keys
PASS Story Intelligence stabilisation gate materialises strict and legacy metrics
PASS Story Intelligence modern materialisation owns finalisation boundary
PASS Story Intelligence narrative materialisation reads strict scene results
PASS Story Intelligence stabilisation routes normal users to book
PASS Story Intelligence narrative candidates require review
PASS Story Intelligence discovers Plot Lines without preconfiguration
PASS Story Intelligence matches existing Plot Lines without duplicates
PASS Narrative research prototype fixture builds hierarchy
PASS Narrative sibling hotel fixture generalises hierarchy
PASS Narrative trivial one-scene question is suppressed
PASS Narrative short significant thread survives
PASS Narrative semantic evolution consolidates by continuity
PASS Narrative existing thread matching is supported
PASS Narrative candidate merge and parent fields are persisted
PASS Narrative prompt uses one scene call with compact schema
PASS Narrative production code remains fixture agnostic
PASS Whole-book Plot Intelligence prompt carries full manuscript context
PASS Whole-book Plot Intelligence schema requires timeline event types
PASS Whole-book Plot Intelligence author seed inputs persist safely
PASS Whole-book Plot Intelligence structured author seed match survives
PASS Whole-book Plot Intelligence unmatched seeds become review candidates
PASS Whole-book Plot Intelligence uses dedicated output token headroom
PASS Story Intelligence narrative review displays author seed provenance
PASS Story Intelligence narrative review avoids raw author-facing IDs
PASS Story Intelligence author seed decisions are preserved
PASS Whole-book Plot Intelligence production code remains fixture agnostic
PASS Story Intelligence narrative review creates canonical records via existing procs
PASS Story Intelligence narrative stage follows knowledge
PASS Word Companion replays live current scene to writing panes
PASS Scan review post supports full-book form submissions
PASS StoryPosition rejects incomplete or invalid runtime scene positions
PASS StoryPosition builds canonical runtime scene navigation
PASS StoryPosition derives canonical scene context identity
PASS Writing Context route uses canonical story context service
PASS Writing Context client follows canonical story position events
PASS Writing Context preserves selected tab and avoids event loops
PASS Writing Intent route uses canonical story context and planning data
PASS Writing Intent client uses shared writing follow helper
PASS Obsolete global Word navigation is removed while writing windows remain live
PASS Appearance preferences and ribbon destinations
PASS Toolbar preferences, authorisation and contextual routes
PASS Application navigation resolves authorised project and book context
PASS Writing pair shares canonical follow infrastructure
PASS Writing workspace presence scopes browser windows
PASS Writing workspace client uses session window identity and stable names
PASS Writing workspace launcher uses progressive screen placement
PASS Writing workspace pages register roles without changing follow behavior
PASS Word Companion exposes writing workspace launch actions
PASS Word Companion writing screens receive resolved context identifiers
PASS Word Companion canonical markers drive runtime follow
PASS Word Companion runtime follows multiple imported scene anchors
PASS Word Companion existing project book linking remains available
PASS Word Companion document identity survives reconnect
PASS Word Companion multiscreen launch and follow remain reachable
PASS Word Companion modes remain distinct
PASS Writing pages do not require Story Intelligence
PASS Word Companion host script has valid tab mapping
PASS Writing screens show diagnostic empty states
PASS Word Companion three-screen flow logs connection identifiers
PASS Admin Story Intelligence reset returns to diagnostics with messages
PASS Project hard delete clears Story Intelligence dependencies in transaction
PASS Permanent project delete keeps archive and name safety gates
PASS Word manuscript cleanup classifies PlotDirector markers by tag only
PASS Word manuscript cleanup preserves content controls content
PASS Word manuscript cleanup UI separates unlink from clean unlink
PASS Word manuscript unlink keeps Story Intelligence data untouched
PASS Word manuscript cleanup remains relinkable and idempotent
PASS Story Intelligence Review Centre route replaces linear review resume
PASS Story Intelligence obsolete create scene workflow is removed
PASS Story Intelligence Review Centre counts only needs-attention categories
PASS Story Intelligence Review Centre uses independent tile grid
PASS Story Intelligence Review Centre opens with character gate
PASS Story Intelligence review modules are independent after character gate
PASS Story Intelligence review module completion is durable and independent
PASS Story Intelligence review module pages omit wizard chrome
PASS Story Intelligence downstream review uses completed scene analysis
PASS Story Intelligence review posts do not use success interstitials
PASS Story Intelligence legacy review completion routes are deleted
PASS Story Intelligence review forms share busy submit guard
PASS Story Intelligence heavy review modules offer bounded rendering
PASS Story Intelligence Review Centre adds no AI calls
PASS Story Intelligence Review Centre uses bounded summary query
PASS Story Intelligence character review queues enrichment beside plot synthesis
PASS Story Intelligence character enrichment uses persisted SignalR progress
PASS Story Intelligence character enrichment preserves author fields
PASS Story Intelligence character enrichment batches by prompt size
PASS Story Intelligence character enrichment promotes structured facts
PASS Character detail can queue single-character enrichment
PASS Single-character enrichment is persisted and duplicate safe
PASS Character detail enrichment status uses scoped SignalR
PASS Story Intelligence detailed review GETs use selected module paths
PASS Story Intelligence completed Character review remains inspectable
PASS Story Intelligence Review Centre completed modules use canonical destinations
PASS Story Intelligence detailed reviews read persisted candidate pages
PASS Story Intelligence module completion lifecycle uses persisted candidates
PASS Story Intelligence Job 6 uses bounded concurrent chapter execution
PASS Story Intelligence global progress uses whole run scene totals
PASS Story Intelligence recovered provider failures stay operational
PASS Story Intelligence recovered JSON repair stays operational
PASS Story Intelligence terminal failures remain user visible
PASS Story Intelligence global banner remains visible through finalising gaps
PASS Story Intelligence global banner rejects stale live snapshots
PASS Story Intelligence live global progress publishes authoritative scene aggregates
PASS Story Intelligence global progress survives initial SignalR start races
PASS Story Intelligence scene analysis completion barrier releases review
PASS Story Intelligence active progress only appears in global strip
PASS Story Intelligence book actions do not open review centre while running

View File

@ -0,0 +1,91 @@
[
"final-arc",
"final-cast-gap-none",
"final-cast-gap-share",
"final-cast-remember-same-job",
"final-cast-same-job-remember",
"final-cast-share-gap",
"final-cast-share-remember",
"final-cast-share-voice",
"final-cast-voice-share",
"final-causality",
"final-change",
"final-facts",
"final-knowledge",
"final-knowledge-clues-source",
"final-knowledge-no-source-source-order",
"final-knowledge-order-no-source-reader",
"final-knowledge-povs-no-source-order",
"final-knowledge-povs-source",
"final-knowledge-reader-order",
"final-knowledge-reader-order-povs",
"final-knowledge-source-no-source",
"final-knowledge-source-povs",
"final-object",
"final-object-history-place",
"final-object-history-track",
"final-object-holder-history",
"final-object-holder-track",
"final-object-place-holder",
"final-object-track-history",
"final-object-track-holder",
"final-object-track-place",
"final-overload",
"final-payoff",
"final-place",
"final-progression-late-uneven",
"final-progression-nothing-character",
"final-progression-nothing-uneven",
"final-progression-tension-late",
"final-progression-tension-nothing",
"final-progression-tension-uneven",
"final-progression-uneven-character",
"final-progression-uneven-late",
"final-progression-uneven-nothing",
"final-purpose",
"final-relationships",
"final-relationships-moving-repeat",
"final-relationships-network-ripples",
"final-relationships-network-stage",
"final-relationships-network-views",
"final-relationships-repeat-moving",
"final-relationships-ripples-network",
"final-relationships-stage-moving",
"final-relationships-stage-network",
"final-relationships-stage-ripples",
"final-relationships-stage-views",
"final-relationships-unprepared-stage",
"final-relationships-views-stage",
"final-series",
"final-structure",
"final-structure-chapter-place",
"final-structure-place-chapter",
"final-structure-place-purpose",
"final-structure-purpose-repeat",
"final-structure-purpose-volume",
"final-structure-repeat-purpose",
"final-structure-volume-purpose",
"final-threads",
"final-threads-apart-gap",
"final-threads-apart-lost",
"final-threads-gap-apart",
"final-threads-gap-lost",
"final-threads-lost-apart",
"final-threads-lost-gap",
"final-threads-scenes-apart",
"final-threads-scenes-lost",
"final-time",
"final-time-age-clash",
"final-time-clash-age",
"final-time-clash-elapsed",
"final-time-clash-reading",
"final-time-elapsed-clash",
"final-time-elapsed-fixed",
"final-time-elapsed-travel",
"final-time-fixed-clash",
"final-time-parallel-clash",
"final-time-reading-clash",
"final-time-reading-parallel",
"final-time-travel-elapsed",
"final-whereabouts"
]

View File

@ -0,0 +1,3 @@
Valid graph writing-solver-curated-v2-stage1-repair: 158 nodes, 52 solutions, 15 features.
Few solution routes to feature: character-development
Few solution routes to feature: manuscript-import

View File

@ -110,3 +110,13 @@ Evidence copy is explicitly bound to exact accepted node/choice pairs. Only matc
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.
## Confirmed-concern and navigation-budget guards
The repaired Stage 1 publication separates real uncertainty from accidental empty results. Exhaustive regression now rejects (1) a fully corroborated concern ending without a solution, (2) substantive terminal answers with no result/reassurance/explicit uncertainty, and (3) navigation consuming all six answers before any corroboration question. Reachability and selected acceptance cases alone are insufficient release gates.
Routes may declare `fromAnswers` (inclusive lower bound) and `beforeAnswers` (exclusive upper bound, zero meaning unbounded). Defaults preserve old graphs. Contradictory or impossible ranges are rejected. Counts refer to accepted answers when choosing the next node. The authored repair reserves the final two slots for corroboration and intention instead of increasing the six-answer ceiling. Last-slot variants explicitly ask which observed difficulty the author wants help with; they do not silently infer intention or relax required-signal gates.
Assembly: `build-dead-end-repair.py` builds the separate immutable candidate from the preserved Stage 1 baseline. `build-repair-presentation.py` binds existing authored copy to restored/final question identities. `build-results.py` applies those bindings automatically when the repaired candidate exists. Original symptoms and diagnosis definitions are unchanged; scored evidence is corrected only on the new corroborating answers. See `CuratedV2/DeadEndRepair/evidence-decisions.json` for provenance.
`SolverGraph.requireCorroboratedResults` is an opt-in validation contract (default false for historical snapshots). If a terminal, non-reassurance outcome satisfies a diagnosis’s nonempty required-signal gates but returns no result, actual repository validation rejects the publication. It does not bypass scoring or alter thresholds. The repaired candidate enables this protection; a regression recreates the original omission and proves rejection.

View File

@ -0,0 +1,69 @@
const {chromium}=require('playwright');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const graph=JSON.parse(fs.readFileSync('PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1-repair/writing-solver-curated-v2-stage1-repair.json'));
const cases=JSON.parse(fs.readFileSync('PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1-repair/acceptance-paths.json')).cases;
const catalog=JSON.parse(fs.readFileSync('PlotLine/Content/WritingSolver/Presentation/results-v1.json'));
const base=process.env.SOLVER_BASE_URL||'http://127.0.0.1:5238';
assert(['127.0.0.1:5238','dev.plotdirector.com'].includes(new URL(base).host));
(async()=>{
const browser=await chromium.launch();
async function journey(page,id){await page.goto(base+'/writing-problems');assert.equal(await page.locator('.solver-library').count(),0);for(const answer of cases.find(c=>c.id===id).answers){assert.equal(await page.locator('input[name=node]').inputValue(),answer.node);assert.equal(await page.locator('.solver-library').count(),0);for(const choice of answer.choices)await page.locator(`input[name=choices][value="${choice}"]`).check();await page.locator('.solver-form button[type=submit]').click();}}
try {
for(const width of [390,1440])for(const javaScriptEnabled of [true,false]){
const context=await browser.newContext({javaScriptEnabled,viewport:{width,height:1100}});
await context.addCookies([{name:'solver-anonymous',value:'true',url:base}]);
const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
for(const id of [3,25,15,30,47,22,43]){
await journey(page,id);const test=cases.find(c=>c.id===id);const content=catalog.results.find(r=>r.solution===test.expectedPrimary);const tool=catalog.capabilities.find(c=>c.id===content.capability);
assert.equal(await page.locator('.solver-result-panel h1').innerText(),graph.solutions.find(s=>s.id===test.expectedPrimary).title);
assert((await page.locator('.solver-result-evidence').innerText()).length>50);
assert(!/\bd\d{2}\b|observed-|concern-confirmed|threshold|\bscores?\b/i.test(await page.locator('.solver-result-panel').innerText()));
assert.equal(await page.locator('.solver-result-panel .solver-result-cta').count(),1);
assert.equal(await page.locator('.solver-result-cta').getAttribute('href'),tool.tour);
assert((await page.locator('.solver-result-cta').innerText()).startsWith('See how'));
assert.equal(await page.locator('.solver-visual-placeholder').count(),1);assert.equal(await page.locator('.solver-tool-visual img').count(),0);
assert.equal(await page.locator('.solver-also').count(),content.secondary?1:0);
assert.equal(await page.locator('.solver-deeper a').count(),content.articleKey?1:0);
if(content.articleKey){const article=await page.locator('.solver-deeper a').getAttribute('href');assert.equal((await context.request.get(base+article)).status(),200);}
assert.equal(await page.locator('.solver-library').count(),0);assert(!(await page.locator('main').innerText()).includes('A little help, whenever you need it'));
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false,`overflow ${id}/${width}`);
assert.equal(await page.locator('meta[name=robots]').getAttribute('content'),'noindex, follow');
assert.equal(await page.locator('html').getAttribute('data-site-theme'),'public');assert.equal(await page.locator('html').getAttribute('data-app-theme'),null);
if(id===3&&width===1440&&javaScriptEnabled&&base.includes('127.0.0.1'))await page.screenshot({path:'/tmp/solver-results-layout.png'});
await page.goBack();assert.equal(await page.locator('input[name=node]').inputValue(),test.answers.at(-1).node);
await page.goForward();assert.equal(await page.locator('.solver-result-panel').count(),1);
await page.getByRole('link',{name:'Start again',exact:true}).click();assert.equal(await page.locator('input[name=node]').inputValue(),'entry');
}
for(const [answers,expected] of [
[['story-not-working','too-many','lost','unwanted'],'d01'],
[['story-not-working','dont-connect','gap','unwanted'],'d02'],
[['losing-track','knowledge','checking','source'],'d22'],
[['unsure','reread-cant-see','characters-consistent','who-they-are','same-job','unwanted'],'d09'],
[['unsure','reread-cant-see','story-hangs-together','takes-over','voice','voice'],'d12'],
[['unsure','reread-cant-see','story-hangs-together','takes-over','gaps','disappears'],'d02']]){
await page.goto(base+'/writing-problems');
for(const choice of answers){await page.locator(`input[name=choices][value="${choice}"]`).check();await page.locator('.solver-form button[type=submit]').click();}
assert.equal(await page.locator('.solver-result-panel h1').innerText(),graph.solutions.find(s=>s.id===expected).title);
assert.equal(await page.locator('.solver-result-cta').count(),1);
assert((await page.locator('.solver-result-evidence').innerText()).length>30);
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);
}
await page.goto(base+'/writing-problems');for(const [node,choice]of[['entry','unsure'],['rescue-happening','reread-cant-see'],['rescue-confidence','using-tool-concern'],['existing-stage','draft-done'],['existing-barrier','discovery']]){assert.equal(await page.locator('input[name=node]').inputValue(),node);await page.locator(`input[value="${choice}"]`).check();await page.locator('.solver-form button[type=submit]').click();}
assert.equal(await page.locator('.solver-neutral').count(),1);assert.equal(await page.locator('.solver-start,.solver-library,.solver-result-panel').count(),0);
await journey(page,50);assert.equal(await page.locator('.solver-result-panel,.solver-resolution,.solver-library').count(),0);assert((await page.locator('main').innerText()).includes('isn’t enough evidence'));
assert.equal(errors.length,0,errors.join('\n'));await context.close();
}
if(base.includes('127.0.0.1')){
const context=await browser.newContext({viewport:{width:1440,height:1000}});const page=await context.newPage();
await journey(page,3);assert.match(await page.locator('.solver-result-cta').innerText(),/^Open .* in my workspace/);
await page.locator('.solver-result-cta').click();assert.equal(await page.locator('select[name=projectId]').count(),1);
const response=await context.request.get(base+'/writing-problems/workspace/plot?projectId=77',{maxRedirects:0});assert.equal(response.status(),302);assert.equal(response.headers().location,'/PlotLineWorkspace?projectId=77');
await page.goto(base+'/writing-problems/workspace/knowledge?projectId=77');assert.equal(await page.locator('select[name=characterId]').count(),1);
const character=await context.request.get(base+'/writing-problems/workspace/knowledge?projectId=77&characterId=88',{maxRedirects:0});assert.equal(character.status(),302);assert.equal(character.headers().location,'/Dynamics/Knowledge/88?projectId=77');
assert.equal((await context.request.get(base+'/writing-problems/workspace/plot?projectId=999')).status(),404);
await context.close();
}
console.log('PASS dead-end repair: reported four-answer route; changed hypothesis; knowledge search; six-answer rescue/POV/intended-main routes; Plot Lines, timeline/continuity, relationships, scene/chapter, series, knowledge and character arc; evidence variants; optional secondary/article; explicit missing visuals; no article dump; reassurance/insufficient evidence; no-JS; 390/1440px; Back/Forward/Restart; public theme and noindex; signed-out tour CTA'+(base.includes('127.0.0.1')?'; signed-in authorised project/character selector and real workspace redirects.':'.'));
}finally{await browser.close();}
})().catch(e=>{console.error(e);process.exit(1)});

View File

@ -17,6 +17,12 @@ using PlotLine.ViewModels;
#pragma warning disable CS8321
if (args.Contains("--writing-solver-dead-ends"))
{
WritingSolverDeadEndTests.Run(args);
return;
}
if (args.Contains("--writing-solver-stage1"))
{
WritingSolverStage1Tests.Run(args);
@ -77,6 +83,7 @@ if (args.Contains("--plot-lines"))
var tests = new (string Name, Action Test)[]
{
("Solver never discards a corroborated concern or exhausts navigation before verification", WritingSolverDeadEndTests.Regression),
("Solver result evidence covers all reachable diagnoses without changing Stage 1 semantics", WritingSolverResultTests.EditorialCoverage),
("Solver result copy follows actual answers, intention, variants and revision", WritingSolverResultTests.ListeningAndVariants),
("Solver workspace CTAs resolve authorised project/character context and real routes", WritingSolverResultTests.WorkspaceRouting),

View File

@ -0,0 +1,128 @@
using System.Text.Json;
using PlotLine.Data;
using PlotLine.Models.WritingSolver;
using PlotLine.Services;
internal static class WritingSolverDeadEndTests
{
private static readonly JsonSerializerOptions Json=WritingSolverRepository.JsonOptions;
private static string Root=>WritingSolverCuratedV2Tests.Root();
public static string DirectoryPath=>Path.Combine(Root,"PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1-repair");
public static SolverGraph Graph()=>WritingSolverRepository.Parse(File.ReadAllText(Path.Combine(DirectoryPath,"writing-solver-curated-v2-stage1-repair.json")));
private static void Check(bool condition,string message){if(!condition)throw new Exception(message);}
public static void Run(string[] args)
{
var graph=JsonSerializer.Deserialize<SolverGraph>(File.ReadAllText(Path.Combine(DirectoryPath,"writing-solver-curated-v2-stage1-repair.json")),Json)!;
var before=Audit(WritingSolverStage1Tests.Graph());var after=Audit(graph);
var folder=Path.Combine(Root,"Docs/WritingSolver/CuratedV2/DeadEndRepair");Directory.CreateDirectory(folder);
var validation=WritingSolverValidator.Validate(graph);
File.WriteAllText(Path.Combine(folder,"audit.json"),JsonSerializer.Serialize(new{Before=before,After=after,Validation=validation},Json));
Console.WriteLine($"Before: {JsonSerializer.Serialize(before.Counts)}");Console.WriteLine($"After: {JsonSerializer.Serialize(after.Counts)}");
Console.WriteLine($"Traversal {after.Exploration.StateCount}, nodes {after.Exploration.Nodes.Count}/{graph.Nodes.Count}, solutions {after.Exploration.Solutions.Count}/52, primary {after.Exploration.PrimarySolutions.Length}; {string.Join("; ",validation)}");
if(args.Contains("--write-unused"))
{
var path=Path.Combine(folder,"unused-variants.json");var previous=File.Exists(path)?JsonSerializer.Deserialize<string[]>(File.ReadAllText(path),Json)!:[];
File.WriteAllText(path,JsonSerializer.Serialize(previous.Concat(graph.Nodes.Where(n=>!after.Exploration.Nodes.ContainsKey(n.Id)).Select(n=>n.Id)).Distinct().Order().ToArray(),Json));
}
if(args.Contains("--write-paths"))WritePaths(graph);
if(File.Exists(Path.Combine(DirectoryPath,"acceptance-paths.json")))
{
var replay=WritingSolverCuratedV2Tests.Replay(graph,Path.Combine(DirectoryPath,"acceptance-paths.json"));
Console.WriteLine($"Acceptance {replay.Count(c=>c.Pass && c.Warnings.Length==0)}/60; prefixes {WritingSolverCuratedV2Tests.MatchedPrefixes(replay,Path.Combine(DirectoryPath,"acceptance-paths.json"))}/{replay.Sum(c=>c.RequestedPath.Length)}");
foreach(var c in replay.Where(c=>!c.Pass||c.Warnings.Length>0))Console.WriteLine($"Case {c.Id}: {string.Join("; ",c.Errors.Concat(c.Warnings))}");
File.WriteAllText(Path.Combine(folder,"cases.json"),JsonSerializer.Serialize(replay,Json));
if(replay.Any(c=>!c.Pass||c.Warnings.Length>0))Environment.ExitCode=1;
}
if(validation.Count>0 || !after.Exploration.Complete || after.Counts.GetValueOrDefault("corroborated-without-result")>0 || after.Counts.GetValueOrDefault("budget-before-corroboration-question")>0 || after.Counts.GetValueOrDefault("unexplained-empty")>0)Environment.ExitCode=1;
}
public sealed record AuditReport(Dictionary<string,int> Counts,Dictionary<string,SolverAnswer[][]> Witnesses,WritingSolverCuratedV2Tests.Exploration Exploration);
public static AuditReport Audit(SolverGraph graph,Action<SolverOutcome>? inspect=null)
{
var counts=new Dictionary<string,int>();var witnesses=new Dictionary<string,List<SolverAnswer[]>>();
var traversal=WritingSolverCuratedV2Tests.Explore(graph,o=>
{
inspect?.Invoke(o);
if(o.Next is not null)return;
string kind;
if(o.Reassurance is not null)kind="authored-neutral";
else if(o.Solutions.Count>0)kind="diagnostic";
else
{
var corroborated=graph.Solutions.Any(s=>s.RequiredSignals.All(w=>o.Scores.GetValueOrDefault(w.Key)>=w.Value));
if(corroborated)kind="corroborated-without-result";
else if(o.Answers.Count==graph.MaxAnswers && !o.Answers.Any(a=>a.Node.StartsWith("check-")||a.Node.StartsWith("final-")))kind="budget-before-corroboration-question";
else if(o.Answers.LastOrDefault() is {} last && graph.Nodes.Single(n=>n.Id==last.Node).Choices.Any(c=>last.Choices.Contains(c.Id) && c.Id=="unsure"))kind="explicit-uncertainty";
else
{
var lastAnswer=o.Answers.LastOrDefault();
var explicitFallback=lastAnswer is not null && graph.Nodes.Single(n=>n.Id==lastAnswer.Node).Choices.Any(c=>lastAnswer.Choices.Contains(c.Id) && c.Fallback && c.Weights.Count==0);
kind=explicitFallback?"other-insufficient":"unexplained-empty";
}
}
counts[kind]=counts.GetValueOrDefault(kind)+1;
if(!witnesses.TryGetValue(kind,out var list))witnesses[kind]=list=[];
if(list.Count<8)list.Add(o.Answers.ToArray());
});
return new(counts,witnesses.ToDictionary(p=>p.Key,p=>p.Value.ToArray()),traversal);
}
public static void Regression()
{
var graph=Graph();var presentation=WritingSolverResultTests.Content();
var audit=Audit(graph,o=>
{
if(o.Scores.GetValueOrDefault("series")==0)Check(!o.Solutions.Any(s=>s.Id is "d50" or "d51"),"A cross-book result escaped without book evidence.");
if(o.Solutions.Count==0)return;
Check(o.Answers.Count>=4,"A diagnosis was reached before four meaningful answers.");
foreach(var solution in o.Solutions)Check(presentation.Evidence(o,solution.Id).Count>0 && presentation.Catalog.Evidence.Any(e=>e.Priority==100 && e.Solutions.Contains(solution.Id) && o.Answers.Any(a=>a.Node==e.Node && a.Choices.Contains(e.Choice))),"Repaired result lost its actual evidence explanation.");
});
Check(audit.Exploration.Complete && audit.Exploration.Errors.Length==0 && audit.Exploration.PrimarySolutions.Length==52,"Repair lost reachability or exceeded the ceiling.");
Check(audit.Counts.GetValueOrDefault("corroborated-without-result")==0,"A fully corroborated concern still ends without a result.");
Check(audit.Counts.GetValueOrDefault("budget-before-corroboration-question")==0,"Navigation exhausted the budget before offering a corroborating question.");
Check(audit.Counts.GetValueOrDefault("unexplained-empty")==0,"A substantive answer still silently ends without a diagnosis or authored neutral outcome.");
var original=WritingSolverStage1Tests.Graph();
foreach(var s in graph.Solutions){var old=original.Solutions.Single(p=>p.Id==s.Id);Check(s.Threshold==old.Threshold && s.Signals.OrderBy(p=>p.Key).SequenceEqual(old.Signals.OrderBy(p=>p.Key)) && s.RequiredSignals.OrderBy(p=>p.Key).SequenceEqual(old.RequiredSignals.OrderBy(p=>p.Key)),"Diagnosis coefficients, thresholds or evidence gates were weakened.");}
var cases=WritingSolverCuratedV2Tests.Replay(graph,Path.Combine(DirectoryPath,"acceptance-paths.json"));Check(cases.Length==60 && cases.All(c=>c.Pass && c.Warnings.Length==0),"Repaired canonical paths regressed.");
var tooMany=Follow(graph,"story-not-working","too-many","lost","unwanted");Check(tooMany.Solutions.FirstOrDefault()?.Id=="d01","Reported four-answer storyline memory complaint still has no result.");
var changedHypothesis=Follow(graph,"story-not-working","dont-connect","gap","unwanted");Check(changedHypothesis.Solutions.FirstOrDefault()?.Id=="d02","A corroborated alternative hypothesis still has no scoring evidence.");
var knowledge=Follow(graph,"losing-track","knowledge","checking","source");Check(knowledge.Solutions.FirstOrDefault()?.Id=="d22","Locating an existing learning event still has no result.");
var finalVoice=Follow(graph,"unsure","reread-cant-see","story-hangs-together","takes-over","voice","voice");Check(finalVoice.Solutions.FirstOrDefault()?.Id=="d12" && finalVoice.Answers.Count==6,"Final-slot corroboration did not collect the POV concern.");
var finalMain=Follow(graph,"unsure","reread-cant-see","story-hangs-together","takes-over","gaps","disappears");Check(finalMain.Solutions.FirstOrDefault()?.Id=="d02" && finalMain.Answers.Count==6,"An intended main plot still runs out of room to identify its supporting-thread problem.");
var longCast=Follow(graph,"unsure","reread-cant-see","characters-consistent","who-they-are","same-job","unwanted");Check(longCast.Solutions.FirstOrDefault()?.Id=="d09" && longCast.Answers.Count==6,"Long rescue navigation still displaces confirmation.");
var route=graph.Nodes.SelectMany(n=>n.Routes).First();var from=route.FromAnswers;var before=route.BeforeAnswers;
route.FromAnswers=4;route.BeforeAnswers=4;
Check(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("Invalid route answer range")),"Contradictory navigation ranges must be rejected.");
route.FromAnswers=from;route.BeforeAnswers=before;
Check(graph.RequireCorroboratedResults,"Repaired publication must enforce corroborated outcomes.");
var lost=graph.Nodes.Single(n=>n.Id=="check-threads-lost-apart").Choices.Single(c=>c.Id=="lost");
var saved=lost.Weights;lost.Weights=lost.Weights.Where(w=>w.Key.StartsWith("observed-")).ToDictionary(w=>w.Key,w=>w.Value);
Check(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("corroborated journey ends without a result")),"Actual publication validation must reject reintroduction of the reported scored-evidence omission.");lost.Weights=saved;
}
public static SolverOutcome Follow(SolverGraph graph,params string[] choices)
{
var history=new List<SolverAnswer>();var outcome=WritingSolverEngine.Evaluate(graph,history);
foreach(var choice in choices){Check(outcome.Next is not null,"Journey ended before its authored answer.");Check(outcome.Next!.Choices.Any(c=>c.Id==choice),$"Missing choice {choice} at {outcome.Next.Id}");history.Add(new(outcome.Next.Id,[choice]));outcome=WritingSolverEngine.Evaluate(graph,history);}
return outcome;
}
private static void WritePaths(SolverGraph graph)
{
var old=JsonSerializer.Deserialize<WritingSolverCuratedV2Tests.AcceptanceFile>(File.ReadAllText(Path.Combine(WritingSolverStage1Tests.DirectoryPath,"acceptance-paths.json")),Json)!;
var cases=old.Cases.Select(test=>
{
var history=new List<SolverAnswer>();var prefixes=new List<WritingSolverCuratedV2Tests.PrefixExpectation>();var outcome=WritingSolverEngine.Evaluate(graph,history);
while(outcome.Next is {} node)
{
var source=node.Id.StartsWith("final-")?"check-"+node.Id[6..]:node.Id;
var answer=test.Answers.FirstOrDefault(a=>a.Node==source);
// A reserved-tail family question can replace a redundant old detail question.
answer??=test.Answers.FirstOrDefault(a=>a.Node.StartsWith("check-"+source.Split('-')[1]) && a.Choices.All(id=>node.Choices.Any(c=>c.Id==id)));
Check(answer is not null,$"Case {test.Id}: no authored answer for {node.Id}.");
history.Add(new(node.Id,answer!.Choices));outcome=WritingSolverEngine.Evaluate(graph,history);
var expected=test.ExpectedPrimary is null?Array.Empty<string>():new[]{test.ExpectedPrimary}.Concat(test.RequiredSupporting).ToArray();
prefixes.Add(new(history.Count,outcome.Next?.Id,outcome.Next is null?expected:[]));
}
return test with{Answers=history.ToArray(),PrefixExpectations=prefixes.ToArray()};
}).ToArray();
File.WriteAllText(Path.Combine(DirectoryPath,"acceptance-paths.json"),JsonSerializer.Serialize(new WritingSolverCuratedV2Tests.AcceptanceFile(graph.Version,cases),Json));
}
}

View File

@ -27,8 +27,9 @@ internal static class WritingSolverResultTests
Check(graph.Features.Any(f=>f.Id==results.Capability(result.Capability).Feature),"Unknown product feature.");
if(result.ArticleKey is not null)Check(help.GetByContextKey(result.ArticleKey) is not null,"Missing reviewed advice article.");
}
var evidenceGraphs=graph.Nodes.Concat(WritingSolverDeadEndTests.Graph().Nodes).ToArray();
foreach(var evidence in results.Catalog.Evidence)
Check(graph.Nodes.Any(n=>n.Id==evidence.Node && n.Choices.Any(c=>c.Id==evidence.Choice)),"Evidence copy refers to an answer that cannot be supplied.");
Check(evidenceGraphs.Any(n=>n.Id==evidence.Node && n.Choices.Any(c=>c.Id==evidence.Choice)),"Evidence copy refers to an answer that cannot be supplied.");
var exploration=WritingSolverCuratedV2Tests.Explore(graph,outcome=>
{
var rendered=results.Present(outcome);

View File

@ -4878,6 +4878,365 @@
],
"text": "A character or narrator may be creating the impression of dominance.",
"priority": 110
},
{
"node": "check-object",
"choice": "track",
"solutions": [
"d40"
],
"text": "A plausible handover or move exists, but you keep losing where it ended up.",
"priority": 100
},
{
"node": "check-object",
"choice": "holder",
"solutions": [
"d41"
],
"text": "The person using the object has no opportunity to receive it.",
"priority": 100
},
{
"node": "check-object",
"choice": "history",
"solutions": [
"d42"
],
"text": "An earlier loss, damage or destruction is incompatible with the later state.",
"priority": 100
},
{
"node": "check-object",
"choice": "place",
"solutions": [
"d42"
],
"text": "The physical position does not fit the earlier scene, rather than the person holding it.",
"priority": 100
},
{
"node": "check-structure",
"choice": "place",
"solutions": [
"d34"
],
"text": "Several positions seem possible and you cannot see what each changes.",
"priority": 100
},
{
"node": "check-structure",
"choice": "purpose",
"solutions": [
"d05"
],
"text": "You cannot say what would be lost if some scenes went.",
"priority": 100
},
{
"node": "check-structure",
"choice": "chapter",
"solutions": [
"d35"
],
"text": "The scenes work individually but the chapter breaks produce uneven stretches.",
"priority": 100
},
{
"node": "check-structure",
"choice": "repeat",
"solutions": [
"d36"
],
"text": "Different scenes give the reader substantially the same thing.",
"priority": 100
},
{
"node": "check-structure",
"choice": "volume",
"solutions": [
"d33",
"d52"
],
"text": "You can describe the scenes but cannot keep the whole arrangement in view.",
"priority": 100
},
{
"node": "check-relationships",
"choice": "repeat",
"solutions": [
"d18"
],
"text": "Their encounters return to the same position despite chances to change.",
"priority": 100
},
{
"node": "check-relationships",
"choice": "unprepared",
"solutions": [
"d17"
],
"text": "The behaviour changes, but you cannot find the moments that would earn the change.",
"priority": 100
},
{
"node": "check-relationships",
"choice": "stage",
"solutions": [
"d16"
],
"text": "Their behaviour suggests different stages, and you cannot place the shift.",
"priority": 100
},
{
"node": "check-relationships",
"choice": "views",
"solutions": [
"d19"
],
"text": "They behave consistently but understand the relationship differently.",
"priority": 100
},
{
"node": "check-relationships",
"choice": "ripples",
"solutions": [
"d15",
"d20"
],
"text": "One event changes several connections and you lose track of its effects.",
"priority": 100
},
{
"node": "check-relationships",
"choice": "network",
"solutions": [
"d15"
],
"text": "You keep confusing who is connected to whom across several relationships.",
"priority": 100
},
{
"node": "final-cast",
"choice": "remember",
"solutions": [
"d08"
],
"text": "You forget who a character is or how they fit in.",
"priority": 100
},
{
"node": "final-cast",
"choice": "remember",
"solutions": [
"d08"
],
"text": "You identified this as a difficulty you want help with.",
"priority": 80
},
{
"node": "final-cast",
"choice": "same-job",
"solutions": [
"d08",
"d09"
],
"text": "Another character could take their place without changing what happens.",
"priority": 100
},
{
"node": "final-cast",
"choice": "same-job",
"solutions": [
"d08",
"d09"
],
"text": "You identified this as a difficulty you want help with.",
"priority": 80
},
{
"node": "final-cast",
"choice": "gap",
"solutions": [
"d10"
],
"text": "Something important is left with the character before a long absence.",
"priority": 100
},
{
"node": "final-cast",
"choice": "gap",
"solutions": [
"d10"
],
"text": "You identified this as a difficulty you want help with.",
"priority": 80
},
{
"node": "final-cast",
"choice": "share",
"solutions": [
"d11"
],
"text": "Their share of the manuscript differs from the role you intended.",
"priority": 100
},
{
"node": "final-cast",
"choice": "share",
"solutions": [
"d11"
],
"text": "You identified this as a difficulty you want help with.",
"priority": 80
},
{
"node": "final-cast",
"choice": "voice",
"solutions": [
"d12"
],
"text": "One narrator carries most of the account although you need the others to carry more.",
"priority": 100
},
{
"node": "final-cast",
"choice": "voice",
"solutions": [
"d12"
],
"text": "You identified this as a difficulty you want help with.",
"priority": 80
},
{
"node": "final-progression",
"choice": "nothing",
"solutions": [
"d43"
],
"text": "Events repeat without changing what anyone can do next.",
"priority": 100
},
{
"node": "final-progression",
"choice": "nothing",
"solutions": [
"d43"
],
"text": "You identified this as a difficulty you want help with.",
"priority": 80
},
{
"node": "final-progression",
"choice": "uneven",
"solutions": [
"d44"
],
"text": "There is progress, but developments arrive in bunches between long waits.",
"priority": 100
},
{
"node": "final-progression",
"choice": "uneven",
"solutions": [
"d44"
],
"text": "You identified this as a difficulty you want help with.",
"priority": 80
},
{
"node": "final-progression",
"choice": "late",
"solutions": [
"d44",
"d47"
],
"text": "Most of the changes that matter are left until the closing section.",
"priority": 100
},
{
"node": "final-progression",
"choice": "late",
"solutions": [
"d44",
"d47"
],
"text": "You identified this as a difficulty you want help with.",
"priority": 80
},
{
"node": "final-progression",
"choice": "tension",
"solutions": [
"d44",
"d45"
],
"text": "The situation changes, but the pressure drops or spikes unexpectedly.",
"priority": 100
},
{
"node": "final-progression",
"choice": "tension",
"solutions": [
"d44",
"d45"
],
"text": "You identified this as a difficulty you want help with.",
"priority": 80
},
{
"node": "final-progression",
"choice": "character",
"solutions": [
"d46"
],
"text": "Events move forward while one character seems unaffected.",
"priority": 100
},
{
"node": "final-progression",
"choice": "character",
"solutions": [
"d46"
],
"text": "You identified this as a difficulty you want help with.",
"priority": 80
},
{
"node": "final-dominance",
"choice": "even",
"solutions": [
"d04"
],
"text": "You want the other threads to carry more of the book than they currently do.",
"priority": 100
},
{
"node": "final-dominance",
"choice": "lost",
"solutions": [
"d01"
],
"text": "You want a central main plot, but keep losing track of the supporting threads.",
"priority": 100
},
{
"node": "final-dominance",
"choice": "connect",
"solutions": [
"d03"
],
"text": "The other threads are present but do not clearly affect the main plot, and you want that connection clearer.",
"priority": 100
},
{
"node": "final-dominance",
"choice": "disappears",
"solutions": [
"d02"
],
"text": "The supporting threads disappear while the main storyline is prominent, and you want those gaps addressed.",
"priority": 100
}
]
}

View File

@ -7,6 +7,7 @@ public sealed class SolverGraph
public string Version { get; set; } = "";
public string ChangeNote { get; set; } = "";
public bool IsDemo { get; set; }
public bool RequireCorroboratedResults { get; set; }
public int MinAnswers { get; set; } = 3;
public int MaxAnswers { get; set; } = 6;
public string EntryNode { get; set; } = "";
@ -57,6 +58,8 @@ public sealed class SolverRoute
public string? Choice { get; set; }
public string? Signal { get; set; }
public int Minimum { get; set; }
public int FromAnswers { get; set; }
public int BeforeAnswers { get; set; }
public int Priority { get; set; }
public bool AllowCycle { get; set; }
}

View File

@ -34,7 +34,8 @@ public static class WritingSolverEngine
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))
var routes = current.Routes.Where(r => answers.Count >= r.FromAnswers && (r.BeforeAnswers == 0 || answers.Count < r.BeforeAnswers)
&& (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))

View File

@ -67,6 +67,7 @@ public static partial class WritingSolverValidator
}
foreach (var route in node.Routes)
{
Check(route.FromAnswers >= 0 && route.FromAnswers < graph.MaxAnswers && (route.BeforeAnswers == 0 || (route.BeforeAnswers > route.FromAnswers && route.BeforeAnswers <= graph.MaxAnswers)), $"Invalid route answer range: {node.Id} -> {route.Target}");
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}");
@ -141,6 +142,9 @@ public static partial class WritingSolverValidator
var diagnosed = new HashSet<string>();
while (pending.TryDequeue(out var outcome))
{
if (graph.RequireCorroboratedResults && outcome.Next is null && outcome.Reassurance is null && outcome.Solutions.Count == 0
&& graph.Solutions.Any(s => s.Active && s.RequiredSignals.Count > 0 && s.RequiredSignals.All(w => outcome.Scores.GetValueOrDefault(w.Key) >= w.Value)))
return ["A corroborated journey ends without a result. Supply its actual scored evidence; do not weaken its evidence gates or diagnosis threshold."];
foreach(var solution in outcome.Solutions) diagnosed.Add(solution.Id);
if (outcome.Next is not { } node) continue;
reached.Add(node.Id);

View File

@ -0,0 +1,130 @@
"""Repair evidence-bearing dead ends without changing diagnosis coefficients/thresholds.
Original Stage 1 is retained as an immutable regression/publication baseline.
"""
import ast,copy,json
from pathlib import Path
r=Path(__file__).resolve().parents[2];base=r/'PlotLine/Content/WritingSolver/Candidates'
g=json.loads((base/'curated-v2-stage1/writing-solver-curated-v2-stage1.json').read_text())
g.update(requireCorroboratedResults=True,version='writing-solver-curated-v2-stage1-repair',changeNote='Repair confirmed-but-unscored observations and reserve the last two answers for corroboration/intention; preserve diagnosis coefficients, thresholds and evidence gates.')
original=json.loads((base/'curated-v2/writing-solver-curated-v2.json').read_text());oldids={n['id'] for n in original['nodes']};nodes={n['id']:n for n in g['nodes']}
# Literal editorial map from the prior assembly, not production code special cases.
tree=ast.parse((r/'Tools/WritingSolver/build-stage1.py').read_text())
families=next(ast.literal_eval(n.value) for n in tree.body if isinstance(n,ast.Assign) and any(isinstance(t,ast.Name) and t.id=='family_nodes' for t in n.targets))
# Each observation supplies the core facts it explicitly asserts, using the existing signal vocabulary.
# No threshold, coefficient or negative/penalty weight is changed. Competing diagnoses still need their own observation gate.
weights={
'threads':{'multiple-threads':6,'overwhelm':4,'scale':1},'dormancy':{'plot-dormancy':6},'connection':{'plot-connection':6},'purpose':{'scene-purpose':5},'payoff':{'setup-payoff':6},'causality':{'causality':5},
'cast':{'large-cast':6},'roles':{'role-overlap':5},'presence':{'character-presence':6},'proportions':{'character-presence':6,'distribution':4},'pov':{'pov':5,'distribution':1},'character-facts':{'character-facts':6,'continuity-conflict':2},'whereabouts':{'location':6,'character-presence':2},
'relationship-network':{'relationship':6,'overwhelm':3},'relationship-state':{'relationship-state':4,'relationship':2},'relationship-speed':{'relationship':4,'abrupt-progression':6},'relationship-stall':{'relationship':4,'flat-progression':5},'relationship-perspective':{'relationship':4,'perspective':5},'relationship-event':{'relationship':6,'dependency':5,'overwhelm':3},
'premature-knowledge':{'knowledge':5,'continuity-conflict':3},'knowledge-source':{'knowledge-origin':5,'knowledge':1},'pov-knowledge':{'knowledge':4,'pov':4},'reveal':{'revelation-order':5,'knowledge':2},'clues':{'clues':5,'knowledge':2},'reader-reveal':{'revelation-order':5,'setup-payoff':3,'distribution':1},
'calendar':{'chronology':6,'continuity-conflict':2},'elapsed':{'duration':5,'chronology':1},'age':{'character-facts':4,'chronology':4},'nonlinear':{'nonlinear':5,'chronology':1},'parallel':{'simultaneous-events':5,'chronology':1},'fixed':{'fixed-date':5,'chronology':1},
'scene-volume':{'scale':6,'overwhelm':2,'checking':2},'scene-position':{'scene-order':5},'chapters':{'chapter-structure':5},'repetition':{'repetition':5},'experiment':{'experiment':5,'revision':1},'movement':{'movement':6,'duration':2,'location':2},'place-state':{'location':5,'state-history':3},'object-track':{'object':6,'checking':2},'custody':{'object':2,'possession':5},'object-history':{'object':2,'state-history':5},
'story-stall':{'flat-progression':5},'pace':{'distribution':5},'tension':{'tension':5,'distribution':3},'arc':{'character-arc':6,'flat-progression':2},'late':{'late-concentration':6,'distribution':2},'dependencies':{'revision':3,'dependency':4},'versions':{'alternative-versions':5,'experiment':2},'series-memory':{'series':4},'series-thread':{'series':5,'multiple-threads':4},'whole-load':{'overwhelm':6,'scale':4}}
# Paired observations use their specific primary evidence, not the union of every diagnosis's
# weight map. Example: an age conflict does not add generic fact inconsistency points;
# a changed house is not given portable-object evidence; one pair is not a cast/network.
paired_primary={('cast','same-job'):'roles',('facts','age'):'age',('structure','volume'):'scene-volume',('whereabouts','journey'):'movement',('place','facts'):'place-state',('progression','tension'):'tension',('progression','late'):'late',('change','versions'):'versions',('relationships','ripples'):'relationship-event',('purpose','thread'):'purpose',('series','both'):'series-thread'}
changed=[]
for node in g['nodes']:
if not node['id'].startswith('check-'):continue
family=node['id'].split('-')[1]
for choice in node['choices']:
observed=[k[9:] for k,v in choice['weights'].items() if k.startswith('observed-') and v>0]
if not observed:continue
key=paired_primary.get((family,choice['id']),observed[0]);assert key in weights,(node['id'],choice['id'],key)
before=copy.deepcopy(choice['weights'])
# Replace only the new Stage 1 corroboration contributions, never original symptom weights.
choice['weights']={k:v for k,v in choice['weights'].items() if k.startswith('observed-') or k in ['concern-confirmed','creative-concern']}
choice['weights'].update(weights[key])
changed.append(dict(node=node['id'],choice=choice['id'],before=before,after=choice['weights'],evidence=choice['text']))
# Restore full family follow-ups when a late focus answer must skip redundant navigation.
def check(family):
id='check-'+family
if id not in nodes:
variants=[n for n in g['nodes'] if n['id'].startswith(id+'-')];assert variants,id
node=copy.deepcopy(variants[0]);node['id']=id;node['choices']=[];node['routes']=[]
for variant in variants:
for c in variant['choices']:
if not any(v['id']==c['id'] for v in node['choices']):node['choices'].append(copy.deepcopy(c))
for route in variant['routes']:
if route not in node['routes']:node['routes'].append(copy.deepcopy(route))
nodes[id]=node;g['nodes'].append(node)
return id
# A useful non-fault observation should not fall through to generic insufficient evidence.
neutral={
('cast','none'):dict(title='An intentional gap does not need fixing.',summary='You have described a deliberate absence with nothing important missing. Keep the gap if it serves the role you want the character to play.',advice=[],feature='characters'),
('relationships','moving'):dict(title='Slow progress is still progress.',summary='You are seeing small changes. Follow those changes across the scenes before deciding that the relationship is stuck.',advice=['Compare what the characters can say or do at the beginning and end of the stretch.'],feature='relationships'),
('arc','steady'):dict(title='A steady character can still move a story.',summary='You have described a deliberately steady character whose events still have consequences. Follow those choices without assuming they need a transformation.',advice=[],feature='character-development')}
for node in g['nodes']:
if not node['id'].startswith('check-'):continue
family=node['id'].split('-')[1]
for choice in node['choices']:
if (family,choice['id']) in neutral:
assert not choice['weights'];choice['reassurance']=neutral[(family,choice['id'])];node['allowNeutralChoices']=True
node['routes']=[v for v in node['routes'] if v.get('choice')!=choice['id']]
# A few prior follow-ups asked about a different concern than the symptom selected.
# Route to an existing relevant discriminator; do not infer a diagnosis from the redirect.
redirects={('track-people','where-everyone-is'):'whereabouts',('continuity-character','where'):'whereabouts',('continuity-character','knowledge'):'knowledge',('continuity-character','presence'):'cast',('flow-character','disappears'):'cast',('flow-thread','no-movement'):'causality',('flow-thread','scenes-advance'):'purpose'}
for (nid,cid),family in redirects.items():
assert any(c['id']==cid for c in nodes[nid]['choices']),(nid,cid)
nodes[nid]['routes']=[v for v in nodes[nid]['routes'] if v.get('choice')!=cid]
nodes[nid]['routes'].append(dict(target=check(family),choice=cid,priority=110,allowCycle=False))
# Keep optional old navigation only while two answer slots remain for proof and intention.
# Neutral adoption routing is deliberately unchanged.
for node in list(g['nodes']):
if node['id'] not in oldids:continue
additions=[]
for route in node['routes']:
if route['target'] not in oldids or route['target'] in ['existing-stage','existing-barrier']:continue
target_family=families.get(route['target'])
if not target_family:continue
fallback=copy.deepcopy(route);fallback['target']=check(target_family);fallback['fromAnswers']=4;fallback['priority']=route['priority']
route['beforeAnswers']=4;additions.append(fallback)
node['routes']+=additions
# Finish a corroboration question in the last slot by asking explicitly about the author's
# concern in the question itself; do not silently treat an observation as unwanted.
titles={'threads':'What is getting in the way of the work you want these storylines to do?','purpose':'Which of these makes the scene difficult to justify or keep track of?','causality':'What about the consequences is not working as you want?','payoff':'Which gap between preparation and payoff would you like help with?','cast':'What about these characters’ roles or appearances would you like help putting right?','relationships':'Which relationship pattern is not working as you want?','knowledge':'Which information problem would you like help untangling?','time':'Which timing problem would you like help putting right?','whereabouts':'What makes the characters’ movements difficult to follow or fit together?','structure':'Which part of the scene arrangement is getting in your way?','object':'Which problem with the object would you like help putting right?','place':'What about the place is no longer working consistently?','progression':'Which pattern is weakening the movement you want?','arc':'What effect on the character would you like to make clearer?','change':'Which consequence of the change would you like help with?','series':'Which cross-book difficulty would you like to get out of your head?','overload':'What is the organisation making harder than it needs to be?','facts':'Which established fact would you like help reconciling?'}
for node in list(g['nodes']):
if not node['id'].startswith('check-'):continue
family=node['id'].split('-')[1];final=copy.deepcopy(node);final['id']='final-'+node['id'][6:];final['title']=titles[family];final['help']='Choose what is getting in the way of what you want. A deliberate choice that is working does not need correcting.';final['routes']=[];final['allowNeutralChoices']=True
for choice in final['choices']:
if any(k.startswith('observed-') and v>0 for k,v in choice['weights'].items()):choice['weights'].update({'concern-confirmed':1,'creative-concern':1})
final['choices'].append(dict(id='deliberate',text='This is deliberate and working as I want',active=True,fallback=False,weights={},order=100,reassurance=dict(title='A deliberate choice does not need correcting.',summary='Keep the choice that serves your story. There is no reason to call it a fault just because its shape is unusual.',advice=[])))
nodes[final['id']]=final;g['nodes'].append(final)
for node in g['nodes']:
new=[]
for route in node['routes']:
if not route['target'].startswith('check-'):continue
last=copy.deepcopy(route);last['target']='final-'+route['target'][6:];last['fromAnswers']=5;last.pop('beforeAnswers',None);new.append(last)
route['beforeAnswers']=5
node['routes']+=new
# A late dominance route must not spend its final answer merely requesting another question.
# Collect the concrete concern and intended main-plot role together, with honest neutral options.
final=copy.deepcopy(nodes['dominance-intention']);final['id']='final-dominance';final['title']='If this is meant to be the main storyline, what would you like to put right?';final['help']='Choose the specific difficulty. A strong main plot is not a problem on its own.';final['routes']=[]
keep=[copy.deepcopy(c) for c in final['choices'] if c['id']!='main']
for cid,text,key in [
('disappears','The supporting threads disappear while this one is prominent, and I want those gaps addressed','dormancy'),
('connect','The other threads are present but do not clearly affect the main plot; I want that connection clearer','connection'),
('lost','I want to keep the main plot central, but I keep losing track of the supporting threads','threads')]:
w=dict(weights[key]);w.update({'observed-'+key:1,'concern-confirmed':1,'creative-concern':1})
keep.insert(1,dict(id=cid,text=text,active=True,fallback=False,order=len(keep),weights=w))
for i,choice in enumerate(keep):choice['order']=i
final['choices']=keep;g['nodes'].append(final);nodes[final['id']]=final
for node in g['nodes']:
additions=[]
for route in node['routes']:
if route['target']!='dominance-intention':continue
last=copy.deepcopy(route);last['target']='final-dominance';last['fromAnswers']=5;last.pop('beforeAnswers',None);additions.append(last);route['beforeAnswers']=5
node['routes']+=additions
# Optional assembly pruning is based on a complete actual-engine audit. Original 44 nodes
# and all diagnoses are protected; only unreachable new confirmation variants are omitted.
prune_file=r/'Docs/WritingSolver/CuratedV2/DeadEndRepair/unused-variants.json'
if prune_file.exists():
omit=set(json.loads(prune_file.read_text()));assert not omit.intersection(oldids),omit.intersection(oldids)
g['nodes']=[n for n in g['nodes'] if n['id'] not in omit]
for n in g['nodes']:n['routes']=[v for v in n['routes'] if v['target'] not in omit]
folder=base/'curated-v2-stage1-repair';folder.mkdir(exist_ok=True)
(folder/'writing-solver-curated-v2-stage1-repair.json').write_text(json.dumps(g,ensure_ascii=False,indent=2)+'\n')
(r/'Docs/WritingSolver/CuratedV2/DeadEndRepair/evidence-decisions.json').write_text(json.dumps(changed,ensure_ascii=False,indent=2)+'\n')

View File

@ -0,0 +1,23 @@
"""Bind existing authored result copy to repaired exact question identities."""
import copy,json
from pathlib import Path
r=Path(__file__).resolve().parents[2];base=r/'PlotLine/Content/WritingSolver'
old=json.loads((base/'Candidates/curated-v2-stage1/writing-solver-curated-v2-stage1.json').read_text());oldids={n['id'] for n in old['nodes']}
g=json.loads((base/'Candidates/curated-v2-stage1-repair/writing-solver-curated-v2-stage1-repair.json').read_text());path=base/'Presentation/results-v1.json';catalog=json.loads(path.read_text())
catalog['evidence']=[e for e in catalog['evidence'] if e['node'] in oldids];source=copy.deepcopy(catalog['evidence'])
dominance={'even':'You want the other threads to carry more of the book than they currently do.','disappears':'The supporting threads disappear while the main storyline is prominent, and you want those gaps addressed.','connect':'The other threads are present but do not clearly affect the main plot, and you want that connection clearer.','lost':'You want a central main plot, but keep losing track of the supporting threads.'}
for node in g['nodes']:
if node['id'] in oldids:continue
for choice in node['choices']:
obs={k for k,v in choice['weights'].items() if k.startswith('observed-') and v>0}
matched=[s['id'] for s in g['solutions'] if obs.intersection(s['requiredSignals'])]
if not matched:continue
if node['id']=='final-dominance':text=dominance[choice['id']]
else:
family=node['id'].split('-')[1]
candidates=[e for e in source if e['node'].startswith('check-'+family) and e['choice']==choice['id'] and e['priority']==100 and set(e['solutions'])==set(matched)]
assert candidates,(node['id'],choice['id'],matched)
text=candidates[0]['text']
catalog['evidence'].append(dict(node=node['id'],choice=choice['id'],solutions=matched,text=text,priority=100))
if node['id'].startswith('final-') and node['id']!='final-dominance':catalog['evidence'].append(dict(node=node['id'],choice=choice['id'],solutions=matched,text='You identified this as a difficulty you want help with.',priority=80))
path.write_text(json.dumps(catalog,ensure_ascii=False,indent=2)+'\n')

View File

@ -119,3 +119,10 @@ for n in g['nodes']:
for cid,text in [('space','You described scenes from this storyline expanding and squeezing out work you still want the other threads to do.'),('gaps','The supporting threads vanish while this one is prominent.'),('apart','Other threads continue, but stop affecting this one.'),('turns','Most of the big turning points belong to this storyline.'),('voice','A character or narrator may be creating the impression of dominance.')]:
evidence.append(dict(node='dominance-observation',choice=cid,solutions=['d04'],text=text,priority=110))
(r/'PlotLine/Content/WritingSolver/Presentation/results-v1.json').write_text(json.dumps(dict(capabilities=capabilities,results=results,evidence=evidence),ensure_ascii=False,indent=2)+'\n')
# Repaired publications reuse this authored copy under a small number of new question IDs.
# Preserve those bindings whenever the presentation catalogue is rebuilt.
repair=r/'PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1-repair/writing-solver-curated-v2-stage1-repair.json'
if repair.exists():
import runpy
runpy.run_path(str(r/'Tools/WritingSolver/build-repair-presentation.py'))