Build deterministic Guided Investigation foundation and continuous Review reading

This commit is contained in:
Nick Beckley 2026-11-17 14:47:06 +00:00
parent ea9ce69e8e
commit 78a84df52f
41 changed files with 5639 additions and 8 deletions

View File

@ -0,0 +1,33 @@
# Guided Investigation foundation — Phase3D.1
Implemented in authenticated Writer → Explore. The public Writing Problem Solver remains independent: no changes to its controllers, graph, pages, solution content, case data, SEO or URLs. Inspection covered SolverGraph, WritingSolverEngine/Traversal, WritingSolverRepository/Validator/Admin, authenticated workspace adapters and existing CuratedV2 case witnesses. Reused concepts are stable IDs, immutable structured publication, strict import validation, scoped workspace navigation and deterministic replay. The new engine does not reuse next-node traversal, cumulative uncapped affinity or public solution URLs.
## Boundaries
- `Models/Investigations/Contracts.cs`: catalogue, hypotheses, evidence, conditions, capabilities, author state and evaluation.
- `InvestigationEngine`: pure function over an immutable catalogue, concern, current answers, available capability IDs and optional continuation bound. No I/O, random, clock, manuscript, COM, AI or external inference dependencies.
- `CatalogueValidator`: version/schema/reference/weight/prerequisite/reachability validation before publication and on load.
- `DestinationRegistry`: trusted authenticated route adapters. Questions and answers contain no URLs. Application access is rechecked before opening a scoped destination.
- `InvestigationService`: book authority, private read, revision/invalidation, deterministic state evaluation, explicit persistence.
- `IInvestigationRepository`/Dapper implementation: only stored-procedure application access; isolated browser tests implement the same boundary in memory.
- `WriterInvestigationsController`: Development gate, author forms, no-store/noindex, CSRF, optimistic version, internal admin policy and diagnostic views.
The author UI uses existing layout/ribbon/theme and Markdown Help. Recommendations are authored strings plus actual supporting question/answer evidence. They never claim manuscript analysis. Opening a recommended tool uses a separate tab; the original investigation remains available. No objective, session, scene status, Word target or manuscript is changed by this engine.
## Persistence
Migration273 adds immutable `WriterInvestigationCatalogues`, author/book-scoped `WriterInvestigations` and append-only `WriterInvestigationEvents`. Every explicit action atomically stores the new aggregate and reproducible evaluation/history snapshot. Answers are current by question ID; earlier versions survive only in events. Revision prunes currently ineligible dependent answers from live evidence, retaining events. Questions presented are recorded on the transition, alongside next-question diagnostics. Multiple investigations have different UUIDs; no automatic overwrite or read-time creation.
SQL verifies active project/book membership plus author ownership for every investigation read/update/event replay. Catalogue version and scope cannot change on update; integer expected-version fencing prevents lost updates. Published catalogues cannot be replaced. Account/book cascades delete private investigations and their event history; catalogues remain as shared content. New rows are not added to shared project JSON exports. Normal database backup covers all three stores. List UI shows100 most recently updated investigations per book; direct private URLs can resume older records. Per-investigation persistence is bounded to1000 transitions and40 configured substantive answers.
Synthetic imports and author/admin endpoints are available only when the host is Development and `WriterInvestigations:Enabled` is not false. Production cannot enable this preview by setting that flag true. Catalogue validation currently requires Synthetic=true. Release/configuration work to enable real catalogues must be a separately qualified phase. No new native binary is needed.
## Later Feature Dependency Graph and Progressive Readiness
The user's additional requirements were recorded during implementation without restarting or refactoring this phase. Diagnostic evidence is independent of destination readiness: changing available capability IDs does not change support, opposition, conflicts, corroboration, scores or diagnostic coverage. Availability affects eligible actions and completion messaging only. This separation is explicitly tested.
Already useful: stable capability IDs, a separate resolver boundary, declared context/authority, availability, explicit prerequisites, hypothesis mappings, immutable catalogue versions and reproducible state. Capability prerequisites currently use answered-question conditions; this is intentionally small and is **not** a complete application dependency graph or book-readiness model. Five adapters are a synthetic test registry, not an inventory of implemented features. Optional chapter/scene/character contexts are not resolved in this phase; only authorised project/book adapters are implemented.
Future constraints to address: capability definitions currently live inside each immutable catalogue, the trusted resolver set is compiled, and prerequisite rules are flat all-answer/exclusion conditions. Do not grow those into an ad hoc feature graph. Introduce a separately versioned shared capability/dependency registry with typed context, requirement and readiness contracts; catalogues should refer to its stable IDs. Preserve old resolver aliases and pinned catalogue references. Readiness must produce missing-preparation facts and journeys, never evidence weights or diagnosis changes. Multi-step preparation should have a separate lifecycle from investigation answer revisions and recommendation history.
Safe sequence: (1) inventory existing implemented features and their actual permission/context/data requirements; (2) define and validate typed dependency edges, cycle policy and resolver aliases; (3) implement pure book-specific readiness with provenance and read-only queries; (4) introduce resumable preparation journeys and missing-prerequisite questions; (5) integrate readiness reasons with investigations without rescoring; (6) build the Feature Family Tree from the same model. Additive migrations can introduce the shared registry and journey state; retain existing catalogue JSON/events unchanged and use an adapter for schema1 imports/replay. Do not rewrite migration273 or repoint historical investigation versions. This later scope, production questions and Phase4 are not implemented here.

View File

@ -0,0 +1,17 @@
# Author experience and preservation
Development Writer → Explore offers “Explore a concern”. The initial invitation asks “What's troubling you about your story?” and reassures that the author need not know the answer. This preview is visibly labelled synthetic Development content and states that it uses questionnaire answers without AI/manuscript analysis. Existing direct authenticated Explore tools remain available.
Each page has one primary question, radio choices, optional plain-text explanation, Back/earlier-answer links, Continue and Save for later. A subtle answer count avoids a guaranteed completion promise. Forms have labels, fieldsets/legends and keyboard radio behaviour; controls use the existing theme. Narrow layouts use normal document flow. JavaScript only guards unsaved departure/duplicate submission; server forms, CSRF and validation are authoritative. Draft explanations can be saved without contributing evidence.
Answer revision recomputes current evidence and prerequisite eligibility. Append-only history retains superseded revisions; the author sees current answers only. Multi-window stale saves return409 with submitted explanation retained for copying; no optimistic overwrite. A service outage returns503 without implying a save succeeded. Author-private lists are scoped to the current book; starting again creates another investigation. Latest100 appear in the sidebar; older private URLs remain resumable.
Results use authored, tentative explanations, up to3 actual contributing question/answer examples per recommendation, uncertainty and eligible tool actions. Two supported explanations can coexist. Insufficient evidence or unavailable tools are acknowledged. Agree saves acceptance; disagree/further continues when eligible questions and the bound permit. Tools open in a new tab after scope/eligibility validation and explicit persisted selection. The investigation remains open to return to; reload after a tool launch before another versioned action.
## Separate continuous Review correction
Normal integrated Review now uses document/page scrolling. The main manuscript pane has no fixed/max height or overflow scroll; comfortable existing Reader typography/width/paragraph formatting remain. Desktop companion is independently sticky with a viewport-bounded utility scroll; narrow companion uses a fixed accessible overlay. This does not constrain manuscript height. Resizing/collapse controls remain.
The existing Reader's accepted update/selection/pause rules remain. Its anchor restoration uses window scrolling for ordinary integrated Review, and the existing Reader scrollport only in Focused Reading. Chapter navigation, observation references/decisions and verified acknowledged Word handoff are unchanged. No canonical Reader storage/service or manuscript mutation architecture was rewritten. Browser qualification covers long prose, page scroll, focused reading, selection and retained companion interactions.
Physical screen-reader, installed PWA, real Word/media and multiple-monitor acceptance remain manual; portable browser tests simulate standalone display mode and native acknowledgements where specified.

View File

@ -0,0 +1,26 @@
# Catalogue schema1 and editorial workflow
The validated example is [synthetic-catalogue.json](synthetic-catalogue.json). It has4 concerns,5 hypotheses,28 questions,6 dimensions and5 authenticated capability adapters. This is Development/test content, not a production matrix. JSON uses case-insensitive property reads, rejects unknown members, and exports the complete structured definition. IDs are ordinal/case-sensitive stable strings,1–80 ASCII letters/digits/dot/underscore/hyphen; use kebab-case consistently. Published versions are immutable.
| Object | Fields and meaning |
|---|---|
| Catalogue | SchemaVersion=1; unique Version; Synthetic=true; MinAnswers/MaxAnswers (2–40 valid bounds); Dimensions; Concerns; Hypotheses; Questions; Capabilities |
| Concern | Id, Text, Priors mapping valid hypothesis IDs to0–2 |
| Hypothesis | Id, Description, Summary/Reason/Uncertainty authored explanation templates; allowed Dimensions; Capabilities; MinDimensions≥2; MinGroups≥2; Threshold; Eligibility |
| Question | Id, Text, Help, Purpose, Group, InformationValue0–20, Hypotheses, Dimensions, Clarifies, AllowExplanation, Eligibility, Retired, optional ReplacedBy, Options |
| Purpose | Discovery, Discrimination, Corroboration, Challenge, Clarification, ActionPreference |
| Option | Id (unique within question), Text, Uncertain, optional Interpretation, Contributions |
| Contribution | Hypothesis, Dimension, Aspect, Weight−3…+3; references must appear in question/hypothesis mappings; duplicate triples prohibited |
| Interpretation | Empty ordinarily; Clarification may use different-aspects, revised-understanding, confirm-conflict, uncertain. Only explicit different-aspects clears the material same-aspect conflict; revisions recalculate evidence |
| Rule | MinAnswers; AllAnswers object mapping question IDs to allowed option-ID arrays; ExcludeAnswered list. All conditions conjunctive |
| Capability | Id, Name, Description, Resolver, ActionText, Available, RequiresBook, RequiresProject, Context, Authority, Prerequisites |
Schema1 capability Context is project or book; Authority must be ProjectAccess. Trusted resolvers: Write, Characters, PlotThreads, Timeline, Relationships. No external/public URL field exists. Chapter/scene/character-specific availability and graph requirements are extension points, not invented schema1 behaviour. Capabilities may be disabled at runtime with `WriterInvestigations:Capabilities:<id>:Enabled=false`, independently of pinned catalogue content and diagnostic evidence.
AdminOnly users in Development can inspect `/admin/writer-investigations`, validate JSON without saving, publish a new version or export current/specified version. Invalid input writes nothing. Use a new version for every publication; existing investigations keep their previous version. Preserve stable semantic IDs; retired questions may specify an existing active replacement but are not silently substituted into historical investigations. Export/import should be code reviewed and validated before future production activation.
Validation checks IDs, required wording/templates, all references/options/dimensions/weights, purposes, bounds, replacement status, rule self-reference/exclusion, prerequisite reachability/cycles, independent supporting dimensions/groups and challenge coverage for each hypothesis, and capability mappings/resolvers. Simulation adds reachable recommendation witnesses and adversarial paths. Structural prerequisite reachability is not an exhaustive proof of every semantic combination; use the automated simulator and authored acceptance cases when developing a richer matrix.
CLI: `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --writer-investigation-sim /absolute/output/coverage.json`. This validates the repository example, focused engine cases and representative deterministic simulations. It never publishes or calls external services. Database publication uses the existing stored-procedure repository after validation; do not bypass the admin validator for editorial imports. The initial Development seed was explicitly applied after backup/migration.
A later shared Feature Dependency Graph should have its own typed/versioned schema and registry; schema1 Rule is not a substitute. Keep an adapter for historical JSON and immutable events rather than rewriting old versions.

View File

@ -0,0 +1,15 @@
# Deterministic evidence scoring
Weights are bounded authored evidence strengths from−3 through+3, not probabilities. Starting-concern priors are0–2, influence question ordering/ranking only, and cannot satisfy the net-evidence threshold or coverage gates.
1. Last answer for a stable question ID wins. Superseded contributions are not added. Optional free text is stored, escaped and never interpreted by an inference service.
2. Each option may contribute to multiple hypotheses and dimensions with positive/negative/zero values. Uncertain options provide no substantive evidence.
3. For each hypothesis × dimension × corroboration group, retain the strongest positive and strongest negative contribution separately. Repeated versions of the same signal cannot add unlimited support.
4. For each dimension, cap summed support at+3 and opposition at−3 across groups. Support and opposition remain inspectable rather than cancelling invisibly. Net evidence is support+opposition; ranking score adds the starting prior.
5. Distinct supporting dimensions and independent supporting groups are counted separately. Positive scores alone cannot finish an investigation. Required gates: configured minimum answers (8 in syntheticv1), hypothesis threshold, at least2 dimensions and2 groups, a substantive relevant Challenge answer, evidence examining at least1 other hypothesis, no material same-aspect conflict, and an eligible capability. These are configurable catalogue requirements, not statistical confidence.
6. Opposing magnitudes≥2 in the same hypothesis/dimension/aspect create a material conflict. Different aspect keys do not conflict automatically. Relevant clarification questions receive priority. An explicit different-aspects answer acknowledges that the apparent conflict concerns distinct moments; scores retain both signals. A changed-understanding answer leaves the conflict pending until an earlier answer is actually revised. Confirm-conflict/uncertain answers leave it unresolved. Uncertain answers are distinct from contradictory substantive evidence.
7. Availability/prerequisite failures never modify diagnostic evidence or scores. The same evidence can support an explanation while the destination is unavailable. Eligibility and preparation are separate from support.
Investigations stop only after the gates, a configured upper bound (12 in syntheticv1), or exhaustion of eligible questions. Outcomes include supported recommendation, two plausible explanations, more information needed and no suitable destination. Two supported results within2 ranking points may be offered; exhausted ambiguous states can report ambiguity without offering unqualified tools. All-uncertain paths return insufficient evidence rather than pretending the starting prior is corroboration.
Diagnostics expose raw contributions, repeated dimension/group count, support, opposition, priors, coverage, conflicts and missing gates. This aggregation is intentionally conservative, deterministic and explainable; independent editorial calibration and a production catalogue are future work.

View File

@ -0,0 +1,13 @@
# Dynamic question selection
There is no next-question pointer. Remove retired/already-answered/ineligible questions. Eligibility supports minimum answer count, all specified question/options and exclusions. Question revision recomputes eligibility and invalidates dependent live answers as necessary.
Rank each eligible question deterministically:
`information value + 3×leading hypothesis overlap + 2×unexamined hypothesis/dimension pairs + 30×relevant unresolved conflicts + 15×leading challenge gaps + 8×leading corroboration gaps + 8 if discrimination covers both leaders`.
Leaders are the first two positive ranking hypotheses. Initial concern priors affect those leaders but do not constrain branches. Information value and content mappings come from the catalogue. Ties use stable question ID with ordinal comparison. No randomness, wall clock or unordered database traversal affects selection.
The chosen candidate and all alternative ranks/reasons are recorded with each explicit state transition. Developer diagnostics name overlapping leaders, unseen dimensions, conflicts, challenge/corroboration gaps and authored value. Those details do not appear in ordinary author screens. Already answered questions are not automatically repeated; earlier-answer links are explicit revisions. If revision invalidates a dependent answer, a later newly eligible presentation may ask it again with its obsolete answer excluded.
The initial synthetic experience is bounded8–12 substantive answers. Further/disagree requests raise the continuation minimum by2, capped at the configured maximum, without discarding answers. At the cap authors can revisit saved answers or begin a separate investigation; the system does not loop or promise certainty. An unanswered explanation can be saved as a draft without becoming diagnostic evidence.

View File

@ -0,0 +1,11 @@
# Phase3D.1 synthetic simulation qualification
Catalogue `synthetic-3d1-v1`:4 concerns,5 hypotheses,28 questions,6 dimensions,5 destinations. The machine-readable report accompanies Phase3D1 evidence. It records228 representative paths and2560 answer transitions: every starting concern × five target-hypothesis witnesses, uncertain and alternating adversarial paths, plus50 reproducible seeded random paths per concern. All5 hypotheses and5 destinations are reachable. Repeated questions, loops, premature recommendations, invalid destinations and non-deterministic replays:0.
The general story concern can reach character motivation and the Characters capability; the concern does not lock a branch. Tests also construct competing supported explanations, conflicting same-aspect answers, explicit different-aspects clarification, answer revision changing recommendations, redundant same-group evidence, unmet prerequisites, upper-bound uncertainty, unavailable destinations and further-investigation continuation. Availability changes leave diagnostic evidence and scores identical. Production cannot enable synthetic content through the feature flag.
SQL qualification exercises atomic state/events, private author ownership even against another active project member, cross-book denial, optimistic stale rollback and immutable catalogue publication. All SQL test mutations roll back. Authenticated Development acceptance and guarded cleanup are reported in Phase3D1-Report.md.
Browser/simulated-PWA tests use actual Razor/controllers and a clearly isolated in-memory repository for transport qualification: scoped Explore, concern-to-unexpected-destination witness, optional draft/resume, answer revision,409 retained text, CSRF400, cross-book/cross-user404, AdminOnly diagnostics/replay/import/export/version pinning, responsive radio keyboard behaviour and Help. No iframe or AI/inference requests occur. Separate tests verify long continuous Review document scrolling and focused reading/observations. Existing integrated Review, Word/session preservation and Writer layout regressions remain covered.
These are representative and targeted adversarial paths, not exhaustive enumeration of all3–4^28 combinations, statistical calibration, production editorial validation or physical accessibility/Windows acceptance. Before production, author literal acceptance witnesses for the real matrix, inspect ambiguity/dead-end distributions, validate typed capability readiness separately, and expand bounded simulation/state-space checks as the catalogue grows. Do not generate a production matrix from this synthetic sample.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -114,3 +114,7 @@ Phase3B qualified: quick popup, More drawer and full writer3.word article verifi
## Phase3C Development qualification complete
Application `78865cf` deployed in release `78865cf-20261116T230802Z`. Build,600 application checks,292 native preservation checks, browser suites and authenticated Development Review acceptance passed. Read-only data hashes matched; disposable account and observations were removed. Native1.0.0.40 is unchanged; physical Windows/media/installed-PWA/multiple-monitor acceptance remains manual. Review Help popup, More drawer and full article passed. See [Phase3C report](Phase3C-Report.md) for evidence and limitations. Phase4 has not started.
## Phase3D.1 Guided Investigation and continuous Review
`writer3.investigations` covers concern choice, optional explanation/draft, one-question flow, explicit saves, answer revision, independent private/book state, uncertain outcomes, authenticated tools and Development-only synthetic/no-AI boundaries. Existing Markdown micro/quick/More/full infrastructure is reused. `writer3.reviewing` now explains normal document scrolling and the accessible companion while preserving Focused Reading and accepted update rules. Browser/PWA Help qualification and live deployment evidence are in Phase3D1-Report.md.

View File

@ -364,3 +364,7 @@ Batches3C.1–3C.6 integrate the canonical Reader, pure chapter/scene intentions
## Phase3C Development qualification complete
Application `78865cf` deployed in release `78865cf-20261116T230802Z`. Build,600 application checks,292 native preservation checks, browser suites and authenticated Development Review acceptance passed. Read-only data hashes matched; disposable account and observations were removed. Native1.0.0.40 is unchanged; physical Windows/media/installed-PWA/multiple-monitor acceptance remains manual. Review Help popup, More drawer and full article passed. See [Phase3C report](Phase3C-Report.md) for evidence and limitations. Phase4 has not started.
## Phase3D.1 — Guided Investigation technical foundation
Explicitly authorised after Phase3C. Batches A–F implement the generic engine/contracts, evidence/selection, immutable catalogues/private history, synthetic28-question catalogue and simulator, authenticated Development Explore, and continuous Review page scrolling. Batch G qualifies build/harness, SQL, browser/PWA, Help and Development deployment. Public Solver and native Windows1.0.0.40 remain unchanged. Evidence/results and remaining manual limits are recorded in Phase3D1-Report.md. Production questions and Phase4 are not started. Later dependency/readiness scope is recorded without a mid-phase redesign; availability never changes diagnostic evidence.

View File

@ -363,3 +363,11 @@ Before substantial implementation, produce screen layouts and interaction states
Do not undertake an unbounded application-wide rewrite.
The successful outcome is not a new-looking Writer. It is a Writer that allows a novice author to begin immediately, supports sophisticated planning when desired, and preserves the powerful specialist and multi-screen facilities already built into PlotDirector.
## Authorised Phase3D.1 foundation amendment — 17 November2026
Guided Investigation is a separate deterministic, data-driven engine inside authenticated Explore. It uses weighted competing hypotheses, independent evidence dimensions/groups, challenges, clarification, dynamically selected questions, immutable catalogue versions and private resumable answer/recommendation history. It uses no external AI service and preserves the public Problem Solver. This phase implements only28 synthetic Development questions and a small destination registry; it does not generate the production matrix or begin Phase4.
Normal integrated Review is an explicit exception to viewport-contained work panels: long manuscript reading uses document/page scrolling, with the contextual companion remaining accessible. Focused Reading and canonical Reader semantics remain authoritative.
Subsequent Feature Dependency Graph and Progressive Readiness requirements are recorded in [investigation architecture](../Investigations/Architecture.md). Missing prerequisites must never alter diagnostic evidence. Complete capability inventory, typed dependency graph, book readiness, preparation journeys/questions and Feature Family Tree share a future dependency model; they are not added mid-phase. Preserve schema1 catalogue/event history through additive adapters/migrations.

View File

@ -0,0 +1,15 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('fs');
const base=process.env.PD_INV_BASE||'http://127.0.0.1:5238',identity=process.env.PD_INV_IDENTITY?JSON.parse(fs.readFileSync(process.env.PD_INV_IDENTITY)):null,w=identity||{UserID:4,book:12,other:13,project:7};
const report=JSON.parse(fs.readFileSync(process.env.PD_INV_COVERAGE||'Docs/Writer/Writer3/Evidence/Phase3D1/simulation.json'));const path=report.RepresentativePaths.find(p=>p.concern==='story'&&p.target==='motivation'&&p.recommendations.includes('motivation'));assert(path,'unexpected destination witness');
(async()=>{const browser=await chromium.launch();try{for(const pwa of[false,true]){const c=await browser.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(({user,pwa})=>{localStorage.setItem('plotdirector.desktop.v1.'+user,JSON.stringify({dismissedAt:Date.now()}));if(pwa)Object.defineProperty(navigator,'standalone',{value:true});},{user:w.UserID,pwa});const p=await c.newPage(),errors=[],external=[];p.on('pageerror',e=>errors.push(e.message));p.on('request',r=>{if(/openai|anthropic|generativelanguage|inference/i.test(r.url()))external.push(r.url());});if(identity){await p.goto(base+'/Account/Login');await p.locator('[name=Email]').fill(w.Email);await p.locator('[name=Password]').fill(w.Password);await Promise.all([p.waitForURL('**/Projects'),p.locator('button[type=submit]').click()]);}
await p.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);await p.getByRole('link',{name:'Explore a concern',exact:true}).click();assert((await p.locator('#investigation-question').textContent()).includes("What's troubling"));assert.equal(await p.locator('iframe').count(),0);if(process.env.PD_INV_SCREENSHOTS&&!pwa){fs.mkdirSync(process.env.PD_INV_SCREENSHOTS,{recursive:true});await p.screenshot({path:process.env.PD_INV_SCREENSHOTS+'/Explore-investigation-start.png'});}
await p.locator('[name=concern][value=story]').check();await p.getByRole('button',{name:'Begin',exact:true}).click();await p.locator('[data-investigation-answer]').waitFor();const id=new URL(p.url()).searchParams.get('id'),url=p.url();const explanation=p.locator('#investigation-explanation');await explanation.fill('Unfinished explanation retained for later');await p.getByRole('button',{name:'Save for later',exact:true}).click();assert.equal(await p.locator('#investigation-explanation').inputValue(),'Unfinished explanation retained for later');
let firstQuestion;for(const entry of path.answers){const form=p.locator('[data-investigation-answer]');if(!await form.count())break;const current=await form.locator('[name=question]').inputValue();firstQuestion??=current;const expected=path.answers.find(x=>x.startsWith(current+'='));assert(expected,'dynamic current question is in deterministic witness');await form.locator(`[name=option][value="${expected.split('=')[1]}"]`).check();await form.locator('[name=explanation]').fill('Synthetic browser answer <script>text only</script>');await form.locator('button[value=answer]').click();}
assert.equal(await p.locator('[data-investigation-answer]').count(),0);assert((await p.locator('#investigation-question').textContent()).includes('possible next step'));assert((await p.locator('body').textContent()).includes('Character'));assert.equal(external.length,0);const open=p.locator('form[action$="/Open"]').first();const formData=await open.evaluate(f=>Object.fromEntries(new FormData(f)));formData.capability=await open.locator('[name=capability]').getAttribute('value');const destination=await p.request.post(base+'/Writer/Explore/Investigate/Open',{form:formData,maxRedirects:0});assert.equal(destination.status(),302);assert(!destination.headers().location.toLowerCase().includes('solver'));assert(destination.headers().location.includes('projectId='+w.project));assert(destination.headers().location.includes('bookId='+w.book));await p.reload();
if(process.env.PD_INV_SCREENSHOTS&&!pwa)await p.screenshot({path:process.env.PD_INV_SCREENSHOTS+'/Explore-investigation-result.png'});
assert.equal((await p.request.get(`${base}/Writer/Explore/Investigate?bookId=${w.other}&id=${id}`)).status(),404);assert.equal((await p.request.post(base+'/Writer/Explore/Investigate/Start',{form:{bookId:String(w.book),concern:'story'},maxRedirects:0})).status(),400);
firstQuestion='motivation-4';await p.goto(url+'&question='+firstQuestion);const stale=await p.locator('[data-investigation-answer]').evaluate(f=>Object.fromEntries(new FormData(f)));stale.operation='answer';stale.option='unsure';stale.explanation='Keep this stale browser text';const q=await c.newPage();await q.goto(url+'&question='+firstQuestion);await q.locator('[name=option][value=yes]').check();await q.locator('button[value=answer]').click();await q.close();const conflict=await p.request.post(base+'/Writer/Explore/Investigate/Answer',{form:stale,maxRedirects:0});assert.equal(conflict.status(),409);assert((await conflict.text()).includes('Keep this stale browser text'));await p.goto(url);assert((await p.locator('body').textContent()).includes('questions answered'));
await p.setViewportSize({width:390,height:844});assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await p.locator('[name=option]').first().focus();await p.keyboard.press('Space');assert(await p.locator('[name=option]').first().isChecked());if(process.env.PD_INV_SCREENSHOTS&&!pwa)await p.screenshot({path:process.env.PD_INV_SCREENSHOTS+'/Explore-investigation-narrow.png'});await p.locator('[data-help-key="writer3.investigations"] button').click();await p.locator('.plotline-help-popover').waitFor();await p.locator('.plotline-help-more').click();await p.locator('[data-help-content] .help-drawer-article').waitFor();await p.locator('[data-help-close]').click();
if(!identity){assert.equal((await p.request.get(base+'/admin/writer-investigations')).status(),403);const other=await browser.newContext();await other.addCookies([{name:'fixture-user',value:'5',url:base}]);assert.equal((await other.request.get(url)).status(),404);await other.close();await c.addCookies([{name:'solver-reviewer',value:'true',url:base}]);assert.equal((await p.request.get(base+'/admin/writer-investigations')).status(),200);const diag=await(await p.request.get(`${base}/admin/writer-investigations/diagnostics?bookId=${w.book}&id=${id}`)).json();assert(diag.events.length>8);assert(diag.evaluation.candidates.length>0);const sim=await p.request.get(`${base}/admin/writer-investigations/simulator?bookId=${w.book}&id=${id}`);assert.equal(sim.status(),200);assert(!(await sim.text()).includes('matches: False'));const exp=await(await p.request.get(base+'/admin/writer-investigations/export')).json();assert(exp.Synthetic);assert.equal(diag.investigation.catalogueVersion,exp.Version);if(!pwa){const admin=await p.request.get(base+'/admin/writer-investigations');const token=(await admin.text()).match(/name="__RequestVerificationToken"[^>]*value="([^"]+)"/)[1];const bad=structuredClone(exp);bad.Questions[0].Options[0].Contributions[0].Weight=99;assert.equal((await p.request.post(base+'/admin/writer-investigations',{form:{json:JSON.stringify(bad),operation:'publish',__RequestVerificationToken:token}})).status(),400);assert.equal((await(await p.request.get(base+'/admin/writer-investigations/export')).json()).Version,exp.Version);exp.Version='synthetic-browser-next';assert.equal((await p.request.post(base+'/admin/writer-investigations',{form:{json:JSON.stringify(exp),operation:'publish',__RequestVerificationToken:token}})).status(),200);assert.equal((await(await p.request.get(base+'/admin/writer-investigations/export')).json()).Version,exp.Version);assert.notEqual((await(await p.request.get(`${base}/admin/writer-investigations/diagnostics?bookId=${w.book}&id=${id}`)).json()).investigation.catalogueVersion,exp.Version);}
}
assert.deepEqual(errors,[]);await c.close();}console.log('PASS Guided Investigation browser/simulated PWA: authenticated Explore, dynamic deterministic witness from general concern to character destination, saved unfinished explanation, resume, authored evidence summary, safe scoped destination, CSRF400, cross-book404, stale409 retained text, revision, narrow keyboard/radio/overflow, Markdown Help, no iframe or AI calls; isolated admin diagnostics/replay and cross-user controls where enabled.');}finally{await browser.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});

View File

@ -1,3 +1,3 @@
const{chromium}=require('playwright'),assert=require('node:assert/strict');
(async()=>{const b=await chromium.launch();try{const p=await b.newPage({viewport:{width:1440,height:1000}});for(const destination of['Write','Explore','Plan','Review','Reflect']){const r=await p.goto(`http://127.0.0.1:5238/Writer/${destination}?projectId=7&bookId=12`);assert.equal(r.status(),200);await p.waitForFunction(()=>document.querySelector('.writer3')?.classList.contains('writer3-viewport'));await p.evaluate(async()=>{await document.fonts.ready;await new Promise(r=>setTimeout(r,50))});const normal=await p.evaluate(()=>({header:document.querySelector('.writer3-header').getBoundingClientRect().height,bottom:document.querySelector('.writer3-workspace').getBoundingClientRect().bottom,height:innerHeight}));assert(normal.header<85,'compact shared header');assert(normal.height-normal.bottom<12,'uses available viewport');await p.evaluate(()=>{document.documentElement.style.overflow='auto';document.documentElement.style.height='auto';document.body.style.overflow='visible';document.body.style.height='auto';document.body.style.minHeight='1800px';document.body.style.paddingTop='180px';window.scrollTo({top:150,behavior:'instant'});window.dispatchEvent(new Event('resize'));});await p.waitForFunction(()=>{const w=document.querySelector('.writer3-workspace');return Math.abs(innerHeight-w.getBoundingClientRect().bottom)<12});assert(await p.evaluate(()=>window.scrollY>100),'scrolled shell fixture');}
(async()=>{const b=await chromium.launch();try{const p=await b.newPage({viewport:{width:1440,height:1000}});for(const destination of['Write','Explore','Plan','Review','Reflect']){const r=await p.goto(`http://127.0.0.1:5238/Writer/${destination}?projectId=7&bookId=12`);assert.equal(r.status(),200);await p.waitForFunction(()=>document.querySelector('.writer3')?.classList.contains('writer3-viewport'));await p.evaluate(async()=>{await document.fonts.ready;await new Promise(r=>setTimeout(r,50))});const normal=await p.evaluate(()=>({header:document.querySelector('.writer3-header').getBoundingClientRect().height,bottom:document.querySelector('.writer3-workspace').getBoundingClientRect().bottom,height:innerHeight}));assert(normal.header<85,'compact shared header');if(destination!=='Review')assert(normal.height-normal.bottom<12,'uses available viewport');await p.evaluate(()=>{document.documentElement.style.overflow='auto';document.documentElement.style.height='auto';document.body.style.overflow='visible';document.body.style.height='auto';document.body.style.minHeight='1800px';document.body.style.paddingTop='180px';window.scrollTo({top:150,behavior:'instant'});window.dispatchEvent(new Event('resize'));});if(destination!=='Review')await p.waitForFunction(()=>{const w=document.querySelector('.writer3-workspace');return Math.abs(innerHeight-w.getBoundingClientRect().bottom)<12});else assert(await p.evaluate(()=>getComputedStyle(document.querySelector('.writer3-main')).overflowY==='visible'),'Review flows in document');assert(await p.evaluate(()=>window.scrollY>100),'scrolled shell fixture');}
await p.goto('http://127.0.0.1:5238/Writer/Explore?projectId=7&bookId=12');const links=await p.locator('.writer3-explore-paths>a').evaluateAll(ns=>ns.map(n=>n.href));assert.equal(links.length,3);for(const href of links){const u=new URL(href);assert(!u.pathname.includes('problem-solver'));assert.equal(u.searchParams.get('projectId'),'7');assert.equal(u.searchParams.get('bookId'),'12');}assert.equal(new Set(links.map(x=>new URL(x).pathname)).size,3);assert.equal(await p.locator('iframe').count(),0);console.log('PASS five destinations compact viewport use and controlled scrolled-shell geometry; Explore has three distinct authenticated scoped tool routes and no public solver/iframe.');}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});

View File

@ -0,0 +1,4 @@
const{chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('fs');
(async()=>{const b=await chromium.launch();try{for(const pwa of[false,true]){const p=await b.newPage({viewport:{width:1440,height:900}});if(pwa)await p.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));for(const width of[1440,1024,390]){await p.setViewportSize({width,height:900});await p.goto('http://127.0.0.1:5238/Writer/Review?projectId=7&bookId=12&reader-long=true');await p.waitForFunction(()=>document.querySelector('.writer3')?.classList.contains('writer3-flow'));const dimensions=await p.evaluate(()=>{const main=document.querySelector('.writer3-main');return{overflow:getComputedStyle(main).overflowY,doc:document.documentElement.scrollHeight,main:main.clientHeight,mainScroll:main.scrollHeight,viewport:innerHeight}});assert.equal(dimensions.overflow,'visible');assert(dimensions.doc>dimensions.viewport+1500,'long manuscript extends document');assert(dimensions.main>=dimensions.mainScroll-3,'no manuscript nested scroll');await p.evaluate(()=>window.scrollTo({top:1400,behavior:'instant'}));assert(await p.evaluate(()=>scrollY>1000));assert.equal(await p.locator('.writer3-main').evaluate(n=>n.scrollTop),0);if(width>=1440){const top=await p.locator('.writer3-reference').evaluate(n=>n.getBoundingClientRect().top);assert(top>=0&&top<100,'companion remains accessible while manuscript scrolls');}
const anchor=await p.evaluate(()=>{const root=document.querySelector('.manuscript-reader'),restore=root.readerPreserveView();const visible=[...document.querySelectorAll('#reader-content [data-paragraph-id]')].find(n=>n.getBoundingClientRect().bottom>0),top=visible.getBoundingClientRect().top;document.querySelector('#reader-content').style.paddingTop='180px';restore();return{before:top,after:visible.getBoundingClientRect().top}});assert(Math.abs(anchor.before-anchor.after)<3,'Reader restores document anchor');
await p.locator('#reader-focus').click();assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');assert.equal(await p.locator('.manuscript-reader').evaluate(n=>getComputedStyle(n).overflowY),'auto');await p.locator('#reader-focus').click();assert.equal(await p.locator('.writer3-main').evaluate(n=>getComputedStyle(n).overflowY),'visible');await p.locator('#reader-content [data-paragraph-id]').nth(4).click();await p.locator('[data-review-record]').click();assert(await p.locator('[data-review-form]').isVisible());await p.locator('[data-review-cancel]').click();if(width===390)await p.keyboard.press('Escape');assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}await p.close();}console.log('PASS continuous Review: long canonical Reader flows through document at1440/1024/390 in browser/simulated PWA; no nested manuscript scroll, document anchor restoration, Focused Reading and passage observation overlay retained.');}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});

View File

@ -72,10 +72,10 @@ const width=p=>p.locator('.writer3-reference').evaluate(n=>n.getBoundingClientRe
for(const theme of ['modern-dark','modern-light','warm-dark','plotdirector'])for(const size of [{width:390,height:844},{width:1024,height:768},{width:1440,height:900},{width:1920,height:1080},{width:2560,height:1440}])for(const d of ['Write','Explore','Plan','Review','Reflect']){
await page.setViewportSize(size);const response=await page.goto(url(d));assert.equal(response.status(),200,`workspace ${d} HTTP status at ${page.url()}`);assert.equal(await page.locator('[data-ribbon-shell]').count(),1,`application shell missing at ${page.url()}`);await page.waitForFunction(()=>typeof window.PlotDirectorApplyApplicationTheme==='function').catch(e=>{throw new Error(`Theme helper unavailable: ${d}/${theme}/${size.width} at ${page.url()}; page errors: ${errors.join('; ')}; ${e.message}`)});await page.waitForFunction(()=>document.querySelector('.writer3').classList.contains('writer3-viewport'));await page.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);await settle(page);
const geometry=await page.evaluate(()=>({x:document.documentElement.scrollWidth-innerWidth,y:document.documentElement.scrollHeight-innerHeight,bottom:document.querySelector('.writer3-workspace').getBoundingClientRect().bottom,root:document.querySelector('.writer3').className,height:document.querySelector('.writer3').style.cssText}));
assert(geometry.x<=2,`${d}/${theme}/${size.width} horizontal overflow ${JSON.stringify(geometry)}`);assert(geometry.y<=3,`${d}/${theme}/${size.width} unnecessary page scroll ${JSON.stringify(geometry)}`);
assert(geometry.bottom<=size.height+2);combinations++;
assert(geometry.x<=2,`${d}/${theme}/${size.width} horizontal overflow ${JSON.stringify(geometry)}`);if(d!=='Review')assert(geometry.y<=3,`${d}/${theme}/${size.width} unnecessary page scroll ${JSON.stringify(geometry)}`);else assert.equal(await page.locator('.writer3-main').evaluate(n=>getComputedStyle(n).overflowY),'visible');
if(d!=='Review')assert(geometry.bottom<=size.height+2);combinations++;
}
await page.setViewportSize({width:1440,height:1000});await page.goto(url('Review'));await settle(page);
await page.setViewportSize({width:1440,height:1000});await page.goto(url('Write'));await settle(page);
if(await page.locator('[data-ribbon-shell]').getAttribute('data-collapsed')==='true'){await page.locator('[data-ribbon-collapse]').click();await page.waitForFunction(()=>!document.querySelector('[data-ribbon-collapse]').disabled);await settle(page);}
const before=await page.locator('.writer3-split').evaluate(n=>n.clientHeight);
// Drive real shell collapse; isolate fixture appearance persistence from unrelated endpoint absence.

View File

@ -0,0 +1,17 @@
using System.Text.Json;
using PlotLine.Data;
using PlotLine.Models.Investigations;
using PlotLine.Services.Investigations;
// Isolated transport fixture. SQL isolation/concurrency/cascades are also qualified against Development separately.
internal sealed class InvestigationMemoryRepository:IInvestigationRepository
{
readonly Dictionary<string,string> catalogues=[];readonly Dictionary<Guid,string> rows=[];readonly Dictionary<Guid,List<string>> events=[];readonly object sync=new();string current="";
public InvestigationMemoryRepository(){var json=File.ReadAllText("Docs/Writer/Investigations/synthetic-catalogue.json");var c=CatalogueValidator.Parse(json);catalogues[c.Version]=json;current=c.Version;}
public Task<Catalogue?> Catalogue(string? version=null){lock(sync)return Task.FromResult(catalogues.TryGetValue(version??current,out var json)?CatalogueValidator.Parse(json):null);}
public Task Publish(string json,string actor){lock(sync){var c=CatalogueValidator.Parse(json);if(catalogues.ContainsKey(c.Version))throw new ArgumentException("Version already exists.");catalogues[c.Version]=json;current=c.Version;}return Task.CompletedTask;}
public Task<IReadOnlyList<Investigation>> List(int user,int book){lock(sync)return Task.FromResult<IReadOnlyList<Investigation>>(rows.Values.Select(Parse).Where(i=>i.UserID==user&&i.BookID==book).OrderByDescending(i=>i.UpdatedUtc).ToArray());}
public Task<Investigation?> Read(int user,int book,Guid id){lock(sync){var i=rows.TryGetValue(id,out var json)?Parse(json):null;return Task.FromResult(i?.UserID==user&&i.BookID==book?i:null);}}
public Task Save(Investigation i,int expected,string operation,Evaluation result){lock(sync){if(rows.TryGetValue(i.ID,out var old)){var prior=Parse(old);if(prior.Version!=expected||prior.UserID!=i.UserID||prior.BookID!=i.BookID)throw new ArgumentException("Stale or unavailable investigation");}else if(expected!=0)throw new ArgumentException("Missing investigation");i.Version=expected+1;rows[i.ID]=JsonSerializer.Serialize(i,CatalogueValidator.Json);if(!events.ContainsKey(i.ID))events[i.ID]=[];events[i.ID].Add(JsonSerializer.Serialize(new{operation,state=i,evaluation=result},CatalogueValidator.Json));}return Task.CompletedTask;}
public Task<string[]> Replay(int user,int book,Guid id){lock(sync){if(!rows.TryGetValue(id,out var json)||Parse(json).UserID!=user||Parse(json).BookID!=book)throw new UnauthorizedAccessException();return Task.FromResult(events[id].ToArray());}}
static Investigation Parse(string json)=>JsonSerializer.Deserialize<Investigation>(json,CatalogueValidator.Json)!;
}

View File

@ -0,0 +1,61 @@
using System.Text.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using PlotLine.Models.Investigations;
using PlotLine.Services.Investigations;
internal static class InvestigationTests
{
static string Root {get{var p=new DirectoryInfo(Directory.GetCurrentDirectory());while(p!=null&&!File.Exists(Path.Combine(p.FullName,"PlotLine.slnx")))p=p.Parent;return p?.FullName??throw new Exception("Repository not found");}}
static Catalogue Load()=>CatalogueValidator.Parse(File.ReadAllText(Path.Combine(Root,"Docs/Writer/Investigations/synthetic-catalogue.json")));
static void Check(bool b,string s){if(!b)throw new Exception(s);}
static void Reject(Action a){try{a();}catch(ArgumentException){return;}throw new Exception("Invalid catalogue accepted");}
static HashSet<string> All(Catalogue c)=>c.Capabilities.Select(d=>d.Id).ToHashSet();
static Evaluation E(Catalogue c,IEnumerable<Answer> a,string concern="story",ISet<string>? caps=null)=>InvestigationEngine.Evaluate(c,concern,a,caps??All(c));
public static void Run()
{
var c=Load();var start=E(c,[]);Check(start.AnswerCount==0&&start.NextQuestion!=null&&start.Recommendations.Count==0,"starting state");Check(E(c,[],"character").Hypotheses[0].Id=="motivation","concern activates prior");
var positive=E(c,[new("motivation-1","yes")]);Check(positive.Hypotheses.Single(h=>h.Id=="motivation").Support==3,"weighted positive");var negative=E(c,[new("motivation-1","no")]);Check(negative.Hypotheses.Single(h=>h.Id=="motivation").Opposition==-3,"negative evidence");
var duplicate=E(c,[new("motivation-1","yes"),new("motivation-2","yes")]);Check(duplicate.Hypotheses.Single(h=>h.Id=="motivation").Support==3&&duplicate.RedundantContributions==1,"redundancy capped");Check(!duplicate.Hypotheses.Single(h=>h.Id=="motivation").Supported,"same dimension not confident");
var corroboration=E(c,[new("motivation-1","yes"),new("motivation-3","yes")]);Check(corroboration.Hypotheses.Single(h=>h.Id=="motivation").Groups==2&&!corroboration.Hypotheses.Single(h=>h.Id=="motivation").Supported,"challenge and competitor required");
var a=new List<Answer>{new("motivation-1","yes"),new("motivation-2","no"),new("motivation-3","yes"),new("motivation-4","no"),new("change-1","no")};var conflict=E(c,a);Check(conflict.Hypotheses.Single(h=>h.Id=="motivation").Conflicts.Length==1,"genuine same-aspect conflict");Check(conflict.NextQuestion=="motivation-clarify","clarification selected");
a.Add(new("motivation-clarify","aspects"));Check(E(c,a).Hypotheses.Single(h=>h.Id=="motivation").Conflicts.Length==0,"explicit distinct aspects");
var revised=E(c,[new("motivation-1","yes"),new("motivation-1","no")]);Check(revised.Hypotheses.Single(h=>h.Id=="motivation").Support==0&&revised.Hypotheses.Single(h=>h.Id=="motivation").Opposition==-3,"superseded evidence removed");
Check(JsonSerializer.Serialize(E(c,a))==JsonSerializer.Serialize(E(c,a)),"deterministic replay");Check(E(c,[]).Candidates.All(q=>!q.Id.EndsWith("clarify")),"prerequisites exclude clarification");
var uncertain=c.Questions.Where(q=>q.Purpose!="Clarification").Take(12).Select(q=>new Answer(q.Id,"unsure")).ToArray();Check(E(c,uncertain).Recommendations.Count==0&&E(c,uncertain).NextQuestion==null,"bounded insufficient evidence");
Check(E(c,[new("motivation-1","yes")]).Recommendations.Count==0,"not early threshold");Check(DestinationRegistry.Resolve(c.Capabilities[0],1,2,false,new Dictionary<string,Answer>())==null,"unauthorised destination denied");Check(DestinationRegistry.Resolve(c.Capabilities[0],1,0,true,new Dictionary<string,Answer>())==null,"missing book denied");var dest=DestinationRegistry.Resolve(c.Capabilities[0],1,2,true,new Dictionary<string,Answer>());Check(dest?.Controller=="Characters","authenticated resolver");
var invalid=Load();invalid.Questions[0].Id=invalid.Questions[1].Id;Reject(()=>CatalogueValidator.Validate(invalid));invalid=Load();invalid.Questions[0].Options[0].Contributions[0].Weight=4;Reject(()=>CatalogueValidator.Validate(invalid));invalid=Load();invalid.Capabilities[0].Resolver="https://public.example";Reject(()=>CatalogueValidator.Validate(invalid));invalid=Load();invalid.Questions[0].Eligibility.AllAnswers[invalid.Questions[0].Id]=["yes"];Reject(()=>CatalogueValidator.Validate(invalid));invalid=Load();invalid.Hypotheses[0].Capabilities=["missing"];Reject(()=>CatalogueValidator.Validate(invalid));invalid=Load();invalid.SchemaVersion=2;Reject(()=>CatalogueValidator.Validate(invalid));Reject(()=>CatalogueValidator.Parse("{\"Questions\":null}"));
var i=new Investigation{Concern="story",Presented=["motivation-1"],Answers=[new("motivation-1","yes")]};InvestigationService.Answer(i,c,"motivation-1","no","Changed my understanding");Check(i.Answers.Count==1&&i.Answers[0].Option=="no","in-place answer revision");Reject(()=>InvestigationService.Answer(i,c,"change-1","yes",null));var round=JsonSerializer.Deserialize<Investigation>(JsonSerializer.Serialize(i,CatalogueValidator.Json),CatalogueValidator.Json)!;Check(round.Answers.SequenceEqual(i.Answers),"persistence round trip");
var supportedAnswers=new List<Answer>{new("motivation-1","yes"),new("motivation-2","yes"),new("motivation-3","yes"),new("motivation-4","no"),new("change-1","no"),new("change-2","no"),new("connections-1","no"),new("organisation-1","no")};
Check(E(c,supportedAnswers).Recommendations.Contains("motivation"),"independent corroboration + challenge permits recommendation");Check(E(c,supportedAnswers,caps:new HashSet<string>()).Outcome=="No suitable destination currently available","destination becoming unavailable is explicit");
var withTool=E(c,supportedAnswers);var withoutTool=E(c,supportedAnswers,caps:new HashSet<string>());Check(withTool.Hypotheses.Select(h=>(h.Id,h.Support,h.Opposition,h.Score,h.Dimensions,h.Groups,h.Challenged,h.Supported)).SequenceEqual(withoutTool.Hypotheses.Select(h=>(h.Id,h.Support,h.Opposition,h.Score,h.Dimensions,h.Groups,h.Challenged,h.Supported))),"missing prerequisites do not change diagnostic evidence");
var continued=InvestigationEngine.Evaluate(c,"story",supportedAnswers,All(c),10);Check(continued.NextQuestion!=null&&continued.Recommendations.Count==0,"author requests further investigation");
supportedAnswers.RemoveAll(a=>a.Question.StartsWith("motivation-"));supportedAnswers.AddRange(new Answer[]{new("motivation-1","no"),new("motivation-2","no"),new("motivation-3","no"),new("motivation-4","yes")});Check(!E(c,supportedAnswers).Recommendations.Contains("motivation"),"revision changes recommendation");
var ambiguous=new List<Answer>{new("motivation-1","yes"),new("motivation-3","yes"),new("motivation-4","no"),new("change-1","yes"),new("change-3","yes"),new("change-4","no"),new("connections-1","no"),new("organisation-1","no")};Check(E(c,ambiguous,"next").Recommendations.Count==2,"two supported plausible explanations");
invalid=Load();invalid.Questions[0].Eligibility.AllAnswers[invalid.Questions[1].Id]=["yes"];invalid.Questions[1].Eligibility.AllAnswers[invalid.Questions[0].Id]=["yes"];Reject(()=>CatalogueValidator.Validate(invalid));
var env=new TestEnvironment{EnvironmentName="Production"};Check(!new InvestigationAccess(env,new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"WriterInvestigations:Enabled","true"}}).Build()).Enabled,"Production cannot enable synthetic experience");env.EnvironmentName="Development";Check(new InvestigationAccess(env,new ConfigurationBuilder().Build()).Enabled,"Development preview enabled");
var report=Simulate();Check(report.UnreachableHypotheses.Length==0&&report.UnreachableDestinations.Length==0,"all hypotheses/destinations reachable");
}
sealed class TestEnvironment:Microsoft.AspNetCore.Hosting.IWebHostEnvironment {public string EnvironmentName{get;set;}="";public string ApplicationName{get;set;}="";public string WebRootPath{get;set;}="";public IFileProvider WebRootFileProvider{get;set;}=new NullFileProvider();public string ContentRootPath{get;set;}="";public IFileProvider ContentRootFileProvider{get;set;}=new NullFileProvider();}
public sealed record Coverage(int SchemaVersion,int Paths,int Steps,string[] Hypotheses,string[] Destinations,string[] UnreachableHypotheses,string[] UnreachableDestinations,int RepeatedQuestions,int Loops,int PrematureRecommendations,int InvalidDestinations,int NonDeterministic,List<object> RepresentativePaths);
public static Coverage Simulate(string? output=null)
{
var c=Load();var hypotheses=new HashSet<string>();var destinations=new HashSet<string>();var paths=new List<object>();int total=0,steps=0,repeats=0,loops=0,premature=0,invalid=0,nondeterministic=0;var random=new Random(31701);
// Every concern × target plus seeded adversarial/random/uncertain paths. No network/database/AI.
foreach(var concern in c.Concerns)foreach(var target in c.Hypotheses.Select(h=>h.Id).Concat(["uncertain","alternating","random"]))for(int seed=0;seed<(target=="random"?50:1);seed++)
{
total++;var answers=new List<Answer>();var seen=new HashSet<string>();Evaluation state=E(c,answers,concern.Id);var trace=new List<string>();
for(int n=0;n<=c.MaxAnswers;n++){
if(JsonSerializer.Serialize(state)!=JsonSerializer.Serialize(E(c,answers,concern.Id)))nondeterministic++;
if(state.NextQuestion==null)break;if(n==c.MaxAnswers){loops++;break;}if(!seen.Add(state.NextQuestion)){repeats++;break;}
var q=c.Questions.Single(q=>q.Id==state.NextQuestion);AnswerOption option;
if(target=="uncertain")option=q.Options.First(o=>o.Uncertain);else if(target=="alternating")option=q.Options[n%q.Options.Count];else if(target=="random")option=q.Options[random.Next(q.Options.Count)];else option=q.Options.OrderByDescending(o=>o.Contributions.Sum(e=>e.Hypothesis==target?e.Weight*20:-Math.Max(0,e.Weight))+(o.Interpretation=="different-aspects"?1:0)).ThenBy(o=>o.Id,StringComparer.Ordinal).First();
answers.Add(new(q.Id,option.Id));trace.Add(q.Id+"="+option.Id);steps++;state=E(c,answers,concern.Id);
if(state.Recommendations.Count>0&&answers.Count<c.MinAnswers)premature++;
}
foreach(var h in state.Recommendations){hypotheses.Add(h);foreach(var cap in c.Hypotheses.Single(x=>x.Id==h).Capabilities){var d=c.Capabilities.Single(x=>x.Id==cap);if(DestinationRegistry.Resolve(d,1,2,true,answers.ToDictionary(a=>a.Question))==null)invalid++;else destinations.Add(cap);}}
if(target!="random")paths.Add(new{concern=concern.Id,target,answers=trace,outcome=state.Outcome,recommendations=state.Recommendations,eligibility=state.Hypotheses});
}
var report=new Coverage(1,total,steps,hypotheses.Order().ToArray(),destinations.Order().ToArray(),c.Hypotheses.Select(h=>h.Id).Except(hypotheses).ToArray(),c.Capabilities.Select(d=>d.Id).Except(destinations).ToArray(),repeats,loops,premature,invalid,nondeterministic,paths);
if(output!=null)File.WriteAllText(output,JsonSerializer.Serialize(report,CatalogueValidator.Json));Check(repeats+loops+premature+invalid+nondeterministic==0,"simulation safety invariant");return report;
}
}

View File

@ -15,6 +15,7 @@ using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
if(args.Contains("--writer-investigation-sim")){InvestigationTests.Run();var output=args.SkipWhile(x=>x!="--writer-investigation-sim").Skip(1).FirstOrDefault();var report=InvestigationTests.Simulate(output);Console.WriteLine($"PASS investigation simulation: {report.Paths} paths, {report.Steps} answers; all hypotheses and destinations reachable; no loops/repeats/premature/invalid/non-deterministic outcomes.");return;}
if(args.Contains("--map-topology-database")){await MapGeographicHierarchyDatabaseTests.Run(args.Last(),true);return;}
if(args.Contains("--map-topology")){MapTopologyTests.Run();return;}
if(args.Contains("--map-geography-hierarchy-database")){await MapGeographicHierarchyDatabaseTests.Run(args.Last());return;}
@ -170,6 +171,7 @@ var tests = new (string Name, Action Test)[]
("Release triage and browser-only onboarding preserve author decisions", ReleaseSprintTests.Run),
("Approved native import source and confirmation remain safe", () => NativeImportTests.Run().GetAwaiter().GetResult()),
("Native installation renewal and revocation remain account/security scoped", () => NativeInstallationTests.Run().GetAwaiter().GetResult()),
("Guided investigation evidence, validation, revision and deterministic simulation",()=>InvestigationTests.Run()),
("Review accepted anchors, immutable provenance and author decisions",()=>WriterReviewTests.Run()),
("Writer Word verified navigation and acknowledgement",()=>WriterWordTests.Run().GetAwaiter().GetResult()),
("Writer inline authoring validation",()=>WriterAuthoringTests.Run()),

View File

@ -0,0 +1,44 @@
-- Development only; migration273 and synthetic catalogue required. All test writes roll back.
IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Wrong database',1;
DECLARE @u int=TRY_CONVERT(int,SESSION_CONTEXT(N'InvestigationTestUserID')),@b int=TRY_CONVERT(int,SESSION_CONTEXT(N'InvestigationTestBookID')),@p int=TRY_CONVERT(int,SESSION_CONTEXT(N'InvestigationTestProjectID')),@otherbook int=TRY_CONVERT(int,SESSION_CONTEXT(N'InvestigationTestOtherBookID'));
IF @u IS NULL OR @b IS NULL OR @p IS NULL OR @otherbook IS NULL THROW 51000,'Configure disposable fixture session context first',1;
IF NOT EXISTS(SELECT 1 FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID WHERE p.ProjectID=@p AND p.ProjectName=N'Disposable Writer Audit 20261116' AND a.UserID=@u AND a.AccessRole=N'Owner') THROW 51000,'Disposable fixture guard failed',1;
DECLARE @id uniqueidentifier=NEWID(),@json nvarchar(max),@event nvarchar(max)=N'{"test":true}';
SET @json=(SELECT @id ID,@u UserID,@b BookID,@p ProjectID,'synthetic-3d1-v1' CatalogueVersion,1 Version,'story' Concern FOR JSON PATH,WITHOUT_ARRAY_WRAPPER);
BEGIN TRANSACTION;
EXEC dbo.WriterInvestigation @Action='save',@UserID=@u,@BookID=@b,@ProjectID=@p,@ID=@id,@CatalogueVersion='synthetic-3d1-v1',@ExpectedVersion=0,@Json=@json,@Event=@event;
SET @json=JSON_MODIFY(@json,'$.Version',2);
EXEC dbo.WriterInvestigation @Action='save',@UserID=@u,@BookID=@b,@ProjectID=@p,@ID=@id,@CatalogueVersion='synthetic-3d1-v1',@ExpectedVersion=1,@Json=@json,@Event=@event;
IF (SELECT COUNT(*) FROM dbo.WriterInvestigationEvents WHERE InvestigationID=@id)<>2 THROW 51001,'Event history missing',1;
IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations WHERE ID=@id AND Version=2 AND CatalogueVersion='synthetic-3d1-v1') THROW 51001,'Resume/version state lost',1;
EXEC dbo.WriterInvestigation @Action='read',@UserID=@u,@BookID=@b,@ID=@id;
ROLLBACK;
SELECT 'PASS persisted update/resume, immutable catalogue binding, atomic event history; rollback clean' Result;
BEGIN TRY
BEGIN TRANSACTION;
SET @json=JSON_MODIFY(@json,'$.Version',1);
EXEC dbo.WriterInvestigation @Action='save',@UserID=@u,@BookID=@b,@ProjectID=@p,@ID=@id,@CatalogueVersion='synthetic-3d1-v1',@ExpectedVersion=0,@Json=@json,@Event=@event;
SET @json=JSON_MODIFY(@json,'$.Version',3);
EXEC dbo.WriterInvestigation @Action='save',@UserID=@u,@BookID=@b,@ProjectID=@p,@ID=@id,@CatalogueVersion='synthetic-3d1-v1',@ExpectedVersion=2,@Json=@json,@Event=@event;
THROW 51001,'Stale save accepted',1;
END TRY BEGIN CATCH IF XACT_STATE()<>0 ROLLBACK;IF ERROR_NUMBER()<>51002 THROW; END CATCH;
IF EXISTS(SELECT 1 FROM dbo.WriterInvestigations WHERE ID=@id) THROW 51001,'Stale rollback leaked',1;
SELECT 'PASS stale optimistic save rejected without leaked history' Result;
BEGIN TRY EXEC dbo.WriterInvestigation @Action='read',@UserID=@u,@BookID=@otherbook,@ID=@id;THROW 51001,'Cross-book read accepted',1;END TRY BEGIN CATCH IF ERROR_NUMBER()<>51000 THROW;END CATCH;
SELECT 'PASS cross-book identity denied' Result;
BEGIN TRY
BEGIN TRANSACTION;
EXEC dbo.User_Create @Email=N'investigation-other-disposable@example.invalid',@DisplayName=N'Disposable investigation SQL actor',@PasswordHash=N'not-a-login-hash',@EmailConfirmed=1;
DECLARE @otheruser int=(SELECT UserID FROM dbo.AppUser WHERE Email=N'investigation-other-disposable@example.invalid');
INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@p,@otheruser,N'Collaborator',1);
SET @json=JSON_MODIFY(@json,'$.Version',1);
EXEC dbo.WriterInvestigation @Action='save',@UserID=@u,@BookID=@b,@ProjectID=@p,@ID=@id,@CatalogueVersion='synthetic-3d1-v1',@ExpectedVersion=0,@Json=@json,@Event=@event;
EXEC dbo.WriterInvestigation @Action='read',@UserID=@otheruser,@BookID=@b,@ID=@id;
THROW 51001,'Other project member read private investigation',1;
END TRY BEGIN CATCH IF XACT_STATE()<>0 ROLLBACK;IF ERROR_NUMBER()<>51000 THROW; END CATCH;
SELECT 'PASS private investigation denied to another active project member; rollback clean' Result;
BEGIN TRY
DECLARE @catalogue nvarchar(max)=(SELECT Json FROM dbo.WriterInvestigationCatalogues WHERE Version='synthetic-3d1-v1');
EXEC dbo.WriterInvestigationCatalogue @Action='publish',@Version='synthetic-3d1-v1',@Json=@catalogue,@Actor=N'test';THROW 51001,'Published version overwritten',1;
END TRY BEGIN CATCH IF ERROR_NUMBER()<>51002 THROW;END CATCH;
SELECT 'PASS catalogue version overwrite rejected' Result;

View File

@ -124,9 +124,13 @@ internal static class ToolbarBrowserHost
public static async Task RunAsync()
{
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { ApplicationName = typeof(ToolbarController).Assembly.FullName, ContentRootPath = Path.GetFullPath("PlotLine") });
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { EnvironmentName = "Development", ApplicationName = typeof(ToolbarController).Assembly.FullName, ContentRootPath = Path.GetFullPath("PlotLine") });
builder.Services.AddControllersWithViews().AddApplicationPart(typeof(ToolbarController).Assembly);
builder.Services.AddSignalR();
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationAccess>();
builder.Services.AddSingleton<IInvestigationRepository,InvestigationMemoryRepository>();
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationService>();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<IWordCompanionPresenceService, WordCompanionPresenceService>();
builder.Services.AddSingleton<IWritingWorkspacePresenceService, WritingWorkspacePresenceService>();
builder.Services.AddSingleton(FixtureProxy<IOnboardingRepository>((name, args) => throw new NotSupportedException(name)));

View File

@ -0,0 +1,53 @@
using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Data;
using PlotLine.Models.Investigations;
using PlotLine.Services.Investigations;
namespace PlotLine.Controllers;
[Authorize]
[ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class WriterInvestigationsController(InvestigationAccess gate,IInvestigationRepository repository,InvestigationService service):Controller
{
int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
async Task<IActionResult> Guard(Func<Task<IActionResult>> run){if(!gate.Enabled)return NotFound();Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";try{return await run();}catch(Exception e)when(e is UnauthorizedAccessException or KeyNotFoundException){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){Response.StatusCode=409;ViewData["Failure"]=e.Message;return View("Failure");}catch(ArgumentException e){Response.StatusCode=400;ViewData["Failure"]=e.Message;return View("Failure");}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){Response.StatusCode=503;ViewData["Failure"]="Investigations are temporarily unavailable. No unconfirmed save should be assumed successful. Return to Explore to resume.";return View("Failure");}}
[HttpGet("/Writer/Explore/Investigate")]
public Task<IActionResult> Index(int bookId,Guid? id,string? question=null)=>Guard(async()=>{
var project=await service.Project(bookId);Catalogue c;Investigation? row=null;Evaluation? state=null;
if(id.HasValue){(row,c)=await service.Read(Author,bookId,id.Value);state=service.Current(c,row);if(question!=null&&!row.Presented.Contains(question))return BadRequest();ViewData["Question"]=question??state.NextQuestion;}
else c=await repository.Catalogue()??throw new ArgumentException("The test catalogue is not available yet.");
return View(new InvestigationPage(row,c,state,await repository.List(Author,bookId),project,bookId));
});
[HttpPost("/Writer/Explore/Investigate/Start"),ValidateAntiForgeryToken]
public Task<IActionResult> Start(int bookId,string concern)=>Guard(async()=>{var row=await service.Start(Author,bookId,concern);return RedirectToAction(nameof(Index),new{bookId,id=row.ID});});
[HttpPost("/Writer/Explore/Investigate/Answer"),ValidateAntiForgeryToken]
public Task<IActionResult> Answer(int bookId,Guid id,int version,string? question,string? option,string? explanation,string operation="answer")=>Guard(async()=>{
ViewData["Explanation"]=explanation;ViewData["Option"]=option;var(i,c)=await service.Read(Author,bookId,id);if(version!=i.Version){Response.StatusCode=409;ViewData["Failure"]="Another window changed this investigation. Your answer is retained below. Resume the latest version before submitting again.";ViewData["Explanation"]=explanation;ViewData["Option"]=option;return View("Failure");}
if((operation is "answer" or "save")&&option!=null){InvestigationService.Answer(i,c,question??"",option??"",explanation);}
else if(operation is "further" or "disagree"){i.Accepted=false;i.ContinueUntil=Math.Min(c.MaxAnswers,i.Answers.Count+2);}
else if(operation=="accept")i.Accepted=true;
else if(operation=="save"){if((explanation?.Length??0)>2000)throw new ArgumentException("Please keep your explanation within2,000 characters.");i.DraftQuestion=question;i.DraftExplanation=explanation;}
else throw new ArgumentException("Choose an answer before continuing.");
await service.Persist(i,c,version,operation);
return RedirectToAction(nameof(Index),new{bookId,id,question=operation=="disagree"&&i.CurrentQuestion==null?i.Answers.LastOrDefault()?.Question:null,saved=operation=="save"?true:(bool?)null});
});
[HttpPost("/Writer/Explore/Investigate/Open"),ValidateAntiForgeryToken]
public Task<IActionResult> Open(int bookId,Guid id,int version,string capability)=>Guard(async()=>{
var(i,c)=await service.Read(Author,bookId,id);if(version!=i.Version)throw new ArgumentException("Resume the latest version before opening a tool.");var result=service.Current(c,i);var d=c.Capabilities.SingleOrDefault(d=>d.Id==capability);
if(d==null||!result.Recommendations.Any(h=>c.Hypotheses.Single(x=>x.Id==h).Capabilities.Contains(capability)))throw new ArgumentException("This destination is not currently recommended.");
var target=DestinationRegistry.Resolve(d,i.ProjectID,i.BookID,true,i.Answers.ToDictionary(a=>a.Question));if(target==null)throw new ArgumentException("This tool is unavailable. Your investigation is retained.");
i.SelectedDestination=capability;await service.Persist(i,c,version,"open-destination");TempData["InvestigationReturn"] = Url.Action(nameof(Index),new{bookId,id});
return RedirectToAction(target.Value.Action,target.Value.Controller,target.Value.Values);
});
[Authorize(Policy="AdminOnly"),HttpGet("/admin/writer-investigations")]
public Task<IActionResult> Admin()=>Guard(async()=>View("Admin",await repository.Catalogue()));
[Authorize(Policy="AdminOnly"),HttpPost("/admin/writer-investigations"),ValidateAntiForgeryToken,RequestSizeLimit(1_200_000)]
public Task<IActionResult> Import(string json,string operation)=>Guard(async()=>{var c=CatalogueValidator.Parse(json);if(operation=="publish")await repository.Publish(JsonSerializer.Serialize(c,CatalogueValidator.Json),User.Identity?.Name??"administrator");ViewData["Message"]=operation=="publish"?"New immutable catalogue version published.":"Validation passed; nothing written.";return View("Admin",c);});
[Authorize(Policy="AdminOnly"),HttpGet("/admin/writer-investigations/export")]
public Task<IActionResult> Export(string? version)=>Guard(async()=>Content(JsonSerializer.Serialize(await repository.Catalogue(version),CatalogueValidator.Json),"application/json"));
[Authorize(Policy="AdminOnly"),HttpGet("/admin/writer-investigations/simulator")]
public Task<IActionResult> Simulator(int bookId,Guid id)=>Guard(async()=>{var(i,c)=await service.Read(Author,bookId,id);ViewData["Events"]=await repository.Replay(Author,bookId,id);return View("Simulator",new InvestigationPage(i,c,service.Current(c,i),[],i.ProjectID,i.BookID));});
[Authorize(Policy="AdminOnly"),HttpGet("/admin/writer-investigations/diagnostics")]
public Task<IActionResult> Diagnostics(int bookId,Guid id)=>Guard(async()=>{var(i,c)=await service.Read(Author,bookId,id);return Json(new{investigation=i,evaluation=service.Current(c,i),destinations=c.Capabilities,events=await repository.Replay(Author,bookId,id)});});
}

View File

@ -0,0 +1,18 @@
using System.Data;
using System.Text.Json;
using Dapper;
using PlotLine.Models.Investigations;
using PlotLine.Services.Investigations;
namespace PlotLine.Data;
public interface IInvestigationRepository
{Task<Catalogue?> Catalogue(string? version=null);Task Publish(string json,string actor);Task<IReadOnlyList<Investigation>> List(int user,int book);Task<Investigation?> Read(int user,int book,Guid id);Task Save(Investigation row,int expected,string operation,Evaluation result);Task<string[]> Replay(int user,int book,Guid id);}
public sealed class InvestigationRepository(ISqlConnectionFactory factory):IInvestigationRepository
{
public async Task<Catalogue?> Catalogue(string? version=null){using var db=factory.CreateConnection();var json=await db.QuerySingleOrDefaultAsync<string>("dbo.WriterInvestigationCatalogue",new{Action="read",Version=version},commandType:CommandType.StoredProcedure);return json==null?null:CatalogueValidator.Parse(json);}
public async Task Publish(string json,string actor){var c=CatalogueValidator.Parse(json);using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterInvestigationCatalogue",new{Action="publish",c.Version,Json=json,Actor=actor},commandType:CommandType.StoredProcedure);}
public async Task<IReadOnlyList<Investigation>> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync<string>("dbo.WriterInvestigation",new{Action="list",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).Select(Parse).ToArray();}
public async Task<Investigation?> Read(int user,int book,Guid id){using var db=factory.CreateConnection();var json=await db.QuerySingleOrDefaultAsync<string>("dbo.WriterInvestigation",new{Action="read",UserID=user,BookID=book,ID=id},commandType:CommandType.StoredProcedure);return json==null?null:Parse(json);}
public async Task Save(Investigation row,int expected,string operation,Evaluation result){using var db=factory.CreateConnection();row.Version=expected+1;await db.ExecuteAsync("dbo.WriterInvestigation",new{Action="save",row.UserID,row.ProjectID,row.BookID,row.ID,row.CatalogueVersion,ExpectedVersion=expected,Json=JsonSerializer.Serialize(row,CatalogueValidator.Json),Event=JsonSerializer.Serialize(new{operation,state=row,evaluation=result},CatalogueValidator.Json)},commandType:CommandType.StoredProcedure);}
public async Task<string[]> Replay(int user,int book,Guid id){using var db=factory.CreateConnection();return(await db.QueryAsync<string>("dbo.WriterInvestigation",new{Action="events",UserID=user,BookID=book,ID=id},commandType:CommandType.StoredProcedure)).ToArray();}
static Investigation Parse(string json)=>JsonSerializer.Deserialize<Investigation>(json,CatalogueValidator.Json)!;
}

View File

@ -0,0 +1,30 @@
---
title: Work Through a Story Concern
category: Workspace
tags: explore, investigation, questions, story
contextKey: writer3.investigations
micro: Work through a concern one question at a time; your answers stay with this book.
quickTitle: Guided Investigation development preview
quickSummary: Choose a concern, answer in your own time and revisit any earlier answer. Save for later preserves your investigation. This development preview uses a small synthetic catalogue, without AI or manuscript analysis.
screenshot:
---
# Begin with what is troubling you
In Writer → Explore choose Explore a concern, then the starting concern that feels closest. You do not need to know what the problem is. Later answers can lead in a different direction.
# One question at a time
Choose an answer, optionally explain it in your own words, then Continue. Your answers are saved with your account and selected book. Save for later also preserves an unfinished explanation. Use the earlier-answer links to change your understanding; the investigation recalculates from your current answers. If a dependent question no longer applies, its old answer remains in history but no longer contributes.
You can keep multiple investigations. Starting another does not overwrite the previous one. Investigations use the question catalogue version with which they began.
# Consider the next step
Suggestions explain which questionnaire answers informed them and what remains uncertain. They do not claim to analyse the manuscript. You can agree, disagree or investigate further when questions remain. Sometimes there is not enough evidence or an appropriate tool is unavailable; the preview will say so.
Opening a recommended tool uses your authorised project and book in another tab. Your investigation remains open, ready to return to. It does not change your working objective, Word position, manuscript, scene status or session. After opening a tool, reload this investigation before another action if its version has changed.
# Development content only
This synthetic catalogue exercises the mechanism, not production-quality writing advice. It is available only in Development. Production question wording, taxonomy and recommendations will be authored and qualified separately. No AI or external inference service is used.

View File

@ -13,6 +13,8 @@ screenshot:
Review embeds the same canonical Manuscript Reader. Choose a chapter, use Previous/Next or enter Focused Reading. These retain Review mode and do not change your saved working focus, actual session target or Word position. Reader contains accepted text, not every unsaved Word keystroke. Accepted manuscript details show available synchronisation times. If there is no accepted text, connect and synchronise the correct manuscript through Word Companion; you can still inspect recorded intentions.
The manuscript flows down the page using normal document scrolling and a comfortable reading width. The companion remains available alongside it, or as an overlay on narrow screens. Focused Reading retains its own full-screen reading view.
Reader uses its existing update policy. Selected text and paused updates defer content replacement. Surviving paragraph anchors preserve reading position where possible. While an observation editor is open, automatic content updates pause; Save or Cancel restores your previous pause preference. An update never resolves an observation automatically.
# Inspect intentions

View File

@ -0,0 +1,78 @@
namespace PlotLine.Models.Investigations;
public sealed class Catalogue
{
public int SchemaVersion {get;set;}=1;
public string Version {get;set;}="";
public bool Synthetic {get;set;}=true;
public int MinAnswers {get;set;}=8;
public int MaxAnswers {get;set;}=12;
public List<string> Dimensions {get;set;}=[];
public List<Concern> Concerns {get;set;}=[];
public List<Hypothesis> Hypotheses {get;set;}=[];
public List<Question> Questions {get;set;}=[];
public List<Capability> Capabilities {get;set;}=[];
}
public sealed class Concern {public string Id {get;set;}="";public string Text {get;set;}="";public Dictionary<string,decimal> Priors {get;set;}=[];}
public sealed class Rule
{
public int MinAnswers {get;set;}
public Dictionary<string,string[]> AllAnswers {get;set;}=[];
public List<string> ExcludeAnswered {get;set;}=[];
}
public sealed class Hypothesis
{
public string Id {get;set;}="";public string Description {get;set;}="";
public string Summary {get;set;}="";public string Reason {get;set;}="";public string Uncertainty {get;set;}="";
public List<string> Dimensions {get;set;}=[];public List<string> Capabilities {get;set;}=[];
public int MinDimensions {get;set;}=2;public int MinGroups {get;set;}=2;public decimal Threshold {get;set;}=4;
public Rule Eligibility {get;set;}=new();
}
public sealed class Question
{
public string Id {get;set;}="";public string Text {get;set;}="";public string Help {get;set;}="";
public string Purpose {get;set;}="Discovery";public string Group {get;set;}="";
public decimal InformationValue {get;set;}=1;public List<string> Hypotheses {get;set;}=[];
public List<string> Dimensions {get;set;}=[];public List<string> Clarifies {get;set;}=[];
public bool AllowExplanation {get;set;}=true;public bool Retired {get;set;}
public string? ReplacedBy {get;set;}public Rule Eligibility {get;set;}=new();public List<AnswerOption> Options {get;set;}=[];
}
public sealed class AnswerOption
{
public string Id {get;set;}="";public string Text {get;set;}="";public bool Uncertain {get;set;}
public string Interpretation {get;set;}="";public List<Contribution> Contributions {get;set;}=[];
}
public sealed class Contribution
{
public string Hypothesis {get;set;}="";public string Dimension {get;set;}="";public string Aspect {get;set;}="general";public decimal Weight {get;set;}
}
public sealed class Capability
{
public string Id {get;set;}="";public string Name {get;set;}="";public string Description {get;set;}="";
public string Resolver {get;set;}="";public string ActionText {get;set;}="";public bool Available {get;set;}=true;
public bool RequiresBook {get;set;}=true;public bool RequiresProject {get;set;}=true;
public string Context {get;set;}="book";public string Authority {get;set;}="ProjectAccess";
public Rule Prerequisites {get;set;}=new();
}
public sealed record Answer(string Question,string Option,string Explanation="");
public sealed record Evidence(string Question,string Option,string Hypothesis,string Dimension,string Group,string Aspect,decimal Raw,bool Uncertain);
public sealed record HypothesisEvidence(string Id,decimal Prior,decimal Support,decimal Opposition,decimal Score,int Dimensions,int Groups,bool Challenged,bool Eligible,bool Supported,string[] Conflicts,string[] Missing);
public sealed record CandidateQuestion(string Id,decimal Rank,string Reason);
public sealed class Evaluation
{
public List<string> AvailableCapabilities {get;set;}=[];public List<Evidence> Evidence {get;set;}=[];public List<HypothesisEvidence> Hypotheses {get;set;}=[];
public List<CandidateQuestion> Candidates {get;set;}=[];public string? NextQuestion {get;set;}
public string Outcome {get;set;}="Investigating";public List<string> Recommendations {get;set;}=[];
public int AnswerCount {get;set;}public int RedundantContributions {get;set;}
}
public sealed class Investigation
{
public Guid ID {get;set;}public int UserID {get;set;}public int ProjectID {get;set;}public int BookID {get;set;}
public string CatalogueVersion {get;set;}="";public string Concern {get;set;}="";
public List<Answer> Answers {get;set;}=[];public List<string> Presented {get;set;}=[];
public string? DraftQuestion {get;set;}public string? DraftExplanation {get;set;}public string? CurrentQuestion {get;set;}public int ContinueUntil {get;set;}public bool Accepted {get;set;}
public string? SelectedDestination {get;set;}public List<RecommendationRecord> Recommendations {get;set;}=[];
public int Version {get;set;}public DateTime CreatedUtc {get;set;}public DateTime UpdatedUtc {get;set;}
}
public sealed record RecommendationRecord(int AnswerCount,string Outcome,List<string> Hypotheses,DateTime Utc);
public sealed record InvestigationPage(Investigation? Investigation,Catalogue Catalogue,Evaluation? Evaluation,IReadOnlyList<Investigation> Saved,int ProjectID,int BookID,string? Error=null);

View File

@ -141,6 +141,9 @@ public class Program
builder.Services.AddScoped<IProjectRepository, ProjectRepository>();
builder.Services.AddScoped<ApplicationNavigation>();
builder.Services.AddScoped<IWritingSolverRepository, WritingSolverRepository>();
builder.Services.AddScoped<PlotLine.Data.IInvestigationRepository,PlotLine.Data.InvestigationRepository>();
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationService>();
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationAccess>();
builder.Services.AddScoped<IWritingSolverWorkspaceContext, WritingSolverWorkspaceContext>();
builder.Services.AddSingleton<WritingSolverResultContext>();
builder.Services.AddScoped<WritingSolverReview>();

View File

@ -0,0 +1,28 @@
using System.Text.Json;
using System.Text.RegularExpressions;
using PlotLine.Models.Investigations;
namespace PlotLine.Services.Investigations;
public static class CatalogueValidator
{
public static readonly JsonSerializerOptions Json=new(){PropertyNameCaseInsensitive=true,WriteIndented=true,UnmappedMemberHandling=System.Text.Json.Serialization.JsonUnmappedMemberHandling.Disallow};
public static Catalogue Parse(string json){if(json.Length>1_000_000)throw new ArgumentException("Catalogue is too large.");try{var c=JsonSerializer.Deserialize<Catalogue>(json,Json)??throw new ArgumentException("Missing catalogue.");Validate(c);return c;}catch(Exception e)when(e is JsonException or NullReferenceException){throw new ArgumentException("Malformed catalogue; lists and objects cannot be null.",e);}}
public static void Validate(Catalogue c)
{
void Require(bool ok,string message){if(!ok)throw new ArgumentException(message);}
void Ids(IEnumerable<string> ids,string label){var a=ids.ToArray();Require(a.Length>0&&a.Length<=2000&&a.All(x=>x!=null&&Regex.IsMatch(x,"^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$"))&&a.Distinct(StringComparer.Ordinal).Count()==a.Length,"Invalid/duplicate "+label+" identifiers.");}
Require(c.SchemaVersion==1&&c.Synthetic,"Only schema1 synthetic catalogues are supported in this phase.");Ids([c.Version],"version");Ids(c.Dimensions,"dimension");Ids(c.Concerns.Select(x=>x.Id),"concern");Ids(c.Hypotheses.Select(x=>x.Id),"hypothesis");Ids(c.Questions.Select(x=>x.Id),"question");Ids(c.Capabilities.Select(x=>x.Id),"capability");
Require(c.MinAnswers>=2&&c.MaxAnswers>=c.MinAnswers&&c.MaxAnswers<=40,"Invalid question bounds.");
var qs=c.Questions.ToDictionary(q=>q.Id);var hs=c.Hypotheses.Select(h=>h.Id).ToHashSet();var ds=c.Dimensions.ToHashSet();var caps=c.Capabilities.Select(d=>d.Id).ToHashSet();
void Text(string s,string label)=>Require(!string.IsNullOrWhiteSpace(s)&&s.Length<=4000,"Missing/oversize "+label);
void RuleCheck(Rule r){Require(r.MinAnswers>=0&&r.MinAnswers<=c.MaxAnswers,"Invalid prerequisite answer bound.");foreach(var pair in r.AllAnswers)Require(qs.TryGetValue(pair.Key,out var q)&&pair.Value.Length>0&&pair.Value.All(id=>q.Options.Any(o=>o.Id==id)),"Invalid prerequisite option.");Require(r.ExcludeAnswered.All(qs.ContainsKey),"Invalid exclusion.");Require(!r.AllAnswers.Keys.Intersect(r.ExcludeAnswered).Any(),"Unsatisfiable prerequisite/exclusion.");}
foreach(var s in c.Concerns){Text(s.Text,"concern");Require(s.Priors.Count>0&&s.Priors.All(p=>hs.Contains(p.Key)&&p.Value>=0&&p.Value<=2),"Invalid initial evidence.");}
foreach(var h in c.Hypotheses){Text(h.Description,"hypothesis");Text(h.Summary,"summary template");Text(h.Reason,"reason template");Text(h.Uncertainty,"uncertainty template");Require(h.Dimensions.Count>0&&h.Dimensions.All(ds.Contains)&&h.Capabilities.Count>0&&h.Capabilities.All(caps.Contains),"Invalid hypothesis mapping.");Require(h.MinDimensions>=2&&h.MinDimensions<=h.Dimensions.Distinct().Count()&&h.MinGroups>=2&&h.MinGroups<=c.MaxAnswers&&h.Threshold>0&&h.Threshold<=3*h.Dimensions.Count,"Invalid coverage requirement.");RuleCheck(h.Eligibility);}
foreach(var q in c.Questions){Text(q.Text,"question");Text(q.Group,"corroboration group");Require(new[]{"Discovery","Discrimination","Corroboration","Challenge","Clarification","ActionPreference"}.Contains(q.Purpose),"Invalid question purpose.");Require(q.InformationValue>=0&&q.InformationValue<=20&&q.Hypotheses.Count>0&&q.Hypotheses.All(hs.Contains)&&q.Dimensions.Count>0&&q.Dimensions.All(ds.Contains)&&q.Clarifies.All(ds.Contains),"Invalid question mapping/priority.");Require(q.ReplacedBy==null||q.Retired&&q.ReplacedBy!=q.Id&&qs.ContainsKey(q.ReplacedBy)&&!qs[q.ReplacedBy].Retired,"Invalid replacement.");RuleCheck(q.Eligibility);Require(!q.Eligibility.AllAnswers.ContainsKey(q.Id)&&!q.Eligibility.ExcludeAnswered.Contains(q.Id),"Self prerequisite/exclusion.");Ids(q.Options.Select(o=>o.Id),"answer");Require(q.Options.Count is >=3 and <=5,"Questions need3–5 answer choices.");foreach(var o in q.Options){Text(o.Text,"answer");Require(new[]{"","different-aspects","revised-understanding","confirm-conflict","uncertain"}.Contains(o.Interpretation),"Invalid clarification interpretation.");Require(o.Interpretation==""||q.Purpose=="Clarification","Interpretation requires clarification question.");foreach(var e in o.Contributions){Require(q.Hypotheses.Contains(e.Hypothesis)&&q.Dimensions.Contains(e.Dimension)&&c.Hypotheses.Single(h=>h.Id==e.Hypothesis).Dimensions.Contains(e.Dimension)&&e.Weight>=-3&&e.Weight<=3,"Invalid evidence reference/weight.");Text(e.Aspect,"evidence aspect");}Require(o.Contributions.Select(e=>(e.Hypothesis,e.Dimension,e.Aspect)).Distinct().Count()==o.Contributions.Count,"Duplicate option evidence.");}}
foreach(var d in c.Capabilities){Text(d.Name,"destination");Text(d.Description,"destination description");Text(d.ActionText,"action wording");Require(DestinationRegistry.Resolvers.Contains(d.Resolver)&&d.Authority=="ProjectAccess"&&d.Context is "book" or "project"&&d.RequiresProject,"Invalid destination resolver/context/authority.");RuleCheck(d.Prerequisites);}
// Monotone prerequisite reachability, then check structural support/challenge paths per hypothesis.
var reachable=new HashSet<string>();bool changed;do{changed=false;foreach(var q in c.Questions.Where(q=>!q.Retired))if(q.Eligibility.AllAnswers.Keys.All(reachable.Contains)&&q.Eligibility.MinAnswers<=reachable.Count&&reachable.Add(q.Id))changed=true;}while(changed);
Require(c.Questions.Where(q=>!q.Retired).All(q=>reachable.Contains(q.Id)),"Unreachable question prerequisite cycle.");
foreach(var h in c.Hypotheses){var rows=c.Questions.Where(q=>reachable.Contains(q.Id)).ToArray();Require(rows.Any(q=>q.Purpose=="Challenge"&&q.Hypotheses.Contains(h.Id)),"Hypothesis lacks challenge.");Require(rows.SelectMany(q=>q.Options.SelectMany(o=>o.Contributions)).Where(e=>e.Hypothesis==h.Id&&e.Weight>0).Select(e=>e.Dimension).Distinct().Count()>=h.MinDimensions,"Hypothesis lacks distinct support dimensions.");Require(rows.Where(q=>q.Options.Any(o=>o.Contributions.Any(e=>e.Hypothesis==h.Id&&e.Weight>0))).Select(q=>q.Group).Distinct().Count()>=h.MinGroups,"Hypothesis lacks corroboration groups.");}
Require(c.Capabilities.All(d=>c.Hypotheses.Any(h=>h.Capabilities.Contains(d.Id))),"Unmapped destination.");
}
}

View File

@ -0,0 +1,13 @@
using PlotLine.Models.Investigations;
namespace PlotLine.Services.Investigations;
// Trusted authenticated adapters only. Catalogue data never supplies a URL or a controller name.
public static class DestinationRegistry
{
public static readonly HashSet<string> Resolvers=["Write","Characters","PlotThreads","Timeline","Relationships"];
public static (string Controller,string Action,object Values)? Resolve(Capability d,int project,int book,bool authorised,IReadOnlyDictionary<string,Answer> answers)
{
if(!authorised||!d.Available||project<=0||d.RequiresBook&&book<=0||!InvestigationEngine.Allows(d.Prerequisites,answers))return null;
var controller=d.Resolver switch{"Write"=>"Writer","Characters"=>"Characters","PlotThreads"=>"PlotLineWorkspace","Timeline"=>"Timeline","Relationships"=>"RelationshipMap",_=>null};
return controller==null?null:(controller,controller=="Writer"?"Write":"Index",new{projectId=project,bookId=book});
}
}

View File

@ -0,0 +1,52 @@
using PlotLine.Models.Investigations;
namespace PlotLine.Services.Investigations;
// Pure deterministic function: no repository, HTTP, manuscript, clock, random source or AI dependency.
public static class InvestigationEngine
{
public static bool Allows(Rule r,IReadOnlyDictionary<string,Answer> a)=>a.Count>=r.MinAnswers&&r.AllAnswers.All(x=>a.TryGetValue(x.Key,out var answer)&&x.Value.Contains(answer.Option))&&!r.ExcludeAnswered.Any(a.ContainsKey);
public static Evaluation Evaluate(Catalogue c,string concern,IEnumerable<Answer> history,ISet<string> available,int continueUntil=0)
{
var seed=c.Concerns.SingleOrDefault(x=>x.Id==concern)??throw new ArgumentException("Choose a starting concern.");
// Last answer wins. Callers keep revision events separately, never obsolete scoring contributions.
var answers=history.GroupBy(x=>x.Question).ToDictionary(x=>x.Key,x=>x.Last());
var result=new Evaluation{AnswerCount=answers.Count,AvailableCapabilities=available.Order(StringComparer.Ordinal).ToList()};
foreach(var a in answers.Values){var q=c.Questions.Single(x=>x.Id==a.Question);var option=q.Options.Single(x=>x.Id==a.Option);result.Evidence.AddRange(option.Contributions.Select(e=>new Evidence(q.Id,option.Id,e.Hypothesis,e.Dimension,q.Group,e.Aspect,e.Weight,option.Uncertain)));}
foreach(var h in c.Hypotheses)
{
var rows=result.Evidence.Where(e=>e.Hypothesis==h.Id&&!e.Uncertain).ToArray();
// A dimension/group contributes its strongest support and strongest opposition once.
var independent=rows.GroupBy(e=>(e.Dimension,e.Group)).Select(g=>new{g.Key.Dimension,Positive=g.Max(e=>Math.Max(0,e.Raw)),Negative=g.Min(e=>Math.Min(0,e.Raw))}).ToArray();
var support=independent.GroupBy(x=>x.Dimension).Sum(g=>Math.Min(3,g.Sum(x=>x.Positive)));
var opposition=independent.GroupBy(x=>x.Dimension).Sum(g=>Math.Max(-3,g.Sum(x=>x.Negative)));
result.RedundantContributions+=Math.Max(0,rows.Count(e=>e.Raw!=0)-independent.Length);
var conflicts=rows.GroupBy(e=>(e.Dimension,e.Aspect)).Where(g=>g.Any(e=>e.Raw>=2)&&g.Any(e=>e.Raw<=-2)).Where(g=>!answers.Values.Any(a=>{var q=c.Questions.Single(x=>x.Id==a.Question);var o=q.Options.Single(x=>x.Id==a.Option);return q.Clarifies.Contains(g.Key.Dimension)&&q.Hypotheses.Contains(h.Id)&&o.Interpretation == "different-aspects";})).Select(g=>$"{h.Id}/{g.Key.Dimension}/{g.Key.Aspect}").ToArray();
var dimensions=independent.Where(x=>x.Positive>0).Select(x=>x.Dimension).Distinct().Count();
var groups=rows.Where(e=>e.Raw>0).Select(e=>e.Group).Distinct().Count();
var challenged=answers.Values.Any(a=>{var q=c.Questions.Single(x=>x.Id==a.Question);return q.Purpose=="Challenge"&&q.Hypotheses.Contains(h.Id)&&!q.Options.Single(o=>o.Id==a.Option).Uncertain;});
var competitors=result.Evidence.Where(e=>e.Hypothesis!=h.Id&&!e.Uncertain&&e.Raw!=0).Select(e=>e.Hypothesis).Distinct().Count();
var eligible=Allows(h.Eligibility,answers)&&h.Capabilities.Any(id=>available.Contains(id)&&c.Capabilities.Any(d=>d.Id==id&&d.Available&&Allows(d.Prerequisites,answers)));
var missing=new List<string>();if(dimensions<h.MinDimensions)missing.Add("distinct dimensions");if(groups<h.MinGroups)missing.Add("independent corroboration");if(!challenged)missing.Add("challenge opportunity");if(competitors<1)missing.Add("competing explanation examined");if(conflicts.Length>0)missing.Add("material conflict clarified");if(support+opposition<h.Threshold)missing.Add("net evidence");
result.Hypotheses.Add(new(h.Id,seed.Priors.GetValueOrDefault(h.Id),support,opposition,support+opposition+seed.Priors.GetValueOrDefault(h.Id),dimensions,groups,challenged,eligible,missing.Count==0,conflicts,missing.ToArray()));
}
result.Hypotheses=result.Hypotheses.OrderByDescending(h=>h.Score).ThenBy(h=>h.Id,StringComparer.Ordinal).ToList();
var plausible=result.Hypotheses.Where(h=>h.Score>0).Take(2).Select(h=>h.Id).ToHashSet();
var covered=result.Evidence.Select(e=>(e.Hypothesis,e.Dimension)).ToHashSet();
foreach(var q in c.Questions.Where(q=>!q.Retired&&!answers.ContainsKey(q.Id)&&Allows(q.Eligibility,answers)))
{
var overlap=q.Hypotheses.Count(plausible.Contains);var gaps=q.Hypotheses.Sum(h=>q.Dimensions.Count(d=>!covered.Contains((h,d))));
var conflicts=result.Hypotheses.Count(h=>q.Hypotheses.Contains(h.Id)&&h.Conflicts.Any(f=>q.Clarifies.Any(d=>f.Contains('/'+d+'/'))));
var challenge=q.Purpose=="Challenge"?result.Hypotheses.Count(h=>plausible.Contains(h.Id)&&q.Hypotheses.Contains(h.Id)&&!h.Challenged):0;
var corroboration=q.Purpose=="Corroboration"?result.Hypotheses.Count(h=>plausible.Contains(h.Id)&&q.Hypotheses.Contains(h.Id)&&h.Groups<c.Hypotheses.Single(x=>x.Id==h.Id).MinGroups):0;
var rank=q.InformationValue+overlap*3+gaps*2+conflicts*30+challenge*15+corroboration*8+(q.Purpose=="Discrimination"&&overlap>1?8:0);
result.Candidates.Add(new(q.Id,rank,$"Relevant leading explanations: {string.Join(", ",q.Hypotheses.Where(plausible.Contains))}; unexamined dimensions: {gaps}; unresolved conflicts: {conflicts}; challenge gaps: {challenge}; corroboration gaps: {corroboration}; authored information value: {q.InformationValue}."));
}
result.Candidates=result.Candidates.OrderByDescending(x=>x.Rank).ThenBy(x=>x.Id,StringComparer.Ordinal).ToList();
var qualified=result.Hypotheses.Where(h=>h.Supported).ToArray();var ready=answers.Count>=Math.Max(c.MinAnswers,continueUntil);
if(ready&&qualified.Length>0){var usable=qualified.Where(h=>h.Eligible).ToArray();if(usable.Length==0)result.Outcome="No suitable destination currently available";else{result.Recommendations=usable.Where(h=>h.Score>=usable[0].Score-2).Take(2).Select(h=>h.Id).ToList();result.Outcome=result.Recommendations.Count==2?"Two plausible explanations":"Supported recommendation";}}
if(result.Outcome=="Investigating"&&(answers.Count>=c.MaxAnswers||result.Candidates.Count==0))result.Outcome=result.Hypotheses.Count(h=>h.Support>0)>=2?"Two plausible explanations":"More information needed";
// Ambiguous terminal outcomes do not invent qualified recommendations.
if(result.Outcome=="Investigating")result.NextQuestion=result.Candidates.FirstOrDefault()?.Id;
return result;
}
}

View File

@ -0,0 +1,31 @@
using PlotLine.Data;
using PlotLine.Models.Investigations;
namespace PlotLine.Services.Investigations;
public sealed class InvestigationAccess(IWebHostEnvironment environment,IConfiguration configuration)
{
public bool Enabled=>environment.IsDevelopment()&&configuration.GetValue("WriterInvestigations:Enabled",true);
}
public sealed class InvestigationService(IInvestigationRepository repository,IBookRepository books,IProjectAccessService access,TimeProvider clock,IConfiguration configuration)
{
public async Task<int> Project(int book){if(!await access.CanAccessEntityAsync("Book",book))throw new UnauthorizedAccessException();var b=await books.GetAsync(book);if(b==null||b.IsArchived)throw new UnauthorizedAccessException();return b.ProjectID;}
public static HashSet<string> Available(Catalogue c,Investigation i)=>c.Capabilities.Where(d=>DestinationRegistry.Resolve(d,i.ProjectID,i.BookID,true,i.Answers.ToDictionary(a=>a.Question))!=null).Select(d=>d.Id).ToHashSet();
public static Evaluation Evaluate(Catalogue c,Investigation i)=>InvestigationEngine.Evaluate(c,i.Concern,i.Answers,Available(c,i),i.ContinueUntil);
public Evaluation Current(Catalogue c,Investigation i)=>InvestigationEngine.Evaluate(c,i.Concern,i.Answers,Available(c,i).Where(id=>configuration.GetValue($"WriterInvestigations:Capabilities:{id}:Enabled",true)).ToHashSet(),i.ContinueUntil);
public async Task<(Investigation,Catalogue)> Read(int user,int book,Guid id){var project=await Project(book);var row=await repository.Read(user,book,id)??throw new KeyNotFoundException();if(row.UserID!=user||row.BookID!=book||row.ProjectID!=project)throw new UnauthorizedAccessException();return(row,await repository.Catalogue(row.CatalogueVersion)??throw new KeyNotFoundException());}
public async Task<Investigation> Start(int user,int book,string concern){var project=await Project(book);var c=await repository.Catalogue()??throw new ArgumentException("The test catalogue is not yet available.");var i=new Investigation{ID=Guid.NewGuid(),UserID=user,ProjectID=project,BookID=book,CatalogueVersion=c.Version,Concern=concern,CreatedUtc=clock.GetUtcNow().UtcDateTime};await Persist(i,c,0,"start");return i;}
public async Task Persist(Investigation i,Catalogue c,int expected,string operation)
{
var state=Current(c,i);i.CurrentQuestion=state.NextQuestion;
if(state.NextQuestion!=null&&!i.Presented.Contains(state.NextQuestion))i.Presented.Add(state.NextQuestion);
if(state.Outcome!="Investigating"&&(i.Recommendations.LastOrDefault() is not {} last||last.AnswerCount!=i.Answers.Count||last.Outcome!=state.Outcome||!last.Hypotheses.SequenceEqual(state.Recommendations)))i.Recommendations.Add(new(i.Answers.Count,state.Outcome,state.Recommendations.ToList(),clock.GetUtcNow().UtcDateTime));
i.UpdatedUtc=clock.GetUtcNow().UtcDateTime;await repository.Save(i,expected,operation,state);
}
public static void Answer(Investigation i,Catalogue c,string question,string option,string? explanation)
{
if(!i.Presented.Contains(question))throw new ArgumentException("This question has not been presented.");var q=c.Questions.SingleOrDefault(q=>q.Id==question)??throw new ArgumentException("Unknown question.");if(!q.Options.Any(o=>o.Id==option))throw new ArgumentException("Choose an answer.");if((explanation?.Length??0)>2000)throw new ArgumentException("Please keep your explanation within2,000 characters.");
var existing=i.Answers.FindIndex(a=>a.Question==question);var next=new Answer(question,option,q.AllowExplanation?explanation??"":"");if(existing>=0)i.Answers[existing]=next;else i.Answers.Add(next);
// Revision may invalidate later prerequisite-dependent answers. Keep them in event history, not live evidence.
bool removed;do{removed=false;foreach(var a in i.Answers.ToArray()){var others=i.Answers.Where(x=>x.Question!=a.Question).ToDictionary(x=>x.Question);if(!InvestigationEngine.Allows(c.Questions.Single(q=>q.Id==a.Question).Eligibility,others)){i.Answers.Remove(a);removed=true;}}}while(removed);
i.DraftQuestion=null;i.DraftExplanation=null;i.Accepted=false;i.SelectedDestination=null;
}
}

View File

@ -85,6 +85,7 @@ public sealed class ProjectAccessFilter(IProjectAccessService access, ICurrentUs
["Scenarios"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "Scenario", ["scenarioId"] = "Scenario", ["projectId"] = "Project", ["bookId"] = "Book", ["sceneId"] = "Scene", ["anchorSceneId"] = "Scene", ["targetChapterId"] = "Chapter" },
["StoryAssets"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "StoryAsset", ["returnAssetId"] = "StoryAsset", ["projectId"] = "Project" },
["Timeline"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "TimelineViewPreset", ["projectId"] = "Project", ["bookId"] = "Book" },
["WriterInvestigations"] = new(StringComparer.OrdinalIgnoreCase) { ["bookId"]="Book" },
["WriterReview"] = new(StringComparer.OrdinalIgnoreCase) { ["bookId"]="Book",["chapterId"]="Chapter" },
["WriterWord"] = new(StringComparer.OrdinalIgnoreCase) { ["bookId"] = "Book", ["chapterId"] = "Chapter", ["sceneId"] = "Scene" },
["WriterAuthoring"] = new(StringComparer.OrdinalIgnoreCase) { ["bookId"] = "Book", ["chapterId"] = "Chapter", ["sceneId"] = "Scene" },

View File

@ -0,0 +1,48 @@
-- Phase3D.1: private deterministic investigations; immutable catalogues and append-only state events.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
IF OBJECT_ID('dbo.WriterInvestigationCatalogues') IS NULL
CREATE TABLE dbo.WriterInvestigationCatalogues(Version varchar(80) NOT NULL PRIMARY KEY,Json nvarchar(max) NOT NULL CHECK(ISJSON(Json)=1),PublishedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),Actor nvarchar(256) NOT NULL);
IF OBJECT_ID('dbo.WriterInvestigations') IS NULL
CREATE TABLE dbo.WriterInvestigations(ID uniqueidentifier NOT NULL PRIMARY KEY,UserID int NOT NULL REFERENCES dbo.AppUser(UserID) ON DELETE CASCADE,ProjectID int NOT NULL,BookID int NOT NULL REFERENCES dbo.Books(BookID) ON DELETE CASCADE,CatalogueVersion varchar(80) NOT NULL REFERENCES dbo.WriterInvestigationCatalogues(Version),Version int NOT NULL,Json nvarchar(max) NOT NULL CHECK(ISJSON(Json)=1),CreatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),UpdatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME());
IF OBJECT_ID('dbo.WriterInvestigationEvents') IS NULL
CREATE TABLE dbo.WriterInvestigationEvents(InvestigationID uniqueidentifier NOT NULL REFERENCES dbo.WriterInvestigations(ID) ON DELETE CASCADE,Version int NOT NULL,Event nvarchar(max) NOT NULL CHECK(ISJSON(Event)=1),CreatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),PRIMARY KEY(InvestigationID,Version));
IF NOT EXISTS(SELECT 1 FROM sys.indexes WHERE object_id=OBJECT_ID('dbo.WriterInvestigations') AND name='IX_WriterInvestigations_AuthorBook') CREATE INDEX IX_WriterInvestigations_AuthorBook ON dbo.WriterInvestigations(UserID,BookID,UpdatedUtc DESC);
GO
CREATE OR ALTER PROCEDURE dbo.WriterInvestigationCatalogue @Action varchar(12),@Version varchar(80)=NULL,@Json nvarchar(max)=NULL,@Actor nvarchar(256)=NULL AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
IF @Action='read' BEGIN SELECT TOP(1) Json FROM dbo.WriterInvestigationCatalogues WHERE @Version IS NULL OR Version=@Version ORDER BY PublishedUtc DESC,Version DESC;RETURN;END;
IF @Action<>'publish' OR @Version IS NULL OR ISJSON(@Json)<>1 OR ISNULL(JSON_VALUE(@Json,'$.Version'),'')<>@Version OR ISNULL(JSON_VALUE(@Json,'$.Synthetic'),'')<>'true' THROW 51000,'Invalid catalogue',1;
IF EXISTS(SELECT 1 FROM dbo.WriterInvestigationCatalogues WHERE Version=@Version) THROW 51002,'Catalogue version is immutable; publish a new version',1;
INSERT dbo.WriterInvestigationCatalogues(Version,Json,Actor) VALUES(@Version,@Json,@Actor);
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterInvestigation @Action varchar(12),@UserID int,@BookID int,@ProjectID int=NULL,@ID uniqueidentifier=NULL,@CatalogueVersion varchar(80)=NULL,@ExpectedVersion int=NULL,@Json nvarchar(max)=NULL,@Event nvarchar(max)=NULL AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
DECLARE @ActualProject int;
SELECT @ActualProject=b.ProjectID FROM dbo.Books b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.IsArchived=0;
IF @ActualProject IS NULL OR (@ProjectID IS NOT NULL AND @ProjectID<>@ActualProject) THROW 51000,'Investigation scope unavailable',1;
IF @Action='list' BEGIN SELECT TOP(100) Json FROM dbo.WriterInvestigations WHERE UserID=@UserID AND BookID=@BookID ORDER BY UpdatedUtc DESC,ID;RETURN;END;
IF @Action IN('read','events') BEGIN
IF NOT EXISTS(SELECT 1 FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID) THROW 51000,'Investigation unavailable',1;
IF @Action='read' SELECT Json FROM dbo.WriterInvestigations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID;
ELSE SELECT e.Event FROM dbo.WriterInvestigationEvents e JOIN dbo.WriterInvestigations i ON i.ID=e.InvestigationID WHERE i.ID=@ID AND i.UserID=@UserID AND i.BookID=@BookID ORDER BY e.Version;
RETURN;
END;
IF @Action<>'save' OR @ID IS NULL OR @ExpectedVersion<0 OR @ExpectedVersion>1000 OR ISJSON(@Json)<>1 OR ISJSON(@Event)<>1 OR DATALENGTH(@Json)>1000000 OR DATALENGTH(@Event)>2000000 THROW 51000,'Invalid investigation save',1;
IF ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.UserID')),-1)<>@UserID OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.BookID')),-1)<>@BookID OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.ProjectID')),-1)<>@ActualProject OR ISNULL(TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Json,'$.ID')),'00000000-0000-0000-0000-000000000000')<>@ID OR ISNULL(JSON_VALUE(@Json,'$.CatalogueVersion'),'')<>@CatalogueVersion OR ISNULL(TRY_CONVERT(int,JSON_VALUE(@Json,'$.Version')),-1)<>@ExpectedVersion+1 THROW 51000,'Investigation identity mismatch',1;
BEGIN TRANSACTION;
IF @ExpectedVersion=0 BEGIN
IF EXISTS(SELECT 1 FROM dbo.WriterInvestigations WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID) THROW 51002,'Investigation already exists; resume it',1;
INSERT dbo.WriterInvestigations(ID,UserID,ProjectID,BookID,CatalogueVersion,Version,Json) VALUES(@ID,@UserID,@ActualProject,@BookID,@CatalogueVersion,1,@Json);
END ELSE BEGIN
UPDATE dbo.WriterInvestigations SET Json=@Json,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND CatalogueVersion=@CatalogueVersion AND Version=@ExpectedVersion;
IF @@ROWCOUNT<>1 THROW 51002,'Another window changed this investigation. Your submitted answer has not replaced it.',1;
END;
INSERT dbo.WriterInvestigationEvents(InvestigationID,Version,Event) VALUES(@ID,@ExpectedVersion+1,@Event);
COMMIT;
END;
GO

View File

@ -1,13 +1,15 @@
@inject PlotLine.Services.Investigations.InvestigationAccess InvestigationAccess
@model WriterDashboardViewModel
<div class="writer3-workspace" aria-label="Story exploration">
<section class="writer3-panel writer3-main" tabindex="0">
@if(InvestigationAccess.Enabled && Model.BookID.HasValue){<section class="writer3-inset"><h2>What's troubling you about your story?</h2><p>You don't need to know the answer yet. Work through a concern one question at a time.</p><a class="btn btn-primary" asp-controller="WriterInvestigations" asp-action="Index" asp-route-bookId="@Model.BookID">Explore a concern</a><p class="writer3-caption">Development preview · Small synthetic test catalogue; questionnaire answers only, without AI or manuscript analysis.</p></section>}
<p class="eyebrow">Start with your question</p><h2>What would you like to explore?</h2><p>You do not need a finished outline or a linked manuscript. Choose a starting point.</p>
<div class="writer3-explore-paths">
<a asp-controller="Writer" asp-action="Write" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID"><span class="writer3-path-mark" aria-hidden="true">01</span><div><h3>Develop a chapter or scene</h3><p>Work with your saved chapter intentions, scene ideas and reminders.</p></div><span aria-hidden="true">→</span></a>
<a asp-controller="@(Model.ProjectID.HasValue?"PlotLineWorkspace":"Projects")" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID"><span class="writer3-path-mark" aria-hidden="true">02</span><div><h3>Develop your plot and threads</h3><p>Use your existing plot lines and threads to develop an idea or untangle a concern.</p></div><span aria-hidden="true">→</span></a>
@if(Model.BookID.HasValue){<a asp-controller="Timeline" asp-action="Index" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID"><span class="writer3-path-mark" aria-hidden="true">03</span><div><h3>Look at your story’s shape</h3><p>Inspect your saved chapters, scenes and story timeline.</p></div><span aria-hidden="true">→</span></a>}
</div>
<p class="writer3-caption">These open your authenticated writing and story tools. Guided exploration is planned for a later update; no manuscript analysis runs here.</p>
<p class="writer3-caption">These open your authenticated writing and story tools. No manuscript analysis runs here.</p>
</section>
<aside class="writer3-panel writer3-reference" tabindex="0" aria-label="Existing story references">
<h2>Your story references</h2>

View File

@ -0,0 +1,8 @@
@using System.Text.Json
@using PlotLine.Services.Investigations
@model PlotLine.Models.Investigations.Catalogue
@{ViewData["Title"]="Guided Investigation test catalogue";ViewData["ProjectSection"]="Writer";}
<div class="investigation"><h1>Guided Investigation · Development diagnostics</h1><p role="status">@ViewData["Message"]</p><p>Author-private simulation uses normal investigations in a disposable book. Choose answers in the author interface, then open its diagnostics link to inspect every evidence contribution, selected question reason, completion gap and append-only replay snapshot. Administrators cannot inspect another author's private investigation through this interface.</p>
<p><a href="/Writer/Explore">Start or resume a test investigation</a> · <a href="/admin/writer-investigations/export">Export current catalogue</a></p>
<form method="post" asp-action="Import"><label for="catalogue-json">Structured catalogue JSON</label><textarea id="catalogue-json" class="form-control" name="json" rows="22" maxlength="1000000">@JsonSerializer.Serialize(Model,CatalogueValidator.Json)</textarea><button class="btn btn-outline-secondary" name="operation" value="validate">Validate without saving</button><button class="btn btn-primary" name="operation" value="publish">Publish new immutable version</button></form>
<p>Existing investigations remain pinned to their published version. Use a new version identifier for every publication. Synthetic content is accessible only in Development. See Docs/Writer/Investigations for the schema and automated simulation workflow.</p></div>

View File

@ -0,0 +1,4 @@
@{ViewData["Title"]="Investigation could not be saved";ViewData["ProjectSection"]="Writer";}
<h1>We couldn't confirm that change</h1><p role="alert">@ViewData["Failure"]</p>
@if(ViewData["Option"]!=null){<p>Your selected answer: @ViewData["Option"]</p>}@if(ViewData["Explanation"]!=null){<label for="retained-answer">Your explanation (copy before returning)</label><textarea id="retained-answer" class="form-control" readonly>@ViewData["Explanation"]</textarea>}
<p><a asp-controller="Writer" asp-action="Explore">Return to Explore to resume</a>. Your previously saved investigation is retained.</p>

View File

@ -0,0 +1,55 @@
@inject Microsoft.AspNetCore.Authorization.IAuthorizationService Authorization
@using PlotLine.Models.Investigations
@using PlotLine.Services.Investigations
@model InvestigationPage
@{
ViewData["Title"]="Writer · Explore";ViewData["ProjectSection"]="Writer";
var row=Model.Investigation;var state=Model.Evaluation;var question=Model.Catalogue.Questions.SingleOrDefault(q=>q.Id==(string?)ViewData["Question"]);var previous=row?.Answers.LastOrDefault(a=>a.Question==question?.Id);
}
<link rel="stylesheet" href="~/css/writer3.css" asp-append-version="true" />
<div class="writer3 investigation" data-book-id="@Model.BookID" data-investigation-id="@row?.ID">
<header class="writer3-header"><div><p class="eyebrow">Writer · Explore</p><h1>Work through a story concern <help-icon key="writer3.investigations" /></h1><p>You don't need to know the answer yet. We can work through it one question at a time.</p></div></header>
<p class="alert alert-info">Development preview · This small test catalogue exercises the mechanism. Its suggestions are not production writing guidance. It uses your answers, without AI or manuscript analysis.</p>
<div class="writer3-workspace">
<section class="writer3-panel" aria-labelledby="investigation-question">
@if(row==null){
<h2 id="investigation-question">What's troubling you about your story?</h2>
<form asp-action="Start" method="post"><input type="hidden" name="bookId" value="@Model.BookID" /><fieldset><legend class="visually-hidden">Choose a starting concern</legend>
@foreach(var concern in Model.Catalogue.Concerns){<label class="investigation-choice"><input type="radio" name="concern" value="@concern.Id" required /> @concern.Text</label>}
</fieldset><button class="btn btn-primary" type="submit">Begin</button></form>
}else if(question!=null){
<p class="writer3-caption">@row.Answers.Count questions answered · There is no fixed number needed for a useful next step.</p>
<h2 id="investigation-question">@question.Text</h2>@if(question.Help!=""){<p id="question-help">@question.Help</p>}
<form asp-action="Answer" method="post" data-investigation-answer>
<input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/><input type="hidden" name="question" value="@question.Id"/>
<fieldset><legend class="visually-hidden">Your answer</legend>@foreach(var option in question.Options){<label class="investigation-choice"><input type="radio" name="option" value="@option.Id" checked="@(previous?.Option==option.Id)" /> @option.Text</label>}</fieldset>
@if(question.AllowExplanation){<label for="investigation-explanation">Anything you'd like to explain? <span class="muted">Optional</span></label><textarea class="form-control" id="investigation-explanation" name="explanation" maxlength="2000" rows="3">@(previous?.Explanation??(row.DraftQuestion==question.Id?row.DraftExplanation:null))</textarea>}
<div class="investigation-actions">
@if(row.Answers.LastOrDefault(a=>a.Question!=question.Id) is {} back){<a asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-id="@row.ID" asp-route-question="@back.Question">Back to an earlier answer</a>}
<button class="btn btn-primary" name="operation" value="answer">Continue</button><button class="btn btn-outline-secondary" name="operation" value="save">Save for later</button></div>
</form>
}else{
<h2 id="investigation-question">@(state!.Recommendations.Count>0?"A possible next step":"Let's leave room for uncertainty")</h2>
<p>Your answers suggest the following. This reflects the questionnaire, not an analysis of your manuscript.</p><p class="writer3-caption">Tools open in another tab. Your investigation stays here so you can return to it.</p>
@if(state.Recommendations.Count==0){<p>There isn't enough independent, consistent evidence for an available tool recommendation yet. You can revisit an answer or save this investigation. @if(state.Outcome=="No suitable destination currently available"){<span>A relevant tool is currently unavailable.</span>}</p>}
@foreach(var id in state.Recommendations){var h=Model.Catalogue.Hypotheses.Single(h=>h.Id==id);<section class="writer3-inset"><h3>@h.Summary</h3><p>@h.Reason</p><p class="muted">@h.Uncertainty</p>
<p>Answers that informed this suggestion:</p><ul>@foreach(var evidence in state.Evidence.Where(e=>e.Hypothesis==id&&e.Raw>0&&!e.Uncertain).DistinctBy(e=>e.Question).Take(3)){var q=Model.Catalogue.Questions.Single(q=>q.Id==evidence.Question);<li>@q.Text — @q.Options.Single(o=>o.Id==evidence.Option).Text</li>}</ul>
@foreach(var cap in Model.Catalogue.Capabilities.Where(d=>h.Capabilities.Contains(d.Id)&&state.AvailableCapabilities.Contains(d.Id))){<p>@cap.Description</p><form asp-action="Open" method="post" target="_blank"><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/><button class="btn btn-primary" name="capability" value="@cap.Id">@cap.ActionText <span class="visually-hidden">(opens another tab; return here afterwards)</span></button></form>}
</section>}
@if(row.Accepted){<p role="status">Your response is saved. Return to this investigation whenever you need it.</p>}
<form asp-action="Answer" method="post"><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@row.ID"/><input type="hidden" name="version" value="@row.Version"/>
<div class="investigation-actions">@if(state.Recommendations.Count>0){<button class="btn btn-outline-secondary" name="operation" value="accept">That sounds right</button>}
<button class="btn btn-outline-secondary" name="operation" value="disagree">That's not quite what I meant</button>
@if(row.Answers.Count<Model.Catalogue.MaxAnswers&&state.Candidates.Count>0){<button class="btn btn-outline-secondary" name="operation" value="further">I'd like to investigate further</button>}
<button class="btn btn-outline-secondary" name="operation" value="save">Save for later</button></div></form>
}
<p class="writer3-caption"><a asp-controller="Writer" asp-action="Explore" asp-route-bookId="@Model.BookID" asp-route-projectId="@Model.ProjectID">Return to Explore</a> · <a asp-action="Index" asp-route-bookId="@Model.BookID">Start another investigation</a></p>
</section>
<aside class="writer3-panel" aria-label="Your investigations">
@if(row!=null){<h2>Your answers</h2><p>Your answers are saved when you continue. Changing one recomputes the investigation; earlier versions remain in its history.</p><ol>@foreach(var a in row.Answers){var q=Model.Catalogue.Questions.Single(q=>q.Id==a.Question);<li><a asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-id="@row.ID" asp-route-question="@a.Question">@q.Text</a><p>@q.Options.Single(o=>o.Id==a.Option).Text</p></li>}</ol>}
<h2>Continue later</h2><ul>@foreach(var saved in Model.Saved){<li><a asp-action="Index" asp-route-bookId="@Model.BookID" asp-route-id="@saved.ID">@Model.Catalogue.Concerns.FirstOrDefault(c=>c.Id==saved.Concern)?.Text · @saved.UpdatedUtc.ToString("dd MMM HH:mm") UTC</a></li>}</ul>
@if((await Authorization.AuthorizeAsync(User,null,"AdminOnly")).Succeeded){<p><a href="/admin/writer-investigations">Test catalogue and simulator</a></p>@if(row!=null){<a href="/admin/writer-investigations/simulator?bookId=@Model.BookID&id=@row.ID" target="_blank">Private diagnostics and replay</a>}}
</aside>
</div>
</div>
@section Scripts{<script src="~/js/writer-investigations.js" asp-append-version="true"></script>}

View File

@ -0,0 +1,13 @@
@using System.Text.Json
@using PlotLine.Services.Investigations
@model PlotLine.Models.Investigations.InvestigationPage
@{ViewData["Title"]="Investigation simulator";ViewData["ProjectSection"]="Writer";var e=Model.Evaluation!;var row=Model.Investigation!;}
<h1>Investigation simulator and replay</h1><p>Private author-owned test @row.ID · catalogue @row.CatalogueVersion · @row.Answers.Count answers · state @e.Outcome</p>
<p><a asp-action="Index" asp-route-bookId="@row.BookID" asp-route-id="@row.ID">Select or revise answers</a> · <a href="/admin/writer-investigations/diagnostics?bookId=@row.BookID&id=@row.ID">Machine-readable diagnostics</a></p>
<h2>Hypotheses and completion requirements</h2><div class="table-responsive"><table class="table"><thead><tr><th>Hypothesis</th><th>Prior</th><th>Support</th><th>Opposition</th><th>Score</th><th>Dimensions/groups</th><th>Challenged</th><th>Destination eligible</th><th>Missing requirements/conflicts</th></tr></thead><tbody>@foreach(var h in e.Hypotheses){<tr><td>@h.Id</td><td>@h.Prior</td><td>@h.Support</td><td>@h.Opposition</td><td>@h.Score</td><td>@h.Dimensions / @h.Groups</td><td>@h.Challenged</td><td>@h.Eligible</td><td>@string.Join(", ",h.Missing) @string.Join(", ",h.Conflicts)</td></tr>}</tbody></table></div>
<h2>Evidence and redundancy</h2><p>@e.RedundantContributions contributions share a dimension/group. Strongest positive/negative per group and dimension caps apply; these are evidence scores, not probabilities.</p>
<div class="table-responsive"><table class="table"><thead><tr><th>Question/answer</th><th>Hypothesis</th><th>Dimension/aspect</th><th>Group</th><th>Raw contribution</th><th>Uncertain</th></tr></thead><tbody>@foreach(var v in e.Evidence){<tr><td>@v.Question / @v.Option</td><td>@v.Hypothesis</td><td>@v.Dimension / @v.Aspect</td><td>@v.Group</td><td>@v.Raw</td><td>@v.Uncertain</td></tr>}</tbody></table></div>
<h2>Next-question selection</h2><p>Selected: @e.NextQuestion</p><ol>@foreach(var q in e.Candidates){<li><strong>@q.Id (@q.Rank)</strong> @q.Reason</li>}</ol>
<h2>Destination mappings</h2><ul>@foreach(var d in Model.Catalogue.Capabilities){<li>@d.Id → @d.Resolver · available @e.AvailableCapabilities.Contains(d.Id) · @d.Description</li>}</ul>
<h2>Replay saved states</h2><p>Each committed action contains the reproducible state and evaluation. Revisions replace live evidence while retaining these earlier events.</p>
@foreach(var json in (string[]?)ViewData["Events"]??[]){using var doc=JsonDocument.Parse(json);var state=doc.RootElement.GetProperty("state").Deserialize<PlotLine.Models.Investigations.Investigation>(CatalogueValidator.Json)!;var recorded=doc.RootElement.GetProperty("evaluation").GetRawText();var old=JsonSerializer.Deserialize<PlotLine.Models.Investigations.Evaluation>(recorded,CatalogueValidator.Json)!;var replay=InvestigationEngine.Evaluate(Model.Catalogue,state.Concern,state.Answers,old.AvailableCapabilities.ToHashSet(),state.ContinueUntil);var identical=JsonSerializer.Serialize(replay,CatalogueValidator.Json)==JsonSerializer.Serialize(JsonSerializer.Deserialize<PlotLine.Models.Investigations.Evaluation>(recorded,CatalogueValidator.Json),CatalogueValidator.Json);<details><summary>Version @state.Version · recomputation matches: @identical</summary><pre>@json</pre></details>}

View File

@ -86,3 +86,13 @@
[data-review-form]{margin:.8rem 0;padding:.7rem 0;border-block:1px solid var(--pd-border-subtle)}
[data-review-error]{border-left:3px solid var(--pd-accent);padding:.6rem}
.writer3 .reader-metadata summary{font-size:.82rem;color:var(--pd-muted)}
/* Phase3D.1F: continuous manuscript reading uses the document, not a viewport panel. */
.writer3-destination[data-writer-destination=Review]{height:auto;overflow:visible}
.writer3-destination[data-writer-destination=Review] .writer3-split{flex:none;align-items:start}
.writer3-destination[data-writer-destination=Review] .writer3-main{height:auto;max-height:none;overflow:visible;scrollbar-gutter:auto}
.writer3-destination[data-writer-destination=Review] .writer3-reference{position:sticky;top:1rem;height:auto;max-height:calc(100dvh - 2rem);overflow:auto}
.writer3-destination[data-writer-destination=Review] .writer3-divider{position:sticky;top:1rem;height:calc(100dvh - 2rem);align-self:start}
.writer3-destination[data-writer-destination=Review] .writer3-split[data-narrow=true][data-overlay=true]>.writer3-reference{position:fixed;inset:1rem 1rem 1rem auto;width:min(calc(100% - 2rem),520px);height:auto;max-height:calc(100dvh - 2rem);z-index:1040}
.investigation{max-width:1200px;margin:1rem auto;padding:0 1rem}.investigation-choice{display:flex;gap:.7rem;padding:.8rem;border:1px solid var(--pd-border);border-radius:8px;margin:.6rem 0;align-items:baseline}.investigation-choice:has(input:checked){border-color:var(--pd-accent)}.investigation-actions{display:flex;flex-wrap:wrap;align-items:center;gap:.7rem;margin:1rem 0}.investigation textarea{margin:.6rem 0}.investigation pre{max-height:28rem;overflow:auto}.investigation fieldset{min-width:0}
@media(max-width:800px){.investigation>.writer3-workspace{grid-template-columns:minmax(0,1fr)}}

View File

@ -58,7 +58,7 @@
? 'Updated chapter available. It will appear after you clear the text selection.'
: pause.checked ? 'Updated chapter available. Automatic updates are paused.' : 'Updated chapter available.';
};
const scrollPanel=root.closest('.writer3-main');
const scrollPanel=root.closest('[data-writer-destination=Review]') ? null : root.closest('.writer3-main');
const viewportTop = () => root.dataset.focus === 'true' ? root.getBoundingClientRect().top : scrollPanel?.getBoundingClientRect().top||0;
const rememberPosition = () => {
const top = viewportTop();

View File

@ -0,0 +1,11 @@
// No inference, requests or tracking: native forms persist explicit actions.
(() => {
const form=document.querySelector('[data-investigation-answer]');if(!form)return;
let dirty=false,submitting=false;form.addEventListener('input',()=>dirty=true);
form.addEventListener('submit',event=>{
if(event.submitter?.value==='answer'&&!form.querySelector('[name=option]:checked')){event.preventDefault();form.querySelector('[name=option]')?.focus();return;}
if(submitting){event.preventDefault();return;}submitting=true;dirty=false;
});
window.addEventListener('pageshow',()=>submitting=false);
window.addEventListener('beforeunload',event=>{if(dirty){event.preventDefault();event.returnValue='';}});
})();

View File

@ -103,7 +103,7 @@
const chrome = (header?.getBoundingClientRect().height || 0) + toolbar.getBoundingClientRect().height
+ parseFloat(style.paddingTop) + parseFloat(style.paddingBottom)
+ (headerStyle ? parseFloat(headerStyle.marginBottom) : 0);
root.classList.toggle('writer3-flow', available < chrome + 160);
root.classList.toggle('writer3-flow', destination === 'Review' || available < chrome + 160);
root.style.setProperty('--writer-workspace-height', `${Math.max(0, Math.floor(available))}px`);
const next = workspace.clientWidth < 900;
if (next !== narrow) {