@validation-os/core 0.15.3 → 0.15.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -651,4 +651,4 @@ export {
651
651
  assembleJourney,
652
652
  derivation_exports
653
653
  };
654
- //# sourceMappingURL=chunk-7QK3MHU6.js.map
654
+ //# sourceMappingURL=chunk-HMAHBGOJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/derivation/index.ts","../src/derivation/round.ts","../src/derivation/rung.ts","../src/derivation/completeness.ts","../src/derivation/strength.ts","../src/derivation/source-quality.ts","../src/types.ts","../src/derivation/confidence.ts","../src/derivation/attribution.ts","../src/derivation/progress.ts","../src/derivation/experiment-confidence.ts","../src/derivation/trajectory.ts","../src/derivation/impact.ts","../src/derivation/risk.ts","../src/derivation/portfolio.ts","../src/derivation/next-move.ts","../src/derivation/stage.ts","../src/derivation/journey.ts"],"sourcesContent":["/**\n * The shared derivation module — pure functions, no I/O.\n *\n * The same module the dashboard, the API (derive-on-write), and Claude Code\n * audits all call, so every writer computes the four derived numbers\n * identically. Ported from the instance's `migration/remodel.mjs` and\n * kept in lock-step with `skills/_shared/ontology.yaml`.\n */\nexport { round2 } from \"./round.js\";\nexport { RUNG_ANCHOR } from \"./rung.js\";\nexport {\n COMPLETENESS_SLOTS,\n completenessSlotPresence,\n missingCompletenessSlots,\n assumptionCompleteness,\n assumptionComplete,\n} from \"./completeness.js\";\nexport type { CompletenessSlot, CompletenessInput } from \"./completeness.js\";\nexport { sign, isConcluded, readingStrength } from \"./strength.js\";\nexport type { StrengthInput } from \"./strength.js\";\nexport { sourceQuality } from \"./source-quality.js\";\nexport {\n confidence,\n scoreAndDedupe,\n commitmentFactor,\n COMMITMENT_FOUND,\n W0,\n W0_BY_RUNG,\n w0ForRung,\n} from \"./confidence.js\";\nexport type { ConfidenceReadingInput, Scored } from \"./confidence.js\";\nexport { confidenceAttribution } from \"./attribution.js\";\nexport type {\n Attribution,\n AttributionReadingInput,\n Mover,\n MoverKind,\n} from \"./attribution.js\";\nexport { experimentProgress } from \"./progress.js\";\nexport type { BarLineInput, Progress } from \"./progress.js\";\nexport { experimentConfidence, MAX_STRENGTH } from \"./experiment-confidence.js\";\nexport type {\n ExperimentConfidenceBarInput,\n ExperimentConfidenceReadingInput,\n} from \"./experiment-confidence.js\";\nexport { confidenceTrajectory } from \"./trajectory.js\";\nexport type { TrajectoryPoint } from \"./trajectory.js\";\nexport { derivedImpacts } from \"./impact.js\";\nexport type { ImpactAssumptionInput } from \"./impact.js\";\nexport { risk } from \"./risk.js\";\nexport { beliefRisk, portfolioProgress } from \"./portfolio.js\";\nexport type {\n BeliefRisk,\n PortfolioBeliefInput,\n PortfolioProgress,\n} from \"./portfolio.js\";\nexport { rankNextMoves, KILL_LANE_THRESHOLD } from \"./next-move.js\";\nexport type {\n MoveKind,\n NextMove,\n NextMoveAssumptionInput,\n NextMoveExperimentInput,\n NextMoveDecisionInput,\n NextMoveInput,\n} from \"./next-move.js\";\nexport {\n beliefTestMeters,\n classifyStage,\n deriveBeliefStage,\n emptyTestMeter,\n} from \"./stage.js\";\nexport type {\n BeliefStage,\n BeliefStageInput,\n ConfSign,\n StageExperimentInput,\n StageKey,\n TestMeter,\n} from \"./stage.js\";\nexport { assembleJourney } from \"./journey.js\";\nexport type {\n AssembleJourneyInput,\n JourneyBeliefInput,\n JourneyEvent,\n JourneyEventKind,\n JourneyExperimentInput,\n} from \"./journey.js\";\n","/**\n * Round to 2 decimals, matching the migration's `+(n).toFixed(2)`.\n * Derived values are stored/displayed rounded; full precision is only used\n * transiently inside a single computation.\n */\nexport function round2(n: number): number {\n return Number(n.toFixed(2));\n}\n","/**\n * The lens-aware ladder anchors (DEV-5879).\n *\n * Source of truth: `skills/_shared/ontology.yaml` → `vocabularies.rung`. A\n * rung is an evidence TYPE; magnitude band (Low/Typical/High) is the intensity\n * within a type. The band applies to EVERY rung, so every rung looks up its\n * anchor through `RUNG_ANCHOR[rung][band]`.\n *\n * Talk: 3 / 6 / 10 (Opinion / Pitch-deck / Anecdotal merged)\n * Desk research: 15 / 15 / 15 (flat — desk research has no meaningful bands,\n * but the field exists for uniformity)\n * Signed up: 30 / 50 / 70 (consumer lens's first do-rung)\n * Observed usage: 30 / 50 / 70 (consumer lens; was Prototype usage + Survey\n * at scale, now collapsed)\n * Signed intent: 30 / 50 / 70 (commercial/investor lens)\n * Paying users: 30 / 50 / 70 (commercial/investor lens)\n *\n * The lens determines which \"do\" rungs are available; Talk + Desk work for\n * any lens. The rung-to-lens mapping is a grading guideline, not a schema\n * constraint — any Rung can appear on any assumption.\n */\nimport type { MagnitudeBand, Rung } from \"../types.js\";\n\nexport const RUNG_ANCHOR: Record<Rung, Record<MagnitudeBand, number>> = {\n Talk: { Low: 3, Typical: 6, High: 10 },\n \"Desk research\": { Low: 15, Typical: 15, High: 15 },\n \"Signed up\": { Low: 30, Typical: 50, High: 70 },\n \"Observed usage\": { Low: 30, Typical: 50, High: 70 },\n \"Signed intent\": { Low: 30, Typical: 50, High: 70 },\n \"Paying users\": { Low: 30, Typical: 50, High: 70 },\n};","/**\n * Assumption completeness — a derived readiness meter, never stored.\n *\n * Replaces the old Gaps / presence-field machinery (OPS-1305): an assumption's\n * Draft-vs-Live readiness is the structural presence of its slots, not a set of\n * hand-maintained tags. `Completeness %` is `filled slots / all slots`; a\n * fully-filled assumption reads 100 and is Live-ready, an empty draft reads low.\n *\n * Slots (each an equal fifth):\n * Description · Lens · Impact · Scoring justification · Dependencies traced\n *\n * Pure, no backend dependency — the same function the recompute pass stamps\n * into the derived tuple and the audit checks readiness against.\n */\n\n/** The structural slots whose presence makes an assumption Live-ready. */\nexport const COMPLETENESS_SLOTS = [\n \"Description\",\n \"Lens\",\n \"Impact\",\n \"Scoring justification\",\n \"Dependencies traced\",\n] as const;\n\nexport type CompletenessSlot = (typeof COMPLETENESS_SLOTS)[number];\n\n/** The record shape completeness reads — an assumption's structural fields. */\nexport interface CompletenessInput {\n Description?: unknown;\n Lens?: unknown;\n Impact?: unknown;\n \"Scoring justification\"?: unknown;\n dependsOnIds?: unknown;\n enablesIds?: unknown;\n}\n\n/** A text slot is present only when it is a non-blank string. */\nfunction hasText(value: unknown): boolean {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\n/** Impact is present when it is a real finite number (0 is a valid score). */\nfunction hasNumber(value: unknown): boolean {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\n/** Dependencies are traced once at least one Depends on / Enables link exists. */\nfunction hasAny(value: unknown): boolean {\n return Array.isArray(value) && value.length > 0;\n}\n\n/** Whether each slot is structurally present. */\nexport function completenessSlotPresence(\n record: CompletenessInput,\n): Record<CompletenessSlot, boolean> {\n return {\n Description: hasText(record.Description),\n Lens: hasText(record.Lens),\n Impact: hasNumber(record.Impact),\n \"Scoring justification\": hasText(record[\"Scoring justification\"]),\n \"Dependencies traced\":\n hasAny(record.dependsOnIds) || hasAny(record.enablesIds),\n };\n}\n\n/** The slots that are absent or blank on a record. */\nexport function missingCompletenessSlots(\n record: CompletenessInput,\n): CompletenessSlot[] {\n const present = completenessSlotPresence(record);\n return COMPLETENESS_SLOTS.filter((slot) => !present[slot]);\n}\n\n/** Completeness as a whole-number percentage (0, 20, 40, 60, 80, 100). */\nexport function assumptionCompleteness(record: CompletenessInput): number {\n const present = completenessSlotPresence(record);\n const filled = COMPLETENESS_SLOTS.filter((slot) => present[slot]).length;\n return Math.round((filled / COMPLETENESS_SLOTS.length) * 100);\n}\n\n/** True when every slot is present — the structural precondition to be Live. */\nexport function assumptionComplete(record: CompletenessInput): boolean {\n return missingCompletenessSlots(record).length === 0;\n}\n","/**\n * Strength — the signed reading value `s` the Confidence average reads.\n *\n * Formula (`ontology.yaml` → `derivations.strength`):\n * rung anchor × magnitude band × sign(Result)\n * — Validated positive, Invalidated negative; 0 unless Validated/Invalidated.\n *\n * Every rung now carries a magnitude band (0.14); the lookup is the same for\n * testing and market rungs.\n */\nimport type { MagnitudeBand, Result, Rung } from \"../types.js\";\nimport { RUNG_ANCHOR } from \"./rung.js\";\n\nexport function sign(result: Result): -1 | 0 | 1 {\n if (result === \"Validated\") return 1;\n if (result === \"Invalidated\") return -1;\n return 0;\n}\n\n/** A reading counts toward Confidence only once concluded either way; an\n * Inconclusive reading carries no signal. The single definition the whole\n * derivation module (and its record→input mappers) share. */\nexport function isConcluded(result: Result): boolean {\n return result === \"Validated\" || result === \"Invalidated\";\n}\n\nexport interface StrengthInput {\n rung: Rung;\n result: Result;\n /** Magnitude band; defaults to \"Typical\" when absent. Applies to ALL rungs. */\n magnitudeBand?: MagnitudeBand;\n}\n\nexport function readingStrength(input: StrengthInput): number {\n const s = sign(input.result);\n if (s === 0) return 0; // Inconclusive contributes nothing.\n const band = input.magnitudeBand ?? \"Typical\";\n return (RUNG_ANCHOR[input.rung]?.[band] ?? 0) * s;\n}","/**\n * Source quality — Representativeness × Credibility.\n *\n * Scales a Reading's *weight* in the Confidence average, within its rung.\n * We keep the raw product as the weight (matching the migration's\n * `remodel.mjs`); the five display anchors {0.25, 0.35, 0.5, 0.7, 1.0} are a\n * storage/display concern, not the weight used in the average.\n */\nimport { round2 } from \"./round.js\";\n\nexport function sourceQuality(\n representativeness: number,\n credibility: number,\n): number {\n return round2(representativeness * credibility);\n}\n","/**\n * Shared registry types — the field vocabulary the whole system speaks.\n *\n * These mirror `skills/_shared/registry-schema.md` and `ontology.yaml` (the\n * single source of truth). Field *meaning* lives there; this file is the\n * checkable TypeScript shape the packages import.\n */\n\n/**\n * The five registers. `goals` was unified into `experiments` and the `people`\n * reference collection retired (OPS-1305): Owner / Agreed by now reference a\n * dashboard user (the auth-sourced team list), not a register row.\n */\nexport const REGISTERS = [\n \"assumptions\",\n \"experiments\",\n \"readings\",\n \"decisions\",\n \"glossary\",\n] as const;\nexport type Register = (typeof REGISTERS)[number];\n\n/** There is no reference collection any more — a collection is a register. */\nexport type Collection = Register;\n\n/** Every stored record carries an id, a version, and timestamps. */\nexport interface BaseRecord {\n id: string;\n /** Optimistic-concurrency token; bumped on every write. */\n version: number;\n createdAt: string;\n updatedAt: string;\n}\n\n// ── Vocabularies (canonical select-option lists) ────────────────────────────\n\nexport type AssumptionStatus = \"Draft\" | \"Live\" | \"Invalidated\";\n/**\n * The unified evidence-plan lifecycle (OPS-1305). `Draft` is the new gate a\n * commit clears (Draft→Running); conclude+verdict stays the Running→Closed\n * gate. Absorbs what the retired Goal record's status used to carry.\n */\nexport type ExperimentStatus = \"Draft\" | \"Running\" | \"Closed\" | \"Archived\";\nexport type DecisionStatus =\n | \"Active\"\n | \"Provisional\"\n | \"Superseded\"\n | \"Reversed\";\nexport type GlossaryStatus = \"Active\" | \"Provisional\" | \"Superseded\";\n\nexport type Result = \"Validated\" | \"Invalidated\" | \"Inconclusive\";\nexport type MagnitudeBand = \"Low\" | \"Typical\" | \"High\";\nexport type Feasibility = \"High\" | \"Medium\" | \"Low\";\n\n/**\n * The lens-aware ladder (DEV-5879). A rung is an evidence TYPE; magnitude band\n * (Low/Typical/High) is the intensity *within* a type. The band applies to\n * EVERY rung, so every rung looks up its anchor through\n * `RUNG_ANCHOR[rung][band]`.\n *\n * Talk: 3 / 6 / 10 (Opinion / Pitch-deck / Anecdotal merged)\n * Desk research: 15 / 15 / 15 (flat)\n * Signed up: 30 / 50 / 70 (consumer lens's first do-rung)\n * Observed usage: 30 / 50 / 70 (consumer lens; was Prototype usage + Survey\n * at scale)\n * Signed intent: 30 / 50 / 70 (commercial/investor lens)\n * Paying users: 30 / 50 / 70 (commercial/investor lens)\n *\n * The lens determines which \"do\" rungs are available; Talk + Desk work for any\n * lens. The rung-to-lens mapping is a grading guideline, not a schema\n * constraint — any Rung can appear on any assumption.\n */\nexport const TESTING_RUNGS = [\n \"Talk\",\n \"Desk research\",\n \"Signed up\",\n \"Observed usage\",\n] as const;\nexport const MARKET_RUNG_VALUES = [\"Signed intent\", \"Paying users\"] as const;\nexport type TestingRung = (typeof TESTING_RUNGS)[number];\nexport type MarketRung = (typeof MARKET_RUNG_VALUES)[number];\nexport type Rung = TestingRung | MarketRung;\n\n/** Representativeness and Credibility are each picked from these. */\nexport type SourceQualityPick = 1.0 | 0.7 | 0.5;\n\n// ── Records ─────────────────────────────────────────────────────────────────\n\n/** The derived numbers stored on an assumption (never hand-typed). */\nexport interface AssumptionDerived {\n derivedImpact: number;\n risk: number;\n confidence: number;\n /** Structural readiness meter, 0–100 (see `derivation/completeness.ts`). */\n completeness: number;\n}\n\nexport interface AssumptionRecord extends BaseRecord {\n Title: string;\n Description: string;\n Lens: string | null;\n Theme: string[];\n /** The hand-scored seed (0–100), the only hand-scored number here. */\n Impact: number | null;\n Status: AssumptionStatus;\n /** Reference to a dashboard user (auth team list), not a `people` row. */\n Owner: string[];\n moot: boolean;\n /**\n * Kept, narrowed to the Impact-seed rationale (OPS-1305): why the seed\n * `Impact` was scored as it was, incl. dated moot lines. The `5 Whys`,\n * `Metric for truth`, and `Gaps` fields are gone — the why-trace lives in the\n * `Depends on / Enables` chain and the audit check-types are transient grill\n * stages, not stored tags. Readiness is the derived `completeness`.\n */\n \"Scoring justification\": string;\n dependsOnIds: string[];\n enablesIds: string[];\n contradictsIds: string[];\n readingIds: string[];\n derived: AssumptionDerived;\n}\n\n/**\n * One belief's scoring inside a reading — the per-assumption verdict an\n * artifact carries. A reading (one artifact ROW) may score several beliefs at\n * once. The Rung is a property of the artifact, so it (and the market magnitude\n * band) lives on the row, ONE per artifact (OPS 0.10): a reading is at a single\n * evidence rung and reads for/against each belief at that rung. Only the Result\n * and its rationale vary per belief. `strength` is derived (row rung × sign of\n * this belief's Result), never hand-typed.\n */\nexport interface BeliefScore {\n assumptionId: string;\n Result: Result;\n /** The rationale for this belief's Result at the row's rung. */\n \"Grading justification\": string;\n /** The verbatim quote or observed fact this belief was graded from. */\n excerpt?: string;\n /** Derived per belief: row rung anchor × sign(Result) [× row magnitude band]. */\n derived: { strength: number };\n /** Provenance: the original reading id this belief was migrated from. */\n sourceReadingId?: string;\n /** Optional review caveat, e.g. a second-hand-credibility note. */\n reviewNote?: string;\n}\n\nexport interface ReadingRecord extends BaseRecord {\n Title: string;\n /** The independence/dedupe key — the generator (person / dataset / cohort). */\n Source: string | null;\n /**\n * Provenance links (recording, dashboard, CRM row, user id) — 0..N, drives no\n * math and never keys dedupe (OPS-1305). Split out from `Source` so the\n * dedupe key stays narrow.\n */\n contextLinks: string[];\n /** The originating plan, or null for a bare/found reading (no Goal origin). */\n experimentId: string | null;\n /** The evidence rung — one per artifact; every belief is scored at it (OPS 0.10). */\n Rung: Rung;\n /** For a Market-rung reading: the magnitude band from the absolute outcome. */\n magnitudeBand?: MagnitudeBand;\n Representativeness: SourceQualityPick;\n Credibility: SourceQualityPick;\n Date: string | null;\n Owner: string[];\n /** Free-text narrative of the reading. */\n body?: string;\n /** Per-belief scores — one artifact row can score several beliefs at once. */\n beliefs: BeliefScore[];\n /** Convenience projection of `beliefs[].assumptionId`; kept in sync on write. */\n assumptionIds: string[];\n derived: { sourceQuality: number };\n}\n\n/**\n * A pre-registered bar line — the per-belief pass/fail test on an experiment,\n * stored as an embedded array on the experiment (no identity of its own; see\n * `connectors/nosql-schema.md`). `barVerdict` is set once at closure and is a\n * report only — never folded into Confidence.\n */\nexport interface BarLine {\n assumptionId: string;\n rightIf: string;\n wrongIf?: string | null;\n plannedRung: Rung;\n barVerdict?: Result | null;\n}\n\n/**\n * The derived numbers stored on an experiment (never hand-typed).\n * `experimentConfidence` is the [0, 100] confidence gauge (50 = neutral),\n * coverage-gated and verdict-aligned; see `derivation/experiment-confidence.ts`.\n */\nexport interface ExperimentDerived {\n experimentConfidence: number;\n}\n\nexport interface ExperimentRecord extends BaseRecord {\n Title: string;\n Instrument: string | null;\n Feasibility: Feasibility | null;\n Status: ExperimentStatus;\n /** Free-text narrative of the plan. */\n body?: string;\n closureReason: \"Completed\" | \"Early-stop\" | \"Kill\" | null;\n /** Optional deadline a committed plan carries (folded in from the Goal). */\n Deadline: string | null;\n /** Terminal closure outcome, null until Closed (folded in from the Goal). */\n Outcome: \"Achieved\" | \"Missed\" | \"Dropped\" | null;\n /** Reference to a dashboard user, not a `people` row. */\n Owner: string[];\n Date: string | null;\n /** The embedded pre-registered bar lines; drives progress-to-conclusion. */\n barLines: BarLine[];\n /** Convenience projection: the assumptions the bar lines test. */\n barLineAssumptionIds: string[];\n /** Derived numbers — recomputed on every touching write. */\n derived?: ExperimentDerived;\n}\n\nexport interface DecisionRecord extends BaseRecord {\n Title: string;\n Status: DecisionStatus;\n /** The one-line statement of what was decided (promoted from the body). */\n Statement: string;\n /** Why the Unanimity score was scored as it was (promoted from the body). */\n \"Unanimity justification\": string;\n /** References to dashboard users (auth team list), not `people` rows. */\n Owner: string[];\n \"Agreed by\": string[];\n basedOnIds: string[];\n resolvesIds: string[];\n}\n\n/** One structured \"don't say\" entry on a glossary term. */\nexport interface GlossaryAvoid {\n audience: string;\n phrase: string;\n fix: string;\n}\n\nexport interface GlossaryRecord extends BaseRecord {\n Title: string;\n Status: GlossaryStatus;\n /** All properties, no body (OPS-1305): the terminology check parses these. */\n Definition: string;\n Avoid: GlossaryAvoid[];\n \"How it differs\": string;\n}\n\n/** A record of any register — the DataProvider's currency. */\nexport type AnyRecord = BaseRecord & Record<string, unknown>;\n\n// ── Relations (both-ends links) ─────────────────────────────────────────────\n\n/** A pointer to one record. */\nexport interface RecordRef {\n register: Collection;\n id: string;\n}\n\n/** The relations the dashboard can set (each writes both ends). */\nexport type Relation =\n | \"assumption-reading\"\n | \"assumption-depends-on\"\n | \"assumption-contradicts\"\n | \"reading-experiment\"\n | \"decision-based-on\"\n | \"decision-resolves\";\n","/**\n * Confidence — signed −100…100, 0 = no evidence.\n *\n * Formula (`ontology.yaml` → `derivations.confidence`):\n * (Σ wi·si) / (Σ_rung W0[rung] + Σ wi), per-rung W0,\n * wi = |si| × Source quality × commitment, si = the reading's signed Strength,\n * commitment = 1.0 for an experiment-linked reading, 0.85 for a found one.\n *\n * W0 is per-rung: each rung has its own prior weight controlling how many\n * distinct sources it takes to approach that rung's anchor (cap). Desk\n * research has a low W0 (2 — one authoritative source nearly saturates);\n * talk rungs have a higher W0 (6.5 — needs ~10 readings to approach the\n * cap); do-rungs (Survey/Prototype/Signed/Paying) have high W0s (~120-410\n * — needs ~20 readings to reach 75% of cap). When readings span multiple\n * rungs, each rung with evidence contributes its W0 to the denominator\n * once (one prior per evidence stream).\n *\n * Only concluded Validated/Invalidated readings enter. Readings sharing a\n * Source against one belief dedupe to the strongest (largest |si|, most\n * recent on ties). Market-rung readings never dedupe (each closed commitment\n * is its own unit). No corroboration bump.\n */\nimport type { MagnitudeBand, Result, Rung } from \"../types.js\";\nimport { MARKET_RUNG_VALUES } from \"../types.js\";\nimport { round2 } from \"./round.js\";\nimport { sourceQuality } from \"./source-quality.js\";\nimport { isConcluded, readingStrength } from \"./strength.js\";\n\n/** Market rungs never dedupe (each closed commitment is its own unit). */\nconst MARKET_RUNG_SET = new Set<Rung>(MARKET_RUNG_VALUES);\nfunction isMarketRung(rung: Rung): boolean {\n return MARKET_RUNG_SET.has(rung);\n}\n\n/**\n * Per-rung prior weight — controls how many distinct sources approach the\n * rung's anchor. Tuned so: Desk 2 readings → ~90% of cap; talk 10 readings →\n * ~90% of cap; do-rungs 20 readings → ~75% of cap. See\n * `docs/evidence-ladder.md` for the derivation.\n */\nexport const W0_BY_RUNG: Record<Rung, number> = {\n // Talk — 10 readings → ~90% of cap.\n Talk: 6.5,\n // Desk research — 2 readings → ~90% of cap (authoritative, rare).\n \"Desk research\": 2,\n // All do-rungs — 20 readings → ~75% of cap. Equal ceilings (70) and equal\n // W0s across consumer (Signed up / Observed usage) and commercial\n // (Signed intent / Paying users) lenses.\n \"Signed up\": 327,\n \"Observed usage\": 327,\n \"Signed intent\": 327,\n \"Paying users\": 327,\n};\n\n/**\n * The neutral prior weight for a rung — how much evidence at this rung is\n * needed to overcome the prior. Per-rung (not a flat constant): see\n * {@link W0_BY_RUNG}.\n */\nexport function w0ForRung(rung: Rung): number {\n return W0_BY_RUNG[rung] ?? 100;\n}\n\n/**\n * The legacy flat W0 — retained for backwards compatibility only. New code\n * should use {@link w0ForRung}. Equal to the old default of 100.\n * @deprecated Use {@link w0ForRung} for per-rung priors.\n */\nexport const W0 = 100;\n\n/**\n * Commitment factor for a *found* reading — one with no originating experiment.\n * A pre-registered (experiment-linked) reading weighs at full commitment (1.0);\n * a found reading is discounted to this. It is a SMALL tiebreaker: it scales the\n * weight only, never the Strength, so it can never reorder readings across rungs\n * (\"Rung dominates\").\n */\nexport const COMMITMENT_FOUND = 0.85;\n\nexport interface ConfidenceReadingInput {\n id: string;\n /** The independence-dedupe key. Null falls back to the reading's own id. */\n source: string | null;\n rung: Rung;\n result: Result;\n representativeness: number;\n credibility: number;\n /** ISO date; used only as the dedupe tie-break (most recent wins). */\n date?: string | null;\n magnitudeBand?: MagnitudeBand;\n /**\n * The originating experiment, or null/undefined for a *found* reading. Drives\n * the commitment factor in the weight (found → {@link COMMITMENT_FOUND}).\n */\n experimentId?: string | null;\n}\n\n/** The commitment weighting for a reading: full for committed, discounted for found. */\nexport function commitmentFactor(experimentId: string | null | undefined): number {\n return experimentId ? 1.0 : COMMITMENT_FOUND;\n}\n\nexport interface Scored {\n input: ConfidenceReadingInput;\n strength: number;\n sq: number;\n /** The reading's weight in the average: |strength| × Source quality × commitment. */\n weight: number;\n}\n\n/**\n * Score every concluded reading and resolve the Source dedupe — the shared\n * front half of the Confidence average. `confidence()` reduces the winners to\n * a number; `confidenceAttribution()` reuses the same winners so the movers it\n * reports always decompose the very number the drawer shows. Market rungs never\n * dedupe (each closed commitment is its own unit).\n */\nexport function scoreAndDedupe(readings: ConfidenceReadingInput[]): Scored[] {\n const scored: Scored[] = readings\n .filter((r) => isConcluded(r.result))\n .map((r) => {\n const strength = readingStrength(r);\n const sq = sourceQuality(r.representativeness, r.credibility);\n const weight = Math.abs(strength) * sq * commitmentFactor(r.experimentId);\n return { input: r, strength, sq, weight };\n })\n .filter((x) => x.strength !== 0);\n\n const best = new Map<string, Scored>();\n for (const x of scored) {\n if (isMarketRung(x.input.rung)) {\n best.set(x.input.id, x);\n continue;\n }\n const key = x.input.source || x.input.id;\n const cur = best.get(key);\n const better =\n !cur ||\n Math.abs(x.strength) > Math.abs(cur.strength) ||\n (Math.abs(x.strength) === Math.abs(cur.strength) &&\n (x.input.date || \"\") > (cur.input.date || \"\"));\n if (better) best.set(key, x);\n }\n return [...best.values()];\n}\n\nexport function confidence(readings: ConfidenceReadingInput[]): number {\n const winners = scoreAndDedupe(readings);\n // Per-rung prior: sum W0 once for each rung that has ≥1 concluded reading.\n // This preserves each rung's accumulation behaviour independently — desk\n // stays fast (low W0), talk stays slow (high W0) — and mixed-rung evidence\n // gets each rung's prior added once (one prior per evidence stream).\n const rungsPresent = new Set(winners.map((x) => x.input.rung));\n let den = 0;\n for (const rung of rungsPresent) den += w0ForRung(rung);\n let num = 0;\n for (const x of winners) {\n num += x.weight * x.strength;\n den += x.weight;\n }\n return den > 0 ? round2(num / den) : 0;\n}\n","/**\n * Confidence attribution — the \"what's moving the number\" half of the\n * understanding layer (OPS-1276). Decomposes an assumption's Confidence into\n * the experiments (and direct readings) contributing to it, ranked by how hard\n * each pushes the number up or down.\n *\n * A winner's contribution is its signed share of the average:\n * cᵢ = (weightᵢ · strengthᵢ) / den,\n * den = Σ_rung W0[rung] + Σ weight (one prior per rung with evidence)\n * so Σ contributions = Σ(wᵢ·sᵢ)/den = Confidence (the W0·0 prior term is 0).\n * The reveal therefore literally adds up to the hero number. Contributions are\n * grouped by the reading's experiment (experiment-less readings — bare/found —\n * fall into a \"direct\" bucket), then ranked by |contribution|. A reading's\n * origin is an experiment or nothing; the retired Goal container is gone\n * (OPS-1305).\n */\nimport { w0ForRung, scoreAndDedupe, type ConfidenceReadingInput } from \"./confidence.js\";\nimport { round2 } from \"./round.js\";\n\n/**\n * The reading shape the attribution reveal consumes. `experimentId` (the\n * grouping key, and the commitment-factor driver) lives on\n * {@link ConfidenceReadingInput}; this alias marks the attribution call sites.\n */\nexport type AttributionReadingInput = ConfidenceReadingInput;\n\n/** What a mover is anchored to — an experiment, or nothing (direct). */\nexport type MoverKind = \"experiment\" | \"direct\";\n\nexport interface Mover {\n /** Stable grouping key: the experiment id, or \"direct\". */\n key: string;\n kind: MoverKind;\n /** The experiment id when `kind === \"experiment\"`, else null. */\n experimentId: string | null;\n /** Signed push on Confidence; the whole set sums to `confidence`. */\n contribution: number;\n /** |contribution| — the rank key and the \"how hard\" magnitude. */\n magnitude: number;\n /** How many (deduped) readings back this mover. */\n readingCount: number;\n /** The winning readings' ids, for drill-through. */\n readingIds: string[];\n}\n\nexport interface Attribution {\n /** The same Confidence the derived box shows (from the same winners). */\n confidence: number;\n /** Movers ranked by |contribution|, strongest first. */\n movers: Mover[];\n}\n\nfunction bucketOf(r: AttributionReadingInput): {\n key: string;\n kind: MoverKind;\n experimentId: string | null;\n} {\n if (r.experimentId) {\n return {\n key: r.experimentId,\n kind: \"experiment\",\n experimentId: r.experimentId,\n };\n }\n return { key: \"direct\", kind: \"direct\", experimentId: null };\n}\n\nexport function confidenceAttribution(\n readings: AttributionReadingInput[],\n): Attribution {\n const winners = scoreAndDedupe(readings);\n // Per-rung prior: sum W0 once for each rung with ≥1 concluded reading,\n // matching the `confidence()` formula.\n const rungsPresent = new Set(winners.map((x) => x.input.rung));\n let den = 0;\n for (const rung of rungsPresent) den += w0ForRung(rung);\n for (const x of winners) den += x.weight;\n\n const byKey = new Map<string, Mover>();\n let num = 0;\n for (const x of winners) {\n num += x.weight * x.strength;\n const b = bucketOf(x.input as AttributionReadingInput);\n const contribution = (x.weight * x.strength) / den;\n const cur = byKey.get(b.key);\n if (cur) {\n cur.contribution += contribution;\n cur.readingCount += 1;\n cur.readingIds.push(x.input.id);\n } else {\n byKey.set(b.key, {\n key: b.key,\n kind: b.kind,\n experimentId: b.experimentId,\n contribution,\n magnitude: 0, // finalised below\n readingCount: 1,\n readingIds: [x.input.id],\n });\n }\n }\n\n const movers = [...byKey.values()].map((m) => ({\n ...m,\n contribution: round2(m.contribution),\n magnitude: round2(Math.abs(m.contribution)),\n }));\n movers.sort((a, b) => b.magnitude - a.magnitude);\n\n return {\n confidence: den > 0 ? round2(num / den) : 0,\n movers,\n };\n}\n","/**\n * Progress-to-conclusion — how close a running experiment is to concluding\n * (OPS-1276). An experiment concludes when every pre-registered bar line has\n * been given a Bar verdict; progress is the count of settled bars against the\n * total. Bar verdict is a report, never a Confidence input (nosql-schema.md),\n * so reading it here is exactly its intended use.\n */\nexport interface BarLineInput {\n /** null/\"\" until the bar is judged at closure. */\n barVerdict?: string | null;\n}\n\nexport interface Progress {\n /** Pre-registered bar lines on the experiment. */\n total: number;\n /** Bars that have a verdict. */\n settled: number;\n /** Bars still awaiting a verdict. */\n toGo: number;\n /** True once every bar is settled (and there is at least one). */\n concluded: boolean;\n}\n\nexport function experimentProgress(bars: BarLineInput[]): Progress {\n const total = bars.length;\n const settled = bars.filter(\n (b) => typeof b.barVerdict === \"string\" && b.barVerdict.trim() !== \"\",\n ).length;\n return {\n total,\n settled,\n toGo: total - settled,\n concluded: total > 0 && settled === total,\n };\n}\n","/**\n * Experiment confidence — a derived [0, 100] gauge for an evidence plan (0.14).\n *\n * Formula (`experimentConfidence`):\n * clamp(50 + 50 × C × S + 5 × A, 0, 100)\n *\n * Where:\n * B = number of bar lines\n * coveredLines = bar lines with ≥1 concluded reading (Validated/Invalidated)\n * C = |coveredLines| / max(B, 1) — coverage factor ∈ [0, 1]\n * For each concluded reading linked to the experiment (deduped by Source,\n * same rule as `confidence.ts`):\n * fᵢ = (strengthᵢ × sqᵢ) / MAX_STRENGTH (signed)\n * strengthᵢ = readingStrength({ rung, result, magnitudeBand })\n * sqᵢ = sourceQuality(representativeness, credibility)\n * F = Σ fᵢ (signed, after dedupe)\n * S = F / (1 + |F|) — soft squash, ℝ → (−1, +1)\n * A = Σ alignedⱼ / B — verdict alignment, per bar\n * alignedⱼ = +1 if barVerdict agrees with the reading sign on bar j,\n * −1 if it contradicts,\n * 0 if Inconclusive or no readings on bar j\n *\n * Neutral = 50 (no evidence yet). Validated readings fill up, Invalidated\n * pull down. Coverage-gated (no readings → C=0 → 50). The 5×A term is a small\n * verdict-alignment nudge so a plan whose bars are settled the way the evidence\n * already points inches further in that direction.\n */\nimport type { MagnitudeBand, Result, Rung } from \"../types.js\";\nimport { round2 } from \"./round.js\";\nimport { sourceQuality } from \"./source-quality.js\";\nimport { isConcluded, readingStrength, sign } from \"./strength.js\";\n\n/** The reference maximum strength — the anchor of the highest rung band. */\nexport const MAX_STRENGTH = 99;\n\nexport interface ExperimentConfidenceBarInput {\n assumptionId: string;\n /** Set at closure; null/absent until then. */\n barVerdict?: Result | null;\n}\n\nexport interface ExperimentConfidenceReadingInput {\n id: string;\n /** The independence-dedupe key. Null falls back to the reading's own id. */\n source: string | null;\n rung: Rung;\n result: Result;\n magnitudeBand?: MagnitudeBand;\n representativeness: number;\n credibility: number;\n /** The assumption (bar line) this reading scores. */\n assumptionId: string;\n}\n\nfunction clamp(n: number, lo: number, hi: number): number {\n return Math.max(lo, Math.min(hi, n));\n}\n\n/**\n * Source dedupe — same rule as `confidence.ts`: group by Source (fall back to\n * the reading's own id), keep the entry with the largest |strength|. Market\n * rungs never dedupe (each closed commitment is its own unit). Mirrored here so\n * experiment confidence stays pure and self-contained.\n */\nfunction dedupeBySource(\n readings: ExperimentConfidenceReadingInput[],\n): ExperimentConfidenceReadingInput[] {\n const MARKET = new Set<Rung>([\"Signed intent\", \"Paying users\"]);\n const best = new Map<string, ExperimentConfidenceReadingInput>();\n for (const r of readings) {\n if (MARKET.has(r.rung)) {\n best.set(r.id, r);\n continue;\n }\n const key = r.source || r.id;\n const cur = best.get(key);\n const s = Math.abs(readingStrength(r));\n const better =\n !cur ||\n s > Math.abs(readingStrength(cur)) ||\n (s === Math.abs(readingStrength(cur)) && (r.id > cur.id));\n if (better) best.set(key, r);\n }\n return [...best.values()];\n}\n\n/**\n * Compute the experiment-confidence gauge. `bars` is the experiment's bar\n * lines; `readings` is the concluded readings linked to the experiment (the\n * caller filters to the experiment's `barLineAssumptionIds`).\n */\nexport function experimentConfidence(\n bars: ExperimentConfidenceBarInput[],\n readings: ExperimentConfidenceReadingInput[],\n): number {\n const B = bars.length;\n\n // Only concluded readings enter; dedupe by Source.\n const concluded = dedupeBySource(\n readings.filter((r) => isConcluded(r.result)),\n );\n\n // Coverage: bar lines with ≥1 concluded reading.\n const barsWithReadings = new Set(\n concluded.map((r) => r.assumptionId),\n );\n const covered = bars.filter((b) => barsWithReadings.has(b.assumptionId)).length;\n const C = B > 0 ? covered / B : 0;\n\n // F = Σ fᵢ (signed).\n let F = 0;\n for (const r of concluded) {\n const strength = readingStrength(r);\n const sq = sourceQuality(r.representativeness, r.credibility);\n F += (strength * sq) / MAX_STRENGTH;\n }\n const S = F / (1 + Math.abs(F));\n\n // Verdict alignment: per bar, +1 if barVerdict agrees with the net reading\n // sign on that bar, −1 if it contradicts, 0 if Inconclusive or no readings.\n const signByBar = new Map<string, number>();\n for (const r of concluded) {\n const s = sign(r.result);\n signByBar.set(r.assumptionId, (signByBar.get(r.assumptionId) ?? 0) + s);\n }\n let A = 0;\n for (const bar of bars) {\n const net = signByBar.get(bar.assumptionId);\n if (net === undefined || net === 0) continue; // no readings or net-zero\n const v = bar.barVerdict;\n if (v !== \"Validated\" && v !== \"Invalidated\") continue; // Inconclusive / unset\n const barSign = v === \"Validated\" ? 1 : -1;\n A += net * barSign > 0 ? 1 : -1;\n }\n if (B > 0) A /= B;\n\n const raw = 50 + 50 * C * S + 5 * A;\n return round2(clamp(raw, 0, 100));\n}","/**\n * Confidence over time — the story of how the number got where it is\n * (OPS-1276). At each date a concluded reading was dated, we recompute\n * Confidence over every concluded reading up to and including that date, using\n * the very same `confidence()` the derived box uses (so the last point equals\n * the hero number). Undated concluded readings have no place on the timeline\n * but still bear on the belief, so they are treated as always-present — folded\n * into every point — which keeps the final point equal to today's Confidence.\n */\nimport { confidence, type ConfidenceReadingInput } from \"./confidence.js\";\nimport { isConcluded } from \"./strength.js\";\n\nexport interface TrajectoryPoint {\n /** ISO date at which Confidence took this value. */\n date: string;\n confidence: number;\n}\n\nexport function confidenceTrajectory(\n readings: ConfidenceReadingInput[],\n): TrajectoryPoint[] {\n const concluded = readings.filter((r) => isConcluded(r.result));\n const undated = concluded.filter((r) => !r.date);\n const dated = concluded.filter((r) => r.date);\n if (dated.length === 0) return [];\n\n const dates = [...new Set(dated.map((r) => r.date as string))].sort();\n return dates.map((date) => ({\n date,\n // Everything dated on/before this point, plus the always-present undated.\n confidence: confidence([\n ...undated,\n ...dated.filter((r) => (r.date as string) <= date),\n ]),\n }));\n}\n","/**\n * Derived Impact — propagates dependents' pull into a belief's seed.\n *\n * Formula (`ontology.yaml` → `derivations.derived_impact`):\n * seed + (100 − seed) × S / (S + 100), where\n * S = Σ Derived Impact of assumptions whose `Depends on` names this row\n * + 100 per standing (Provisional/Active) decision naming it via\n * `Based on assumption`.\n * Goals never contribute. Moot rows pin to 0 and contribute nothing.\n *\n * One reverse-topological pass (dependents first) with memoization and a\n * cycle guard, matching the instance's `migration/remodel.mjs`.\n */\nimport { round2 } from \"./round.js\";\n\nexport interface ImpactAssumptionInput {\n id: string;\n /** The hand-scored seed (0–100); null treated as 0. */\n impact: number | null;\n moot?: boolean;\n /** Ids this assumption depends on. */\n dependsOnIds: string[];\n}\n\n/**\n * @param assumptions the full register (never a filtered slice — a filter\n * silently drops dependents from the propagation).\n * @param basedOnCounts id → number of standing decisions with a `Based on`\n * link to that assumption. Each contributes +100 to S.\n */\nexport function derivedImpacts(\n assumptions: ImpactAssumptionInput[],\n basedOnCounts: Record<string, number> = {},\n): Map<string, number> {\n const byId = new Map(assumptions.map((a) => [a.id, a]));\n\n // dependents(X) = assumptions whose dependsOnIds includes X.\n const dependents = new Map<string, string[]>();\n for (const a of assumptions) dependents.set(a.id, []);\n for (const a of assumptions) {\n for (const dep of a.dependsOnIds) dependents.get(dep)?.push(a.id);\n }\n\n const memo = new Map<string, number>();\n const compute = (id: string, seen: Set<string>): number => {\n const cached = memo.get(id);\n if (cached !== undefined) return cached;\n if (seen.has(id)) return 0; // cycle guard\n seen.add(id);\n const a = byId.get(id);\n if (!a) return 0;\n if (a.moot) {\n memo.set(id, 0);\n return 0;\n }\n const seed = a.impact ?? 0;\n let S = 0;\n for (const depId of dependents.get(id) ?? []) {\n const d = byId.get(depId);\n if (d && !d.moot) S += compute(depId, seen);\n }\n S += 100 * (basedOnCounts[id] ?? 0);\n const value = seed + (100 - seed) * (S / (S + 100));\n const rounded = round2(value);\n memo.set(id, rounded);\n return rounded;\n };\n\n const out = new Map<string, number>();\n for (const a of assumptions) out.set(a.id, compute(a.id, new Set()));\n return out;\n}\n","/**\n * Risk — the belief's live standing.\n *\n * Formula (`ontology.yaml` → `derivations.risk`):\n * Derived Impact × (1 − max(0, Confidence) / 100)\n * Ranges 0 to Derived Impact. Negative confidence does not raise Risk above\n * Derived Impact (the max(0, …) clamp).\n */\nimport { round2 } from \"./round.js\";\n\nexport function risk(derivedImpact: number, confidence: number): number {\n return round2(derivedImpact * (1 - Math.max(0, confidence) / 100));\n}\n","/**\n * Portfolio progress — the one *cross-belief* reading (OPS-1293 / OPS-1300).\n *\n * Every other derived number here is per-record (risk/confidence/impact of one\n * belief). This is the whole-set roll-up behind the pipeline's headline: a\n * **burn-up**, \"% of identified risk bought down\" = Risk Retired ÷ Risk-ever-\n * identified across *all* beliefs, resolved ones included.\n *\n * Like `rankNextMoves`, it is a whole-set ordering computed **fresh on read**,\n * not stored — it stays out of the OPS-1251 on-write recompute (it only reads\n * numbers already kept current). Pure and numeric: the dashboard maps records\n * to these inputs (as `understanding.ts` maps readings), so the rule lives\n * once, here.\n *\n * The model (matches the OPS-1296 prototype's self-consistent maths):\n * - **ever-identified** for a belief = the risk it represented at Confidence\n * ≤ 0, i.e. its Derived Impact. A moot row's Derived Impact is pinned to 0,\n * which would erase it from *both* sides of the fraction, so we floor\n * ever-identified at the hand-scored seed Impact — mooting a belief must\n * *retire* its risk, never shrink the denominator (the burn-up's whole\n * point: resolved risk stays counted).\n * - **live** risk = the belief's current Risk, or 0 once resolved (a kill or\n * a moot resolves the uncertainty — that risk is bought down, not carried).\n * - **retired** = ever-identified − live.\n */\nimport { round2 } from \"./round.js\";\n\nexport interface PortfolioBeliefInput {\n id: string;\n /** Derived Impact — the belief's risk at Confidence ≤ 0 (0 when moot). */\n derivedImpact: number;\n /** The hand-scored seed Impact; the ever-identified floor when moot zeroes\n * Derived Impact. Null/absent treated as 0. */\n seedImpact: number | null;\n /** The belief's current live Risk (stored `derived.risk`). */\n risk: number;\n /** Resolved — Invalidated (killed) or moot. Its live risk reads 0 (fully\n * retired), whatever the stored Risk number says. */\n resolved: boolean;\n}\n\n/** One belief's contribution to the burn-up. */\nexport interface BeliefRisk {\n /** Risk-ever-identified — the denominator's per-belief share. */\n identified: number;\n /** Live risk still carried (0 once resolved). */\n live: number;\n /** Risk bought down — the numerator's per-belief share. */\n retired: number;\n}\n\nexport interface PortfolioProgress {\n /** Σ risk-ever-identified — the burn-up denominator. */\n identified: number;\n /** Σ risk bought down — the burn-up numerator. */\n retired: number;\n /** Σ risk still live. */\n live: number;\n /** Retired ÷ identified as a percentage (0 when nothing is identified). */\n percent: number;\n /** Beliefs still in play (not resolved). */\n liveCount: number;\n /** Beliefs resolved (killed or moot). */\n resolvedCount: number;\n}\n\n/** One belief's identified / live / retired risk — the rule in one place. */\nexport function beliefRisk(b: PortfolioBeliefInput): BeliefRisk {\n const seed = b.seedImpact ?? 0;\n const identified = Math.max(b.derivedImpact, seed, 0);\n // Live risk can never exceed what was ever identified — the clamp keeps a\n // stale/over-large stored Risk from making retired go negative.\n const live = b.resolved ? 0 : Math.min(identified, Math.max(0, b.risk));\n return {\n identified: round2(identified),\n live: round2(live),\n retired: round2(identified - live),\n };\n}\n\n/**\n * Roll every belief up into the portfolio burn-up. Pass the *whole* set\n * (resolved rows included) — a filtered slice understates the denominator and\n * makes fresh or retired risk read as backsliding.\n */\nexport function portfolioProgress(\n beliefs: PortfolioBeliefInput[],\n): PortfolioProgress {\n let identified = 0;\n let live = 0;\n let liveCount = 0;\n let resolvedCount = 0;\n for (const b of beliefs) {\n const r = beliefRisk(b);\n identified += r.identified;\n live += r.live;\n if (b.resolved) resolvedCount += 1;\n else liveCount += 1;\n }\n const retired = identified - live;\n return {\n identified: round2(identified),\n retired: round2(retired),\n live: round2(live),\n percent: identified > 0 ? round2((retired / identified) * 100) : 0,\n liveCount,\n resolvedCount,\n };\n}\n","/**\n * Next-move ranking — the front door's single source of truth for \"what should\n * I do next\" (build OPS-1304; placement OPS-1292; action vocabulary OPS-1291).\n *\n * Ranks *beliefs* — Model A: point at one belief, not a heterogeneous triage\n * queue (OPS-1291) — by the method's Feasibility × Risk rule (`docs/method.md`,\n * `ontology.yaml` → `derived_views.next_move`), and names the single act each\n * belief's stage demands. A belief at Confidence ≤ −50 jumps into a distinct\n * kill/re-test lane that sorts above the Feasibility × Risk order regardless of\n * rank — the one place act-urgency beats belief-risk (`derived_views.kill_lane`).\n *\n * Computed fresh on read: a whole-set ordering, so it stays OUT of the OPS-1251\n * on-write recompute — it reads the derived numbers (Risk, Confidence) those\n * writes already keep current. Pure: no I/O, no caching, no weights framework —\n * the enum→multiplier map below IS the formula (OPS-1292: \"no weights /\n * strategies / caching / framework\").\n */\nimport type { Feasibility } from \"../types.js\";\nimport { round2 } from \"./round.js\";\n\n/** The kill/re-test threshold — Confidence at or below this is the kill lane. */\nexport const KILL_LANE_THRESHOLD = -50;\n\n/**\n * The acts the front door can name, one per belief-stage. The front door\n * *names* all of them; only a subset are human step-in forms — the rest are\n * agent-run / off-dashboard (OPS-1294). Which is which is a presentation\n * concern the dashboard owns, not this ranking.\n */\nexport type MoveKind =\n | \"score-impact\" // Framed — the belief isn't weighted yet (Impact unscored)\n | \"design-experiment\" // Planned — no test plans this belief yet\n | \"record-reading\" // Tested — a test is running, evidence still landing\n | \"decide\" // Known — evidence has landed and no decision rests on it\n | \"retest\"; // kill lane — Confidence ≤ −50, jumps the ordering\n\n/**\n * One belief's next move. `move`/`score`/`reason` are the OPS-1292 output\n * contract; the rest is context the front door renders (the risk chip, the kill\n * banner, the step-in adaptation) — every field read from the inputs, nothing\n * new computed here.\n */\nexport interface NextMove {\n /** The act this belief's stage demands. */\n move: MoveKind;\n assumptionId: string;\n /** The belief statement — the hero headline. */\n title: string;\n /** Feasibility × Risk. Kill-lane rows carry their Risk and sort first. */\n score: number;\n /** Plain-language \"why this\" — explains from the inputs, no jargon. */\n reason: string;\n /** The belief's live derived Risk (0–100). */\n risk: number;\n /** The belief's live derived Confidence (signed −100…100). */\n confidence: number;\n /** The feasibility that fed the score; null when no test plans it yet. */\n feasibility: Feasibility | null;\n /** Confidence ≤ −50 — the override lane. */\n killLane: boolean;\n}\n\n/** A belief and its live derived numbers (the ranking's primary input). */\nexport interface NextMoveAssumptionInput {\n id: string;\n title: string;\n /** AssumptionStatus; `Invalidated` rows are already killed and drop out. */\n status: string;\n /** The hand-scored seed (0–100); null means unscored → \"score impact\". */\n impact: number | null;\n /** Mooted beliefs (Impact pinned to 0 by a decision) drop out of ranking. */\n moot: boolean;\n /** Derived Risk (already recomputed on write — read, never recomputed). */\n risk: number;\n /** Derived Confidence (already recomputed on write). */\n confidence: number;\n /** How many concluded (Validated/Invalidated) readings back this belief. */\n concludedReadings: number;\n}\n\n/** An experiment, reduced to what stage + feasibility resolution needs. */\nexport interface NextMoveExperimentInput {\n /** ExperimentStatus — \"Running\" | \"Closed\". */\n status: string;\n feasibility: Feasibility | null;\n /** The assumption ids this experiment's bar lines name. */\n assumptionIds: string[];\n}\n\n/** A decision, reduced to which beliefs it rests on or resolves. */\nexport interface NextMoveDecisionInput {\n /** DecisionStatus; only standing (Active/Provisional) decisions count. */\n status: string;\n /** The assumption ids this decision rests on (`based on`) or resolves. */\n assumptionIds: string[];\n}\n\nexport interface NextMoveInput {\n assumptions: NextMoveAssumptionInput[];\n experiments: NextMoveExperimentInput[];\n decisions: NextMoveDecisionInput[];\n}\n\n/**\n * Feasibility → the score multiplier. Cheaper (more feasible) tests rank\n * higher, so the cheapest honest test of the riskiest belief is on top\n * (`method.md`). A belief with no planned test yet has unknown feasibility →\n * the neutral middle, so Risk decides its place honestly.\n */\nconst FEASIBILITY_WEIGHT: Record<Feasibility, number> = {\n High: 1,\n Medium: 0.6,\n Low: 0.3,\n};\nconst NEUTRAL_FEASIBILITY_WEIGHT = FEASIBILITY_WEIGHT.Medium;\n\nfunction isStanding(decisionStatus: string): boolean {\n return decisionStatus === \"Active\" || decisionStatus === \"Provisional\";\n}\n\n/** Pick the cheapest (highest-weight) feasibility among a belief's tests. */\nfunction bestFeasibility(\n feasibilities: (Feasibility | null)[],\n): Feasibility | null {\n let best: Feasibility | null = null;\n let bestWeight = -1;\n for (const f of feasibilities) {\n if (!f) continue;\n const w = FEASIBILITY_WEIGHT[f];\n if (w > bestWeight) {\n bestWeight = w;\n best = f;\n }\n }\n return best;\n}\n\n/**\n * The act a belief's stage demands (before the kill-lane override).\n *\n * Deliberately NOT the `stage.ts` structural classifier: that answers \"how far\n * along the Framed→Planned→Tested→Known artifacts are\" (framing completeness,\n * bar-line settlement); this answers \"what should the founder do next\" from the\n * evidence state (is it weighted, has evidence concluded, does a test run, does\n * a decision rest on it). Same belief can be structurally `tested` yet owe a\n * `decide` here — the journey rail (stage) and next-move card (act) are two\n * readings of one belief, so they share the test-plan *meter* (`beliefTestMeters`)\n * but not the classifier.\n */\nfunction stageMove(\n a: NextMoveAssumptionInput,\n hasRunningTest: boolean,\n hasAnyTest: boolean,\n hasStandingDecision: boolean,\n): MoveKind | null {\n if (a.impact === null) return \"score-impact\"; // Framed → weight it\n if (a.concludedReadings === 0) {\n // No evidence yet: if a test is running, wait for readings; else plan one.\n return hasRunningTest ? \"record-reading\" : \"design-experiment\";\n }\n // Evidence has landed. If nothing rests on it yet, it's time to decide;\n // once a standing decision does, the belief is resolved and drops out.\n if (!hasStandingDecision) return \"decide\";\n return null;\n}\n\n/** Plain-language \"why this\" — explains the move from the inputs. */\nfunction reasonFor(move: MoveKind, a: NextMoveAssumptionInput): string {\n switch (move) {\n case \"retest\":\n return `Confidence has fallen to ${Math.round(a.confidence)} — the evidence is turning against this belief. Kill it or test it again.`;\n case \"score-impact\":\n return \"This belief isn't weighted yet — score its impact so its risk can rank against the rest.\";\n case \"design-experiment\":\n return `Your riskiest untested belief. Design the cheapest honest test that could move it.`;\n case \"record-reading\":\n return \"A test is running against this belief — evidence is still landing.\";\n case \"decide\":\n return \"The evidence is in and nothing rests on it yet — time to make the call.\";\n }\n}\n\n/**\n * Rank every unresolved belief into its next move (Model A). Returns a plain\n * sorted list, most-pressing first: the kill lane on top (by Risk), then the\n * rest by Feasibility × Risk, tie-broken by the most-negative Confidence\n * (`derived_views.test_next_surface`), then by id for a stable order. The front\n * door takes the head as the hero and the tail as \"On deck\" / manual override.\n */\nexport function rankNextMoves(input: NextMoveInput): NextMove[] {\n const { assumptions, experiments, decisions } = input;\n\n // Which experiments (and their feasibilities/statuses) name each belief.\n const testsByAssumption = new Map<\n string,\n { running: boolean; any: boolean; feasibilities: (Feasibility | null)[] }\n >();\n for (const exp of experiments) {\n const running = exp.status === \"Running\";\n for (const id of exp.assumptionIds) {\n const entry = testsByAssumption.get(id) ?? {\n running: false,\n any: false,\n feasibilities: [],\n };\n entry.any = true;\n entry.running = entry.running || running;\n entry.feasibilities.push(exp.feasibility);\n testsByAssumption.set(id, entry);\n }\n }\n\n // Which beliefs a standing decision rests on or resolves.\n const decidedAssumptions = new Set<string>();\n for (const d of decisions) {\n if (!isStanding(d.status)) continue;\n for (const id of d.assumptionIds) decidedAssumptions.add(id);\n }\n\n const moves: NextMove[] = [];\n for (const a of assumptions) {\n if (a.moot || a.status === \"Invalidated\") continue;\n\n const killLane = a.confidence <= KILL_LANE_THRESHOLD;\n const tests = testsByAssumption.get(a.id);\n const feasibility = bestFeasibility(tests?.feasibilities ?? []);\n\n const move: MoveKind | null = killLane\n ? \"retest\"\n : stageMove(\n a,\n tests?.running ?? false,\n tests?.any ?? false,\n decidedAssumptions.has(a.id),\n );\n if (move === null) continue; // resolved — no move\n\n const weight = feasibility\n ? FEASIBILITY_WEIGHT[feasibility]\n : NEUTRAL_FEASIBILITY_WEIGHT;\n // Kill-lane rows carry their raw Risk so they order among themselves by\n // Risk; the killLane flag (not the score) floats them above everyone else.\n const score = round2(killLane ? a.risk : weight * a.risk);\n\n moves.push({\n move,\n assumptionId: a.id,\n title: a.title,\n score,\n reason: reasonFor(move, a),\n risk: a.risk,\n confidence: a.confidence,\n feasibility,\n killLane,\n });\n }\n\n moves.sort((x, y) => {\n if (x.killLane !== y.killLane) return x.killLane ? -1 : 1;\n if (y.score !== x.score) return y.score - x.score;\n if (x.confidence !== y.confidence) return x.confidence - y.confidence;\n return x.assumptionId < y.assumptionId ? -1 : 1;\n });\n return moves;\n}\n","/**\n * Per-belief stage — where one belief sits on the loop's four-stage spine\n * (Framed → Planned → Tested → Known) and its four meters (OPS-1329).\n *\n * This is the *single-belief* analogue of the pipeline's cross-belief roll-up:\n * the pipeline row-builder used to derive framing / test-plan / test-progress\n * inline, and the front-door move ladder (OPS-1304) re-walked the same stages a\n * second way. The shared classification lives here now, so the pipeline board,\n * the front door, and the per-belief journey rail all read one rule rather than\n * three that can drift.\n *\n * Pure and computed fresh on read (like `portfolio.ts` / `next-move.ts`): it\n * only reads numbers already kept current, so it stays out of the OPS-1251\n * on-write recompute. The record → meter mapping (bar lines, presence fields)\n * lives in the dashboard, as elsewhere; this module takes the reduced inputs.\n */\nimport { KILL_LANE_THRESHOLD } from \"./next-move.js\";\n\n/** The four loop stages a belief travels, in order (OPS-1293). */\nexport type StageKey = \"framed\" | \"planned\" | \"tested\" | \"known\";\n\n/** Sign of a belief's Confidence — the Known meter's direction. */\nexport type ConfSign = \"pos\" | \"neg\" | \"zero\";\n\n/** One belief's test state, aggregated across every experiment aimed at it. */\nexport interface TestMeter {\n /** A bar line (or the convenience projection) names this belief. */\n planned: boolean;\n /** Pre-registered bars that have a verdict. */\n settled: number;\n /** Pre-registered bars in total. */\n total: number;\n}\n\n/** A test's bar lines, reduced to what the meter needs (register-agnostic). */\nexport interface StageExperimentInput {\n /** Each bar line naming a belief, and whether it has settled (has a verdict). */\n bars: { assumptionId: string; settled: boolean }[];\n /** Beliefs this test plans via the convenience projection (bars may be unexpanded). */\n plannedAssumptionIds: string[];\n}\n\n/** The reduced inputs one belief's stage is derived from. */\nexport interface BeliefStageInput {\n /** Framing completeness, 0–100 (`assumptionCompleteness`). */\n framed: number;\n /** Live derived Confidence (signed −100…100). */\n confidence: number;\n /** This belief's aggregated test state. */\n test: TestMeter;\n}\n\n/** One belief's position on the spine plus its four meters. */\nexport interface BeliefStage {\n /** Where the belief sits: framed → planned → tested → known. */\n stage: StageKey;\n /** Meter 1 — framing completeness, 0–100. */\n framed: number;\n /** Meter 2 — a test has been designed against this belief. */\n planned: boolean;\n /** Meter 3 — pre-registered bars settled / total. */\n tested: { settled: number; total: number };\n /** Meter 4 — signed Known: the belief's Confidence. */\n confidence: number;\n /** Sign bucket for the Known gauge direction. */\n confSign: ConfSign;\n /** Confidence ≤ −50 — the kill/re-test overlay (the same lane as the front door). */\n killZone: boolean;\n}\n\n/** An empty test state — a belief no experiment has named yet. */\nexport function emptyTestMeter(): TestMeter {\n return { planned: false, settled: 0, total: 0 };\n}\n\n/**\n * For every belief, the state of the tests aimed at it — whether one is designed\n * and how many of its pre-registered bars have settled, aggregated across all\n * experiments. Factored out of the pipeline row-builder so the board and a\n * single belief's rail agree by construction.\n */\nexport function beliefTestMeters(\n experiments: StageExperimentInput[],\n): Map<string, TestMeter> {\n const byAssumption = new Map<string, TestMeter>();\n const ensure = (id: string): TestMeter => {\n let s = byAssumption.get(id);\n if (!s) {\n s = emptyTestMeter();\n byAssumption.set(id, s);\n }\n return s;\n };\n for (const exp of experiments) {\n for (const b of exp.bars) {\n if (!b.assumptionId) continue;\n const s = ensure(b.assumptionId);\n s.planned = true;\n s.total += 1;\n if (b.settled) s.settled += 1;\n }\n // A designed test may name a belief via the convenience projection even when\n // its bar lines aren't expanded — still counts as Planned.\n for (const id of exp.plannedAssumptionIds) ensure(id).planned = true;\n }\n return byAssumption;\n}\n\n/**\n * Classify a belief on the spine from its meters. The kill-zone overlay is\n * *not* a stage — a belief whose evidence has turned is still structurally\n * wherever its framing/tests put it (a re-test moves it backward via the Known\n * meter, OPS-1300), so this stays pure status.\n */\nexport function classifyStage(framed: number, test: TestMeter): StageKey {\n if (framed < 100) return \"framed\";\n if (!test.planned) return \"planned\";\n if (test.total === 0 || test.settled < test.total) return \"tested\";\n return \"known\";\n}\n\n/** One belief's stage + four meters — the rail's data. */\nexport function deriveBeliefStage(input: BeliefStageInput): BeliefStage {\n const { framed, confidence, test } = input;\n return {\n stage: classifyStage(framed, test),\n framed,\n planned: test.planned,\n tested: { settled: test.settled, total: test.total },\n confidence,\n confSign: confidence > 0 ? \"pos\" : confidence < 0 ? \"neg\" : \"zero\",\n killZone: confidence <= KILL_LANE_THRESHOLD,\n };\n}\n","/**\n * The per-belief journey event log (OPS-1329) — the belief's life ordered into\n * dated events: bet → score → experiment → readings → confidence-cross → now.\n * It is the *story* half of the journey drill-in (the *rail* half is `stage.ts`).\n *\n * No new maths: Confidence at each point is read off `confidenceTrajectory`\n * (the very numbers the understanding layer already shows), and the current\n * number off `confidence()`. Nothing is invented — an event whose underlying\n * datum is absent (no impact score, no experiment, no concluded reading, no\n * kill-zone cross) is simply omitted, and no date is ever faked (an event with\n * no real date carries `date: null` and takes its place by structural order).\n *\n * Pure and label-free: the dashboard journey view-model adds the copy. Computed\n * fresh on read, out of the OPS-1251 on-write recompute.\n */\nimport type { Result } from \"../types.js\";\nimport type { AttributionReadingInput } from \"./attribution.js\";\nimport { confidence } from \"./confidence.js\";\nimport { KILL_LANE_THRESHOLD } from \"./next-move.js\";\nimport { isConcluded } from \"./strength.js\";\nimport { confidenceTrajectory } from \"./trajectory.js\";\n\n/** The kinds of event a belief's life produces, in structural order. */\nexport type JourneyEventKind =\n | \"bet\" // the belief was written\n | \"score\" // its impact was scored\n | \"experiment\" // a test was designed against it\n | \"reading\" // evidence landed\n | \"confidence-cross\" // Confidence fell into the kill zone\n | \"now\"; // the belief's state today\n\n/** The structural order the story walks — the tie-break for undated events. */\nconst KIND_ORDER: Record<JourneyEventKind, number> = {\n bet: 0,\n score: 1,\n experiment: 2,\n reading: 3,\n \"confidence-cross\": 4,\n now: 5,\n};\n\n/** One event in a belief's life. Label-free — the view-model adds the copy. */\nexport interface JourneyEvent {\n kind: JourneyEventKind;\n /** ISO date, or null when no real date exists (never faked). */\n date: string | null;\n /** Confidence known at this event (reading / cross / now); null otherwise. */\n confidence: number | null;\n /** The reading's verdict, for `reading` events; null otherwise. */\n result: Result | null;\n /** The source record id (reading id, experiment id) when the event has one. */\n refId: string | null;\n}\n\n/** The belief itself, reduced to what the log needs. */\nexport interface JourneyBeliefInput {\n /** When the bet was written — the `bet` event's date. */\n createdAt: string | null;\n /** Impact has been scored (a non-null seed) — emits the `score` event. */\n impactScored: boolean;\n}\n\n/** A test aimed at this belief, reduced to what the log needs. */\nexport interface JourneyExperimentInput {\n id: string;\n /** When the test was designed; null when unknown (event still emitted, undated). */\n date: string | null;\n}\n\nexport interface AssembleJourneyInput {\n belief: JourneyBeliefInput;\n /** The belief's own readings (already filtered to this assumption). */\n readings: AttributionReadingInput[];\n /** The experiments testing this belief. */\n experiments: JourneyExperimentInput[];\n /** \"Now\" as an ISO date — passed in so the log stays pure. */\n now: string;\n}\n\n/**\n * Assemble one belief's chronological event log. Events sort by date, undated\n * events anchored to the bet's date and ordered structurally; `now` is always\n * last.\n */\nexport function assembleJourney(input: AssembleJourneyInput): JourneyEvent[] {\n const { belief, readings, experiments, now } = input;\n const events: JourneyEvent[] = [];\n\n if (belief.createdAt) {\n events.push(event(\"bet\", belief.createdAt));\n }\n if (belief.impactScored) {\n // No scored-on date is stored, so the score rides structurally after the\n // bet rather than carrying an invented date.\n events.push(event(\"score\", null));\n }\n for (const e of experiments) {\n events.push(event(\"experiment\", e.date, { refId: e.id }));\n }\n\n const trajectory = confidenceTrajectory(readings);\n const confByDate = new Map(trajectory.map((p) => [p.date, p.confidence]));\n for (const r of readings) {\n const dated = r.date ?? null;\n // Confidence is known only for a concluded reading that lands on a\n // trajectory date (undated / inconclusive readings carry no number).\n const conf =\n dated && isConcluded(r.result) ? (confByDate.get(dated) ?? null) : null;\n events.push(\n event(\"reading\", dated, { confidence: conf, result: r.result, refId: r.id }),\n );\n }\n\n // The first point at which the evidence dragged Confidence into the kill zone.\n const cross = trajectory.find((p) => p.confidence <= KILL_LANE_THRESHOLD);\n if (cross) {\n events.push(event(\"confidence-cross\", cross.date, { confidence: cross.confidence }));\n }\n\n // Undated events anchor to the bet so they sit at the start in structural\n // order; `now` is appended after sorting so it is unconditionally last.\n const anchor = belief.createdAt ?? \"\";\n events.sort((a, b) => {\n const ka = a.date ?? anchor;\n const kb = b.date ?? anchor;\n if (ka !== kb) return ka < kb ? -1 : 1;\n return KIND_ORDER[a.kind] - KIND_ORDER[b.kind];\n });\n events.push(event(\"now\", now, { confidence: confidence(readings) }));\n\n return events;\n}\n\nfunction event(\n kind: JourneyEventKind,\n date: string | null,\n extra: Partial<Pick<JourneyEvent, \"confidence\" | \"result\" | \"refId\">> = {},\n): JourneyEvent {\n return {\n kind,\n date,\n confidence: extra.confidence ?? null,\n result: extra.result ?? null,\n refId: extra.refId ?? null,\n };\n}\n"],"mappings":";;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,SAAS,OAAO,GAAmB;AACxC,SAAO,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC5B;;;ACgBO,IAAM,cAA2D;AAAA,EACtE,MAAM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QAAO,KAAK,KAAK,KAAK;AACrC,WAAO,WAAW,EAAE,IAAI,IAAI,WAAW,EAAE,IAAI;AAAA,EAC/C,CAAC;AACD,SAAO,KAAK,MAAM,OAAO,KAAK,EAAE,YAAY,WAAW,QAAQ,EAAE,CAAC,CAAC;AAEnE,SAAO;AACT;AAEA,SAAS,MACP,MACA,MACA,QAAwE,CAAC,GAC3D;AACd,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,YAAY,MAAM,cAAc;AAAA,IAChC,QAAQ,MAAM,UAAU;AAAA,IACxB,OAAO,MAAM,SAAS;AAAA,EACxB;AACF;","names":["confidence","confidence"]}
@@ -1,2 +1,2 @@
1
- export { e as AssembleJourneyInput, f as Attribution, A as AttributionReadingInput, B as BarLineInput, g as BeliefRisk, h as BeliefStage, j as BeliefStageInput, k as COMMITMENT_FOUND, C as COMPLETENESS_SLOTS, b as CompletenessInput, a as CompletenessSlot, l as ConfSign, n as ConfidenceReadingInput, E as ExperimentConfidenceBarInput, o as ExperimentConfidenceReadingInput, I as ImpactAssumptionInput, J as JourneyBeliefInput, p as JourneyEvent, q as JourneyEventKind, t as JourneyExperimentInput, K as KILL_LANE_THRESHOLD, M as MAX_STRENGTH, u as MoveKind, v as Mover, w as MoverKind, N as NextMove, x as NextMoveAssumptionInput, y as NextMoveDecisionInput, z as NextMoveExperimentInput, D as NextMoveInput, P as PortfolioBeliefInput, F as PortfolioProgress, G as Progress, R as RUNG_ANCHOR, S as Scored, H as StageExperimentInput, L as StageKey, O as StrengthInput, T as TestMeter, Q as TrajectoryPoint, W as W0, U as W0_BY_RUNG, V as assembleJourney, d as assumptionComplete, c as assumptionCompleteness, X as beliefRisk, Y as beliefTestMeters, Z as classifyStage, _ as commitmentFactor, $ as completenessSlotPresence, a0 as confidence, a1 as confidenceAttribution, a2 as confidenceTrajectory, a3 as deriveBeliefStage, a4 as derivedImpacts, a5 as emptyTestMeter, a6 as experimentConfidence, a7 as experimentProgress, a8 as isConcluded, m as missingCompletenessSlots, a9 as portfolioProgress, aa as rankNextMoves, r as readingStrength, ab as risk, ac as round2, ad as scoreAndDedupe, ae as sign, s as sourceQuality, af as w0ForRung } from '../index-9yJs8_Ei.js';
2
- import '../types-DGDJsWNi.js';
1
+ export { e as AssembleJourneyInput, f as Attribution, A as AttributionReadingInput, B as BarLineInput, g as BeliefRisk, h as BeliefStage, j as BeliefStageInput, k as COMMITMENT_FOUND, C as COMPLETENESS_SLOTS, b as CompletenessInput, a as CompletenessSlot, l as ConfSign, n as ConfidenceReadingInput, E as ExperimentConfidenceBarInput, o as ExperimentConfidenceReadingInput, I as ImpactAssumptionInput, J as JourneyBeliefInput, p as JourneyEvent, q as JourneyEventKind, t as JourneyExperimentInput, K as KILL_LANE_THRESHOLD, M as MAX_STRENGTH, u as MoveKind, v as Mover, w as MoverKind, N as NextMove, x as NextMoveAssumptionInput, y as NextMoveDecisionInput, z as NextMoveExperimentInput, D as NextMoveInput, P as PortfolioBeliefInput, F as PortfolioProgress, G as Progress, R as RUNG_ANCHOR, S as Scored, H as StageExperimentInput, L as StageKey, O as StrengthInput, T as TestMeter, Q as TrajectoryPoint, W as W0, U as W0_BY_RUNG, V as assembleJourney, d as assumptionComplete, c as assumptionCompleteness, X as beliefRisk, Y as beliefTestMeters, Z as classifyStage, _ as commitmentFactor, $ as completenessSlotPresence, a0 as confidence, a1 as confidenceAttribution, a2 as confidenceTrajectory, a3 as deriveBeliefStage, a4 as derivedImpacts, a5 as emptyTestMeter, a6 as experimentConfidence, a7 as experimentProgress, a8 as isConcluded, m as missingCompletenessSlots, a9 as portfolioProgress, aa as rankNextMoves, r as readingStrength, ab as risk, ac as round2, ad as scoreAndDedupe, ae as sign, s as sourceQuality, af as w0ForRung } from '../index-DMPfDeEw.js';
2
+ import '../types-B845UmLh.js';
@@ -33,7 +33,7 @@ import {
33
33
  sign,
34
34
  sourceQuality,
35
35
  w0ForRung
36
- } from "../chunk-7QK3MHU6.js";
36
+ } from "../chunk-HMAHBGOJ.js";
37
37
  import "../chunk-PZ5AY32C.js";
38
38
  export {
39
39
  COMMITMENT_FOUND,
@@ -1,4 +1,4 @@
1
- import { r as Rung, l as MagnitudeBand, q as Result, F as Feasibility } from './types-DGDJsWNi.js';
1
+ import { r as Rung, l as MagnitudeBand, q as Result, F as Feasibility } from './types-B845UmLh.js';
2
2
 
3
3
  /**
4
4
  * Round to 2 decimals, matching the migration's `+(n).toFixed(2)`.
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { R as Relation, C as Collection, A as AssumptionRecord, a as ReadingRecord, D as DecisionRecord, b as AssumptionDerived, E as ExperimentRecord, c as ExperimentDerived, d as AnyRecord } from './types-DGDJsWNi.js';
2
- export { e as AssumptionStatus, B as BarLine, f as BaseRecord, g as BeliefScore, h as DecisionStatus, i as ExperimentStatus, F as Feasibility, G as GlossaryAvoid, j as GlossaryRecord, k as GlossaryStatus, M as MARKET_RUNG_VALUES, l as MagnitudeBand, m as MarketRung, n as REGISTERS, o as RecordRef, p as Register, q as Result, r as Rung, S as SourceQualityPick, T as TESTING_RUNGS, s as TestingRung } from './types-DGDJsWNi.js';
3
- export { D as DataProvider, N as NotFoundError, S as StaleVersionError, i as isNotFoundError, a as isStaleVersionError } from './provider-DBfUvG4N.js';
4
- import { A as AttributionReadingInput } from './index-9yJs8_Ei.js';
5
- export { C as ASSUMPTION_PRESENCE_SLOTS, a as AssumptionPresenceSlot, b as CompletenessInput, c as assumptionCompleteness, d as assumptionPresenceComplete, i as derivation, m as missingPresenceSlots, s as recomputeSourceQuality, r as recomputeStrength } from './index-9yJs8_Ei.js';
1
+ import { R as Relation, C as Collection, A as AssumptionRecord, a as ReadingRecord, D as DecisionRecord, b as AssumptionDerived, E as ExperimentRecord, c as ExperimentDerived, d as AnyRecord } from './types-B845UmLh.js';
2
+ export { e as AssumptionStatus, B as BarLine, f as BaseRecord, g as BeliefScore, h as DecisionStatus, i as ExperimentStatus, F as Feasibility, G as GlossaryAvoid, j as GlossaryRecord, k as GlossaryStatus, M as MARKET_RUNG_VALUES, l as MagnitudeBand, m as MarketRung, n as REGISTERS, o as RecordRef, p as Register, q as Result, r as Rung, S as SourceQualityPick, T as TESTING_RUNGS, s as TestingRung } from './types-B845UmLh.js';
3
+ export { D as DataProvider, N as NotFoundError, S as StaleVersionError, i as isNotFoundError, a as isStaleVersionError } from './provider-biEHIhDh.js';
4
+ import { A as AttributionReadingInput } from './index-DMPfDeEw.js';
5
+ export { C as ASSUMPTION_PRESENCE_SLOTS, a as AssumptionPresenceSlot, b as CompletenessInput, c as assumptionCompleteness, d as assumptionPresenceComplete, i as derivation, m as missingPresenceSlots, s as recomputeSourceQuality, r as recomputeStrength } from './index-DMPfDeEw.js';
6
6
 
7
7
  /**
8
8
  * Relation config — the single table describing, for each linkable relation,
package/dist/index.js CHANGED
@@ -20,7 +20,7 @@ import {
20
20
  readingStrength,
21
21
  risk,
22
22
  sourceQuality
23
- } from "./chunk-7QK3MHU6.js";
23
+ } from "./chunk-HMAHBGOJ.js";
24
24
  import "./chunk-PZ5AY32C.js";
25
25
 
26
26
  // src/reading-input.ts
@@ -1,4 +1,4 @@
1
- import { C as Collection, d as AnyRecord, R as Relation, o as RecordRef } from './types-DGDJsWNi.js';
1
+ import { C as Collection, d as AnyRecord, R as Relation, o as RecordRef } from './types-B845UmLh.js';
2
2
 
3
3
  /**
4
4
  * The `DataProvider` — the single integration seam between the dashboard/API
package/dist/testing.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { D as DataProvider } from './provider-DBfUvG4N.js';
2
- import { C as Collection, d as AnyRecord, R as Relation, o as RecordRef } from './types-DGDJsWNi.js';
1
+ import { D as DataProvider } from './provider-biEHIhDh.js';
2
+ import { C as Collection, d as AnyRecord, R as Relation, o as RecordRef } from './types-B845UmLh.js';
3
3
 
4
4
  interface InMemoryProviderOptions {
5
5
  now?: () => string;
@@ -106,6 +106,8 @@ interface BeliefScore {
106
106
  Result: Result;
107
107
  /** The rationale for this belief's Result at the row's rung. */
108
108
  "Grading justification": string;
109
+ /** The verbatim quote or observed fact this belief was graded from. */
110
+ excerpt?: string;
109
111
  /** Derived per belief: row rung anchor × sign(Result) [× row magnitude band]. */
110
112
  derived: {
111
113
  strength: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@validation-os/core",
3
- "version": "0.15.3",
3
+ "version": "0.15.5",
4
4
  "description": "The DataProvider seam, the shared derivation module (pure functions), and shared registry types for validation-os.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/derivation/index.ts","../src/derivation/round.ts","../src/derivation/rung.ts","../src/derivation/completeness.ts","../src/derivation/strength.ts","../src/derivation/source-quality.ts","../src/types.ts","../src/derivation/confidence.ts","../src/derivation/attribution.ts","../src/derivation/progress.ts","../src/derivation/experiment-confidence.ts","../src/derivation/trajectory.ts","../src/derivation/impact.ts","../src/derivation/risk.ts","../src/derivation/portfolio.ts","../src/derivation/next-move.ts","../src/derivation/stage.ts","../src/derivation/journey.ts"],"sourcesContent":["/**\n * The shared derivation module — pure functions, no I/O.\n *\n * The same module the dashboard, the API (derive-on-write), and Claude Code\n * audits all call, so every writer computes the four derived numbers\n * identically. Ported from the instance's `migration/remodel.mjs` and\n * kept in lock-step with `skills/_shared/ontology.yaml`.\n */\nexport { round2 } from \"./round.js\";\nexport { RUNG_ANCHOR } from \"./rung.js\";\nexport {\n COMPLETENESS_SLOTS,\n completenessSlotPresence,\n missingCompletenessSlots,\n assumptionCompleteness,\n assumptionComplete,\n} from \"./completeness.js\";\nexport type { CompletenessSlot, CompletenessInput } from \"./completeness.js\";\nexport { sign, isConcluded, readingStrength } from \"./strength.js\";\nexport type { StrengthInput } from \"./strength.js\";\nexport { sourceQuality } from \"./source-quality.js\";\nexport {\n confidence,\n scoreAndDedupe,\n commitmentFactor,\n COMMITMENT_FOUND,\n W0,\n W0_BY_RUNG,\n w0ForRung,\n} from \"./confidence.js\";\nexport type { ConfidenceReadingInput, Scored } from \"./confidence.js\";\nexport { confidenceAttribution } from \"./attribution.js\";\nexport type {\n Attribution,\n AttributionReadingInput,\n Mover,\n MoverKind,\n} from \"./attribution.js\";\nexport { experimentProgress } from \"./progress.js\";\nexport type { BarLineInput, Progress } from \"./progress.js\";\nexport { experimentConfidence, MAX_STRENGTH } from \"./experiment-confidence.js\";\nexport type {\n ExperimentConfidenceBarInput,\n ExperimentConfidenceReadingInput,\n} from \"./experiment-confidence.js\";\nexport { confidenceTrajectory } from \"./trajectory.js\";\nexport type { TrajectoryPoint } from \"./trajectory.js\";\nexport { derivedImpacts } from \"./impact.js\";\nexport type { ImpactAssumptionInput } from \"./impact.js\";\nexport { risk } from \"./risk.js\";\nexport { beliefRisk, portfolioProgress } from \"./portfolio.js\";\nexport type {\n BeliefRisk,\n PortfolioBeliefInput,\n PortfolioProgress,\n} from \"./portfolio.js\";\nexport { rankNextMoves, KILL_LANE_THRESHOLD } from \"./next-move.js\";\nexport type {\n MoveKind,\n NextMove,\n NextMoveAssumptionInput,\n NextMoveExperimentInput,\n NextMoveDecisionInput,\n NextMoveInput,\n} from \"./next-move.js\";\nexport {\n beliefTestMeters,\n classifyStage,\n deriveBeliefStage,\n emptyTestMeter,\n} from \"./stage.js\";\nexport type {\n BeliefStage,\n BeliefStageInput,\n ConfSign,\n StageExperimentInput,\n StageKey,\n TestMeter,\n} from \"./stage.js\";\nexport { assembleJourney } from \"./journey.js\";\nexport type {\n AssembleJourneyInput,\n JourneyBeliefInput,\n JourneyEvent,\n JourneyEventKind,\n JourneyExperimentInput,\n} from \"./journey.js\";\n","/**\n * Round to 2 decimals, matching the migration's `+(n).toFixed(2)`.\n * Derived values are stored/displayed rounded; full precision is only used\n * transiently inside a single computation.\n */\nexport function round2(n: number): number {\n return Number(n.toFixed(2));\n}\n","/**\n * The lens-aware ladder anchors (DEV-5879).\n *\n * Source of truth: `skills/_shared/ontology.yaml` → `vocabularies.rung`. A\n * rung is an evidence TYPE; magnitude band (Low/Typical/High) is the intensity\n * within a type. The band applies to EVERY rung, so every rung looks up its\n * anchor through `RUNG_ANCHOR[rung][band]`.\n *\n * Talk: 3 / 6 / 10 (Opinion / Pitch-deck / Anecdotal merged)\n * Desk research: 15 / 15 / 15 (flat — desk research has no meaningful bands,\n * but the field exists for uniformity)\n * Signed up: 30 / 50 / 70 (consumer lens's first do-rung)\n * Observed usage: 30 / 50 / 70 (consumer lens; was Prototype usage + Survey\n * at scale, now collapsed)\n * Signed intent: 30 / 50 / 70 (commercial/investor lens)\n * Paying users: 30 / 50 / 70 (commercial/investor lens)\n *\n * The lens determines which \"do\" rungs are available; Talk + Desk work for\n * any lens. The rung-to-lens mapping is a grading guideline, not a schema\n * constraint — any Rung can appear on any assumption.\n */\nimport type { MagnitudeBand, Rung } from \"../types.js\";\n\nexport const RUNG_ANCHOR: Record<Rung, Record<MagnitudeBand, number>> = {\n Talk: { Low: 3, Typical: 6, High: 10 },\n \"Desk research\": { Low: 15, Typical: 15, High: 15 },\n \"Signed up\": { Low: 30, Typical: 50, High: 70 },\n \"Observed usage\": { Low: 30, Typical: 50, High: 70 },\n \"Signed intent\": { Low: 30, Typical: 50, High: 70 },\n \"Paying users\": { Low: 30, Typical: 50, High: 70 },\n};","/**\n * Assumption completeness — a derived readiness meter, never stored.\n *\n * Replaces the old Gaps / presence-field machinery (OPS-1305): an assumption's\n * Draft-vs-Live readiness is the structural presence of its slots, not a set of\n * hand-maintained tags. `Completeness %` is `filled slots / all slots`; a\n * fully-filled assumption reads 100 and is Live-ready, an empty draft reads low.\n *\n * Slots (each an equal fifth):\n * Description · Lens · Impact · Scoring justification · Dependencies traced\n *\n * Pure, no backend dependency — the same function the recompute pass stamps\n * into the derived tuple and the audit checks readiness against.\n */\n\n/** The structural slots whose presence makes an assumption Live-ready. */\nexport const COMPLETENESS_SLOTS = [\n \"Description\",\n \"Lens\",\n \"Impact\",\n \"Scoring justification\",\n \"Dependencies traced\",\n] as const;\n\nexport type CompletenessSlot = (typeof COMPLETENESS_SLOTS)[number];\n\n/** The record shape completeness reads — an assumption's structural fields. */\nexport interface CompletenessInput {\n Description?: unknown;\n Lens?: unknown;\n Impact?: unknown;\n \"Scoring justification\"?: unknown;\n dependsOnIds?: unknown;\n enablesIds?: unknown;\n}\n\n/** A text slot is present only when it is a non-blank string. */\nfunction hasText(value: unknown): boolean {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\n/** Impact is present when it is a real finite number (0 is a valid score). */\nfunction hasNumber(value: unknown): boolean {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\n/** Dependencies are traced once at least one Depends on / Enables link exists. */\nfunction hasAny(value: unknown): boolean {\n return Array.isArray(value) && value.length > 0;\n}\n\n/** Whether each slot is structurally present. */\nexport function completenessSlotPresence(\n record: CompletenessInput,\n): Record<CompletenessSlot, boolean> {\n return {\n Description: hasText(record.Description),\n Lens: hasText(record.Lens),\n Impact: hasNumber(record.Impact),\n \"Scoring justification\": hasText(record[\"Scoring justification\"]),\n \"Dependencies traced\":\n hasAny(record.dependsOnIds) || hasAny(record.enablesIds),\n };\n}\n\n/** The slots that are absent or blank on a record. */\nexport function missingCompletenessSlots(\n record: CompletenessInput,\n): CompletenessSlot[] {\n const present = completenessSlotPresence(record);\n return COMPLETENESS_SLOTS.filter((slot) => !present[slot]);\n}\n\n/** Completeness as a whole-number percentage (0, 20, 40, 60, 80, 100). */\nexport function assumptionCompleteness(record: CompletenessInput): number {\n const present = completenessSlotPresence(record);\n const filled = COMPLETENESS_SLOTS.filter((slot) => present[slot]).length;\n return Math.round((filled / COMPLETENESS_SLOTS.length) * 100);\n}\n\n/** True when every slot is present — the structural precondition to be Live. */\nexport function assumptionComplete(record: CompletenessInput): boolean {\n return missingCompletenessSlots(record).length === 0;\n}\n","/**\n * Strength — the signed reading value `s` the Confidence average reads.\n *\n * Formula (`ontology.yaml` → `derivations.strength`):\n * rung anchor × magnitude band × sign(Result)\n * — Validated positive, Invalidated negative; 0 unless Validated/Invalidated.\n *\n * Every rung now carries a magnitude band (0.14); the lookup is the same for\n * testing and market rungs.\n */\nimport type { MagnitudeBand, Result, Rung } from \"../types.js\";\nimport { RUNG_ANCHOR } from \"./rung.js\";\n\nexport function sign(result: Result): -1 | 0 | 1 {\n if (result === \"Validated\") return 1;\n if (result === \"Invalidated\") return -1;\n return 0;\n}\n\n/** A reading counts toward Confidence only once concluded either way; an\n * Inconclusive reading carries no signal. The single definition the whole\n * derivation module (and its record→input mappers) share. */\nexport function isConcluded(result: Result): boolean {\n return result === \"Validated\" || result === \"Invalidated\";\n}\n\nexport interface StrengthInput {\n rung: Rung;\n result: Result;\n /** Magnitude band; defaults to \"Typical\" when absent. Applies to ALL rungs. */\n magnitudeBand?: MagnitudeBand;\n}\n\nexport function readingStrength(input: StrengthInput): number {\n const s = sign(input.result);\n if (s === 0) return 0; // Inconclusive contributes nothing.\n const band = input.magnitudeBand ?? \"Typical\";\n return (RUNG_ANCHOR[input.rung]?.[band] ?? 0) * s;\n}","/**\n * Source quality — Representativeness × Credibility.\n *\n * Scales a Reading's *weight* in the Confidence average, within its rung.\n * We keep the raw product as the weight (matching the migration's\n * `remodel.mjs`); the five display anchors {0.25, 0.35, 0.5, 0.7, 1.0} are a\n * storage/display concern, not the weight used in the average.\n */\nimport { round2 } from \"./round.js\";\n\nexport function sourceQuality(\n representativeness: number,\n credibility: number,\n): number {\n return round2(representativeness * credibility);\n}\n","/**\n * Shared registry types — the field vocabulary the whole system speaks.\n *\n * These mirror `skills/_shared/registry-schema.md` and `ontology.yaml` (the\n * single source of truth). Field *meaning* lives there; this file is the\n * checkable TypeScript shape the packages import.\n */\n\n/**\n * The five registers. `goals` was unified into `experiments` and the `people`\n * reference collection retired (OPS-1305): Owner / Agreed by now reference a\n * dashboard user (the auth-sourced team list), not a register row.\n */\nexport const REGISTERS = [\n \"assumptions\",\n \"experiments\",\n \"readings\",\n \"decisions\",\n \"glossary\",\n] as const;\nexport type Register = (typeof REGISTERS)[number];\n\n/** There is no reference collection any more — a collection is a register. */\nexport type Collection = Register;\n\n/** Every stored record carries an id, a version, and timestamps. */\nexport interface BaseRecord {\n id: string;\n /** Optimistic-concurrency token; bumped on every write. */\n version: number;\n createdAt: string;\n updatedAt: string;\n}\n\n// ── Vocabularies (canonical select-option lists) ────────────────────────────\n\nexport type AssumptionStatus = \"Draft\" | \"Live\" | \"Invalidated\";\n/**\n * The unified evidence-plan lifecycle (OPS-1305). `Draft` is the new gate a\n * commit clears (Draft→Running); conclude+verdict stays the Running→Closed\n * gate. Absorbs what the retired Goal record's status used to carry.\n */\nexport type ExperimentStatus = \"Draft\" | \"Running\" | \"Closed\" | \"Archived\";\nexport type DecisionStatus =\n | \"Active\"\n | \"Provisional\"\n | \"Superseded\"\n | \"Reversed\";\nexport type GlossaryStatus = \"Active\" | \"Provisional\" | \"Superseded\";\n\nexport type Result = \"Validated\" | \"Invalidated\" | \"Inconclusive\";\nexport type MagnitudeBand = \"Low\" | \"Typical\" | \"High\";\nexport type Feasibility = \"High\" | \"Medium\" | \"Low\";\n\n/**\n * The lens-aware ladder (DEV-5879). A rung is an evidence TYPE; magnitude band\n * (Low/Typical/High) is the intensity *within* a type. The band applies to\n * EVERY rung, so every rung looks up its anchor through\n * `RUNG_ANCHOR[rung][band]`.\n *\n * Talk: 3 / 6 / 10 (Opinion / Pitch-deck / Anecdotal merged)\n * Desk research: 15 / 15 / 15 (flat)\n * Signed up: 30 / 50 / 70 (consumer lens's first do-rung)\n * Observed usage: 30 / 50 / 70 (consumer lens; was Prototype usage + Survey\n * at scale)\n * Signed intent: 30 / 50 / 70 (commercial/investor lens)\n * Paying users: 30 / 50 / 70 (commercial/investor lens)\n *\n * The lens determines which \"do\" rungs are available; Talk + Desk work for any\n * lens. The rung-to-lens mapping is a grading guideline, not a schema\n * constraint — any Rung can appear on any assumption.\n */\nexport const TESTING_RUNGS = [\n \"Talk\",\n \"Desk research\",\n \"Signed up\",\n \"Observed usage\",\n] as const;\nexport const MARKET_RUNG_VALUES = [\"Signed intent\", \"Paying users\"] as const;\nexport type TestingRung = (typeof TESTING_RUNGS)[number];\nexport type MarketRung = (typeof MARKET_RUNG_VALUES)[number];\nexport type Rung = TestingRung | MarketRung;\n\n/** Representativeness and Credibility are each picked from these. */\nexport type SourceQualityPick = 1.0 | 0.7 | 0.5;\n\n// ── Records ─────────────────────────────────────────────────────────────────\n\n/** The derived numbers stored on an assumption (never hand-typed). */\nexport interface AssumptionDerived {\n derivedImpact: number;\n risk: number;\n confidence: number;\n /** Structural readiness meter, 0–100 (see `derivation/completeness.ts`). */\n completeness: number;\n}\n\nexport interface AssumptionRecord extends BaseRecord {\n Title: string;\n Description: string;\n Lens: string | null;\n Theme: string[];\n /** The hand-scored seed (0–100), the only hand-scored number here. */\n Impact: number | null;\n Status: AssumptionStatus;\n /** Reference to a dashboard user (auth team list), not a `people` row. */\n Owner: string[];\n moot: boolean;\n /**\n * Kept, narrowed to the Impact-seed rationale (OPS-1305): why the seed\n * `Impact` was scored as it was, incl. dated moot lines. The `5 Whys`,\n * `Metric for truth`, and `Gaps` fields are gone — the why-trace lives in the\n * `Depends on / Enables` chain and the audit check-types are transient grill\n * stages, not stored tags. Readiness is the derived `completeness`.\n */\n \"Scoring justification\": string;\n dependsOnIds: string[];\n enablesIds: string[];\n contradictsIds: string[];\n readingIds: string[];\n derived: AssumptionDerived;\n}\n\n/**\n * One belief's scoring inside a reading — the per-assumption verdict an\n * artifact carries. A reading (one artifact ROW) may score several beliefs at\n * once. The Rung is a property of the artifact, so it (and the market magnitude\n * band) lives on the row, ONE per artifact (OPS 0.10): a reading is at a single\n * evidence rung and reads for/against each belief at that rung. Only the Result\n * and its rationale vary per belief. `strength` is derived (row rung × sign of\n * this belief's Result), never hand-typed.\n */\nexport interface BeliefScore {\n assumptionId: string;\n Result: Result;\n /** The rationale for this belief's Result at the row's rung. */\n \"Grading justification\": string;\n /** Derived per belief: row rung anchor × sign(Result) [× row magnitude band]. */\n derived: { strength: number };\n /** Provenance: the original reading id this belief was migrated from. */\n sourceReadingId?: string;\n /** Optional review caveat, e.g. a second-hand-credibility note. */\n reviewNote?: string;\n}\n\nexport interface ReadingRecord extends BaseRecord {\n Title: string;\n /** The independence/dedupe key — the generator (person / dataset / cohort). */\n Source: string | null;\n /**\n * Provenance links (recording, dashboard, CRM row, user id) — 0..N, drives no\n * math and never keys dedupe (OPS-1305). Split out from `Source` so the\n * dedupe key stays narrow.\n */\n contextLinks: string[];\n /** The originating plan, or null for a bare/found reading (no Goal origin). */\n experimentId: string | null;\n /** The evidence rung — one per artifact; every belief is scored at it (OPS 0.10). */\n Rung: Rung;\n /** For a Market-rung reading: the magnitude band from the absolute outcome. */\n magnitudeBand?: MagnitudeBand;\n Representativeness: SourceQualityPick;\n Credibility: SourceQualityPick;\n Date: string | null;\n Owner: string[];\n /** Free-text narrative of the reading. */\n body?: string;\n /** Per-belief scores — one artifact row can score several beliefs at once. */\n beliefs: BeliefScore[];\n /** Convenience projection of `beliefs[].assumptionId`; kept in sync on write. */\n assumptionIds: string[];\n derived: { sourceQuality: number };\n}\n\n/**\n * A pre-registered bar line — the per-belief pass/fail test on an experiment,\n * stored as an embedded array on the experiment (no identity of its own; see\n * `connectors/nosql-schema.md`). `barVerdict` is set once at closure and is a\n * report only — never folded into Confidence.\n */\nexport interface BarLine {\n assumptionId: string;\n rightIf: string;\n wrongIf?: string | null;\n plannedRung: Rung;\n barVerdict?: Result | null;\n}\n\n/**\n * The derived numbers stored on an experiment (never hand-typed).\n * `experimentConfidence` is the [0, 100] confidence gauge (50 = neutral),\n * coverage-gated and verdict-aligned; see `derivation/experiment-confidence.ts`.\n */\nexport interface ExperimentDerived {\n experimentConfidence: number;\n}\n\nexport interface ExperimentRecord extends BaseRecord {\n Title: string;\n Instrument: string | null;\n Feasibility: Feasibility | null;\n Status: ExperimentStatus;\n /** Free-text narrative of the plan. */\n body?: string;\n closureReason: \"Completed\" | \"Early-stop\" | \"Kill\" | null;\n /** Optional deadline a committed plan carries (folded in from the Goal). */\n Deadline: string | null;\n /** Terminal closure outcome, null until Closed (folded in from the Goal). */\n Outcome: \"Achieved\" | \"Missed\" | \"Dropped\" | null;\n /** Reference to a dashboard user, not a `people` row. */\n Owner: string[];\n Date: string | null;\n /** The embedded pre-registered bar lines; drives progress-to-conclusion. */\n barLines: BarLine[];\n /** Convenience projection: the assumptions the bar lines test. */\n barLineAssumptionIds: string[];\n /** Derived numbers — recomputed on every touching write. */\n derived?: ExperimentDerived;\n}\n\nexport interface DecisionRecord extends BaseRecord {\n Title: string;\n Status: DecisionStatus;\n /** The one-line statement of what was decided (promoted from the body). */\n Statement: string;\n /** Why the Unanimity score was scored as it was (promoted from the body). */\n \"Unanimity justification\": string;\n /** References to dashboard users (auth team list), not `people` rows. */\n Owner: string[];\n \"Agreed by\": string[];\n basedOnIds: string[];\n resolvesIds: string[];\n}\n\n/** One structured \"don't say\" entry on a glossary term. */\nexport interface GlossaryAvoid {\n audience: string;\n phrase: string;\n fix: string;\n}\n\nexport interface GlossaryRecord extends BaseRecord {\n Title: string;\n Status: GlossaryStatus;\n /** All properties, no body (OPS-1305): the terminology check parses these. */\n Definition: string;\n Avoid: GlossaryAvoid[];\n \"How it differs\": string;\n}\n\n/** A record of any register — the DataProvider's currency. */\nexport type AnyRecord = BaseRecord & Record<string, unknown>;\n\n// ── Relations (both-ends links) ─────────────────────────────────────────────\n\n/** A pointer to one record. */\nexport interface RecordRef {\n register: Collection;\n id: string;\n}\n\n/** The relations the dashboard can set (each writes both ends). */\nexport type Relation =\n | \"assumption-reading\"\n | \"assumption-depends-on\"\n | \"assumption-contradicts\"\n | \"reading-experiment\"\n | \"decision-based-on\"\n | \"decision-resolves\";\n","/**\n * Confidence — signed −100…100, 0 = no evidence.\n *\n * Formula (`ontology.yaml` → `derivations.confidence`):\n * (Σ wi·si) / (Σ_rung W0[rung] + Σ wi), per-rung W0,\n * wi = |si| × Source quality × commitment, si = the reading's signed Strength,\n * commitment = 1.0 for an experiment-linked reading, 0.85 for a found one.\n *\n * W0 is per-rung: each rung has its own prior weight controlling how many\n * distinct sources it takes to approach that rung's anchor (cap). Desk\n * research has a low W0 (2 — one authoritative source nearly saturates);\n * talk rungs have a higher W0 (6.5 — needs ~10 readings to approach the\n * cap); do-rungs (Survey/Prototype/Signed/Paying) have high W0s (~120-410\n * — needs ~20 readings to reach 75% of cap). When readings span multiple\n * rungs, each rung with evidence contributes its W0 to the denominator\n * once (one prior per evidence stream).\n *\n * Only concluded Validated/Invalidated readings enter. Readings sharing a\n * Source against one belief dedupe to the strongest (largest |si|, most\n * recent on ties). Market-rung readings never dedupe (each closed commitment\n * is its own unit). No corroboration bump.\n */\nimport type { MagnitudeBand, Result, Rung } from \"../types.js\";\nimport { MARKET_RUNG_VALUES } from \"../types.js\";\nimport { round2 } from \"./round.js\";\nimport { sourceQuality } from \"./source-quality.js\";\nimport { isConcluded, readingStrength } from \"./strength.js\";\n\n/** Market rungs never dedupe (each closed commitment is its own unit). */\nconst MARKET_RUNG_SET = new Set<Rung>(MARKET_RUNG_VALUES);\nfunction isMarketRung(rung: Rung): boolean {\n return MARKET_RUNG_SET.has(rung);\n}\n\n/**\n * Per-rung prior weight — controls how many distinct sources approach the\n * rung's anchor. Tuned so: Desk 2 readings → ~90% of cap; talk 10 readings →\n * ~90% of cap; do-rungs 20 readings → ~75% of cap. See\n * `docs/evidence-ladder.md` for the derivation.\n */\nexport const W0_BY_RUNG: Record<Rung, number> = {\n // Talk — 10 readings → ~90% of cap.\n Talk: 6.5,\n // Desk research — 2 readings → ~90% of cap (authoritative, rare).\n \"Desk research\": 2,\n // All do-rungs — 20 readings → ~75% of cap. Equal ceilings (70) and equal\n // W0s across consumer (Signed up / Observed usage) and commercial\n // (Signed intent / Paying users) lenses.\n \"Signed up\": 327,\n \"Observed usage\": 327,\n \"Signed intent\": 327,\n \"Paying users\": 327,\n};\n\n/**\n * The neutral prior weight for a rung — how much evidence at this rung is\n * needed to overcome the prior. Per-rung (not a flat constant): see\n * {@link W0_BY_RUNG}.\n */\nexport function w0ForRung(rung: Rung): number {\n return W0_BY_RUNG[rung] ?? 100;\n}\n\n/**\n * The legacy flat W0 — retained for backwards compatibility only. New code\n * should use {@link w0ForRung}. Equal to the old default of 100.\n * @deprecated Use {@link w0ForRung} for per-rung priors.\n */\nexport const W0 = 100;\n\n/**\n * Commitment factor for a *found* reading — one with no originating experiment.\n * A pre-registered (experiment-linked) reading weighs at full commitment (1.0);\n * a found reading is discounted to this. It is a SMALL tiebreaker: it scales the\n * weight only, never the Strength, so it can never reorder readings across rungs\n * (\"Rung dominates\").\n */\nexport const COMMITMENT_FOUND = 0.85;\n\nexport interface ConfidenceReadingInput {\n id: string;\n /** The independence-dedupe key. Null falls back to the reading's own id. */\n source: string | null;\n rung: Rung;\n result: Result;\n representativeness: number;\n credibility: number;\n /** ISO date; used only as the dedupe tie-break (most recent wins). */\n date?: string | null;\n magnitudeBand?: MagnitudeBand;\n /**\n * The originating experiment, or null/undefined for a *found* reading. Drives\n * the commitment factor in the weight (found → {@link COMMITMENT_FOUND}).\n */\n experimentId?: string | null;\n}\n\n/** The commitment weighting for a reading: full for committed, discounted for found. */\nexport function commitmentFactor(experimentId: string | null | undefined): number {\n return experimentId ? 1.0 : COMMITMENT_FOUND;\n}\n\nexport interface Scored {\n input: ConfidenceReadingInput;\n strength: number;\n sq: number;\n /** The reading's weight in the average: |strength| × Source quality × commitment. */\n weight: number;\n}\n\n/**\n * Score every concluded reading and resolve the Source dedupe — the shared\n * front half of the Confidence average. `confidence()` reduces the winners to\n * a number; `confidenceAttribution()` reuses the same winners so the movers it\n * reports always decompose the very number the drawer shows. Market rungs never\n * dedupe (each closed commitment is its own unit).\n */\nexport function scoreAndDedupe(readings: ConfidenceReadingInput[]): Scored[] {\n const scored: Scored[] = readings\n .filter((r) => isConcluded(r.result))\n .map((r) => {\n const strength = readingStrength(r);\n const sq = sourceQuality(r.representativeness, r.credibility);\n const weight = Math.abs(strength) * sq * commitmentFactor(r.experimentId);\n return { input: r, strength, sq, weight };\n })\n .filter((x) => x.strength !== 0);\n\n const best = new Map<string, Scored>();\n for (const x of scored) {\n if (isMarketRung(x.input.rung)) {\n best.set(x.input.id, x);\n continue;\n }\n const key = x.input.source || x.input.id;\n const cur = best.get(key);\n const better =\n !cur ||\n Math.abs(x.strength) > Math.abs(cur.strength) ||\n (Math.abs(x.strength) === Math.abs(cur.strength) &&\n (x.input.date || \"\") > (cur.input.date || \"\"));\n if (better) best.set(key, x);\n }\n return [...best.values()];\n}\n\nexport function confidence(readings: ConfidenceReadingInput[]): number {\n const winners = scoreAndDedupe(readings);\n // Per-rung prior: sum W0 once for each rung that has ≥1 concluded reading.\n // This preserves each rung's accumulation behaviour independently — desk\n // stays fast (low W0), talk stays slow (high W0) — and mixed-rung evidence\n // gets each rung's prior added once (one prior per evidence stream).\n const rungsPresent = new Set(winners.map((x) => x.input.rung));\n let den = 0;\n for (const rung of rungsPresent) den += w0ForRung(rung);\n let num = 0;\n for (const x of winners) {\n num += x.weight * x.strength;\n den += x.weight;\n }\n return den > 0 ? round2(num / den) : 0;\n}\n","/**\n * Confidence attribution — the \"what's moving the number\" half of the\n * understanding layer (OPS-1276). Decomposes an assumption's Confidence into\n * the experiments (and direct readings) contributing to it, ranked by how hard\n * each pushes the number up or down.\n *\n * A winner's contribution is its signed share of the average:\n * cᵢ = (weightᵢ · strengthᵢ) / den,\n * den = Σ_rung W0[rung] + Σ weight (one prior per rung with evidence)\n * so Σ contributions = Σ(wᵢ·sᵢ)/den = Confidence (the W0·0 prior term is 0).\n * The reveal therefore literally adds up to the hero number. Contributions are\n * grouped by the reading's experiment (experiment-less readings — bare/found —\n * fall into a \"direct\" bucket), then ranked by |contribution|. A reading's\n * origin is an experiment or nothing; the retired Goal container is gone\n * (OPS-1305).\n */\nimport { w0ForRung, scoreAndDedupe, type ConfidenceReadingInput } from \"./confidence.js\";\nimport { round2 } from \"./round.js\";\n\n/**\n * The reading shape the attribution reveal consumes. `experimentId` (the\n * grouping key, and the commitment-factor driver) lives on\n * {@link ConfidenceReadingInput}; this alias marks the attribution call sites.\n */\nexport type AttributionReadingInput = ConfidenceReadingInput;\n\n/** What a mover is anchored to — an experiment, or nothing (direct). */\nexport type MoverKind = \"experiment\" | \"direct\";\n\nexport interface Mover {\n /** Stable grouping key: the experiment id, or \"direct\". */\n key: string;\n kind: MoverKind;\n /** The experiment id when `kind === \"experiment\"`, else null. */\n experimentId: string | null;\n /** Signed push on Confidence; the whole set sums to `confidence`. */\n contribution: number;\n /** |contribution| — the rank key and the \"how hard\" magnitude. */\n magnitude: number;\n /** How many (deduped) readings back this mover. */\n readingCount: number;\n /** The winning readings' ids, for drill-through. */\n readingIds: string[];\n}\n\nexport interface Attribution {\n /** The same Confidence the derived box shows (from the same winners). */\n confidence: number;\n /** Movers ranked by |contribution|, strongest first. */\n movers: Mover[];\n}\n\nfunction bucketOf(r: AttributionReadingInput): {\n key: string;\n kind: MoverKind;\n experimentId: string | null;\n} {\n if (r.experimentId) {\n return {\n key: r.experimentId,\n kind: \"experiment\",\n experimentId: r.experimentId,\n };\n }\n return { key: \"direct\", kind: \"direct\", experimentId: null };\n}\n\nexport function confidenceAttribution(\n readings: AttributionReadingInput[],\n): Attribution {\n const winners = scoreAndDedupe(readings);\n // Per-rung prior: sum W0 once for each rung with ≥1 concluded reading,\n // matching the `confidence()` formula.\n const rungsPresent = new Set(winners.map((x) => x.input.rung));\n let den = 0;\n for (const rung of rungsPresent) den += w0ForRung(rung);\n for (const x of winners) den += x.weight;\n\n const byKey = new Map<string, Mover>();\n let num = 0;\n for (const x of winners) {\n num += x.weight * x.strength;\n const b = bucketOf(x.input as AttributionReadingInput);\n const contribution = (x.weight * x.strength) / den;\n const cur = byKey.get(b.key);\n if (cur) {\n cur.contribution += contribution;\n cur.readingCount += 1;\n cur.readingIds.push(x.input.id);\n } else {\n byKey.set(b.key, {\n key: b.key,\n kind: b.kind,\n experimentId: b.experimentId,\n contribution,\n magnitude: 0, // finalised below\n readingCount: 1,\n readingIds: [x.input.id],\n });\n }\n }\n\n const movers = [...byKey.values()].map((m) => ({\n ...m,\n contribution: round2(m.contribution),\n magnitude: round2(Math.abs(m.contribution)),\n }));\n movers.sort((a, b) => b.magnitude - a.magnitude);\n\n return {\n confidence: den > 0 ? round2(num / den) : 0,\n movers,\n };\n}\n","/**\n * Progress-to-conclusion — how close a running experiment is to concluding\n * (OPS-1276). An experiment concludes when every pre-registered bar line has\n * been given a Bar verdict; progress is the count of settled bars against the\n * total. Bar verdict is a report, never a Confidence input (nosql-schema.md),\n * so reading it here is exactly its intended use.\n */\nexport interface BarLineInput {\n /** null/\"\" until the bar is judged at closure. */\n barVerdict?: string | null;\n}\n\nexport interface Progress {\n /** Pre-registered bar lines on the experiment. */\n total: number;\n /** Bars that have a verdict. */\n settled: number;\n /** Bars still awaiting a verdict. */\n toGo: number;\n /** True once every bar is settled (and there is at least one). */\n concluded: boolean;\n}\n\nexport function experimentProgress(bars: BarLineInput[]): Progress {\n const total = bars.length;\n const settled = bars.filter(\n (b) => typeof b.barVerdict === \"string\" && b.barVerdict.trim() !== \"\",\n ).length;\n return {\n total,\n settled,\n toGo: total - settled,\n concluded: total > 0 && settled === total,\n };\n}\n","/**\n * Experiment confidence — a derived [0, 100] gauge for an evidence plan (0.14).\n *\n * Formula (`experimentConfidence`):\n * clamp(50 + 50 × C × S + 5 × A, 0, 100)\n *\n * Where:\n * B = number of bar lines\n * coveredLines = bar lines with ≥1 concluded reading (Validated/Invalidated)\n * C = |coveredLines| / max(B, 1) — coverage factor ∈ [0, 1]\n * For each concluded reading linked to the experiment (deduped by Source,\n * same rule as `confidence.ts`):\n * fᵢ = (strengthᵢ × sqᵢ) / MAX_STRENGTH (signed)\n * strengthᵢ = readingStrength({ rung, result, magnitudeBand })\n * sqᵢ = sourceQuality(representativeness, credibility)\n * F = Σ fᵢ (signed, after dedupe)\n * S = F / (1 + |F|) — soft squash, ℝ → (−1, +1)\n * A = Σ alignedⱼ / B — verdict alignment, per bar\n * alignedⱼ = +1 if barVerdict agrees with the reading sign on bar j,\n * −1 if it contradicts,\n * 0 if Inconclusive or no readings on bar j\n *\n * Neutral = 50 (no evidence yet). Validated readings fill up, Invalidated\n * pull down. Coverage-gated (no readings → C=0 → 50). The 5×A term is a small\n * verdict-alignment nudge so a plan whose bars are settled the way the evidence\n * already points inches further in that direction.\n */\nimport type { MagnitudeBand, Result, Rung } from \"../types.js\";\nimport { round2 } from \"./round.js\";\nimport { sourceQuality } from \"./source-quality.js\";\nimport { isConcluded, readingStrength, sign } from \"./strength.js\";\n\n/** The reference maximum strength — the anchor of the highest rung band. */\nexport const MAX_STRENGTH = 99;\n\nexport interface ExperimentConfidenceBarInput {\n assumptionId: string;\n /** Set at closure; null/absent until then. */\n barVerdict?: Result | null;\n}\n\nexport interface ExperimentConfidenceReadingInput {\n id: string;\n /** The independence-dedupe key. Null falls back to the reading's own id. */\n source: string | null;\n rung: Rung;\n result: Result;\n magnitudeBand?: MagnitudeBand;\n representativeness: number;\n credibility: number;\n /** The assumption (bar line) this reading scores. */\n assumptionId: string;\n}\n\nfunction clamp(n: number, lo: number, hi: number): number {\n return Math.max(lo, Math.min(hi, n));\n}\n\n/**\n * Source dedupe — same rule as `confidence.ts`: group by Source (fall back to\n * the reading's own id), keep the entry with the largest |strength|. Market\n * rungs never dedupe (each closed commitment is its own unit). Mirrored here so\n * experiment confidence stays pure and self-contained.\n */\nfunction dedupeBySource(\n readings: ExperimentConfidenceReadingInput[],\n): ExperimentConfidenceReadingInput[] {\n const MARKET = new Set<Rung>([\"Signed intent\", \"Paying users\"]);\n const best = new Map<string, ExperimentConfidenceReadingInput>();\n for (const r of readings) {\n if (MARKET.has(r.rung)) {\n best.set(r.id, r);\n continue;\n }\n const key = r.source || r.id;\n const cur = best.get(key);\n const s = Math.abs(readingStrength(r));\n const better =\n !cur ||\n s > Math.abs(readingStrength(cur)) ||\n (s === Math.abs(readingStrength(cur)) && (r.id > cur.id));\n if (better) best.set(key, r);\n }\n return [...best.values()];\n}\n\n/**\n * Compute the experiment-confidence gauge. `bars` is the experiment's bar\n * lines; `readings` is the concluded readings linked to the experiment (the\n * caller filters to the experiment's `barLineAssumptionIds`).\n */\nexport function experimentConfidence(\n bars: ExperimentConfidenceBarInput[],\n readings: ExperimentConfidenceReadingInput[],\n): number {\n const B = bars.length;\n\n // Only concluded readings enter; dedupe by Source.\n const concluded = dedupeBySource(\n readings.filter((r) => isConcluded(r.result)),\n );\n\n // Coverage: bar lines with ≥1 concluded reading.\n const barsWithReadings = new Set(\n concluded.map((r) => r.assumptionId),\n );\n const covered = bars.filter((b) => barsWithReadings.has(b.assumptionId)).length;\n const C = B > 0 ? covered / B : 0;\n\n // F = Σ fᵢ (signed).\n let F = 0;\n for (const r of concluded) {\n const strength = readingStrength(r);\n const sq = sourceQuality(r.representativeness, r.credibility);\n F += (strength * sq) / MAX_STRENGTH;\n }\n const S = F / (1 + Math.abs(F));\n\n // Verdict alignment: per bar, +1 if barVerdict agrees with the net reading\n // sign on that bar, −1 if it contradicts, 0 if Inconclusive or no readings.\n const signByBar = new Map<string, number>();\n for (const r of concluded) {\n const s = sign(r.result);\n signByBar.set(r.assumptionId, (signByBar.get(r.assumptionId) ?? 0) + s);\n }\n let A = 0;\n for (const bar of bars) {\n const net = signByBar.get(bar.assumptionId);\n if (net === undefined || net === 0) continue; // no readings or net-zero\n const v = bar.barVerdict;\n if (v !== \"Validated\" && v !== \"Invalidated\") continue; // Inconclusive / unset\n const barSign = v === \"Validated\" ? 1 : -1;\n A += net * barSign > 0 ? 1 : -1;\n }\n if (B > 0) A /= B;\n\n const raw = 50 + 50 * C * S + 5 * A;\n return round2(clamp(raw, 0, 100));\n}","/**\n * Confidence over time — the story of how the number got where it is\n * (OPS-1276). At each date a concluded reading was dated, we recompute\n * Confidence over every concluded reading up to and including that date, using\n * the very same `confidence()` the derived box uses (so the last point equals\n * the hero number). Undated concluded readings have no place on the timeline\n * but still bear on the belief, so they are treated as always-present — folded\n * into every point — which keeps the final point equal to today's Confidence.\n */\nimport { confidence, type ConfidenceReadingInput } from \"./confidence.js\";\nimport { isConcluded } from \"./strength.js\";\n\nexport interface TrajectoryPoint {\n /** ISO date at which Confidence took this value. */\n date: string;\n confidence: number;\n}\n\nexport function confidenceTrajectory(\n readings: ConfidenceReadingInput[],\n): TrajectoryPoint[] {\n const concluded = readings.filter((r) => isConcluded(r.result));\n const undated = concluded.filter((r) => !r.date);\n const dated = concluded.filter((r) => r.date);\n if (dated.length === 0) return [];\n\n const dates = [...new Set(dated.map((r) => r.date as string))].sort();\n return dates.map((date) => ({\n date,\n // Everything dated on/before this point, plus the always-present undated.\n confidence: confidence([\n ...undated,\n ...dated.filter((r) => (r.date as string) <= date),\n ]),\n }));\n}\n","/**\n * Derived Impact — propagates dependents' pull into a belief's seed.\n *\n * Formula (`ontology.yaml` → `derivations.derived_impact`):\n * seed + (100 − seed) × S / (S + 100), where\n * S = Σ Derived Impact of assumptions whose `Depends on` names this row\n * + 100 per standing (Provisional/Active) decision naming it via\n * `Based on assumption`.\n * Goals never contribute. Moot rows pin to 0 and contribute nothing.\n *\n * One reverse-topological pass (dependents first) with memoization and a\n * cycle guard, matching the instance's `migration/remodel.mjs`.\n */\nimport { round2 } from \"./round.js\";\n\nexport interface ImpactAssumptionInput {\n id: string;\n /** The hand-scored seed (0–100); null treated as 0. */\n impact: number | null;\n moot?: boolean;\n /** Ids this assumption depends on. */\n dependsOnIds: string[];\n}\n\n/**\n * @param assumptions the full register (never a filtered slice — a filter\n * silently drops dependents from the propagation).\n * @param basedOnCounts id → number of standing decisions with a `Based on`\n * link to that assumption. Each contributes +100 to S.\n */\nexport function derivedImpacts(\n assumptions: ImpactAssumptionInput[],\n basedOnCounts: Record<string, number> = {},\n): Map<string, number> {\n const byId = new Map(assumptions.map((a) => [a.id, a]));\n\n // dependents(X) = assumptions whose dependsOnIds includes X.\n const dependents = new Map<string, string[]>();\n for (const a of assumptions) dependents.set(a.id, []);\n for (const a of assumptions) {\n for (const dep of a.dependsOnIds) dependents.get(dep)?.push(a.id);\n }\n\n const memo = new Map<string, number>();\n const compute = (id: string, seen: Set<string>): number => {\n const cached = memo.get(id);\n if (cached !== undefined) return cached;\n if (seen.has(id)) return 0; // cycle guard\n seen.add(id);\n const a = byId.get(id);\n if (!a) return 0;\n if (a.moot) {\n memo.set(id, 0);\n return 0;\n }\n const seed = a.impact ?? 0;\n let S = 0;\n for (const depId of dependents.get(id) ?? []) {\n const d = byId.get(depId);\n if (d && !d.moot) S += compute(depId, seen);\n }\n S += 100 * (basedOnCounts[id] ?? 0);\n const value = seed + (100 - seed) * (S / (S + 100));\n const rounded = round2(value);\n memo.set(id, rounded);\n return rounded;\n };\n\n const out = new Map<string, number>();\n for (const a of assumptions) out.set(a.id, compute(a.id, new Set()));\n return out;\n}\n","/**\n * Risk — the belief's live standing.\n *\n * Formula (`ontology.yaml` → `derivations.risk`):\n * Derived Impact × (1 − max(0, Confidence) / 100)\n * Ranges 0 to Derived Impact. Negative confidence does not raise Risk above\n * Derived Impact (the max(0, …) clamp).\n */\nimport { round2 } from \"./round.js\";\n\nexport function risk(derivedImpact: number, confidence: number): number {\n return round2(derivedImpact * (1 - Math.max(0, confidence) / 100));\n}\n","/**\n * Portfolio progress — the one *cross-belief* reading (OPS-1293 / OPS-1300).\n *\n * Every other derived number here is per-record (risk/confidence/impact of one\n * belief). This is the whole-set roll-up behind the pipeline's headline: a\n * **burn-up**, \"% of identified risk bought down\" = Risk Retired ÷ Risk-ever-\n * identified across *all* beliefs, resolved ones included.\n *\n * Like `rankNextMoves`, it is a whole-set ordering computed **fresh on read**,\n * not stored — it stays out of the OPS-1251 on-write recompute (it only reads\n * numbers already kept current). Pure and numeric: the dashboard maps records\n * to these inputs (as `understanding.ts` maps readings), so the rule lives\n * once, here.\n *\n * The model (matches the OPS-1296 prototype's self-consistent maths):\n * - **ever-identified** for a belief = the risk it represented at Confidence\n * ≤ 0, i.e. its Derived Impact. A moot row's Derived Impact is pinned to 0,\n * which would erase it from *both* sides of the fraction, so we floor\n * ever-identified at the hand-scored seed Impact — mooting a belief must\n * *retire* its risk, never shrink the denominator (the burn-up's whole\n * point: resolved risk stays counted).\n * - **live** risk = the belief's current Risk, or 0 once resolved (a kill or\n * a moot resolves the uncertainty — that risk is bought down, not carried).\n * - **retired** = ever-identified − live.\n */\nimport { round2 } from \"./round.js\";\n\nexport interface PortfolioBeliefInput {\n id: string;\n /** Derived Impact — the belief's risk at Confidence ≤ 0 (0 when moot). */\n derivedImpact: number;\n /** The hand-scored seed Impact; the ever-identified floor when moot zeroes\n * Derived Impact. Null/absent treated as 0. */\n seedImpact: number | null;\n /** The belief's current live Risk (stored `derived.risk`). */\n risk: number;\n /** Resolved — Invalidated (killed) or moot. Its live risk reads 0 (fully\n * retired), whatever the stored Risk number says. */\n resolved: boolean;\n}\n\n/** One belief's contribution to the burn-up. */\nexport interface BeliefRisk {\n /** Risk-ever-identified — the denominator's per-belief share. */\n identified: number;\n /** Live risk still carried (0 once resolved). */\n live: number;\n /** Risk bought down — the numerator's per-belief share. */\n retired: number;\n}\n\nexport interface PortfolioProgress {\n /** Σ risk-ever-identified — the burn-up denominator. */\n identified: number;\n /** Σ risk bought down — the burn-up numerator. */\n retired: number;\n /** Σ risk still live. */\n live: number;\n /** Retired ÷ identified as a percentage (0 when nothing is identified). */\n percent: number;\n /** Beliefs still in play (not resolved). */\n liveCount: number;\n /** Beliefs resolved (killed or moot). */\n resolvedCount: number;\n}\n\n/** One belief's identified / live / retired risk — the rule in one place. */\nexport function beliefRisk(b: PortfolioBeliefInput): BeliefRisk {\n const seed = b.seedImpact ?? 0;\n const identified = Math.max(b.derivedImpact, seed, 0);\n // Live risk can never exceed what was ever identified — the clamp keeps a\n // stale/over-large stored Risk from making retired go negative.\n const live = b.resolved ? 0 : Math.min(identified, Math.max(0, b.risk));\n return {\n identified: round2(identified),\n live: round2(live),\n retired: round2(identified - live),\n };\n}\n\n/**\n * Roll every belief up into the portfolio burn-up. Pass the *whole* set\n * (resolved rows included) — a filtered slice understates the denominator and\n * makes fresh or retired risk read as backsliding.\n */\nexport function portfolioProgress(\n beliefs: PortfolioBeliefInput[],\n): PortfolioProgress {\n let identified = 0;\n let live = 0;\n let liveCount = 0;\n let resolvedCount = 0;\n for (const b of beliefs) {\n const r = beliefRisk(b);\n identified += r.identified;\n live += r.live;\n if (b.resolved) resolvedCount += 1;\n else liveCount += 1;\n }\n const retired = identified - live;\n return {\n identified: round2(identified),\n retired: round2(retired),\n live: round2(live),\n percent: identified > 0 ? round2((retired / identified) * 100) : 0,\n liveCount,\n resolvedCount,\n };\n}\n","/**\n * Next-move ranking — the front door's single source of truth for \"what should\n * I do next\" (build OPS-1304; placement OPS-1292; action vocabulary OPS-1291).\n *\n * Ranks *beliefs* — Model A: point at one belief, not a heterogeneous triage\n * queue (OPS-1291) — by the method's Feasibility × Risk rule (`docs/method.md`,\n * `ontology.yaml` → `derived_views.next_move`), and names the single act each\n * belief's stage demands. A belief at Confidence ≤ −50 jumps into a distinct\n * kill/re-test lane that sorts above the Feasibility × Risk order regardless of\n * rank — the one place act-urgency beats belief-risk (`derived_views.kill_lane`).\n *\n * Computed fresh on read: a whole-set ordering, so it stays OUT of the OPS-1251\n * on-write recompute — it reads the derived numbers (Risk, Confidence) those\n * writes already keep current. Pure: no I/O, no caching, no weights framework —\n * the enum→multiplier map below IS the formula (OPS-1292: \"no weights /\n * strategies / caching / framework\").\n */\nimport type { Feasibility } from \"../types.js\";\nimport { round2 } from \"./round.js\";\n\n/** The kill/re-test threshold — Confidence at or below this is the kill lane. */\nexport const KILL_LANE_THRESHOLD = -50;\n\n/**\n * The acts the front door can name, one per belief-stage. The front door\n * *names* all of them; only a subset are human step-in forms — the rest are\n * agent-run / off-dashboard (OPS-1294). Which is which is a presentation\n * concern the dashboard owns, not this ranking.\n */\nexport type MoveKind =\n | \"score-impact\" // Framed — the belief isn't weighted yet (Impact unscored)\n | \"design-experiment\" // Planned — no test plans this belief yet\n | \"record-reading\" // Tested — a test is running, evidence still landing\n | \"decide\" // Known — evidence has landed and no decision rests on it\n | \"retest\"; // kill lane — Confidence ≤ −50, jumps the ordering\n\n/**\n * One belief's next move. `move`/`score`/`reason` are the OPS-1292 output\n * contract; the rest is context the front door renders (the risk chip, the kill\n * banner, the step-in adaptation) — every field read from the inputs, nothing\n * new computed here.\n */\nexport interface NextMove {\n /** The act this belief's stage demands. */\n move: MoveKind;\n assumptionId: string;\n /** The belief statement — the hero headline. */\n title: string;\n /** Feasibility × Risk. Kill-lane rows carry their Risk and sort first. */\n score: number;\n /** Plain-language \"why this\" — explains from the inputs, no jargon. */\n reason: string;\n /** The belief's live derived Risk (0–100). */\n risk: number;\n /** The belief's live derived Confidence (signed −100…100). */\n confidence: number;\n /** The feasibility that fed the score; null when no test plans it yet. */\n feasibility: Feasibility | null;\n /** Confidence ≤ −50 — the override lane. */\n killLane: boolean;\n}\n\n/** A belief and its live derived numbers (the ranking's primary input). */\nexport interface NextMoveAssumptionInput {\n id: string;\n title: string;\n /** AssumptionStatus; `Invalidated` rows are already killed and drop out. */\n status: string;\n /** The hand-scored seed (0–100); null means unscored → \"score impact\". */\n impact: number | null;\n /** Mooted beliefs (Impact pinned to 0 by a decision) drop out of ranking. */\n moot: boolean;\n /** Derived Risk (already recomputed on write — read, never recomputed). */\n risk: number;\n /** Derived Confidence (already recomputed on write). */\n confidence: number;\n /** How many concluded (Validated/Invalidated) readings back this belief. */\n concludedReadings: number;\n}\n\n/** An experiment, reduced to what stage + feasibility resolution needs. */\nexport interface NextMoveExperimentInput {\n /** ExperimentStatus — \"Running\" | \"Closed\". */\n status: string;\n feasibility: Feasibility | null;\n /** The assumption ids this experiment's bar lines name. */\n assumptionIds: string[];\n}\n\n/** A decision, reduced to which beliefs it rests on or resolves. */\nexport interface NextMoveDecisionInput {\n /** DecisionStatus; only standing (Active/Provisional) decisions count. */\n status: string;\n /** The assumption ids this decision rests on (`based on`) or resolves. */\n assumptionIds: string[];\n}\n\nexport interface NextMoveInput {\n assumptions: NextMoveAssumptionInput[];\n experiments: NextMoveExperimentInput[];\n decisions: NextMoveDecisionInput[];\n}\n\n/**\n * Feasibility → the score multiplier. Cheaper (more feasible) tests rank\n * higher, so the cheapest honest test of the riskiest belief is on top\n * (`method.md`). A belief with no planned test yet has unknown feasibility →\n * the neutral middle, so Risk decides its place honestly.\n */\nconst FEASIBILITY_WEIGHT: Record<Feasibility, number> = {\n High: 1,\n Medium: 0.6,\n Low: 0.3,\n};\nconst NEUTRAL_FEASIBILITY_WEIGHT = FEASIBILITY_WEIGHT.Medium;\n\nfunction isStanding(decisionStatus: string): boolean {\n return decisionStatus === \"Active\" || decisionStatus === \"Provisional\";\n}\n\n/** Pick the cheapest (highest-weight) feasibility among a belief's tests. */\nfunction bestFeasibility(\n feasibilities: (Feasibility | null)[],\n): Feasibility | null {\n let best: Feasibility | null = null;\n let bestWeight = -1;\n for (const f of feasibilities) {\n if (!f) continue;\n const w = FEASIBILITY_WEIGHT[f];\n if (w > bestWeight) {\n bestWeight = w;\n best = f;\n }\n }\n return best;\n}\n\n/**\n * The act a belief's stage demands (before the kill-lane override).\n *\n * Deliberately NOT the `stage.ts` structural classifier: that answers \"how far\n * along the Framed→Planned→Tested→Known artifacts are\" (framing completeness,\n * bar-line settlement); this answers \"what should the founder do next\" from the\n * evidence state (is it weighted, has evidence concluded, does a test run, does\n * a decision rest on it). Same belief can be structurally `tested` yet owe a\n * `decide` here — the journey rail (stage) and next-move card (act) are two\n * readings of one belief, so they share the test-plan *meter* (`beliefTestMeters`)\n * but not the classifier.\n */\nfunction stageMove(\n a: NextMoveAssumptionInput,\n hasRunningTest: boolean,\n hasAnyTest: boolean,\n hasStandingDecision: boolean,\n): MoveKind | null {\n if (a.impact === null) return \"score-impact\"; // Framed → weight it\n if (a.concludedReadings === 0) {\n // No evidence yet: if a test is running, wait for readings; else plan one.\n return hasRunningTest ? \"record-reading\" : \"design-experiment\";\n }\n // Evidence has landed. If nothing rests on it yet, it's time to decide;\n // once a standing decision does, the belief is resolved and drops out.\n if (!hasStandingDecision) return \"decide\";\n return null;\n}\n\n/** Plain-language \"why this\" — explains the move from the inputs. */\nfunction reasonFor(move: MoveKind, a: NextMoveAssumptionInput): string {\n switch (move) {\n case \"retest\":\n return `Confidence has fallen to ${Math.round(a.confidence)} — the evidence is turning against this belief. Kill it or test it again.`;\n case \"score-impact\":\n return \"This belief isn't weighted yet — score its impact so its risk can rank against the rest.\";\n case \"design-experiment\":\n return `Your riskiest untested belief. Design the cheapest honest test that could move it.`;\n case \"record-reading\":\n return \"A test is running against this belief — evidence is still landing.\";\n case \"decide\":\n return \"The evidence is in and nothing rests on it yet — time to make the call.\";\n }\n}\n\n/**\n * Rank every unresolved belief into its next move (Model A). Returns a plain\n * sorted list, most-pressing first: the kill lane on top (by Risk), then the\n * rest by Feasibility × Risk, tie-broken by the most-negative Confidence\n * (`derived_views.test_next_surface`), then by id for a stable order. The front\n * door takes the head as the hero and the tail as \"On deck\" / manual override.\n */\nexport function rankNextMoves(input: NextMoveInput): NextMove[] {\n const { assumptions, experiments, decisions } = input;\n\n // Which experiments (and their feasibilities/statuses) name each belief.\n const testsByAssumption = new Map<\n string,\n { running: boolean; any: boolean; feasibilities: (Feasibility | null)[] }\n >();\n for (const exp of experiments) {\n const running = exp.status === \"Running\";\n for (const id of exp.assumptionIds) {\n const entry = testsByAssumption.get(id) ?? {\n running: false,\n any: false,\n feasibilities: [],\n };\n entry.any = true;\n entry.running = entry.running || running;\n entry.feasibilities.push(exp.feasibility);\n testsByAssumption.set(id, entry);\n }\n }\n\n // Which beliefs a standing decision rests on or resolves.\n const decidedAssumptions = new Set<string>();\n for (const d of decisions) {\n if (!isStanding(d.status)) continue;\n for (const id of d.assumptionIds) decidedAssumptions.add(id);\n }\n\n const moves: NextMove[] = [];\n for (const a of assumptions) {\n if (a.moot || a.status === \"Invalidated\") continue;\n\n const killLane = a.confidence <= KILL_LANE_THRESHOLD;\n const tests = testsByAssumption.get(a.id);\n const feasibility = bestFeasibility(tests?.feasibilities ?? []);\n\n const move: MoveKind | null = killLane\n ? \"retest\"\n : stageMove(\n a,\n tests?.running ?? false,\n tests?.any ?? false,\n decidedAssumptions.has(a.id),\n );\n if (move === null) continue; // resolved — no move\n\n const weight = feasibility\n ? FEASIBILITY_WEIGHT[feasibility]\n : NEUTRAL_FEASIBILITY_WEIGHT;\n // Kill-lane rows carry their raw Risk so they order among themselves by\n // Risk; the killLane flag (not the score) floats them above everyone else.\n const score = round2(killLane ? a.risk : weight * a.risk);\n\n moves.push({\n move,\n assumptionId: a.id,\n title: a.title,\n score,\n reason: reasonFor(move, a),\n risk: a.risk,\n confidence: a.confidence,\n feasibility,\n killLane,\n });\n }\n\n moves.sort((x, y) => {\n if (x.killLane !== y.killLane) return x.killLane ? -1 : 1;\n if (y.score !== x.score) return y.score - x.score;\n if (x.confidence !== y.confidence) return x.confidence - y.confidence;\n return x.assumptionId < y.assumptionId ? -1 : 1;\n });\n return moves;\n}\n","/**\n * Per-belief stage — where one belief sits on the loop's four-stage spine\n * (Framed → Planned → Tested → Known) and its four meters (OPS-1329).\n *\n * This is the *single-belief* analogue of the pipeline's cross-belief roll-up:\n * the pipeline row-builder used to derive framing / test-plan / test-progress\n * inline, and the front-door move ladder (OPS-1304) re-walked the same stages a\n * second way. The shared classification lives here now, so the pipeline board,\n * the front door, and the per-belief journey rail all read one rule rather than\n * three that can drift.\n *\n * Pure and computed fresh on read (like `portfolio.ts` / `next-move.ts`): it\n * only reads numbers already kept current, so it stays out of the OPS-1251\n * on-write recompute. The record → meter mapping (bar lines, presence fields)\n * lives in the dashboard, as elsewhere; this module takes the reduced inputs.\n */\nimport { KILL_LANE_THRESHOLD } from \"./next-move.js\";\n\n/** The four loop stages a belief travels, in order (OPS-1293). */\nexport type StageKey = \"framed\" | \"planned\" | \"tested\" | \"known\";\n\n/** Sign of a belief's Confidence — the Known meter's direction. */\nexport type ConfSign = \"pos\" | \"neg\" | \"zero\";\n\n/** One belief's test state, aggregated across every experiment aimed at it. */\nexport interface TestMeter {\n /** A bar line (or the convenience projection) names this belief. */\n planned: boolean;\n /** Pre-registered bars that have a verdict. */\n settled: number;\n /** Pre-registered bars in total. */\n total: number;\n}\n\n/** A test's bar lines, reduced to what the meter needs (register-agnostic). */\nexport interface StageExperimentInput {\n /** Each bar line naming a belief, and whether it has settled (has a verdict). */\n bars: { assumptionId: string; settled: boolean }[];\n /** Beliefs this test plans via the convenience projection (bars may be unexpanded). */\n plannedAssumptionIds: string[];\n}\n\n/** The reduced inputs one belief's stage is derived from. */\nexport interface BeliefStageInput {\n /** Framing completeness, 0–100 (`assumptionCompleteness`). */\n framed: number;\n /** Live derived Confidence (signed −100…100). */\n confidence: number;\n /** This belief's aggregated test state. */\n test: TestMeter;\n}\n\n/** One belief's position on the spine plus its four meters. */\nexport interface BeliefStage {\n /** Where the belief sits: framed → planned → tested → known. */\n stage: StageKey;\n /** Meter 1 — framing completeness, 0–100. */\n framed: number;\n /** Meter 2 — a test has been designed against this belief. */\n planned: boolean;\n /** Meter 3 — pre-registered bars settled / total. */\n tested: { settled: number; total: number };\n /** Meter 4 — signed Known: the belief's Confidence. */\n confidence: number;\n /** Sign bucket for the Known gauge direction. */\n confSign: ConfSign;\n /** Confidence ≤ −50 — the kill/re-test overlay (the same lane as the front door). */\n killZone: boolean;\n}\n\n/** An empty test state — a belief no experiment has named yet. */\nexport function emptyTestMeter(): TestMeter {\n return { planned: false, settled: 0, total: 0 };\n}\n\n/**\n * For every belief, the state of the tests aimed at it — whether one is designed\n * and how many of its pre-registered bars have settled, aggregated across all\n * experiments. Factored out of the pipeline row-builder so the board and a\n * single belief's rail agree by construction.\n */\nexport function beliefTestMeters(\n experiments: StageExperimentInput[],\n): Map<string, TestMeter> {\n const byAssumption = new Map<string, TestMeter>();\n const ensure = (id: string): TestMeter => {\n let s = byAssumption.get(id);\n if (!s) {\n s = emptyTestMeter();\n byAssumption.set(id, s);\n }\n return s;\n };\n for (const exp of experiments) {\n for (const b of exp.bars) {\n if (!b.assumptionId) continue;\n const s = ensure(b.assumptionId);\n s.planned = true;\n s.total += 1;\n if (b.settled) s.settled += 1;\n }\n // A designed test may name a belief via the convenience projection even when\n // its bar lines aren't expanded — still counts as Planned.\n for (const id of exp.plannedAssumptionIds) ensure(id).planned = true;\n }\n return byAssumption;\n}\n\n/**\n * Classify a belief on the spine from its meters. The kill-zone overlay is\n * *not* a stage — a belief whose evidence has turned is still structurally\n * wherever its framing/tests put it (a re-test moves it backward via the Known\n * meter, OPS-1300), so this stays pure status.\n */\nexport function classifyStage(framed: number, test: TestMeter): StageKey {\n if (framed < 100) return \"framed\";\n if (!test.planned) return \"planned\";\n if (test.total === 0 || test.settled < test.total) return \"tested\";\n return \"known\";\n}\n\n/** One belief's stage + four meters — the rail's data. */\nexport function deriveBeliefStage(input: BeliefStageInput): BeliefStage {\n const { framed, confidence, test } = input;\n return {\n stage: classifyStage(framed, test),\n framed,\n planned: test.planned,\n tested: { settled: test.settled, total: test.total },\n confidence,\n confSign: confidence > 0 ? \"pos\" : confidence < 0 ? \"neg\" : \"zero\",\n killZone: confidence <= KILL_LANE_THRESHOLD,\n };\n}\n","/**\n * The per-belief journey event log (OPS-1329) — the belief's life ordered into\n * dated events: bet → score → experiment → readings → confidence-cross → now.\n * It is the *story* half of the journey drill-in (the *rail* half is `stage.ts`).\n *\n * No new maths: Confidence at each point is read off `confidenceTrajectory`\n * (the very numbers the understanding layer already shows), and the current\n * number off `confidence()`. Nothing is invented — an event whose underlying\n * datum is absent (no impact score, no experiment, no concluded reading, no\n * kill-zone cross) is simply omitted, and no date is ever faked (an event with\n * no real date carries `date: null` and takes its place by structural order).\n *\n * Pure and label-free: the dashboard journey view-model adds the copy. Computed\n * fresh on read, out of the OPS-1251 on-write recompute.\n */\nimport type { Result } from \"../types.js\";\nimport type { AttributionReadingInput } from \"./attribution.js\";\nimport { confidence } from \"./confidence.js\";\nimport { KILL_LANE_THRESHOLD } from \"./next-move.js\";\nimport { isConcluded } from \"./strength.js\";\nimport { confidenceTrajectory } from \"./trajectory.js\";\n\n/** The kinds of event a belief's life produces, in structural order. */\nexport type JourneyEventKind =\n | \"bet\" // the belief was written\n | \"score\" // its impact was scored\n | \"experiment\" // a test was designed against it\n | \"reading\" // evidence landed\n | \"confidence-cross\" // Confidence fell into the kill zone\n | \"now\"; // the belief's state today\n\n/** The structural order the story walks — the tie-break for undated events. */\nconst KIND_ORDER: Record<JourneyEventKind, number> = {\n bet: 0,\n score: 1,\n experiment: 2,\n reading: 3,\n \"confidence-cross\": 4,\n now: 5,\n};\n\n/** One event in a belief's life. Label-free — the view-model adds the copy. */\nexport interface JourneyEvent {\n kind: JourneyEventKind;\n /** ISO date, or null when no real date exists (never faked). */\n date: string | null;\n /** Confidence known at this event (reading / cross / now); null otherwise. */\n confidence: number | null;\n /** The reading's verdict, for `reading` events; null otherwise. */\n result: Result | null;\n /** The source record id (reading id, experiment id) when the event has one. */\n refId: string | null;\n}\n\n/** The belief itself, reduced to what the log needs. */\nexport interface JourneyBeliefInput {\n /** When the bet was written — the `bet` event's date. */\n createdAt: string | null;\n /** Impact has been scored (a non-null seed) — emits the `score` event. */\n impactScored: boolean;\n}\n\n/** A test aimed at this belief, reduced to what the log needs. */\nexport interface JourneyExperimentInput {\n id: string;\n /** When the test was designed; null when unknown (event still emitted, undated). */\n date: string | null;\n}\n\nexport interface AssembleJourneyInput {\n belief: JourneyBeliefInput;\n /** The belief's own readings (already filtered to this assumption). */\n readings: AttributionReadingInput[];\n /** The experiments testing this belief. */\n experiments: JourneyExperimentInput[];\n /** \"Now\" as an ISO date — passed in so the log stays pure. */\n now: string;\n}\n\n/**\n * Assemble one belief's chronological event log. Events sort by date, undated\n * events anchored to the bet's date and ordered structurally; `now` is always\n * last.\n */\nexport function assembleJourney(input: AssembleJourneyInput): JourneyEvent[] {\n const { belief, readings, experiments, now } = input;\n const events: JourneyEvent[] = [];\n\n if (belief.createdAt) {\n events.push(event(\"bet\", belief.createdAt));\n }\n if (belief.impactScored) {\n // No scored-on date is stored, so the score rides structurally after the\n // bet rather than carrying an invented date.\n events.push(event(\"score\", null));\n }\n for (const e of experiments) {\n events.push(event(\"experiment\", e.date, { refId: e.id }));\n }\n\n const trajectory = confidenceTrajectory(readings);\n const confByDate = new Map(trajectory.map((p) => [p.date, p.confidence]));\n for (const r of readings) {\n const dated = r.date ?? null;\n // Confidence is known only for a concluded reading that lands on a\n // trajectory date (undated / inconclusive readings carry no number).\n const conf =\n dated && isConcluded(r.result) ? (confByDate.get(dated) ?? null) : null;\n events.push(\n event(\"reading\", dated, { confidence: conf, result: r.result, refId: r.id }),\n );\n }\n\n // The first point at which the evidence dragged Confidence into the kill zone.\n const cross = trajectory.find((p) => p.confidence <= KILL_LANE_THRESHOLD);\n if (cross) {\n events.push(event(\"confidence-cross\", cross.date, { confidence: cross.confidence }));\n }\n\n // Undated events anchor to the bet so they sit at the start in structural\n // order; `now` is appended after sorting so it is unconditionally last.\n const anchor = belief.createdAt ?? \"\";\n events.sort((a, b) => {\n const ka = a.date ?? anchor;\n const kb = b.date ?? anchor;\n if (ka !== kb) return ka < kb ? -1 : 1;\n return KIND_ORDER[a.kind] - KIND_ORDER[b.kind];\n });\n events.push(event(\"now\", now, { confidence: confidence(readings) }));\n\n return events;\n}\n\nfunction event(\n kind: JourneyEventKind,\n date: string | null,\n extra: Partial<Pick<JourneyEvent, \"confidence\" | \"result\" | \"refId\">> = {},\n): JourneyEvent {\n return {\n kind,\n date,\n confidence: extra.confidence ?? null,\n result: extra.result ?? null,\n refId: extra.refId ?? null,\n };\n}\n"],"mappings":";;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,SAAS,OAAO,GAAmB;AACxC,SAAO,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC5B;;;ACgBO,IAAM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