Deepen Writing Solver journeys with corroboration and authorial intention

This commit is contained in:
Nick Beckley 2026-11-01 19:55:04 +00:00
parent 9852c42461
commit 983c3a9359
28 changed files with 150064 additions and 46 deletions

View File

@ -0,0 +1,66 @@
# Journey depth: all 52 solutions
Minimum and median (“typical”) answered questions among all distinct reachable terminal scoring states containing that result. Primary-only values are shown separately. These are exhaustive graph statistics, **not observed visitor frequencies**; broad multi-select and uncertain navigation paths influence the medians. A question counts once regardless of selected checkboxes. The entry question counts as a meaningful family/focus interaction. Neutral/reassurance outcomes are excluded from diagnostic depth.
The baseline is the unchanged Development V2 fixture. The revised graph is the separate Stage 1 candidate. All original solution IDs, coefficients and thresholds are preserved. Gates require corroboration; no diagnosis can resolve below four answers. All 52 remain primary-capable. No below-four diagnostic exceptions need justification.
| Solution | Before min / median | After min / median | Primary before min / median | Primary after min / median | Corroborating observation |
|---|---|---|---|---|---|
| D01: There are too many storylines to keep in your head | 3 / 4 | 4 / 5 | 3 / 4 | 4 / 5 | threads |
| D02: A storyline disappears for too long | 2 / 4 | 4 / 6 | 2 / 4 | 4 / 6 | dormancy |
| D03: Your storylines don't feel connected | 2 / 4 | 4 / 6 | 2 / 4 | 4 / 6 | connection |
| D04: One storyline is taking over the book | 2 / 4 | 4 / 6 | 2 / 4 | 4 / 6 | imbalance |
| D05: You're not sure what some scenes are contributing | 2 / 4 | 4 / 6 | 2 / 4 | 4 / 6 | purpose |
| D06: Your setups and payoffs have become disconnected | 3 / 5 | 5 / 5 | 3 / 5 | 5 / 5 | payoff |
| D07: Things happen, but the story doesn't seem to build | 2 / 4 | 4 / 5.5 | 2 / 4 | 4 / 5.5 | causality |
| D08: There are too many characters to keep straight | 3 / 4 | 4 / 5 | 3 / 4 | 4 / 5 | cast |
| D09: Some characters may be doing the same job in the story | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | roles |
| D10: An important character disappears for a long stretch | 3 / 5 | 5 / 6 | 3 / 5 | 5 / 6 | presence |
| D11: Your characters aren't appearing in the proportions you expected | 4 / 5 | 5 / 6 | 4 / 5 | 5 / 6 | proportions |
| D12: Your points of view are becoming difficult to balance | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | pov |
| D13: A character's details don't stay consistent | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | character-facts |
| D14: You're losing track of where your characters are | 3 / 5 | 4 / 5 | 4 / 5 | 4 / 5 | whereabouts |
| D15: There are too many character relationships to hold in your head | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | relationship-network |
| D16: You're not sure where a relationship has reached | 3 / 5 | 5 / 6 | 3 / 4.5 | 5 / 6 | relationship-state |
| D17: A relationship changes before it feels earned | 3 / 5 | 5 / 6 | 3 / 5 | 5 / 6 | relationship-speed |
| D18: A relationship stops moving for too long | 3 / 5 | 5 / 6 | 3 / 5 | 5 / 6 | relationship-stall |
| D19: Your characters see the same relationship differently | 3 / 4.5 | 5 / 6 | 3 / 4.5 | 5 / 6 | relationship-perspective |
| D20: One event has changed too many relationships to track easily | 3 / 5 | 5 / 6 | 3 / 5 | 5 / 6 | relationship-event |
| D21: A character knows something they haven't learned yet | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | premature-knowledge |
| D22: You can't remember how a character learned something | 3 / 4 | 4 / 5 | 3 / 4 | 4 / 5 | knowledge-source |
| D23: Different POV characters know different pieces of the story | 3 / 4 | 4 / 5 | 3 / 4 | 4 / 5 | pov-knowledge |
| D24: Your revelations have ended up in the wrong order | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | reveal |
| D25: There are too many clues and discoveries to keep straight | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | clues |
| D26: You're not sure whether a reveal comes too early or too late | 3 / 4 | 5 / 6 | 3 / 4.5 | 5 / 6 | reader-reveal |
| D27: Your timeline doesn't add up | 3 / 4 | 5 / 6 | 3 / 3.5 | 5 / 6 | calendar |
| D28: The amount of time between events doesn't work | 3 / 5 | 5 / 6 | 3 / 5 | 5 / 6 | elapsed |
| D29: A character's age doesn't match the dates | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | age |
| D30: Your reading order and chronological order are different | 3 / 5 | 5 / 6 | 3 / 5 | 5 / 6 | nonlinear |
| D31: Too many things are happening at the same time | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | parallel |
| D32: Your fictional timeline has to fit around real dates | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | fixed |
| D33: There are too many scenes to see the structure clearly | 3 / 3 | 4 / 5 | 3 / 3 | 4 / 5 | scene-volume |
| D34: You don't know where a scene belongs | 3 / 4 | 4 / 6 | 3 / 4 | 4 / 6 | scene-position |
| D35: Your chapter structure feels uneven | 3 / 4 | 5 / 5.5 | 3 / 4 | 5 / 5.5 | chapters |
| D36: Several scenes may be doing the same job | 3 / 4 | 4 / 6 | 3 / 4 | 4 / 6 | repetition |
| D37: You want to rearrange the story without wrecking it | 3 / 3 | 4 / 6 | 3 / 3 | 4 / 6 | experiment |
| D38: A character's movement between places doesn't make sense | 3 / 5 | 4 / 6 | 3 / 4 | 4 / 6 | movement |
| D39: A location has changed without you meaning it to | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | place-state |
| D40: You've lost track of an important object | 3 / 4.5 | 4 / 5.5 | 3 / 5 | 4 / 5.5 | object-track |
| D41: A character has an object they shouldn't have | 3 / 4 | 4 / 5.5 | 3 / 4 | 4 / 5.5 | custody |
| D42: An object's history contradicts itself | 3 / 4 | 4 / 5.5 | 3 / 4 | 4 / 5.5 | object-history |
| D43: The story seems to stop moving | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | story-stall |
| D44: Some parts of the story rush while others drag | 3 / 4 | 5 / 6 | 3 / 3 | 5 / 6 | pace |
| D45: The tension rises and falls in the wrong places | 3 / 4 | 5 / 5.5 | 3 / 4.5 | 5 / 5.5 | tension |
| D46: A character's development goes flat | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | arc |
| D47: Too much development is packed into the ending | 3 / 4 | 5 / 6 | 3 / 4 | 5 / 6 | late |
| D48: Every change seems to break something else | 2 / 3 | 4 / 6 | 2 / 3 | 4 / 6 | dependencies |
| D49: You have more than one possible version of the story | 3 / 3 | 4 / 6 | 3 / 3 | 4 / 6 | versions |
| D50: Your series has become too big to remember reliably | 3 / 4 | 4 / 5 | 3 / 3.5 | 4 / 5 | series-memory |
| D51: A storyline stretches across several books | 3 / 4 | 5 / 5.5 | 3 / 4 | 5 / 5.5 | series-thread |
| D52: Your novel has become too much to hold in your head | 3 / 4 | 4 / 5 | 3 / 4 | 4 / 5 | whole-load |
“Observed” gates represent the concrete consequence described in the new follow-up, not another score for choosing a category. The complete question/choice text is in the candidate JSON. Creative-concern gates prevent mere inequality, deliberate slowness or nonlinear narration from being treated automatically as faults. Management diagnoses can finish after corroboration when the author has already explicitly described the difficulty.
The 60 acceptance complaints are diagnostic examples plus four non-diagnostic paths. Among the original 57 diagnostic examples: 5 took two answers, 42 took three, 10 took four. Among the revised 56 diagnostic examples: 14 take four, 34 take five, 8 take six. Case 57 becomes reassurance after the additional answer confirms actual slow progress, rather than stagnation. Cases 13/50/58 still do not establish a diagnosis. Their revised lengths are 5/3/4; no result is invented to meet a depth target.
Remaining review judgement: minimum-four paths for clearly stated scene-purpose and causal complaints still merit owner review for perceived depth. Their follow-ups now ask what would be lost or whether the next event depends on the previous one, then establish intention. They are not counted as improved merely because their length increased. A score alone never supplies the missing corroboration.

View File

@ -0,0 +1,60 @@
# Audit of all original 44 nodes
Scope includes every original node/choice, all 52 results and all 60 supplied complaints. No original node is deleted. The revised graph contains 152 active nodes: original navigation/symptom/adoption nodes plus authored corroboration/intention questions and focused variants. Focused variants show the current hypothesis and a nearby alternative rather than a broad diagnostic catalogue.
Before: early scores could terminate after two or three answers. Many choice labels contained the resulting title; reaching a threshold did not establish independent consequences or intention. After: unchanged scores propose hypotheses; new gates require a concrete observation. Specific choices route to focused follow-ups, with intention where material. Exact coefficient and threshold equality is asserted in regression tests.
Largest one-choice score fraction is a static risk indicator (largest contribution to any diagnosis divided by its threshold), not a claim that the result qualifies in isolation or a request to retune the coefficient.
| Original node | Earliest question number before | One-choice fraction | Audit and disposition |
|---|---|---|---|
| `entry` | 1 | 0.58 | Family/focus only; retain wording/layout, use six distinct semantic SVG icons. No result at the opening. |
| `rescue-happening` | 2 | 1.00 | Focus/rescue navigation; retain usable uncertainty. Tracking is limited to two concerns. Broad answers do not confirm a diagnosis. |
| `rescue-confidence` | 3 | 0.75 | Focus/rescue navigation; retain usable uncertainty. Tracking is limited to two concerns. Broad answers do not confirm a diagnosis. |
| `track-what` | 2 | 0.32 | Focus/rescue navigation; retain usable uncertainty. Tracking is limited to two concerns. Broad answers do not confirm a diagnosis. |
| `track-people` | 3 | 1.27 | Symptom wording can resemble a result; now requires independent consequence evidence. Retain specialised observable-context routing. An intention answer is collected where a creative or contextual distinction matters. |
| `track-knowledge` | 3 | 1.42 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-knowledge-clues-source`, `check-knowledge-no-source-source-order`, `check-knowledge-order-no-source-reader`, `check-knowledge-povs-no-source-order`, `check-knowledge-povs-source`, `check-knowledge-reader-order`, `check-knowledge-reader-order-povs`, `check-knowledge-source-no-source`, `check-knowledge-source-povs`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `track-time` | 3 | 1.38 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-time-age-clash`, `check-time-clash-age`, `check-time-clash-elapsed`, `check-time-fixed-clash`, `check-time-reading-clash`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `track-plots` | 3 | 1.25 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-threads-apart-lost`, `check-threads-gap-apart`, `check-threads-gap-lost`, `check-threads-lost-gap`, `check-threads-scenes-lost`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `track-places` | 3 | 1.09 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-place`, `check-whereabouts`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `track-objects` | 3 | 1.58 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-object-history-track`, `check-object-holder-track`, `check-object-track-history`, `check-object-track-holder`, `check-object-track-place`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `track-structure` | 3 | 1.33 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-structure-chapter-place`, `check-structure-place-chapter`, `check-structure-place-purpose`, `check-structure-purpose-repeat`, `check-structure-purpose-volume`, `check-structure-repeat-purpose`, `check-structure-volume-purpose`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `story-problem` | 2 | 1.36 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-causality`, `check-purpose`, `check-threads-apart-gap`, `check-threads-gap-apart`, `check-threads-lost-apart`, `dominance-observation`. An intention answer is collected where a creative or contextual distinction matters. |
| `story-view` | 4 | 1.00 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-threads`, `check-threads-apart-lost`, `check-threads-gap-apart`, `check-threads-lost-apart`, `check-threads-scenes-apart`. An intention answer is collected where a creative or contextual distinction matters. |
| `story-connection` | 3 | 1.20 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-causality`. An intention answer is collected where a creative or contextual distinction matters. |
| `story-payoff` | 3 | 1.09 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-payoff`. An intention answer is collected where a creative or contextual distinction matters. |
| `feel-where` | 2 | 0.91 | Focus/rescue navigation; retain usable uncertainty. Tracking is limited to two concerns. Broad answers do not confirm a diagnosis. |
| `feel-how` | 3 | 1.20 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-progression-nothing-uneven`, `check-progression-uneven-character`, `check-progression-uneven-late`, `check-progression-uneven-nothing`. An intention answer is collected where a creative or contextual distinction matters. |
| `flow-target` | 4 | 1.00 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-progression-nothing-uneven`. An intention answer is collected where a creative or contextual distinction matters. |
| `flow-whole` | 3 | 1.45 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-progression-late-uneven`, `check-progression-nothing-character`, `check-progression-nothing-uneven`, `check-progression-uneven-nothing`. An intention answer is collected where a creative or contextual distinction matters. |
| `flow-thread` | 3 | 1.00 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-threads-apart-gap`, `check-threads-gap-apart`, `check-threads-scenes-apart`. An intention answer is collected where a creative or contextual distinction matters. |
| `flow-character` | 3 | 1.50 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-arc`. An intention answer is collected where a creative or contextual distinction matters. |
| `flow-relationship` | 3 | 1.50 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-relationships-moving-repeat`, `check-relationships-repeat-moving`, `check-relationships-ripples-network`, `check-relationships-stage-moving`, `check-relationships-stage-views`, `check-relationships-unprepared-stage`, `check-relationships-views-stage`, `check-series`. An intention answer is collected where a creative or contextual distinction matters. |
| `flow-tension` | 3 | 1.77 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-progression-tension-late`, `check-progression-tension-nothing`, `check-progression-tension-uneven`. An intention answer is collected where a creative or contextual distinction matters. |
| `continuity-what` | 2 | 0.58 | Focus/rescue navigation; retain usable uncertainty. Tracking is limited to two concerns. Broad answers do not confirm a diagnosis. |
| `continuity-character` | 3 | 1.25 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-facts`. An intention answer is collected where a creative or contextual distinction matters. |
| `continuity-time` | 3 | 1.58 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-time-age-clash`, `check-time-clash-age`, `check-time-clash-reading`, `check-time-elapsed-clash`, `check-time-elapsed-travel`, `check-time-travel-elapsed`. An intention answer is collected where a creative or contextual distinction matters. |
| `continuity-object` | 3 | 1.55 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-object-history-place`, `check-object-history-track`, `check-object-holder-history`, `check-object-holder-track`, `check-object-place-holder`. An intention answer is collected where a creative or contextual distinction matters. |
| `change-what` | 2 | 1.46 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-change`. An intention answer is collected where a creative or contextual distinction matters. |
| `change-damage` | 3 | 1.17 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-change`. An intention answer is collected where a creative or contextual distinction matters. |
| `change-order` | 3 | 1.60 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-change`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `change-knowledge` | 3 | 1.33 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-knowledge`, `check-knowledge-no-source-source-order`. An intention answer is collected where a creative or contextual distinction matters. |
| `scale-what` | 2 | 0.50 | Focus/rescue navigation; retain usable uncertainty. Tracking is limited to two concerns. Broad answers do not confirm a diagnosis. |
| `scale-effect` | 3 | 1.32 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-overload`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `series-what` | 3 | 1.25 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-series`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `series-thread` | 4 | 1.50 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-series`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `cast-size` | 3 | 1.27 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-cast-gap-share`, `check-cast-remember-same-job`, `check-cast-same-job-remember`, `check-cast-share-remember`, `check-cast-voice-share`, `check-facts`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `cast-presence` | 4 | 1.27 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-cast-gap-none`, `check-cast-share-gap`, `check-cast-share-voice`, `check-cast-voice-share`. An intention answer is collected where a creative or contextual distinction matters. |
| `relationship-map` | 4 | 1.21 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-relationships-network-ripples`, `check-relationships-network-stage`, `check-relationships-network-views`, `check-relationships-ripples-network`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `time-duration` | 4 | 1.09 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-time-elapsed-clash`, `check-time-elapsed-fixed`, `check-time-travel-elapsed`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `time-parallel` | 4 | 1.36 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-time`, `check-time-parallel-clash`, `check-time-travel-elapsed`. Explicit management difficulty can establish the concern; creative hypotheses still require an actual intention answer. |
| `time-nonlinear` | 4 | 1.09 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-time-reading-clash`, `check-time-reading-parallel`. An intention answer is collected where a creative or contextual distinction matters. |
| `existing-stage` | 4 | 0.00 | Adoption context/reassurance; retain all authored concerns and neutral behaviour; no artificial extension. |
| `existing-barrier` | 5 | 0.00 | Adoption context/reassurance; retain all authored concerns and neutral behaviour; no artificial extension. |
| `character-meeting` | 4 | 1.25 | Symptom wording can resemble a result; now requires independent consequence evidence. Follow-ups: `check-relationships-stage-moving`, `check-relationships-stage-network`, `check-relationships-stage-ripples`, `check-relationships-stage-views`, `check-relationships-unprepared-stage`. An intention answer is collected where a creative or contextual distinction matters. |
## Redundancy and competing explanations
The original symptom/context questions were not discarded wholesale. Their specialised routes still separate ages, elapsed time, simultaneous events, handovers, setup/payoff, roles and narrative viewpoints. New focused variants retain only the relevant consequence and nearby alternatives. A previously explicit management concern is not asked again merely to reach five answers. Duplicate identical `continuity-what/place` route entries are collapsed without changing routing behaviour.
Each result’s observation gate and before/after depths are in `JourneyDepth.md`; all literal authored routes and every prefix are in the candidate acceptance file. The repeated-wording risk is addressed by corroboration, not by cosmetically renaming the result. Uncertainty never creates a gate. If the six-answer budget is exhausted without corroboration, the solver gives insufficient-evidence advice rather than treating accumulated category points as proof.

View File

@ -0,0 +1,63 @@
# Writing Problem Solver: Stage 1 diagnostic journey
Development only. Continues from `9852c42`. No result-page, screenshot, application-theme or article-library redesign is included.
## What changed
The early answers now propose hypotheses. They cannot produce a diagnosis solely by crossing a score threshold: each result also needs an observed consequence and a concern that the author wants help with. Creative results require an actual intention answer. A management concern elsewhere cannot stand in for creative intention.
All 52 existing solution coefficients and thresholds, all original scoring weights, the 15 feature pages, solution copy, warm public styling and original adoption endpoint are retained. The original V2 graph is left intact as a regression baseline. Stage 1 is a new immutable candidate: `writing-solver-curated-v2-stage1`.
The original 44 nodes are audited in `NodeAudit.md`. The revised graph has 152 active nodes, including focused variants: it asks about the current symptom and nearby alternatives rather than presenting the whole family again. The broad tracking question accepts up to two concerns, with working multi-select, JavaScript guidance and server enforcement. This establishes a useful focus rather than accumulating unrelated signals from a long checklist.
Specific management complaints already explain why help is wanted. After corroboration, those routes can finish without another intention question. Creative balance, relationships, character movement, pacing and narrative arrangement distinguish deliberate choices from unwanted effects. Deliberate-and-working and legitimate uncertainty can end in authored reassurance immediately. Existing adoption reassurance is not lengthened.
The six opening cards retain their layout and use six distinct paths in the existing SVG icon partial: search, connections, pulse, shield/check, branching changes and a shelf. Their stroke, size and colour remain consistent.
## Depth and examples
| Diagnostic acceptance paths | Before | After |
|---|---:|---:|
| 2 answers | 5 | 0 |
| 3 answers | 42 | 0 |
| 4 answers | 10 | 14 |
| 5 answers | 0 | 34 |
| 6 answers | 0 | 8 |
There were 57 diagnostic examples; there are now 56 because the added answer in case 57 confirms deliberate progress and correctly leads to reassurance. The other three non-diagnostic examples remain non-diagnostic. Median diagnostic example depth increases from **3 to 5**. Every reachable diagnosis now takes 4–6 answers. Minimum depth across solutions is four for 22 diagnoses, five for 30. `JourneyDepth.md` provides minimum/median and primary-only figures for every result; graph-state medians are not visitor usage statistics.
- **One storyline taking over:** before, “story not coming together” → “takes over” → D04, two answers. Now those establish a hypothesis; “its scenes expand and squeeze out the work of others” is followed by “is it meant to carry most of the book?” Wanting the other threads to carry more corroborates D04 after four answers. Intended main plot + forgotten supporting thread takes six answers and gives D02 instead. Threads continuing without affecting one another gives D03. Concentrated late turning points gives D47. A narrator creating the apparent dominance gives D12; unexpected character proportions give D11. These alternatives have real engine witnesses, not just different wording around the same result.
- **Cannot remember who told someone:** previously three answers. Now the follow-up distinguishes an actual missing learning opportunity from an existing but unlocatable conversation or discovery; the latter corroborates D22 after four. A different answer can leave a different hypothesis or insufficient evidence, rather than blindly repeating the selected label.
- **A protagonist disappears too long:** previously four. Now the follow-up asks whether something important is left with the character, then checks whether the gap differs from the intended role; the diagnostic path takes six. An intentional gap with nothing missing can end in reassurance.
- **Single relationship feels unearned:** previously three. Now the scenes must lack the moments earning the change, and the author must want that development made clearer; five answers. Deliberately slow but actually progressing is not called stagnation.
## Semantics and retained scoring
The eight previously approved secondary-result exceptions are resolved by positive evidence gates, with no exception list in Stage 1. Their exact causes and genuine counter-witnesses are in `SemanticExceptions.md`. Strict expectations are not weakened. The original V2 exception fixtures remain unchanged and continue to document their old failures.
New observations carry existing scoring signals only where they establish new evidence: disconnected threads, a forgotten supporting thread, late concentration, uneven pace, story stagnation, an unaffected character, absence/proportions, narrator share, role overlap and impossible elapsed travel. `signal-mapping-decisions.json` records all existing-choice additions and new scoring observations. Existing-choice additions are concern evidence only and contribute no score points.
Genuine supporting results are explicitly preserved, including D33/D52 for case 30, D29/D13, D20/D15, D39/D42, D45/D44, D47/D44 and D49/D37. Advice previously permitted only as an optional cross-check is no longer asserted if the new response does not corroborate it. Explicitly mixed cross-book evidence still returns both D51 and D50.
## Verification
- Real repository validator passes the Stage 1 JSON normally: **152 nodes, 52 solutions, 15 features**. The existing non-blocking feature-route warnings remain for character-development and manuscript-import.
- Exhaustive traversal: **85,140 unique states**, all **152 nodes** reachable, all **52 solutions** reachable and primary-capable, below the unchanged 100,000 distinct-state ceiling. No diagnosis resolves below four answers.
- Expanded strict acceptance: **60/60 cases, 291/291 prefixes**, including supporting and forbidden-result checks. Authored expanded paths are frozen separately from the untouched original V2 expectations. Normal tests do not regenerate expectations.
- Original V2 literal regressions and its exact historical eight-exception guard remain in the full harness.
- Normal solution build passes with the two existing nullable warnings in the harness. Full executable regression: **387 PASS results**, exit zero. Command and browser outputs are captured beside this report.
- Browser verification covers all 52 solution and 15 feature pages without JavaScript, 390px/1440px journeys, representative four/five/six-answer diagnoses, all six opening choices/icons, Restart, Back/Forward, earlier-answer revision, multi-select, no-JavaScript diagnosis and adoption, all eight existing adoption concerns, theme isolation, no overflow/significant layout shift and noindex.
The traversal now deduplicates semantic states **before** enqueueing. State identity and the 100,000-distinct-state ceiling are unchanged; identical pending answers no longer count twice. The original baseline still has 11,325 unique states. This is not a score or reachability shortcut.
## Owner review and limits
Four-answer scene-purpose and causal-link paths remain worth hands-on review for whether they feel sufficiently thoughtful. Their new questions ask what would be lost without the scene or whether the next event depends on the previous one, followed by intention. No route is justified merely by reaching a click count.
Exhaustive path frequencies are structural coverage, not estimates of author problems. Series-memory and cross-book thread results have large state shares and remain a hands-on review focus; neither can appear without series evidence. All 52 results remain primary-capable, and no coefficient is tuned to equalise their prevalence. Long uncertain routes may exhaust the six-answer budget without sufficient evidence; they give insufficient-evidence advice instead of guessing. Authored deliberate/uncertain reassurance also contributes many neutral terminal states. Detailed terminal/primary counts are retained in `traversal.json`: 18,812 diagnostic states, 8,035 authored-reassurance states, 9,025 insufficient-evidence states before the budget and 24,965 at six answers. These count distinct structural states, not users. D51 is primary in 5,760 diagnostic states and D50 in 4,544. No-series traversal returns neither D50 nor D51. Longer paths can now accumulate a raw D50 score of 12 without series evidence; the positive series-memory corroboration requirement correctly keeps that score from becoming a result. No threshold is changed to conceal it.
The earlier 16 suspicious mappings remain review items; Stage 1 does not use this work as a pretext for broad retuning. No visual or editorial work reserved for later stages is included. Development publication and operational verification are recorded in `Deployment.md` after activation.
## Files
Runtime changes are limited to the solver model, engine, validator/traversal, the question renderer/selection enhancement, server selection guidance and the existing icon partial. The Stage 1 data and acceptance file are separate from the original curated package. Regression additions are `WritingSolverStage1Tests.cs`, the Stage 1 browser suite and test registration. Framework documentation, this report, node/depth audits and signal decisions record the new contract. `Tools/WritingSolver/build-stage1.py` is the deterministic editorial assembly script; it does not publish or access a database.

View File

@ -0,0 +1,35 @@
# Eight prior semantic exceptions: Stage 1 disposition
The original V2 and its strict failing expectations are retained unchanged as historical fixtures. Stage 1 does not change any of the 52 solution coefficients or thresholds, and does not remove or change any original scoring weight. A positive corroboration requirement is added to each solution; creative judgements also need an actual intention answer. Observation/concern signals do not contribute score points.
| Case | Why the old unwanted result qualified | New discriminating evidence and result |
|---|---|---|
| 15 | D15 received enough general `relationship` evidence from one unearned romance; it did not require a network problem. | Scenes lack the moments that would earn the change, and the author wants it earned. D17; no network observation, so no D15. D16 is not asserted merely from relationship points either. |
| 16 | D15 reused single-relationship evidence; D43 reused `flat-progression` from that relationship as if the whole story stalled. | Encounters repeat the same position despite chances to change; author confirms this is unwanted. D18. Neither a relationship network problem nor whole-story stagnation is corroborated. |
| 17 | D15 reused generic relationship totals from characters perceiving one relationship differently. | Both behave consistently but interpret the relationship differently; author wants help with that distinction. D19, without D15. |
| 25 | D29's chronology/continuity coefficients and D13's continuity coefficient can cross threshold without any character-fact evidence. | Two stated event positions cannot both be true. D27. No age or character-fact observation is supplied; D29/D13 are ineligible. Genuine age/fact cases remain reachable and case 12 retains D29/D13. |
| 39 | D39 can qualify from state-history/continuity without a location, and D13 from continuity without character facts. | Earlier destruction/loss is incompatible with later object state; author confirms no intended explanation. D42. No place-state or character-fact observation, hence no D39/D13. Genuine changed-place case 36 retains D39/D42. |
| 43 | D43 reuses the same flat-progression points as a character arc; a flat arc did not establish a stalled whole story. | The character's choices return to the same place after significant events; the author wants those events to affect them. D46, no D43. The genuine main-story witness remains D43-primary. |
| 52 | Same D15 single-relationship/network conflation as case 15. | Unprepared change + unwanted outcome establish D17, not network overload. |
| 57 | D15 again reused relationship points. More fundamentally, the earlier D18 score did not distinguish deliberate slow progress from actual stagnation. | New answer explicitly says small changes are happening, then confirms that this is the intended progression. Authored reassurance, no D18 or D15. This is a changed **author response**, not a relaxation of a forbidden expectation. The “repeat the same position despite opportunities” branch still genuinely diagnoses D18. |
All eight are resolved in the expanded semantic fixtures. No Stage 1 exception allowlist is used. Case 57's original complaint was a request to check that a deliberately slow relationship still progresses; the new answer establishes that it does. If the author instead observes repetition without movement and wants change, the stall diagnosis remains available.
## Genuine supporting results
Positive corroboration must not indiscriminately eliminate useful supporting advice. Stage 1 explicitly requires the following corroborated supports in its frozen fixtures:
- Case 8: role overlap with cast confusion, D09/D08.
- Case 12: age is an established conflicting character fact, D29/D13.
- Case 18: one event's effects spread across several connections, D20/D15.
- Case 30: scene volume overwhelms the whole arrangement, D33/D52; D05 and D50 remain forbidden.
- Case 35: impossible travel also establishes an elapsed-time problem, D38/D28. The new consequence supplies `duration=2`; this strengthens the actual timing evidence rather than changing either diagnosis.
- Case 36: a place's incompatible material states warrant the related state-history view, D39/D42.
- Cases 42/44: tension interruptions / late concentrated change also establish uneven rhythm, D45/D44 and D47/D44.
- Case 46: keeping alternative versions supports safe experimentation, D49/D37.
A separate mixed witness explicitly confirms both cross-book facts and an open thread, retaining D51 with D50 support. All 52 diagnoses, including D13, D15, D29, D39, D43, D50 and D51, remain primary-capable under exhaustive traversal.
Some historically optional supports are **not confirmed by the deeper response**: a minor character's large share does not establish an important character's absence; a dominant POV does not establish inconsistent knowledge; one unearned relationship change does not establish uncertainty about its stage; a long-running mystery does not by itself establish broad series-memory overload; moving discovery scenes does not automatically prove a reader-facing reveal-timing problem. Such advice is no longer emitted merely because shared points happen to qualify it. The relevant alternative observations/results remain available. This is narrowing according to added evidence, not relabelling an incorrect result as acceptable.
The 16 previously suspicious mappings are not broadly retuned. All their original scoring weights remain present; the new observation gates constrain the conclusions they can support. They remain useful owner review items from `../DevelopmentGate/KnownReviewItems.md`.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,3 @@
Validation: ; states 85140; nodes 152/152; solutions 52; primary 52
Acceptance 60/60; prefixes 291/291
PASS Stage 1 full traversal, reviewed 60 paths/prefixes, intentional outcomes and revision

View File

@ -0,0 +1 @@
PASS Stage 1 rendering: distinct six opening icons/choices and Restart; 4/5/6-answer diagnostics; all 67 no-JS pages; desktop/mobile neutral, nonlinear, absence, multi-select, revision and Back/Forward journeys; all adoption concerns and no-JS reassurance; no overflow/CLS; noindex.

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(113,19): warning CS8602: Dereference of a possibly null reference. [/srv/repos/PlotDirector/PlotLine.Tests/PlotLine.Tests.csproj]
/srv/repos/PlotDirector/PlotLine.Tests/Program.cs(3684,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(113,19): warning CS8602: Dereference of a possibly null reference. [/srv/repos/PlotDirector/PlotLine.Tests/PlotLine.Tests.csproj]
/srv/repos/PlotDirector/PlotLine.Tests/Program.cs(3684,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:12.78

View File

@ -0,0 +1,387 @@
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

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,3 @@
Valid graph writing-solver-curated-v2-stage1: 152 nodes, 52 solutions, 15 features.
Few solution routes to feature: character-development
Few solution routes to feature: manuscript-import

View File

@ -83,3 +83,18 @@ Old/demo graphs omit these properties and keep their previous behaviour. Additiv
Before development graph publication, `Tools/WritingSolver backup development` takes a unique COPY_ONLY/CHECKSUM backup and verifies mapped-file existence/size. It refuses any configured database other than `PlotDirector_Development`. Then `publish FILE` uses the normal repository validation and `dbo.WritingSolver_Publish` transaction. This is not a restore test.
Curated V2's reconciled semantic expectations live in its `acceptance-paths.json`. The original literal baseline is retained under `Docs/WritingSolver/CuratedV2/DevelopmentGate/`. The owner explicitly approved **eight known secondary-result exceptions for Development only**; regression checks permit exactly those known supports, prohibit new exceptions, and continue to require all 60 correct primaries and all literal prefixes. The strict semantic report remains 52/60, rather than being relabelled green. These acceptance exceptions are test/review metadata, not production scoring overrides.
## Stage 1 corroboration and intention (November 2026)
Additive schema-v1 fields retain their defaults for earlier snapshots:
- `SolverSolution.requiredSignals`: positive evidence minima, default empty. These determine eligibility in addition to the unchanged weighted score/threshold. They do not contribute points. Early symptom scores can therefore represent hypotheses without publishing a conclusion.
- `SolverNode.requireAnswer`: default false. A selected follow-up marked true cannot be skipped merely because a hypothesis crosses threshold; the existing maximum-answer limit still applies.
- `SolverNode.maxChoices`: default zero/unlimited. A positive value is valid only on a multi-select question (2–12). The engine enforces the limit with or without JavaScript; the renderer and enhancement script explain it. Stage 1 asks for at most two broad tracking concerns to establish a useful focus.
- `SolverNode.allowNeutralChoices`: default false. On a single-choice diagnostic question, explicitly authored choice reassurance can end the conversation without a solution. Such choices must have no weights or applicable onward route. This allows “the choice is deliberate and working” to end immediately, rather than adding another reassurance question. Existing node-level neutral endpoints retain their stricter requirements and previous behaviour.
A current Stage 1 diagnosis requires an observed consequence and a stated concern. Creative diagnoses additionally require an actual intention answer: a management concern elsewhere (for example, remembering several books) cannot establish that a slow relationship is unwanted. Explicit, specific management complaints can establish the concern before the follow-up, so the solver need not repeat an intention question after corroboration. Deliberate-but-hard-to-manage is distinct from deliberate-and-working.
`WritingSolverTraversal` evaluates and deduplicates semantic states before enqueuing them. The identity remains visited node sequence + complete signal totals + next node. The **100,000 distinct-state limit is unchanged**; duplicate pending answers with identical evidence no longer consume extra budget. No scores or reachable outcomes are discarded. The original V2 still explores 11,325 states. Explicit tests separately cover choice-specific reassurance because that existing semantic traversal identity merges neutral presentation variants.
The original `curated-v2` graph and 60-case expectations remain historical regression fixtures. Stage 1 is a separate immutable publication version in `Candidates/curated-v2-stage1`. Its authored expanded paths and semantic expectations are frozen in its own `acceptance-paths.json`. `--writing-solver-stage1` audits that file; `--write-paths` is an explicit authoring operation, not part of normal regressions. Production publication is not authorised by the Development gate.

View File

@ -0,0 +1,134 @@
// Real MVC/Razor journeys; restricted to loopback and the Development host.
const { chromium } = require('playwright');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const candidate = path.resolve('PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1');
const graph = JSON.parse(fs.readFileSync(path.join(candidate,'writing-solver-curated-v2-stage1.json'),'utf8'));
const cases = JSON.parse(fs.readFileSync(path.join(candidate,'acceptance-paths.json'),'utf8')).cases;
const base = process.env.SOLVER_BASE_URL || 'http://127.0.0.1:5238';
assert(['127.0.0.1:5238','127.0.0.1:5050','dev.plotdirector.com'].includes(new URL(base).host),'Test only local or Development.');
(async () => {
const browser = await chromium.launch();
try {
const context=await browser.newContext({javaScriptEnabled:false,viewport:{width:1440,height:1000}});
const page=await context.newPage();
for (const [kind,pages] of [['writing-problems',graph.solutions],['features',graph.features]]) {
for(const record of pages) {
const response=await page.goto(`${base}/${kind}/${record.slug}`);
assert.equal(response.status(),200,record.id);
assert.equal(await page.locator('h1').innerText(),record.title,record.id);
assert.equal(await page.locator('link[rel=canonical]').getAttribute('href'),`https://plotdirector.com/${kind}/${record.slug}`,record.id);
assert.equal(await page.locator('meta[name=description]').getAttribute('content'),record.description,record.id);
assert.equal(await page.locator('meta[property="og:description"]').getAttribute('content'),record.description,record.id);
assert.equal(await page.locator('meta[name=robots]').getAttribute('content'),'noindex, follow',record.id);
assert(await page.locator('script[type="application/ld+json"]').count(),record.id);
assert((await page.locator('body').innerText()).includes(record.summary),record.id);
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false,record.id);
assert(!((await page.locator('main').innerText()).includes('\uFFFD')),`Replacement character in ${record.id}`);
for(const script of await page.locator('script[type="application/ld+json"]').allTextContents()) JSON.parse(script);
if(kind==='writing-problems') {
for(const link of record.features) {
const feature=graph.features.find(f=>f.id===link.feature);
assert(await page.locator(`a[href="/features/${feature.slug}"]`).count(),`${record.id}/${feature.id}`);
}
}
}
}
await page.goto(base+'/writing-problems');
for(const choice of ['unsure','reread-cant-see','using-tool-concern','draft-done','too-much-written']) {
await page.locator(`input[name=choices][value="${choice}"]`).check();
await page.locator('.solver-form button[type=submit]').click();
}
assert.match(await page.locator('.solver-neutral h1').innerText(),/don't need to start again/);
assert.equal(await page.locator('.solver-library').count(),0);
assert(await page.locator('a[href="/features/manuscript-import"]').count());
// A full diagnostic conversation is usable without JavaScript.
await page.goto(base+'/writing-problems');
for(const answer of cases.find(c=>c.id===3).answers) {
for(const choice of answer.choices) 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 h1').innerText(),graph.solutions.find(s=>s.id==='d04').title);
await page.getByRole('link',{name:'Start again',exact:true}).click();assert.equal(await page.locator('input[name=node]').inputValue(),'entry');
await context.close();
for(const width of [390,1440]) {
const context=await browser.newContext({viewport:{width,height:1000}});
await context.addInitScript(()=>{
localStorage.setItem('plotdirector.applicationTheme','rose-pink');
window.__shifts=[];
new PerformanceObserver(list=>list.getEntries().forEach(e=>{if(!e.hadRecentInput)window.__shifts.push(e.value);})).observe({type:'layout-shift',buffered:true});
});
const page=await context.newPage();
await page.goto(base+'/writing-problems');
const paths=await page.locator('.solver-choices--areas .solver-icon path').evaluateAll(ps=>ps.map(p=>p.getAttribute('d')));
assert.equal(paths.length,6);assert.equal(new Set(paths).size,6);
for(const choice of graph.nodes.find(n=>n.id==='entry').choices.filter(c=>!c.fallback)){
await page.goto(base+'/writing-problems');await page.locator(`input[value="${choice.id}"]`).check();await page.locator('.solver-form button[type=submit]').click();assert.equal(await page.locator('.solver-result').count(),0);assert.equal(await page.locator('input[name=node]').count(),1);
await page.getByRole('link',{name:'Restart',exact:true}).click();assert.equal(await page.locator('input[name=node]').inputValue(),'entry');
}
const errors=[];page.on('pageerror',e=>errors.push(e.message));
for(const id of [1,3,9,13,20,23,50,55,56,57,58,60]) {
await page.goto(base+'/writing-problems');
const test=cases.find(c=>c.id===id);
for(let i=0;i<test.answers.length;i++) {
const answer=test.answers[i];
assert.equal(await page.locator('input[name=node]').getAttribute('value'),answer.node,`case ${id} prefix ${i}`);
for(const choice of answer.choices) await page.locator(`input[name=choices][value="${choice}"]`).check();
await page.locator('.solver-form button[type=submit]').click();
const expected=test.prefixExpectations[i];
assert.equal(await page.locator('input[name=node]').count() ? await page.locator('input[name=node]').getAttribute('value') : null,expected.expectedNext,`case ${id} prefix ${i+1}`);
assert.equal(await page.locator('.solver-result').count(),expected.expectedResults.length,`case ${id} prefix ${i+1}`);
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false,`case ${id} width ${width}`);
}
assert.equal(await page.locator('html').getAttribute('data-site-theme'),'public');
assert.equal(await page.locator('html').getAttribute('data-app-theme'),null);
assert((await page.evaluate(()=>window.__shifts.reduce((a,b)=>a+b,0)))<.1,`layout shift in case ${id}`);
}
// Browser history returns to the actual prior question; revise to neutral knowledge-state advice.
await page.goto(base+'/writing-problems');
for(const answer of cases.find(c=>c.id===20).answers) {
for(const choice of answer.choices) await page.locator(`input[name=choices][value="${choice}"]`).check();
await page.locator('.solver-form button[type=submit]').click();
}
await page.goBack();
assert.equal(await page.locator('input[name=node]').getAttribute('value'),cases.find(c=>c.id===20).answers.at(-1).node);
await page.goForward();assert(await page.locator('.solver-result h1').innerText().then(s=>s===graph.solutions.find(s=>s.id==='d22').title));
for(let i=0;i<cases.find(c=>c.id===20).answers.length-2;i++) await page.goBack();
assert.equal(await page.locator('input[name=node]').getAttribute('value'),'track-knowledge');
await page.locator('input[value="who-knows-fact"]').check();await page.locator('.solver-form button[type=submit]').click();
assert.equal(await page.locator('.solver-result').count(),0);
await page.locator('input[value="unsure"]').check();await page.locator('.solver-form button[type=submit]').click();
assert(await page.locator('main').innerText().then(t=>t.includes('isn’t enough evidence')));
// All adoption concerns use their authored content, with at most one relevant capability.
const endpoint=graph.nodes.find(n=>n.neutralEndpoint);
for(const concern of endpoint.choices.filter(c=>c.active)) {
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'],[endpoint.id,concern.id]]) {
assert.equal(await page.locator('input[name=node]').getAttribute('value'),node);
await page.locator(`input[name=choices][value="${choice}"]`).check();
await page.locator('.solver-form button[type=submit]').click();
}
const expected=concern.reassurance || endpoint.reassurance;
assert.equal(await page.locator('.solver-neutral h1').innerText(),expected.title);
assert.equal(await page.locator('.solver-neutral .solver-intro').innerText(),expected.summary);
assert.equal(await page.locator('.solver-result').count(),0);
assert.equal(await page.locator('.solver-library').count(),0);
assert(!(await page.locator('main').innerText()).includes('isn’t enough evidence'));
assert.equal(await page.locator('.solver-neutral a[href^="/features/"]').count(),expected.feature ? 1 : 0);
if(expected.feature) assert(await page.locator(`.solver-neutral a[href="/features/${graph.features.find(f=>f.id===expected.feature).slug}"]`).count());
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);
}
await page.goBack();await page.goForward();assert.equal(await page.locator('.solver-neutral').count(),1);
await page.goBack();await page.goBack();await page.goBack();
assert.equal(await page.locator('input[name=node]').getAttribute('value'),'rescue-confidence');
await page.locator('input[value="story-moving"]').check();await page.locator('.solver-form button[type=submit]').click();
assert.equal(await page.locator('.solver-neutral').count(),0);
assert.equal(await page.locator('input[name=node]').getAttribute('value'),'flow-target');
assert.equal(errors.length,0,errors.join('\n'));
await context.close();
}
// Stage 1 leaves the existing public presentation intact.
console.log('PASS Stage 1 rendering: distinct six opening icons/choices and Restart; 4/5/6-answer diagnostics; all 67 no-JS pages; desktop/mobile neutral, nonlinear, absence, multi-select, revision and Back/Forward journeys; all adoption concerns and no-JS reassurance; no overflow/CLS; noindex.');
} finally {await browser.close();}
})().catch(error=>{console.error(error);process.exit(1);});

View File

@ -17,6 +17,12 @@ using PlotLine.ViewModels;
#pragma warning disable CS8321
if (args.Contains("--writing-solver-stage1"))
{
WritingSolverStage1Tests.Run(args);
return;
}
if (args.Contains("--writing-solver-choice-semantics"))
{
WritingSolverChoiceSemanticsTests.Run(args);
@ -71,6 +77,8 @@ if (args.Contains("--plot-lines"))
var tests = new (string Name, Action Test)[]
{
("Stage 1 preserves all 60 strict conversations, corroboration, intent, reachability and adoption", WritingSolverStage1Tests.Verification),
("Stage 1 evidence gates, required follow-ups, bounded multi-select and neutral choices are enforced", WritingSolverStage1Tests.Framework),
("Neutral endpoints require explicit valid terminal declarations", WritingSolverNeutralTests.Validation),
("Neutral reassurance follows selected concerns without evidence and survives revision", WritingSolverNeutralTests.ReassuranceAndRevision),
("Scene navigation does not invent purpose evidence; genuine D05 witnesses survive", () => WritingSolverChoiceSemanticsTests.VerifyCorrection()),

View File

@ -86,37 +86,29 @@ internal static class WritingSolverCuratedV2Tests
}
// Faithful instrumentation of the existing validator traversal, including its exact
// history/score key and seen+pending ceiling. This intentionally does not replace it.
// history/score key and 100,000 unique discovered-state ceiling. This intentionally does not replace it.
public static Exploration Explore(SolverGraph graph, Action<SolverOutcome>? inspect = null)
{
var pending=new Queue<SolverAnswer[]>();pending.Enqueue([]);
var seen=new HashSet<string>();var nodes=new Dictionary<string,SolverAnswer[]>();var solutions=new Dictionary<string,SolverAnswer[]>();
var pending=new Queue<SolverOutcome>();var initial=WritingSolverEngine.Evaluate(graph,[]);pending.Enqueue(initial);
var seen=new HashSet<string>{WritingSolverTraversal.Key(initial)};var nodes=new Dictionary<string,SolverAnswer[]>();var solutions=new Dictionary<string,SolverAnswer[]>();
var primary=new HashSet<string>();var errors=new List<string>();long attempts=0;var peak=1;var terminals=0;var neutral=0;var maximum=0;var complete=true;
while(pending.TryDequeue(out var history))
while(pending.TryDequeue(out var outcome))
{
attempts++;
var outcome=WritingSolverEngine.Evaluate(graph,history);
var key=string.Join(",",outcome.Answers.Select(a=>a.Node))+":"+string.Join(",",outcome.Scores.OrderBy(s=>s.Key).Select(s=>$"{s.Key}={s.Value}"))+":"+outcome.Next?.Id;
if(!seen.Add(key)) continue;
if(seen.Count+pending.Count>100000) {errors.Add("The real validator's seen+pending ceiling was exceeded.");complete=false;break;}
inspect?.Invoke(outcome);
maximum=Math.Max(maximum,outcome.Answers.Count);
foreach(var solution in outcome.Solutions) solutions.TryAdd(solution.Id,outcome.Answers.ToArray());
if(outcome.Solutions.FirstOrDefault() is { } winner) primary.Add(winner.Id);
if(outcome.Next is not { } node) {terminals++;if(outcome.Solutions.Count==0) neutral++;continue;}
nodes.TryAdd(node.Id,outcome.Answers.ToArray());
foreach(var choice in node.Choices.Where(c=>c.Active)) pending.Enqueue([..history,new(node.Id,[choice.Id])]);
if(node.Multiple)
foreach(var history in WritingSolverTraversal.Extensions(outcome))
{
var substantive=node.Choices.Where(c=>c.Active && !c.Fallback).ToArray();
Require(substantive.Length<=12,$"Too many multi-select choices at {node.Id}.");
for(var mask=1;mask<(1<<substantive.Length);mask++)
{
if((mask & (mask-1))==0) continue;
var ids=substantive.Where((_,i)=>(mask & (1<<i))!=0).Select(c=>c.Id).ToArray();
pending.Enqueue([..history,new(node.Id,ids)]);
}
var next=WritingSolverEngine.Evaluate(graph,history);
if(!seen.Add(WritingSolverTraversal.Key(next)))continue;
if(seen.Count>100000){errors.Add("The real validator's distinct-state ceiling was exceeded.");complete=false;break;}
pending.Enqueue(next);
}
if(!complete)break;
peak=Math.Max(peak,pending.Count);
}
errors.AddRange(graph.Nodes.Where(n=>n.Active && !nodes.ContainsKey(n.Id)).Select(n=>$"Unreachable active node: {n.Id}"));

View File

@ -0,0 +1,164 @@
using System.Text.Json;
using PlotLine.Data;
using PlotLine.Models.WritingSolver;
using PlotLine.Services;
internal static class WritingSolverStage1Tests
{
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");
public static SolverGraph Graph() => WritingSolverRepository.Parse(File.ReadAllText(Path.Combine(DirectoryPath,"writing-solver-curated-v2-stage1.json")));
private static void Require(bool condition,string message) { if(!condition) throw new Exception(message); }
public static void Run(string[] args)
{
// Read without Parse so failed traversal still produces its evidence report.
var graph=JsonSerializer.Deserialize<SolverGraph>(File.ReadAllText(Path.Combine(DirectoryPath,"writing-solver-curated-v2-stage1.json")),Json)!;
var folder=Path.Combine(Root,"Docs/WritingSolver/CuratedV2/Stage1");Directory.CreateDirectory(folder);
var before=WritingSolverCuratedV2Tests.Graph();
var oldDepth=Depths(before);var newDepth=Depths(graph);
var validation=WritingSolverValidator.Validate(graph);
var terminalKinds=new Dictionary<string,int>();var resultPresence=new Dictionary<string,int>();var primaryFrequency=new Dictionary<string,int>();var noSeriesD50Max=0;
var exploration=WritingSolverCuratedV2Tests.Explore(graph,outcome=>
{
if(outcome.Scores.GetValueOrDefault("series")==0)
{
var d50=graph.Solutions.Single(s=>s.Id=="d50");noSeriesD50Max=Math.Max(noSeriesD50Max,d50.Signals.Sum(w=>outcome.Scores.GetValueOrDefault(w.Key)*w.Value));
Require(!outcome.Solutions.Any(s=>s.Id is "d50" or "d51"),"A cross-book diagnosis escaped without series evidence.");
}
if(outcome.Next is not null)return;
var kind=outcome.Reassurance is not null?"authored-reassurance":outcome.Solutions.Count>0?"diagnostic":outcome.Answers.Count==graph.MaxAnswers?"insufficient-at-budget":"insufficient-before-budget";
terminalKinds[kind]=terminalKinds.GetValueOrDefault(kind)+1;
foreach(var solution in outcome.Solutions)resultPresence[solution.Id]=resultPresence.GetValueOrDefault(solution.Id)+1;
if(outcome.Solutions.FirstOrDefault() is {} primary)primaryFrequency[primary.Id]=primaryFrequency.GetValueOrDefault(primary.Id)+1;
});
File.WriteAllText(Path.Combine(folder,"traversal.json"),JsonSerializer.Serialize(new {Validation=validation,Exploration=exploration,Before=oldDepth,After=newDepth,TerminalKinds=terminalKinds,ResultPresence=resultPresence,PrimaryFrequency=primaryFrequency,NoSeriesD50Maximum=noSeriesD50Max},Json));
Console.WriteLine($"Validation: {string.Join("; ",validation)}; states {exploration.StateCount}; nodes {exploration.Nodes.Count}/{graph.Nodes.Count}; solutions {exploration.Solutions.Count}; primary {exploration.PrimarySolutions.Length}");
var file=Path.Combine(DirectoryPath,"acceptance-paths.json");
if(args.Contains("--write-paths"))File.WriteAllText(file,JsonSerializer.Serialize(new WritingSolverCuratedV2Tests.AcceptanceFile(graph.Version,ExtendCases(graph)),Json));
var cases=JsonSerializer.Deserialize<WritingSolverCuratedV2Tests.AcceptanceFile>(File.ReadAllText(file),Json)!.Cases;
var results=WritingSolverCuratedV2Tests.Replay(graph,file);
File.WriteAllText(Path.Combine(folder,"acceptance-results.json"),JsonSerializer.Serialize(results,Json));
foreach(var result in results.Where(r=>!r.Pass || r.Warnings.Length>0))Console.WriteLine($"Case {result.Id}: {string.Join("; ",result.Errors.Concat(result.Warnings))}");
Console.WriteLine($"Acceptance {results.Count(r=>r.Pass)}/60; prefixes {WritingSolverCuratedV2Tests.MatchedPrefixes(results,file)}/{cases.Sum(c=>c.Answers.Length)}");
Require(validation.Count==0 && exploration.Complete && exploration.Errors.Length==0 && exploration.PrimarySolutions.Length==52,"Stage 1 validation/reachability gate failed.");
Require(results.All(r=>r.Pass && r.Warnings.Length==0),"Stage 1 acceptance gate failed.");
Require(newDepth.All(d=>d.Minimum>=4),"A diagnosis resolves before four evidence-bearing answers.");
SemanticsAndRevision(graph,cases);
Console.WriteLine("PASS Stage 1 full traversal, reviewed 60 paths/prefixes, intentional outcomes and revision");
}
public static void Verification()
{
var graph=Graph();
var cases=JsonSerializer.Deserialize<WritingSolverCuratedV2Tests.AcceptanceFile>(File.ReadAllText(Path.Combine(DirectoryPath,"acceptance-paths.json")),Json)!.Cases;
var results=WritingSolverCuratedV2Tests.Replay(graph,Path.Combine(DirectoryPath,"acceptance-paths.json"));
Require(results.Length==60 && results.All(r=>r.Pass && r.Warnings.Length==0),"Stage 1 strict 60-case/prefix/support/forbidden regression.");
var traversal=WritingSolverCuratedV2Tests.Explore(graph,o=>{if(o.Scores.GetValueOrDefault("series")==0)Require(!o.Solutions.Any(s=>s.Id is "d50" or "d51"),"Cross-book diagnosis without series evidence.");});
Require(traversal.Complete && traversal.Errors.Length==0 && traversal.Nodes.Count==graph.Nodes.Count && traversal.Solutions.Count==52 && traversal.PrimarySolutions.Length==52,"Stage 1 exhaustive reachability regression.");
SemanticsAndRevision(graph,cases);
var endpoint=graph.Nodes.Single(n=>n.NeutralEndpoint);
foreach(var choice in endpoint.Choices)
{
var result=WritingSolverEngine.Evaluate(graph,[..traversal.Nodes[endpoint.Id],new(endpoint.Id,[choice.Id])]);
Require(result.Reassurance== (choice.Reassurance??endpoint.Reassurance) && result.Solutions.Count==0 && result.Next is null,"Adoption regression.");
}
Require(new[]{4,5,6}.All(depth=>cases.Any(c=>c.ExpectedPrimary is not null && c.Answers.Length==depth)),"Missing representative journey depth.");
}
public static void Framework()
{
var graph=Graph();
Require(graph.Nodes.Single(n=>n.Id=="entry").Choices.Where(c=>!c.Fallback).Select(c=>c.Icon).Distinct().Count()==6,"Opening icons must be distinct.");
var prefix=new[]{new SolverAnswer("entry",["losing-track"])};
var rejected=WritingSolverEngine.Evaluate(graph,[..prefix,new("track-what",["people","time","plots"])]);
Require(rejected.Answers.Count==1 && rejected.Next?.Id=="track-what","Server must reject an over-limit selection.");
var pair=WritingSolverEngine.Evaluate(graph,[..prefix,new("track-what",["knowledge","objects"])]);
Require(pair.Answers.Count==2 && pair.Next is not null,"Two-area selection must work.");
// Removing corroboration must suppress a high-scoring hypothesis, not lower its score.
var paths=JsonSerializer.Deserialize<WritingSolverCuratedV2Tests.AcceptanceFile>(File.ReadAllText(Path.Combine(DirectoryPath,"acceptance-paths.json")),Json)!.Cases;
var dominance=paths.Single(c=>c.Id==3).Answers;
var early=WritingSolverEngine.Evaluate(graph,dominance.Take(2));
var d04=graph.Solutions.Single(s=>s.Id=="d04");
Require(d04.Signals.Sum(w=>early.Scores.GetValueOrDefault(w.Key)*w.Value)>=d04.Threshold && early.Solutions.Count==0 && early.Next?.Id=="dominance-observation","A hypothesis score must not skip the discriminator.");
var confirms=graph.Nodes.Single(n=>n.Id=="dominance-intention").Choices.Single(c=>c.Id=="even");
var saved=confirms.Weights;confirms.Weights=[];
Require(WritingSolverEngine.Evaluate(graph,dominance).Solutions.Count==0,"A score without confirming evidence must not qualify.");confirms.Weights=saved;
var invalid=graph.Solutions[0];invalid.RequiredSignals["unknown-evidence"]=1;
Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("required diagnostic evidence")),"Unknown evidence gates must be rejected.");invalid.RequiredSignals.Remove("unknown-evidence");
var neutral=graph.Nodes.Single(n=>n.Id=="dominance-intention").Choices.Single(c=>c.Id=="deliberate");neutral.Weights["scale"]=1;
Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("Neutral choice must")),"A neutral choice must not fabricate evidence.");neutral.Weights.Clear();
graph.Nodes.Single(n=>n.Id=="track-what").MaxChoices=1;
Require(WritingSolverValidator.Validate(graph).Any(e=>e.Contains("multi-select limit")),"Malformed choice limits must be rejected.");
}
public sealed record Depth(string Id,string Title,int? Minimum,double? Typical,int Count,int? PrimaryMinimum,double? PrimaryTypical);
private static Depth[] Depths(SolverGraph graph)
{
var depths=graph.Solutions.ToDictionary(s=>s.Id,_=>new List<int>());var primary=graph.Solutions.ToDictionary(s=>s.Id,_=>new List<int>());
WritingSolverCuratedV2Tests.Explore(graph,o=>{if(o.Next is not null)return;foreach(var s in o.Solutions)depths[s.Id].Add(o.Answers.Count);if(o.Solutions.FirstOrDefault() is {} winner)primary[winner.Id].Add(o.Answers.Count);});
double? Median(List<int> x){x.Sort();return x.Count==0?null:(x[(x.Count-1)/2]+x[x.Count/2])/2.0;}
return graph.Solutions.Select(s=>new Depth(s.Id,s.Title,depths[s.Id].Count==0?null:depths[s.Id].Min(),Median(depths[s.Id]),depths[s.Id].Count,primary[s.Id].Count==0?null:primary[s.Id].Min(),Median(primary[s.Id]))).ToArray();
}
private static WritingSolverCuratedV2Tests.AcceptanceCase[] ExtendCases(SolverGraph graph)
{
var old=JsonSerializer.Deserialize<WritingSolverCuratedV2Tests.AcceptanceFile>(File.ReadAllText(Path.Combine(WritingSolverCuratedV2Tests.DirectoryPath,"acceptance-paths.json")),Json)!;
// Authored observations for each original complaint. Expectations are kept independent of actual scoring.
var supporting=new Dictionary<int,string[]>{[8]=["d08"],[12]=["d13"],[18]=["d15"],[30]=["d52"],[35]=["d28"],[36]=["d42"],[42]=["d44"],[44]=["d44"],[46]=["d37"]};
var picks=new Dictionary<int,string>{[1]="apart",[2]="gap",[3]="space",[4]="nothing",[5]="reset",[6]="remember",[7]="remember",[8]="same-job",[9]="gap",[10]="share",[11]="voice",[12]="age",[13]="unsure",[14]="network",[15]="unprepared",[16]="repeat",[17]="views",[18]="ripples",[19]="no-source",[20]="source",[21]="povs",[22]="order",[23]="clues",[24]="reader",[25]="clash",[26]="elapsed",[27]="reading",[28]="parallel",[29]="fixed",[30]="volume",[31]="place",[32]="chapter",[33]="repeat",[34]="try",[35]="journey",[36]="facts",[37]="track",[38]="holder",[39]="history",[40]="nothing",[41]="uneven",[42]="tension",[43]="unchanged",[44]="late",[45]="ripples",[46]="versions",[47]="facts",[48]="thread",[49]="whole",[50]="other",[51]="order",[52]="unprepared",[53]="gap",[54]="gap",[55]="reading",[56]="gap",[57]="moving",[58]="unsure",[59]="facts",[60]="order"};
return 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 original=test.Answers.FirstOrDefault(a=>a.Node==node.Id);
string[] ids;
if(original is not null)ids=original.Choices;
else if(node.Id=="dominance-intention")ids=["even"];
else if(node.Id.StartsWith("intent-"))ids=[test.Id==57?"deliberate":"unwanted"];
else if(node.Id=="flow-target")ids=["main-story"];
else if(node.Id=="time-parallel")ids=["parallel"];
else if(node.Id=="flow-relationship")ids=["see-development"];
else ids=[picks[test.Id]];
Require(ids.All(id=>node.Choices.Any(c=>c.Id==id)), $"Case {test.Id} lacks authored choice {string.Join(',',ids)} for {node.Id}");
history.Add(new(node.Id,ids));outcome=WritingSolverEngine.Evaluate(graph,history);
// Explicit semantic expected results: no diagnostics before completion; reviewed primary/supports at completion.
var expected=test.Id==57?Array.Empty<string>():new[]{test.ExpectedPrimary}.Where(s=>s is not null).Cast<string>().Concat(supporting.GetValueOrDefault(test.Id)??test.RequiredSupporting).ToArray();
prefixes.Add(new(history.Count,outcome.Next?.Id,outcome.Next is not null?[]:expected));
}
var expectedPrimary=test.Id==57?null:test.ExpectedPrimary;
return test with {Answers=history.ToArray(),PrefixExpectations=prefixes.ToArray(),ExpectedPrimary=expectedPrimary,AcceptableSupporting=test.AcceptableSupporting,RequiredSupporting=supporting.GetValueOrDefault(test.Id)??test.RequiredSupporting,Notes=test.Notes+" Stage 1: new observations are explicitly authored; case 57 confirms deliberate slow progress, so no stall diagnosis is claimed."};
}).ToArray();
}
private static void SemanticsAndRevision(SolverGraph graph,WritingSolverCuratedV2Tests.AcceptanceCase[] cases)
{
foreach(var test in cases)
{
var outcome=WritingSolverEngine.Evaluate(graph,test.Answers);
if(test.ExpectedPrimary is not null)Require(outcome.Answers.Count is >=4 and <=6,$"Premature diagnosis in case {test.Id}");
for(var i=0;i<test.Answers.Length;i++)Require(WritingSolverEngine.Evaluate(graph,test.Answers.Take(i)).Next is not null,$"Premature prefix in case {test.Id}");
}
var dominance=cases.Single(c=>c.Id==3).Answers;
var deliberate=dominance.Select(a=>a.Node=="dominance-intention"?new SolverAnswer(a.Node,["deliberate"]):a).ToArray();
Require(WritingSolverEngine.Evaluate(graph,deliberate).Reassurance is not null,"Intentional dominance must be neutral.");
var revised=new[]{new SolverAnswer("entry",["losing-track"])}.Concat(dominance.Skip(1));
var replay=WritingSolverEngine.Evaluate(graph,revised);Require(replay.Answers.Count==1 && replay.Next?.Id=="track-what","Revision did not discard stale suffix.");
SolverOutcome Follow(params (string Node,string Choice)[] answers) => WritingSolverEngine.Evaluate(graph,answers.Select(a=>new SolverAnswer(a.Node,[a.Choice])));
foreach(var (observation,check,choice,intent,expected) in new[]{
("gaps","check-threads","gap","intent-threads","d02"),
("apart","check-threads","apart","intent-threads","d03"),
("turns","check-progression","late","intent-progression","d47"),
("voice","check-cast","voice","intent-cast","d12"),
("voice","check-cast","share","intent-cast","d11")})
{
var branch=new List<(string,string)>{("entry","story-not-working"),("story-problem","takes-over"),("dominance-observation",observation)};
if(observation is "gaps" or "apart")branch.Add(("dominance-intention","main"));
branch.Add((check,choice));branch.Add((intent,"unwanted"));
var result=Follow(branch.ToArray());
Require(result.Answers.Count==branch.Count && result.Solutions.FirstOrDefault()?.Id==expected,$"Dominance discriminator {observation}/{choice} did not identify {expected}.");
}
var mixed=Follow(("entry","too-much"),("scale-what","series"),("series-what","threads"),("series-thread","last-left"),("check-series","both"));
Require(mixed.Solutions.Select(s=>s.Id).SequenceEqual(new[]{"d51","d50"}),"Genuine cross-book thread and memory support must coexist.");
var old=WritingSolverCuratedV2Tests.Graph();
foreach(var s in graph.Solutions){var prior=old.Solutions.Single(x=>x.Id==s.Id);Require(s.Threshold==prior.Threshold && s.Signals.OrderBy(w=>w.Key).SequenceEqual(prior.Signals.OrderBy(w=>w.Key)),"Stage 1 changed reviewed coefficients/thresholds.");}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -29,7 +29,7 @@ public sealed class WritingProblemsController(IWritingSolverRepository repositor
Response.Headers["Referrer-Policy"] = "no-referrer";
var graph = await repository.GetAsync();
List<SolverAnswer> history = [];
string? error = choose ? "Choose an answer to continue. Use Something else on its own if the other answers don’t fit." : null;
string? error = choose ? "Choose an answer to continue, keeping to the number shown in the question. Use Something else on its own if the other answers don’t fit." : null;
try { history = Decode(graph,state); }
catch (Exception ex) when (ex is CryptographicException or JsonException or InvalidDataException)
{ error = "Your previous conversation has expired or changed. Let’s start afresh."; }

View File

@ -22,7 +22,10 @@ public sealed class SolverNode
public string Help { get; set; } = "";
public bool Active { get; set; } = true;
public bool Multiple { get; set; }
public int MaxChoices { get; set; }
public bool NeutralEndpoint { get; set; }
public bool RequireAnswer { get; set; }
public bool AllowNeutralChoices { get; set; }
public SolverReassurance? Reassurance { get; set; }
public int Order { get; set; }
public Dictionary<string,int> Affinity { get; set; } = [];
@ -77,6 +80,7 @@ public sealed class SolverSolution : SolverPage
{
public Dictionary<string,int> Signals { get; set; } = [];
public int Threshold { get; set; } = 3;
public Dictionary<string,int> RequiredSignals { get; set; } = [];
public string Principle { get; set; } = "";
public List<SolverFeatureLink> Features { get; set; } = [];
public List<string> Related { get; set; } = [];

View File

@ -14,21 +14,21 @@ public static class WritingSolverEngine
var ids = answer.Choices.Distinct(StringComparer.Ordinal).ToArray();
var choices = next.Choices.Where(c => c.Active && ids.Contains(c.Id)).ToArray();
if (ids.Length == 0 || choices.Length != ids.Length || (!next.Multiple && ids.Length != 1)
|| (choices.Any(c => c.Fallback) && ids.Length != 1)) break;
|| (choices.Any(c => c.Fallback) && ids.Length != 1) || (next.MaxChoices > 0 && ids.Length > next.MaxChoices)) break;
accepted.Add(new(answer.Node, ids));
foreach (var choice in choices)
foreach (var weight in choice.Weights)
scores[weight.Key] = scores.GetValueOrDefault(weight.Key) + weight.Value;
if (next.NeutralEndpoint)
if (next.NeutralEndpoint || (next.AllowNeutralChoices && choices.Length == 1 && choices[0].Reassurance is not null))
return new(null, [], scores, accepted, choices.Single().Reassurance ?? next.Reassurance);
next = SelectNext(graph, next, ids, accepted, scores);
}
var solutions = graph.Solutions.Where(s => s.Active)
.Select(s => new { Solution = s, Score = s.Signals.Sum(w => scores.GetValueOrDefault(w.Key) * w.Value) })
.Where(s => s.Score >= s.Solution.Threshold)
.Where(s => s.Score >= s.Solution.Threshold && s.Solution.RequiredSignals.All(w => scores.GetValueOrDefault(w.Key) >= w.Value))
.OrderByDescending(s => s.Score).ThenBy(s => s.Solution.Order).ThenBy(s => s.Solution.Id, StringComparer.Ordinal)
.Select(s => s.Solution).Take(3).ToArray();
if (accepted.Count >= graph.MaxAnswers || (accepted.Count >= graph.MinAnswers && solutions.Length > 0)) next = null;
if (accepted.Count >= graph.MaxAnswers || (accepted.Count >= graph.MinAnswers && solutions.Length > 0 && next?.RequireAnswer != true)) next = null;
return new(next, next is null ? solutions : [], scores, accepted);
}

View File

@ -0,0 +1,25 @@
using PlotLine.Models.WritingSolver;
namespace PlotLine.Services;
// The queue contains unique semantic states. Duplicate answers with identical evidence
// must not consume the distinct-state budget before they are dequeued.
public static class WritingSolverTraversal
{
public static string Key(SolverOutcome outcome) => string.Join(",",outcome.Answers.Select(a=>a.Node))+":"+
string.Join(",",outcome.Scores.OrderBy(s=>s.Key).Select(s=>$"{s.Key}={s.Value}"))+":"+outcome.Next?.Id;
public static IEnumerable<SolverAnswer[]> Extensions(SolverOutcome outcome)
{
if(outcome.Next is not {} node)yield break;
foreach(var choice in node.Choices.Where(c=>c.Active))yield return [..outcome.Answers,new(node.Id,[choice.Id])];
if(!node.Multiple)yield break;
var substantive=node.Choices.Where(c=>c.Active && !c.Fallback).ToArray();
if(substantive.Length>12)throw new InvalidDataException("Split multi-select nodes with more than 12 substantive choices.");
for(var mask=1;mask<(1<<substantive.Length);mask++)
{
if((mask & (mask-1))==0)continue;
var ids=substantive.Where((_,i)=>(mask & (1<<i))!=0).Select(c=>c.Id).ToArray();
if(node.MaxChoices>0 && ids.Length>node.MaxChoices)continue;
yield return [..outcome.Answers,new(node.Id,ids)];
}
}
}

View File

@ -36,6 +36,7 @@ public static partial class WritingSolverValidator
{
Check(node.Type is "area" or "question", $"Unknown node type: {node.Id}");
Check(!string.IsNullOrWhiteSpace(node.Title), $"Missing question: {node.Id}");
Check(node.MaxChoices == 0 || (node.Multiple && node.MaxChoices is >= 2 and <= 12), $"Invalid multi-select limit: {node.Id}");
Unique(node.Choices.Select(c => c.Id), $"choice in {node.Id}");
Check(!node.Active || node.Choices.Any(c => c.Active && c.Fallback), $"Missing fallback choice: {node.Id}");
void Reassurance(SolverReassurance? content, string label)
@ -51,7 +52,10 @@ public static partial class WritingSolverValidator
Check(node.Choices.All(c => c.Weights.Count == 0), $"Neutral endpoint must not create diagnostic evidence: {node.Id}");
Check(node.Reassurance is not null, $"Missing neutral endpoint fallback reassurance: {node.Id}");
}
else Check(node.Reassurance is null && node.Choices.All(c => c.Reassurance is null), $"Reassurance requires an explicit neutral endpoint: {node.Id}");
else Check(node.Reassurance is null && (node.AllowNeutralChoices || node.Choices.All(c => c.Reassurance is null)), $"Reassurance requires an explicit neutral endpoint: {node.Id}");
Check(!node.AllowNeutralChoices || (!node.NeutralEndpoint && !node.Multiple && node.Choices.Any(c => c.Reassurance is not null)), $"Neutral choices require a single-choice diagnostic question with explicit reassurance: {node.Id}");
foreach (var choice in node.Choices.Where(c => node.AllowNeutralChoices && c.Reassurance is not null))
Check(choice.Weights.Count == 0 && !node.Routes.Any(r => r.Choice is null || r.Choice == choice.Id), $"Neutral choice must have no evidence or onward route: {node.Id}/{choice.Id}");
Reassurance(node.Reassurance, node.Id);
foreach (var choice in node.Choices) Reassurance(choice.Reassurance, $"{node.Id}/{choice.Id}");
Weights(node.Affinity, node.Id);
@ -84,6 +88,7 @@ public static partial class WritingSolverValidator
foreach (var solution in graph.Solutions)
{
Weights(solution.Signals, solution.Id);
Check(solution.RequiredSignals.All(w => signalNames.Contains(w.Key) && w.Value is > 0 and <= 100), $"Invalid required diagnostic evidence: {solution.Id}");
Check(solution.Threshold > 0 && solution.Signals.Count > 0 && solution.Signals.Keys.All(signalNames.Contains), $"Invalid diagnosis signals: {solution.Id}");
Check(solution.Features.Count > 0 && solution.Features.Any(f => f.Primary), $"Missing primary feature: {solution.Id}");
Unique(solution.Features.Select(f => f.Feature), $"feature mapping in {solution.Id}");
@ -118,7 +123,7 @@ public static partial class WritingSolverValidator
Check(upperBound >= solution.Threshold, $"Unreachable solution (insufficient signals): {solution.Id}");
}
foreach (var node in graph.Nodes.Where(n => n.Active && n.Routes.Count == 0))
Check(node.NeutralEndpoint || node.Choices.Any(c => c.Weights.Keys.Any(k => graph.Solutions.Any(s => s.Active && s.Signals.ContainsKey(k)))), $"Dead end without diagnostic evidence: {node.Id}");
Check(node.NeutralEndpoint || node.Choices.Any(c => c.Weights.Keys.Any(k => graph.Solutions.Any(s => s.Active && (s.Signals.ContainsKey(k) || s.RequiredSignals.ContainsKey(k))))), $"Dead end without diagnostic evidence: {node.Id}");
if (errors.Count == 0) errors.AddRange(ValidateJourneys(graph));
return errors;
}
@ -128,31 +133,23 @@ public static partial class WritingSolverValidator
var errors = new List<string>();
if (graph.Nodes.Any(n => n.Active && n.Multiple && n.Choices.Count(c => c.Active && !c.Fallback) > 12))
return ["Split multi-select nodes with more than 12 substantive choices to keep exhaustive validation bounded."];
var pending = new Queue<SolverAnswer[]>();
pending.Enqueue([]);
var seen = new HashSet<string>();
var pending = new Queue<SolverOutcome>();
var initial = WritingSolverEngine.Evaluate(graph,[]);
pending.Enqueue(initial);
var discovered = new HashSet<string> { WritingSolverTraversal.Key(initial) };
var reached = new HashSet<string>();
var diagnosed = new HashSet<string>();
while (pending.TryDequeue(out var history))
while (pending.TryDequeue(out var outcome))
{
var outcome = WritingSolverEngine.Evaluate(graph, history);
var key = string.Join(",", outcome.Answers.Select(a => a.Node)) + ":" + string.Join(",",outcome.Scores.OrderBy(s=>s.Key).Select(s=>$"{s.Key}={s.Value}")) + ":" + outcome.Next?.Id;
if (!seen.Add(key)) continue;
if (seen.Count + pending.Count > 100000) return ["Journey validation exceeded 100,000 distinct states. Simplify the graph or split redundant choices; no data has been published."];
foreach(var solution in outcome.Solutions) diagnosed.Add(solution.Id);
if (outcome.Next is not { } node) continue;
reached.Add(node.Id);
var choices = node.Choices.Where(c=>c.Active).ToArray();
foreach(var choice in choices) pending.Enqueue([..history,new(node.Id,[choice.Id])]);
if (node.Multiple)
foreach(var history in WritingSolverTraversal.Extensions(outcome))
{
var substantive = choices.Where(c=>!c.Fallback).ToArray();
for(var mask=1;mask<(1<<substantive.Length);mask++)
{
if ((mask & (mask-1))==0) continue;
var ids = substantive.Where((_,i)=>(mask & (1<<i))!=0).Select(c=>c.Id).ToArray();
pending.Enqueue([..history,new(node.Id,ids)]);
}
var next = WritingSolverEngine.Evaluate(graph,history);
if (!discovered.Add(WritingSolverTraversal.Key(next))) continue;
if (discovered.Count > 100000) return ["Journey validation exceeded 100,000 distinct states. Simplify the graph or split redundant choices; no data has been published."];
pending.Enqueue(next);
}
}
errors.AddRange(graph.Nodes.Where(n=>n.Active && !reached.Contains(n.Id)).Select(n=>$"Unreachable node under scoring/routing rules: {n.Id}"));

View File

@ -1,5 +1,10 @@
@model string
@{ var path=Model switch {
"search" => "M21 21l-5-5M18 10a8 8 0 1 1-16 0a8 8 0 0 1 16 0",
"connections" => "M8 6h8M6 8v8M18 8v8M8 18h8M6 3a3 3 0 1 1 0 6a3 3 0 0 1 0-6M18 3a3 3 0 1 1 0 6a3 3 0 0 1 0-6M6 15a3 3 0 1 1 0 6a3 3 0 0 1 0-6M18 15a3 3 0 1 1 0 6a3 3 0 0 1 0-6",
"pulse" => "M2 12h5l3-8 4 16 3-8h5",
"shield-check" => "M12 2l9 4v6c0 5-9 10-9 10S3 17 3 12V6l9-4M8 12l3 3 5-6",
"branch" => "M6 3v12a6 6 0 0 0 6 6h6M6 9h6a6 6 0 0 0 6-6M15 18l3 3-3 2M15 2l3 1-1 3",
"people" => "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M16 3a4 4 0 0 1 0 8M22 21v-2a4 4 0 0 0-3-3.87M13 7a4 4 0 1 1-8 0a4 4 0 0 1 8 0",
"clock" => "M12 8v4l3 3M9 2h6M12 2v2M21 13a9 9 0 1 1-18 0a9 9 0 0 1 18 0",
"pin" => "M20 10c0 6-8 12-8 12S4 16 4 10a8 8 0 1 1 16 0M15 10a3 3 0 1 1-6 0a3 3 0 0 1 6 0",

View File

@ -16,7 +16,7 @@
@Html.AntiForgeryToken()
<input type="hidden" name="state" value="@Model.History" />
<input type="hidden" name="node" value="@next.Id" />
<fieldset>
<fieldset data-max-choices="@next.MaxChoices">
<legend class="@(beginning ? "solver-entry-legend" : "solver-question")">@next.Title</legend>
<p class="solver-help" id="solver-help">@next.Help</p>
<div class="solver-choices @(next.Type == "area" ? "solver-choices--areas" : "")">

View File

@ -9,9 +9,13 @@
form.querySelector('.solver-selection-error').hidden = true;
}));
form.addEventListener('submit', event => {
if (!inputs.some(input => input.checked)) {
const limit = Number(form.querySelector('fieldset').dataset.maxChoices || 0);
const count = inputs.filter(input => input.checked).length;
if (!count || (limit && count > limit)) {
event.preventDefault();
form.querySelector('.solver-selection-error').hidden = false;
const error = form.querySelector('.solver-selection-error');
error.textContent = count ? `Please choose up to ${limit} areas so we can focus on what is troubling you most.` : 'Please choose an answer to continue.';
error.hidden = false;
inputs[0]?.focus();
}
});

View File

@ -0,0 +1,236 @@
import json,copy
from pathlib import Path
root=Path(__file__).resolve().parents[2]; folder=root/'PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1'
g=json.loads((folder.parent/'curated-v2/writing-solver-curated-v2.json').read_text())
g.update(version='writing-solver-curated-v2-stage1',minAnswers=4,changeNote='Stage 1: symptom hypotheses, observable consequences and authorial intention; explicit evidence gates; no coefficient or threshold changes.')
nodes={n['id']:n for n in g['nodes']}
for n in g['nodes']: n['requireAnswer']=True
# Domain-specific corroboration is eligibility evidence, not another score boost.
# Existing symptom coefficients/thresholds are deliberately retained.
def ch(id,text,confirm=(),weights=None,fallback=False):
w=dict(weights or {});w.update({'observed-'+s:1 for s in confirm})
return dict(id=id,text=text,help='',icon='book',active=True,fallback=fallback,order=0,weights=w)
def node(id,title,choices,help='Choose the observation that comes closest. It is fine if you cannot tell yet.'):
n=dict(id=id,type='question',title=title,help=help,active=True,multiple=False,requireAnswer=True,order=len(g['nodes'])+1,affinity={},choices=choices,routes=[])
for i,c in enumerate(choices): c['order']=i
g['nodes'].append(n);nodes[id]=n;return n
def route(n,target,choice=None,priority=10):
r=dict(target=target,priority=priority,allowCycle=False)
if choice:r['choice']=choice
nodes[n]['routes'].append(r)
def reassure(title,summary):return dict(title=title,summary=summary,advice=['Keep the choice that serves your story. You can return here if keeping track of its consequences becomes difficult.'])
def family(id,title,options,intention):
# Each observed consequence names the evidence it actually supports. Uncertainty grants none.
q=node('check-'+id,title,[ch(*o) for o in options]+[ch('unsure','I cannot tell from what I have noticed yet',fallback=True)])
intent=node('intent-'+id,intention,[ch('unwanted','It is getting in the way of what I want the reader to experience',weights={'concern-confirmed':1}),ch('manage','The choice is deliberate, but keeping its consequences straight is difficult',weights={'concern-confirmed':1}),ch('deliberate','It is deliberate, and I am not finding a problem with it'),ch('unsure','I am not sure whether it is a problem yet',fallback=True)])
intent['allowNeutralChoices']=True
intent['choices'][2]['reassurance']=reassure('A deliberate choice does not need correcting.','Different stories need different shapes. From what you have said, there is no reason to treat this choice itself as a fault.')
intent['choices'][3]['reassurance']=reassure('You do not have to decide that yet.','Look at one passage where you notice it and what changes for the reader. There is not enough evidence here to label it as a problem.')
for c in q['choices']:
if not c['fallback']:route(q['id'],intent['id'],c['id'])
return q['id']
f={}
f['threads']=family('threads','When you return to the other storylines, what do you notice?',[
('lost','I have to search back just to remember which threads are still open',['threads'],{}),
('gap','A thread returns and I have forgotten why it matters',['dormancy'],{'plot-dormancy':2}),
('apart','The threads continue, but events in one scarcely affect the others',['connection'],{'plot-connection':2}),
('scenes','I can follow each thread, but cannot tell what individual scenes add',['purpose'],{'scene-purpose':3})], 'Is this making the story harder to follow, or is the separation doing what you want?')
f['purpose']=family('purpose','Think of one of those scenes. What would be lost if you took it out?',[
('nothing','I cannot find anything later that depends on it',['purpose'],{}),('same','Another scene already gives the reader the same thing',['repetition'],{'repetition':5}),('missing-link','An action or reaction later would no longer make sense',['causality'],{'causality':5}),('thread','I would lose part of a thread, but cannot see where that thread goes',['threads','purpose'],{})], 'Are you trying to change what these scenes do, or keep their contribution visible?')
f['causality']=family('causality','After a significant event, what tends to happen next?',[
('reset','The next event could happen much the same way without it',['causality'],{}),('offstage','The consequences matter, but appear in a different thread without a clear connection',['connection'],{'plot-connection':4}),('promise','I am waiting for an earlier promise to matter, rather than for the next reaction',['payoff'],{'setup-payoff':5})], 'Is that looseness intentional, or are you trying to make the consequences clearer?')
f['payoff']=family('payoff','When the later moment arrives, what is missing for the reader?',[
('remember','The earlier promise never seems to get an answer',['payoff'],{}),('prepare','The answer arrives, but there was little reason to expect it',['payoff'],{}),('clues','I cannot keep straight which clues have already been noticed',['clues'],{'clues':4}),('order','The answer is present, but the reader meets it before the necessary information',['reveal'],{'revelation-order':4})], 'Is that uncertainty something you want the reader to feel, or something you need to untangle?')
f['cast']=family('cast','When you look for that character again, what makes the gap or overlap troublesome?',[
('remember','I have forgotten who they are or how they fit in',['cast'],{}),('same-job','Another character could take their place without changing what happens',['roles'],{'role-overlap':3}),('gap','We leave something important with them and do not return to it for a long time',['presence'],{}),('share','They take more or less space than the role I intended for them',['proportions'],{}),('voice','One narrator gives most of the account, although I need the others to carry more',['pov'],{}),('none','The gap is intentional and nothing feels missing',[],{})], 'Does this differ from the role you want these characters to play?')
f['relationships']=family('relationships','What do the scenes between them actually show?',[
('unprepared','Their behaviour changes, but I cannot find the moments that would earn it',['relationship-speed'],{}),('repeat','Their encounters keep returning to the same position despite chances to change',['relationship-stall'],{}),('stage','They behave as though they are at different stages, and I cannot place the shift',['relationship-state'],{'relationship-state':3}),('views','Each behaves consistently, but they understand the relationship differently',['relationship-perspective'],{}),('ripples','One event changes several connections and I keep losing track of the knock-on effects',['relationship-event','relationship-network'],{}),('network','I keep confusing who is connected to whom across several relationships',['relationship-network'],{}),('moving','Small changes are happening; the relationship is simply developing slowly',[],{})], 'Is that relationship pattern serving your intention, or is something missing from the development?')
f['knowledge']=family('knowledge','When you check the relevant scene, where does the uncertainty remain?',[
('no-source','Someone acts on information, but I cannot find any way they could have learned it',['premature-knowledge'],{}),('source','I know they learn it; I cannot locate the conversation or discovery',['knowledge-source'],{}),('povs','I can find the facts, but lose track of which narrator has which pieces',['pov-knowledge'],{}),('clues','I lose the trail of clues as different people encounter them',['clues'],{}),('order','The scenes establish it, but their current order puts the discovery after the reaction',['reveal'],{}),('reader','The characters are consistent; it is the reader who gets the answer at the wrong moment',['reader-reveal'],{})], 'Is the information gap deliberate for the reader, or is it making the manuscript harder to manage?')
f['time']=family('time','What happens when you put those moments side by side?',[
('clash','Two stated dates or event positions cannot both be true',['calendar'],{}),('elapsed','The sequence is clear, but the gap between events does not fit',['elapsed'],{}),('age','The calendar would work if the character had a different age',['age'],{}),('reading','The events fit in time, but the reader encounters them in a different order',['nonlinear'],{}),('parallel','Separate chains of events overlap and I lose where each has reached',['parallel'],{}),('fixed','A real-world date cannot move, so the invented events must fit around it',['fixed'],{}),('travel','The route or journey cannot fit between the two appearances',['movement'],{})], 'Is the arrangement intentional, or are you trying to reconcile something that cannot currently fit?')
f['whereabouts']=family('whereabouts','What is difficult when you follow the character from one appearance to the next?',[
('where','The moves could work, but I keep forgetting where the character last was',['whereabouts'],{}),('journey','The next appearance leaves no possible journey from the previous one',['movement'],{}),('parallel','Several people move at once and I lose which events overlap',['parallel'],{})], 'Are you trying to repair an impossible move, or make a workable journey easier to keep straight?')
f['structure']=family('structure','What makes arranging those scenes difficult in practice?',[
('volume','I can describe the scenes, but cannot keep the whole arrangement in view',['scene-volume'],{}),('place','A scene could sit in several places and I cannot see what each position changes',['scene-position'],{}),('chapter','The scenes work individually, but the chapter breaks produce uneven stretches',['chapters'],{}),('repeat','Different scenes give the reader substantially the same thing',['repetition'],{}),('purpose','I cannot say what would be lost if some scenes went',['purpose'],{})], 'Does the current arrangement produce the experience you want?')
f['object']=family('object','Following the object from its last clear appearance, what is missing?',[
('track','A plausible handover or move exists, but I keep losing where it ended up',['object-track'],{}),('holder','The person using it has no opportunity to receive it',['custody'],{}),('history','An earlier loss, damage or destruction is incompatible with its later state',['object-history'],{}),('place','Its physical position does not fit the earlier scene, rather than the person holding it',['object-history'],{})], 'Is there an explanation you intend the reader to discover, or a continuity problem to untangle?')
f['place']=family('place','What changes when you revisit the place?',[
('facts','The same room, building or landscape has incompatible details',['place-state'],{}),('people','The place is consistent; it is the characters’ route that does not fit',['movement'],{'movement':3}),('object','Only an object there has changed state; the place itself is consistent',['object-history'],{'object':3})], 'Is the difference part of the story, or an unintended change you need to track?')
f['progression']=family('progression','During the stretch that feels wrong, what is actually changing?',[
('nothing','Events repeat without changing what anyone can do next',['story-stall'],{}),('uneven','There is progress, but important developments arrive in bunches between long waits',['pace'],{}),('late','Most of the changes that matter are left until the closing section',['late'],{}),('tension','The situation changes, but the pressure the reader feels drops or spikes unexpectedly',['tension'],{}),('character','The events move forward; it is one character who seems unaffected',['arc'],{})], 'Is that rhythm deliberate, or is it weakening the movement you want?')
f['arc']=family('arc','How does the character respond when something important happens?',[
('unchanged','Their choices return to the same place even after events that should affect them',['arc'],{}),('late','The responses change, but nearly all the change arrives near the ending',['late'],{}),('absent','The change may be there; we spend too long away from the character to follow it',['presence'],{'character-presence':3}),('steady','They are deliberately steady, and events still have consequences',[],{})], 'Do you want the character to change here, or are you concerned about making a steady character readable?')
f['change']=family('change','After a small change, what do you find yourself checking?',[
('ripples','I have to chase effects through several scenes before I can trust the change',['dependencies'],{}),('position','I mainly need to see where the moved scene fits',['scene-position'],{}),('try','I want to try a different arrangement while keeping the current one safe',['experiment'],{}),('versions','Several arrangements could work and I need to compare them',['versions'],{}),('information','Discoveries and reactions now appear in the wrong order',['reveal'],{})], 'Are you trying to repair the present version, or explore alternatives without losing it?')
f['series']=family('series','When you return to an earlier book, what sends you searching?',[
('facts','I need established facts from several books before I can trust a new passage',['series-memory'],{}),('thread','A thread remains open across books and I cannot see where each book advances it',['series-thread'],{}),('both','Both the established facts and the threads spanning the books are hard to follow',['series-memory','series-thread'],{})], 'Is the difficulty keeping the books consistent, rather than deciding how many books the story should have?')
f['overload']=family('overload','What tends to slip when you stop maintaining all those notes?',[
('whole','Several kinds of detail slip together; fixing one makes me lose another',['whole-load'],{}),('scenes','Mostly where scenes fit in the larger arrangement',['scene-volume'],{}),('threads','Mostly which storylines are still open',['threads'],{}),('cast','Mostly who the characters are and how they fit',['cast'],{})], 'Is the organisation helping you write, or taking over the attention you need for the story?')
# Dedicated dominance investigation: consequence before intention, with competing explanations.
q=node('dominance-observation','What makes it feel as though that storyline is taking over?',[
ch('space','Its scenes keep expanding and squeeze out things I still want the others to do'),ch('gaps','The other threads vanish while this one is prominent'),ch('apart','The other threads continue, but stop affecting this one'),ch('turns','Most of the big turning points belong to it'),ch('voice','It may be one character or narrator making it feel that way'),ch('unsure','I cannot tell what gives me that impression yet',fallback=True)])
node('dominance-intention','Is that storyline meant to carry most of the book?',[
ch('even','I want the other threads to carry more of the book than they do', ['imbalance'],{'concern-confirmed':1}),ch('main','Yes; I am worried about what happens to the supporting threads'),ch('deliberate','Yes, and the supporting threads are doing what I want'),ch('unsure','I have not decided what balance I want yet',fallback=True)])
nodes['dominance-intention']['allowNeutralChoices']=True
nodes['dominance-intention']['choices'][2]['reassurance']=reassure('A main storyline can carry most of the book.','Unequal space is not evidence of a fault. What matters is whether the supporting threads do the work you want them to do.')
nodes['dominance-intention']['choices'][3]['reassurance']=reassure('Decide what each thread needs to contribute first.','You do not need equal quantities. Think about what would be lost without each supporting thread before deciding whether its share is too small.')
route('dominance-intention',f['threads'],'main')
for c in q['choices']:
route(q['id'], f['cast'] if c['id']=='voice' else ('check-progression' if c['id']=='turns' else 'dominance-intention'),c['id'])
# Intention is expressed in the language of the actual concern, not a repeated questionnaire label.
intent_copy={
'threads':('The threads are not doing the work I want them to do','The separation is deliberate; remembering each thread is the difficulty','The threads are doing what I want, even though their shares differ'),
'purpose':('I want these scenes to contribute something that is currently missing','Their contribution is deliberate; keeping it visible is the difficulty','These scenes already give the reader what I want'),
'causality':('I want the events to lead into each other more clearly','The loose connection is deliberate; tracking the consequences is difficult','The looseness is doing what I want'),
'payoff':('The later moment is not giving the reader the response I intended','The delay is deliberate; keeping the promises and answers straight is hard','The uncertainty is deliberate and the answer arrives as I want'),
'cast':('Their presence or overlap differs from the role I intended','Their roles are deliberate; keeping their appearances straight is hard','Their appearances already serve the roles I want'),
'relationships':('I want a change or a connection that the scenes are not making clear','The relationship pattern is deliberate; keeping track of it is hard','The relationship is progressing, or staying steady, as I want'),
'knowledge':('The information reaches someone at a point I did not intend','The information gaps are deliberate; keeping track of them is hard','The information gaps are deliberate and are working as intended'),
'time':('I need these events to fit together, and at the moment they do not','The arrangement is deliberate; keeping the actual timing straight is hard','The timing works as intended; I only wondered if it was unusual'),
'whereabouts':('The appearances do not currently fit the journey I intended','The journeys work; keeping track of everybody is the difficulty','The journeys are clear and work as intended'),
'structure':('The arrangement is not producing the experience I want','The arrangement is deliberate; keeping the whole structure visible is hard','The arrangement already produces the experience I want'),
'object':('There is no intended explanation; the appearances need to agree','The explanation exists; keeping the handovers or history straight is hard','There is a deliberate explanation and I can keep it straight'),
'place':('It is an unintended change to an established place','The change is deliberate; keeping the place’s history straight is hard','The change is deliberate and its history is clear'),
'progression':('The rhythm is weakening the movement I want','The rhythm is deliberate; seeing how it develops is hard','The rhythm already gives the reader the experience I want'),
'arc':('I want the events to affect the character more clearly','The arc is deliberate; keeping its small changes visible is hard','The character is steady or changing just as I want'),
'change':('I need to repair the consequences of a change','I want to compare alternatives while keeping the current version safe','The change works, and I can follow its consequences'),
'series':('I keep finding or fearing conflicts with the earlier books','The long span is intentional; remembering established material is hard','I can already follow the facts and threads across the books'),
'overload':('Keeping everything organised is taking attention away from writing','The complexity is intentional; I need less work to keep track of it','The organisation is helping me write and nothing is slipping'),
'facts':('It is an unintended conflict in an established fact','The change is intentional; keeping the versions or history straight is hard','The difference is intentional and I can follow it clearly')}
# Solution eligibility records precisely which corroborating observation is needed.
groups={
'threads':['d01'],'dormancy':['d02'],'connection':['d03'],'imbalance':['d04'],'purpose':['d05'],'payoff':['d06'],'causality':['d07'],
'cast':['d08'],'roles':['d09'],'presence':['d10'],'proportions':['d11'],'pov':['d12'],'character-facts':['d13'],'whereabouts':['d14'],
'relationship-network':['d15'],'relationship-state':['d16'],'relationship-speed':['d17'],'relationship-stall':['d18'],'relationship-perspective':['d19'],'relationship-event':['d20'],
'premature-knowledge':['d21'],'knowledge-source':['d22'],'pov-knowledge':['d23'],'reveal':['d24'],'clues':['d25'],'reader-reveal':['d26'],
'calendar':['d27'],'elapsed':['d28'],'age':['d29'],'nonlinear':['d30'],'parallel':['d31'],'fixed':['d32'],'scene-volume':['d33'],'scene-position':['d34'],'chapters':['d35'],'repetition':['d36'],'experiment':['d37'],'movement':['d38'],'place-state':['d39'],'object-track':['d40'],'custody':['d41'],'object-history':['d42'],'story-stall':['d43'],'pace':['d44'],'tension':['d45'],'arc':['d46'],'late':['d47'],'dependencies':['d48'],'versions':['d49'],'series-memory':['d50'],'series-thread':['d51'],'whole-load':['d52']}
for s in g['solutions']:
evidence=next(k for k,v in groups.items() if s['id'] in v)
s['requiredSignals']={'observed-'+evidence:1,'concern-confirmed':1}
# Character facts need a specific observation, not a calendar contradiction.
f['facts']=family('facts','When you compare the two passages, what cannot both be true?',[
('detail','An established appearance, background or other character fact changes',['character-facts'],{}),('age','The age and the dates cannot both be right',['age'],{}),('knowledge','The facts are consistent; the character knows something they have not learned',['premature-knowledge'],{})], 'Is the discrepancy intentional, or an established fact you need to keep consistent?')
# A changed hypothesis needs positive evidence of its own, not just removal of the first result.
# These new observations carry the existing core signals they explicitly establish.
additional={
('check-threads','apart'):{'plot-connection':4},
('dominance-observation','gaps'):{'plot-dormancy':4},
('check-progression','late'):{'late-concentration':4},
('check-progression','uneven'):{'distribution':3},
('check-progression','nothing'):{'flat-progression':4},
('check-progression','character'):{'character-arc':6,'flat-progression':1},
('check-cast','gap'):{'character-presence':6},
('check-cast','share'):{'character-presence':6,'distribution':2},
('check-cast','voice'):{'pov':6},
('check-cast','same-job'):{'role-overlap':5},
('check-whereabouts','journey'):{'duration':2}}
for (nid,cid),weights in additional.items():
next(c for c in nodes[nid]['choices'] if c['id']==cid)['weights'].update(weights)
# A management concern elsewhere must not stand in for creative intention here.
# Creative diagnoses always need an actual intention answer, even on a long/series route.
creative={'d02','d03','d04','d05','d06','d07','d09','d11','d12','d17','d18','d19','d26','d30','d35','d36','d39','d43','d44','d45','d46','d47'}
for solution in g['solutions']:
if solution['id'] in creative:solution['requiredSignals']['creative-concern']=1
for n in g['nodes']:
if n['id'].startswith('intent-'):
for c in n['choices']:
if c['id'] in ('unwanted','manage'):c['weights']['creative-concern']=1
next(c for c in nodes['dominance-intention']['choices'] if c['id']=='even')['weights']['creative-concern']=1
# Retain genuinely corroborated support, not merely the first label selected.
# These paired observations explicitly concern both the specific and broader management problem.
paired={('check-cast','same-job'):['cast'],('check-facts','age'):['character-facts'],
('check-structure','volume'):['whole-load'],('check-whereabouts','journey'):['elapsed'],
('check-place','facts'):['object-history'],('check-progression','tension'):['pace'],
('check-progression','late'):['pace'],('check-change','versions'):['experiment']}
for (nid,cid),signals in paired.items():
next(c for c in nodes[nid]['choices'] if c['id']==cid)['weights'].update({'observed-'+signal:1 for signal in signals})
# Original symptom choices retain all weights. Add routes only where no specialised continuation applies.
family_nodes={
'track-knowledge':'knowledge','track-time':'time','track-plots':'threads','track-places':'whereabouts','track-objects':'object','track-structure':'structure',
'story-problem':'threads','story-view':'threads','story-connection':'causality','story-payoff':'payoff','feel-how':'progression','flow-target':'progression','flow-whole':'progression','flow-thread':'threads','flow-character':'arc','flow-relationship':'relationships','flow-tension':'progression',
'continuity-character':'facts','continuity-time':'time','continuity-object':'object','change-what':'change','change-damage':'change','change-order':'change','change-knowledge':'knowledge','scale-effect':'overload','series-what':'series','series-thread':'series','cast-size':'cast','cast-presence':'cast','relationship-map':'relationships','time-duration':'time','time-parallel':'time','time-nonlinear':'time','character-meeting':'relationships','track-people':'cast','continuity-what':'time'}
# Choice-specific discrimination follows the actual symptom instead of a domain catch-all.
special={('story-problem','takes-over'):'dominance-observation',('story-problem','scene-contribution'):f['purpose'],('story-problem','events-dont-build'):f['causality'],('story-problem','dont-connect'):f['threads'],('continuity-what','knowledge'):f['knowledge'],('continuity-what','where-person'):f['whereabouts'],('continuity-what','wrong-point'):f['time'],('track-places','details'):f['place'],('cast-size','details'):f['facts']}
nodes['track-what']['maxChoices']=2
nodes['track-what']['help']='Choose up to two areas that are troubling you most. We will follow the more specific concern first; you can restart for another area.'
# Stable existing specialised routes run first. Low-priority continuations serve genuine leaf answers only.
for id,fam in family_nodes.items():
n=nodes[id]
# Drop accidental exact duplicate place routes from the supplied source.
n['routes']=list({json.dumps(r,sort_keys=True):r for r in n['routes']}.values())
for c in n['choices']:
if c.get('fallback') and not c.get('weights'): continue
existing=any(r.get('choice')==c['id'] for r in n['routes'])
if (id,c['id']) in special:
n['routes']=[r for r in n['routes'] if r.get('choice')!=c['id']]
route(id,special[(id,c['id'])],c['id'],110)
elif not existing:route(id,f[fam],c['id'],-100)
route('flow-relationship',f['series'],priority=20)
nodes['flow-relationship']['routes'][-1].update(signal='series',minimum=4)
for id,texts in intent_copy.items():
for choice,text in zip(nodes['intent-'+id]['choices'],texts):choice['text']=text
# A management difficulty or explicitly unwanted gap already states why help is wanted.
# Do not repeat that intention question after the author corroborates the concrete consequence.
# Creative balance, relationship/character progression, pace and deliberate narrative order still ask intention.
implicit={
'track-knowledge':['when-learned','who-told','checking','who-knows-fact'],
'track-time':['what-day','manual-calculations'],
'track-plots':['active','where-appear','forgotten','disappears','too-much'],
'track-places':['where-character','previous-location','scenes-there','who-visited','too-many'],
'track-objects':['where','who-has','changes-hands','what-happened','where-appears'],
'track-structure':['where-scene','too-many'],
'cast-size':['forget-minor','too-many'],
'relationship-map':['too-many','how-know','family','friends','romances','enemies'],
'scale-effect':['search','notes','reread','forget','organise','all'],
'time-duration':[c['id'] for c in nodes['time-duration']['choices'] if not c['fallback']],
'time-parallel':['where','doing','parallel'],
'series-what':[c['id'] for c in nodes['series-what']['choices'] if not c['fallback']],
'series-thread':[c['id'] for c in nodes['series-thread']['choices'] if not c['fallback']],
'change-order':['one-scene','several','different-structure','compare','safe-experiment']}
for nid,ids in implicit.items():
for c in nodes[nid]['choices']:
if c['id'] in ids:c['weights']['concern-confirmed']=1
for n in g['nodes']:
if n['id'].startswith(('check-','intent-')):n['requireAnswer']=False
# Narrow the follow-up to the live hypothesis and its nearest competing explanation.
# The full family menu is not shown after an already specific symptom.
subset={
'knowledge':{'knows-too-early':['no-source','source','order'],'when-learned':['source','no-source'],'who-told':['source','no-source'],'pov-differences':['povs','no-source','order'],'secrets':['reader','order','povs'],'clues':['clues','source'],'moving-scenes':['order','no-source','reader'],'checking':['source','povs'],'reader-too-early':['reader','order'],'who-knows-fact':['povs','source'],'knows-too-early-change':['order','no-source']},
'time':{'what-day':['clash','elapsed'],'elapsed':['elapsed','clash'],'dates-conflict':['clash','age'],'ages':['age','clash'],'reading-order':['reading','clash'],'real-dates':['fixed','clash'],'manual-calculations':['clash','elapsed'],'events-incompatible':['clash','age'],'too-little':['elapsed','travel'],'too-much':['elapsed','clash'],'travel':['travel','elapsed'],'age':['age','clash'],'reference-before':['clash','reading'],'moved-scenes':['clash','reading'],'pregnancy':['elapsed','clash'],'illness':['elapsed','clash'],'investigation':['elapsed','clash'],'development':['elapsed','clash'],'deadline':['elapsed','fixed'],'ordinary':['elapsed','clash'],'parallel':['parallel','clash'],'overlap':['parallel','clash'],'reaction':['parallel','clash'],'flashbacks':['reading','clash'],'periods':['reading','parallel'],'chapters':['reading','clash'],'memory':['reading','clash'],'back-forward':['reading','clash'],'characters':['reading','parallel']},
'relationships':{'stops':['repeat','moving'],'too-quick':['unprepared','stage'],'unearned':['unprepared','stage'],'stage':['stage','views'],'consequences':['ripples','network'],'different-view':['views','stage'],'see-development':['stage','moving'],'slow-but-moving':['moving','repeat'],'how-know':['network','stage'],'family':['network','stage'],'friends':['network','views'],'romances':['network','stage'],'enemies':['network','views'],'event-affects':['ripples','network'],'too-many':['network','ripples'],'first-meeting':['stage','network'],'whether-at-all':['stage','views'],'refers-before':['stage','views'],'too-advanced':['unprepared','stage'],'moved':['stage','ripples'],'shared-scenes':['stage','moving']},
'cast':{'interchangeable':['same-job','remember'],'who-they-are':['remember','same-job'],'forget-minor':['remember','same-job'],'importance':['share','remember'],'important-disappear':['gap','share'],'pov':['voice','share'],'too-many':['remember','same-job'],'major-barely':['gap','none'],'protagonist-disappears':['gap','none'],'minor-everywhere':['share','voice'],'pov-dominates':['voice','share'],'character-dominates':['share','voice'],'cant-see':['share','gap']},
'progression':{'nothing-changes':['nothing','character'],'too-much-at-once':['uneven','late'],'sudden':['uneven','character'],'too-long':['nothing','uneven'],'bunched':['uneven','late'],'disappears':['nothing','uneven'],'unnatural':['uneven','nothing'],'main-story':['nothing','uneven'],'everything':['nothing','uneven'],'slow-start':['uneven','nothing'],'middle-loses':['nothing','uneven'],'everything-end':['late','uneven'],'ending-rushed':['late','uneven'],'speed-changes':['uneven','nothing'],'long-flat':['nothing','character'],'cant-see-build':['nothing','uneven'],'shape-wrong':['uneven','nothing'],'flat':['tension','nothing'],'rises-disappears':['tension','uneven'],'jumps':['tension','uneven'],'end':['tension','late'],'peaks':['tension','uneven'],'cant-tell':['tension','nothing']},
'object':{'where':['track','holder'],'who-has':['track','holder'],'changes-hands':['track','holder'],'shouldnt-have':['holder','track'],'who-saw':['track','history'],'what-happened':['history','track'],'where-appears':['track','place'],'evidence':['track','history'],'wrong-person':['holder','track'],'wrong-place':['place','holder'],'before-acquired':['holder','history'],'destroyed':['history','place'],'changed':['history','track'],'lost-history':['history','track']},
'structure':{'where-scene':['place','purpose'],'chapter':['chapter','place'],'why-scene':['purpose','repeat'],'character-scenes':['volume','purpose'],'storyline-scenes':['purpose','volume'],'repeated':['repeat','purpose'],'chronological-position':['place','chapter'],'too-many':['volume','purpose']},
'threads':{'too-many':['lost','apart'],'disappears':['gap','apart'],'dont-connect':['apart','gap'],'active':['lost','gap'],'where-appear':['gap','lost'],'connect':['apart','lost'],'characters-between':['apart','lost'],'scenes-per-thread':['scenes','lost'],'forgotten':['gap','lost'],'too-much':['lost','gap'],'threads-separately':['lost','apart'],'overlaps':['apart','lost'],'scenes-advance':['scenes','apart'],'where-disappears':['gap','apart'],'what-dominates':['lost','apart'],'whole-story':['lost','apart'],'no-movement':['gap','apart'],'too-fast':['apart','gap'],'concentrated':['gap','apart'],'not-connect':['apart','gap']},
}
for n in list(g['nodes'][:44]):
for r in n['routes']:
if not r['target'].startswith('check-') or not r.get('choice'):continue
base=nodes[r['target']];fam=base['id'][6:]
ids=subset.get(fam,{}).get(r['choice'])
if not ids:continue
ident=base['id']+'-'+ '-'.join(ids)
if ident not in nodes:
variant=copy.deepcopy(base);variant['id']=ident;variant['choices']=[c for c in variant['choices'] if c['id'] in ids or c['fallback']];variant['routes']=[x for x in variant['routes'] if x.get('choice') in ids]
g['nodes'].append(variant);nodes[ident]=variant
r['target']=ident
# Any generic family node that is no longer referenced is editorial scaffolding, not a live question.
referenced={r['target'] for n in g['nodes'] for r in n['routes']}
g['nodes']=[n for n in g['nodes'] if not n['id'].startswith('check-') or n['id'] in referenced]
route('track-what','scale-effect','several',120)
# Keep the existing genuine neutral path short; normal endpoint engine rule remains untouched.
icons=['search','connections','pulse','shield-check','branch','shelf']
for c,icon in zip(nodes['entry']['choices'],icons):c['icon']=icon
# Knowledge and character role need observable distinctions before confirmation.
# A long-navigation path may use all six answers before resolving; no fabricated diagnosis is returned.
(folder/'writing-solver-curated-v2-stage1.json').write_text(json.dumps(g,ensure_ascii=False,indent=2)+'\n')