@orkestrel/interpret 0.0.4 → 0.0.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.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#records","#emitter","#ensureAlive","#destroyed","#records","#emitter","#ensureAlive","#counter","#destroyed","#session","#subjects","#definitions","#history","#previous","#emitter","#ensureAlive","#destroyed","#records","#emitter","#ensureAlive","#destroyed","#lexicon","#formatters","#floor","#carryOver","#fillDefaults","#resolveComputations","#collectAmbiguities","#orderComputations","#actions","#domains","#verbs","#contractions","#abbreviations","#corrections","#applyStage","#templates","#context","#normalizer","#extractor","#clarifier","#formatter","#generator","#similarity","#floor","#narrator","#emitter","#ensureAlive","#abort","#gate","#destroyed","#assemble"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/managers/DefinitionManager.ts","../../../src/core/managers/SubjectManager.ts","../../../src/core/managers/InterpretContext.ts","../../../src/core/managers/TemplateManager.ts","../../../src/core/Narrator.ts","../../../src/core/stages/Clarifier.ts","../../../src/core/stages/Extractor.ts","../../../src/core/stages/Formatter.ts","../../../src/core/stages/Generator.ts","../../../src/core/stages/Normalizer.ts","../../../src/core/Interpret.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { Lexicon } from './types.js'\n\n// Frozen default data for the interprets module (AGENTS §5 — constants are\n// UPPER_SNAKE_CASE data, the sole home for module-scope literal defaults).\n// Every vocabulary map here is intentionally NEUTRAL and small — domain\n// worldview (insurance verbs, en-US misspelling corrections, business\n// domains) is the caller's business, supplied via options (AGENTS-flagged\n// scsr defect: a \"generic\" core module baked in ~100 hardcoded corrections).\n\n/**\n * Default `similarity` for `createInterpret` / `matchAlias` — the fuzzy\n * alias-match score threshold (0..1).\n *\n * @remarks\n * Domain-qualified (not a bare `DEFAULT_SIMILARITY`) so the name stays free\n * of collision on the shared `@src/core` barrel, mirroring the\n * `DEFAULT_REASON_BAIL` precedent.\n */\nexport const DEFAULT_INTERPRET_SIMILARITY = 0.8\n\n/**\n * Default `floor` for `createInterpret` / `matchTemplate` — the minimum\n * intent confidence a template match (or the classified intent itself) must\n * clear.\n */\nexport const DEFAULT_INTERPRET_FLOOR = 0.3\n\n/** Default `history` cap for an `InterpretContext`'s `previous()` ring buffer. */\nexport const DEFAULT_INTERPRET_HISTORY = 16\n\n/** Default `id` for an `Interpret` orchestrator. */\nexport const INTERPRET_ID = 'interpret'\n\n/** Confidence assigned to an exact keyword-proximity entity match. */\nexport const CONFIDENCE_EXACT = 1\n\n/** Confidence assigned to an exact alias-phrase entity match. */\nexport const CONFIDENCE_ALIAS = 0.9\n\n/** Confidence assigned when a single entity mapping collects every extracted number. */\nexport const CONFIDENCE_COLLECT = 0.9\n\n/** Confidence assigned to a positional (order-based) entity match fallback. */\nexport const CONFIDENCE_POSITIONAL = 0.7\n\n/** Confidence assigned to a same-domain carried-over field. */\nexport const CONFIDENCE_CARRIED = 0.7\n\n/** Confidence assigned to a template default fill. */\nexport const CONFIDENCE_DEFAULT = 1\n\n/** Confidence assigned to a successfully resolved computed field. */\nexport const CONFIDENCE_COMPUTED = 0.9\n\n/**\n * The numeric-entity extraction pattern shared by `extractNumbers` and\n * `assignEntities` — an optional leading `$`, thousands-comma-grouped digits,\n * an optional decimal fraction, and an optional trailing `%`.\n *\n * @remarks\n * Carries the global flag, so every call site builds a fresh `RegExp` from\n * `.source` / `.flags` (mirrors the core-root `PLACEHOLDER_PATTERN` pattern)\n * rather than sharing this instance's mutable `lastIndex` across scans.\n */\nexport const NUMBER_PATTERN = /(?:\\$\\s*)?(\\d+(?:,\\d{3})*(?:\\.\\d+)?)\\s*%?/g\n\n/**\n * Prototype-pollution-unsafe field-path segments — `setField` refuses to\n * write ANY path containing one, returning its input unchanged.\n */\nexport const UNSAFE_FIELD_SEGMENTS: readonly string[] = Object.freeze([\n\t'__proto__',\n\t'prototype',\n\t'constructor',\n])\n\n/**\n * Neutral built-in contraction expansions for `Normalizer` — small on\n * purpose; callers merge their own map over this one.\n */\nexport const DEFAULT_CONTRACTIONS: Readonly<Record<string, string>> = Object.freeze({\n\t\"can't\": 'cannot',\n\t\"won't\": 'will not',\n\t\"it's\": 'it is',\n\t\"don't\": 'do not',\n})\n\n/** Neutral built-in abbreviation expansions for `Normalizer` — empty by default. */\nexport const DEFAULT_ABBREVIATIONS: Readonly<Record<string, string>> = Object.freeze({})\n\n/** Neutral built-in misspelling corrections for `Normalizer` — empty by default. */\nexport const DEFAULT_CORRECTIONS: Readonly<Record<string, string>> = Object.freeze({})\n\n/** Neutral built-in action-verb vocabulary for `Extractor#extract`'s intent classification — empty by default. */\nexport const DEFAULT_ACTIONS: Readonly<Record<string, string>> = Object.freeze({})\n\n/** Neutral built-in domain-keyword vocabulary for `Extractor#extract`'s intent classification — empty by default. */\nexport const DEFAULT_DOMAINS: Readonly<Record<string, readonly string[]>> = Object.freeze({})\n\n/** Neutral built-in intent-verb phrasing for `Formatter#format` — empty by default. */\nexport const DEFAULT_VERBS: Readonly<Record<string, string>> = Object.freeze({})\n\n/**\n * The neutral default `Lexicon` a `Narrator` merges caller data over.\n *\n * @remarks\n * `phrases` and `labels` are empty — there is no built-in vocabulary or\n * label overrides (AGENTS §21 mechanism-never-policy). `templates` carries\n * the structural, display-neutral strings the reverse helpers formerly\n * hardcoded, keyed by\n * `{table}.{reasoning}` for the four reasons kinds, `result.quantitative.failed`\n * for the quantitative-result failure suffix, and `subject.fields` /\n * `subject.empty` for `describeSubject`. Every string is a plain\n * `interpolateMessage` template — `{{name}}`-style placeholders resolved\n * against the caller-supplied `values` record.\n */\nexport const DEFAULT_LEXICON: Lexicon = Object.freeze({\n\tphrases: Object.freeze({}),\n\tlabels: Object.freeze({}),\n\ttemplates: Object.freeze({\n\t\t'definition.quantitative': '{{name}}: {{count}} factor group(s)',\n\t\t'definition.logical': '{{name}}: {{count}} rule(s), strategy {{strategy}}',\n\t\t'definition.symbolic': '{{name}}: solve {{count}} equation(s)',\n\t\t'definition.inferential':\n\t\t\t'{{name}}: {{facts}} fact(s)/{{inferences}} inference(s), {{strategy}}',\n\t\t'result.quantitative': 'scored {{value}} across {{count}} group(s)',\n\t\t'result.quantitative.failed': '; failed: {{errors}}',\n\t\t'result.logical': '{{status}}: {{count}} rule(s)',\n\t\t'result.symbolic': 'solved {{solved}}',\n\t\t'result.inferential': 'derived {{count}} fact(s)',\n\t\t'subject.fields': 'with {{fields}}',\n\t\t'subject.empty': 'with no fields',\n\t}),\n})\n","import type { InterpretErrorCode } from './types.js'\n\n// AGENTS §12: misuse of the interprets layer `throw`s an `InterpretError`\n// carrying a machine-readable `code`, so a `catch` branches on `error.code`.\n\n/**\n * An error thrown by the interprets layer.\n *\n * @remarks\n * Thrown for: an injected stage implementation throwing during its phase\n * (`NORMALIZE_FAILED` / `EXTRACT_FAILED` / `CLARIFY_FAILED` /\n * `FORMAT_FAILED` / `GENERATE_FAILED`), `createTemplate` handed data that\n * fails `isTemplate` (`INVALID_TEMPLATE`), and any use of a destroyed\n * `Interpret` / manager / context (`DESTROYED`). `NO_TEMPLATE` and\n * `LOW_CONFIDENCE` never throw — they surface as a visible incomplete\n * {@link Interpretation} instead (never an arbitrary fallback template).\n * `context`, when present, carries the offending stage / template id.\n */\nexport class InterpretError extends Error {\n\treadonly code: InterpretErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: InterpretErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'InterpretError'\n\t\tthis.code = code\n\t\tthis.context = context\n\t}\n}\n\n/**\n * Narrow an unknown caught value to an {@link InterpretError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is an {@link InterpretError}\n *\n * @example\n * ```ts\n * import { isInterpretError } from '@src/core'\n *\n * try {\n * \tinterpret.template('missing')\n * } catch (error) {\n * \tif (isInterpretError(error) && error.code === 'DESTROYED') return\n * }\n * ```\n */\nexport function isInterpretError(value: unknown): value is InterpretError {\n\treturn value instanceof InterpretError\n}\n","import type { ComputedField, EntityMapping, FieldDefault, Template } from './types.js'\nimport { arrayOf, isBoolean, isString, notOf, recordOf, unionOf } from '@orkestrel/contract'\nimport { isDefinition, isFieldPath, isSymbolicExpression } from '@orkestrel/reason'\n\n// AGENTS §14: every guard here is a TOTAL function — adversarial input (junk,\n// hostile prototypes, cyclic/deep nesting) returns `false`, never throws.\n// Every record guard is EXACT (`recordOf`): an extra key fails. `isTemplate`\n// composes reasons' exported `isSymbolicExpression` (already recursive\n// through `lazyOf`) and `isDefinition` rather than minting local duplicates —\n// a second `isSymbolicExpression` would collide under the shared `@src/core`\n// barrel's `export *` (TypeScript silently drops BOTH conflicting star\n// re-exports), breaking reasons' own guard and failing the AGENTS §22 parity\n// gate. `interprets` therefore owns no recursive expression guard of its own.\n\n/**\n * Determine whether a value is an {@link EntityMapping} — a literal\n * alias-phrase extraction rule pointing at a subject field.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed entity mapping\n *\n * @example\n * ```ts\n * import { isEntityMapping } from '@src/core'\n *\n * isEntityMapping({ entity: 'age', aliases: ['years old'], field: 'age' }) // true\n * isEntityMapping({ entity: 'age', aliases: [/\\d+/], field: 'age' }) // false — RegExp alias\n * ```\n */\nexport function isEntityMapping(value: unknown): value is EntityMapping {\n\treturn recordOf(\n\t\t{\n\t\t\tentity: isString,\n\t\t\taliases: arrayOf(isString),\n\t\t\tfield: isFieldPath,\n\t\t\trequired: isBoolean,\n\t\t},\n\t\t['required'],\n\t)(value)\n}\n\n/**\n * Determine whether a value is a {@link FieldDefault} — a fallback value a\n * {@link Template} fills onto an unresolved field.\n *\n * @remarks\n * `value` is unconstrained (any value, including `null` or `undefined`) as\n * long as the key is present — the trivially-true guard `notOf(unionOf())`\n * mirrors the reasons `Check.value` precedent.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed field default\n *\n * @example\n * ```ts\n * import { isFieldDefault } from '@src/core'\n *\n * isFieldDefault({ field: 'term', value: 12 }) // true\n * isFieldDefault({ field: 'term' }) // false — value missing\n * ```\n */\nexport function isFieldDefault(value: unknown): value is FieldDefault {\n\treturn recordOf({ field: isFieldPath, value: notOf(unionOf()) })(value)\n}\n\n/**\n * Determine whether a value is a {@link ComputedField} — a declaratively\n * computed field carrying a reasons {@link SymbolicExpression} tree.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed computed field\n *\n * @example\n * ```ts\n * import { constant, operation, variable } from '@orkestrel/reason'\n * import { isComputedField } from '@src/core'\n *\n * isComputedField({\n * \tfield: 'monthly',\n * \texpression: operation('divide', variable('deductible'), constant(12)),\n * }) // true\n * isComputedField({ field: 'monthly', expression: { form: 'variable' } }) // false — name missing\n * ```\n */\nexport function isComputedField(value: unknown): value is ComputedField {\n\treturn recordOf({ field: isFieldPath, expression: isSymbolicExpression })(value)\n}\n\n/**\n * Determine whether a value is a {@link Template} — a named, versionable\n * interpretation template.\n *\n * @remarks\n * `definition` is validated with reasons' `isDefinition` — a `Template`'s\n * definition is already expressed in terrain reasons vocabulary, so no\n * parallel interprets-owned definition guard exists.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed template\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { isTemplate } from '@src/core'\n *\n * isTemplate({\n * \tid: 't1',\n * \tname: 'Arithmetic',\n * \tdomain: 'arithmetic',\n * \tintents: ['calculate'],\n * \tmappings: [],\n * \tdefaults: [],\n * \tcomputations: [],\n * \tdefinition: quantitativeDefinition('t1', 'Arithmetic', [\n * \t\tfactorGroup('total', 'sum', [fieldFactor('value', 'value')]),\n * \t]),\n * }) // true\n * isTemplate({ id: 't1' }) // false — most fields missing\n * ```\n */\nexport function isTemplate(value: unknown): value is Template {\n\treturn recordOf({\n\t\tid: isString,\n\t\tname: isString,\n\t\tdomain: isString,\n\t\tintents: arrayOf(isString),\n\t\tmappings: arrayOf(isEntityMapping),\n\t\tdefaults: arrayOf(isFieldDefault),\n\t\tcomputations: arrayOf(isComputedField),\n\t\tdefinition: isDefinition,\n\t})(value)\n}\n","import type { FieldPath } from '@orkestrel/contract'\nimport type { Subject, SymbolicExpression } from '@orkestrel/reason'\nimport type { Entity, EntityMapping, Intent, NarratorInterface, Template } from './types.js'\nimport { isFiniteNumber, isRecord, parseJSONAs, resolveField } from '@orkestrel/contract'\nimport { applyOperation } from '@orkestrel/reason'\nimport {\n\tCONFIDENCE_ALIAS,\n\tCONFIDENCE_COLLECT,\n\tCONFIDENCE_EXACT,\n\tCONFIDENCE_POSITIONAL,\n\tNUMBER_PATTERN,\n\tUNSAFE_FIELD_SEGMENTS,\n} from './constants.js'\nimport { isTemplate } from './validators.js'\n\n// The interprets pure-leaf inventory (AGENTS §5/§7) — every function here is\n// a referentially-transparent computation with no instance state, exported\n// and independently unit-testable. Stateful orchestration (the five-stage\n// pipeline, entity assignment sequencing, template registration) lives on the\n// `Interpret` orchestrator and its stage classes, never here.\n\n// === Regex safety\n\n/**\n * Escape every regex metacharacter in `text` so it matches literally when\n * compiled into a `RegExp`.\n *\n * @param text - The literal text to escape\n * @returns `text` with every regex metacharacter backslash-escaped\n *\n * @example\n * ```ts\n * import { escapeRegExp } from '@src/core'\n *\n * escapeRegExp('a.b*c') // 'a\\\\.b\\\\*c'\n * new RegExp(escapeRegExp('a.b*c')).test('a.b*c') // true\n * ```\n */\nexport function escapeRegExp(text: string): string {\n\treturn text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n// === Field paths — safe copy-on-write writes\n\n/**\n * Copy-on-write write a value at a (possibly nested) field path on a subject.\n *\n * @remarks\n * Never mutates `subject` — every level a `field` array descends through is\n * freshly copied, so the input and every intermediate record stay untouched\n * (AGENTS §11). Prototype-pollution-safe: a `field` containing `__proto__`,\n * `prototype`, or `constructor` at ANY segment (checked against\n * `UNSAFE_FIELD_SEGMENTS`) is refused as a no-op, returning `subject`\n * unchanged. A non-record value already sitting at an intermediate segment is\n * replaced by a fresh record rather than descended into.\n *\n * @param subject - The subject to derive from\n * @param field - The (possibly nested) field path to write\n * @param value - The value to write\n * @returns A fresh subject with `value` written at `field`, or `subject`\n * unchanged when `field` carries an unsafe segment\n *\n * @example\n * ```ts\n * import { setField } from '@src/core'\n *\n * setField({ age: 25 }, 'age', 30) // { age: 30 }\n * setField({}, ['address', 'city'], 'Reno') // { address: { city: 'Reno' } }\n * setField({}, ['__proto__', 'polluted'], true) // {} — refused, unchanged\n * ```\n */\n/**\n * Derive the sibling field path for a computed aggregate of `field` — the\n * suffix is appended to `field`'s OWN last segment, so the aggregate nests\n * beside the source field rather than flattening past it.\n *\n * @remarks\n * For an array {@link FieldPath} (e.g. `['address', 'amounts']`) with suffix\n * `'Sum'` the result is `['address', 'amountsSum']` — nested beside\n * `address.amounts`. For a plain string field the result stays a flat string\n * (`'amounts'` → `'amountsSum'`), matching the existing single-key behavior.\n *\n * @param field - The source field path\n * @param suffix - The aggregate suffix (`'Sum'`, `'Count'`, `'Average'`, `'Minimum'`, `'Maximum'`)\n * @returns The sibling field path for the aggregate\n *\n * @example\n * ```ts\n * import { deriveAggregateField } from '@src/core'\n *\n * deriveAggregateField(['address', 'amounts'], 'Sum') // ['address', 'amountsSum']\n * deriveAggregateField('amounts', 'Sum') // 'amountsSum'\n * ```\n */\nexport function deriveAggregateField(field: FieldPath, suffix: string): FieldPath {\n\tif (Array.isArray(field)) {\n\t\tconst last = field[field.length - 1]\n\t\treturn [...field.slice(0, -1), `${last}${suffix}`]\n\t}\n\treturn `${field}${suffix}`\n}\n\nexport function setField(subject: Subject, field: FieldPath, value: unknown): Subject {\n\tconst path = Array.isArray(field) ? field : [field]\n\tif (path.length === 0) return subject\n\tif (path.some((segment) => UNSAFE_FIELD_SEGMENTS.includes(segment))) return subject\n\tconst [key, ...rest] = path\n\tif (key === undefined) return subject\n\tif (rest.length === 0) return { ...subject, [key]: value }\n\tconst child = subject[key]\n\tconst nested = isRecord(child) ? child : {}\n\treturn { ...subject, [key]: setField(nested, rest, value) }\n}\n\n// === Message interpolation\n\n/**\n * Interpolate `{{dotted.path}}` tokens in a message template against a record.\n *\n * @remarks\n * Each token is split on `.` into a {@link FieldPath} array and resolved with\n * the contracts `resolveField` (a plain string field is ONE key, never\n * dot-split — the split here is the token-to-path bridge). A finite number\n * renders with `en-US` thousand grouping (`5010` → `5,010`); any other\n * resolved value String-coerces. An UNRESOLVED path (the resolved value is\n * `undefined`) renders as the empty string — the deterministic \"nothing to\n * show\" rule.\n *\n * @param template - The message template carrying `{{dotted.path}}` tokens\n * @param record - The record tokens resolve against\n * @returns The template with every token replaced\n *\n * @example\n * ```ts\n * import { interpolateMessage } from '@src/core'\n *\n * interpolateMessage('Limit is {{limit}}', { limit: 5010 }) // 'Limit is 5,010'\n * interpolateMessage('Missing {{gone}}', {}) // 'Missing '\n * ```\n */\nexport function interpolateMessage(\n\ttemplate: string,\n\trecord: Readonly<Record<string, unknown>>,\n): string {\n\treturn template.replace(/\\{\\{\\s*([^}]+?)\\s*\\}\\}/g, (_match, path: string) => {\n\t\tconst value = resolveField(record, path.split('.'))\n\t\tif (value === undefined) return ''\n\t\tif (isFiniteNumber(value)) return value.toLocaleString('en-US')\n\t\treturn String(value)\n\t})\n}\n\n// === Normalization\n\n/**\n * Replace every whole-word occurrence of a map's keys with their values.\n *\n * @remarks\n * Word-boundary safe (`in` never matches inside `information`) and\n * case-insensitive; each key is regex-escaped via the core-root\n * `escapeRegExp` before compiling, so a caller-supplied phrase containing\n * regex metacharacters is matched literally. Multiple keys apply in\n * `Object.entries` order — the `Normalizer` stage sequences its three maps\n * (contractions, abbreviations, corrections) with three separate calls.\n *\n * @param text - The text to substitute within\n * @param map - The `{ from: to }` substitution map\n * @returns `text` with every whole-word match replaced\n *\n * @example\n * ```ts\n * import { applyReplacements } from '@src/core'\n *\n * applyReplacements(\"can't stop\", { \"can't\": 'cannot' }) // 'cannot stop'\n * applyReplacements('information', { in: 'IN' }) // 'information' — word-boundary safe\n * ```\n */\nexport function applyReplacements(text: string, map: Readonly<Record<string, string>>): string {\n\tlet result = text\n\tfor (const [from, to] of Object.entries(map)) {\n\t\tconst pattern = new RegExp(`\\\\b${escapeRegExp(from)}\\\\b`, 'gi')\n\t\tresult = result.replace(pattern, to)\n\t}\n\treturn result\n}\n\n/**\n * Collapse every run of whitespace to a single space and trim the ends.\n *\n * @param text - The text to collapse\n * @returns The collapsed text\n *\n * @example\n * ```ts\n * import { collapseWhitespace } from '@src/core'\n *\n * collapseWhitespace(' a b\\t c ') // 'a b c'\n * ```\n */\nexport function collapseWhitespace(text: string): string {\n\treturn text.replace(/\\s+/g, ' ').trim()\n}\n\n// === Tokenization (internal plumbing shared by extraction & classification)\n\n/**\n * Split text into lowercase tokens, stripping punctuation outside a small\n * numeric/currency-safe allowlist.\n *\n * @remarks\n * Shared by `classifyIntent` and `assignEntities` — pure ECMAScript\n * (no locale-aware `Intl` segmentation), so multi-byte / astral text tokenizes\n * on ASCII word boundaries only.\n *\n * @param text - The text to tokenize\n * @returns The lowercase tokens, punctuation-stripped, empty tokens dropped\n *\n * @example\n * ```ts\n * import { tokenize } from '@src/core'\n *\n * tokenize('The rate is 85%.') // ['the', 'rate', 'is', '85%']\n * ```\n */\nexport function tokenize(text: string): readonly string[] {\n\treturn text\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9\\s./%$'-]/g, ' ')\n\t\t.split(/\\s+/)\n\t\t.filter((token) => token.length > 0)\n}\n\n// === Extraction\n\n/**\n * Mine every numeric literal from text — optional leading `$`, thousands\n * commas, an optional decimal fraction, an optional trailing `%`.\n *\n * @remarks\n * Numbers-only: this is the module's entire extraction contract (AGENTS\n * §21 mechanism-never-policy) — no date, text-entity, or negation parsing.\n *\n * @param text - The text to scan\n * @returns Every extracted number, in left-to-right order\n *\n * @example\n * ```ts\n * import { extractNumbers } from '@src/core'\n *\n * extractNumbers('income was $50,000, age 25') // [50000, 25]\n * ```\n */\nexport function extractNumbers(text: string): readonly number[] {\n\tconst pattern = new RegExp(NUMBER_PATTERN.source, NUMBER_PATTERN.flags)\n\tconst numbers: number[] = []\n\tlet match = pattern.exec(text)\n\twhile (match !== null) {\n\t\tconst raw = match[1]\n\t\tif (raw !== undefined) {\n\t\t\tconst value = Number(raw.replace(/,/g, ''))\n\t\t\tif (Number.isFinite(value)) numbers.push(value)\n\t\t}\n\t\tmatch = pattern.exec(text)\n\t}\n\treturn numbers\n}\n\n/**\n * Assign already-extracted numbers to a matched template's entity mappings.\n *\n * @remarks\n * Strategy, in order: (1) a SINGLE mapping collects every number (an array\n * when more than one, a scalar otherwise) at `CONFIDENCE_COLLECT`. Otherwise,\n * per mapping, the rightmost token in the text that equals the entity name\n * (`CONFIDENCE_EXACT`), an alias exactly (`CONFIDENCE_ALIAS`), or an alias\n * fuzzily (via `matchAlias`, confidence = its returned score) becomes a\n * keyword anchor; anchors sort left-to-right and each claims its nearest\n * unused number by text position. (3) Any mapping still unfilled claims the\n * next unused number positionally, at `CONFIDENCE_POSITIONAL`. Every entity\n * carries provenance `category: 'extracted'` with `detail` naming the\n * strategy that filled it (`'collect' | 'keyword' | 'alias' | 'positional'`).\n * Runs ONLY after a template has matched (an orchestrator-owned step, never\n * inside `Extractor`, which stays template-agnostic).\n *\n * @param numbers - The numbers already extracted from `text` via `extractNumbers`\n * @param mappings - The matched template's entity mappings\n * @param text - The same text `numbers` was extracted from (for keyword proximity)\n * @param similarity - The fuzzy alias-match score threshold (0..1)\n * @returns The assigned entities, one per filled mapping\n *\n * @example\n * ```ts\n * import { assignEntities } from '@src/core'\n *\n * const mappings = [\n * \t{ entity: 'age', aliases: ['years old'], field: 'age' },\n * \t{ entity: 'score', aliases: ['credit score'], field: 'score' },\n * ]\n * assignEntities([25, 720], mappings, '25 year old with score 720', 0.8)\n * // [{ name: 'age', value: 25, ... }, { name: 'score', value: 720, ... }]\n * ```\n */\nexport function assignEntities(\n\tnumbers: readonly number[],\n\tmappings: readonly EntityMapping[],\n\ttext: string,\n\tsimilarity: number,\n): readonly Entity[] {\n\tif (mappings.length === 0 || numbers.length === 0) return []\n\n\tif (mappings.length === 1) {\n\t\tconst mapping = mappings[0]\n\t\tif (mapping === undefined) return []\n\t\treturn [\n\t\t\t{\n\t\t\t\tname: mapping.entity,\n\t\t\t\tvalue: numbers.length === 1 ? numbers[0] : numbers,\n\t\t\t\tprovenance: { category: 'extracted', detail: 'collect' },\n\t\t\t\tconfidence: CONFIDENCE_COLLECT,\n\t\t\t},\n\t\t]\n\t}\n\n\tconst tokens = tokenize(text)\n\tconst lowerText = text.toLowerCase()\n\n\tconst positions: number[] = []\n\tconst positionPattern = new RegExp(NUMBER_PATTERN.source, NUMBER_PATTERN.flags)\n\tlet positionMatch = positionPattern.exec(text)\n\twhile (positionMatch !== null) {\n\t\tpositions.push(positionMatch.index)\n\t\tpositionMatch = positionPattern.exec(text)\n\t}\n\n\tconst keywordMatches: {\n\t\tmapping: EntityMapping\n\t\tposition: number\n\t\tconfidence: number\n\t\tdetail: 'keyword' | 'alias'\n\t}[] = []\n\n\tfor (const mapping of mappings) {\n\t\tlet matchedPosition = -1\n\t\tlet matchedConfidence = 0\n\t\tlet matchedDetail: 'keyword' | 'alias' = 'keyword'\n\t\tconst entityToken = mapping.entity.toLowerCase()\n\n\t\tfor (const token of tokens) {\n\t\t\tconst tokenPosition = lowerText.indexOf(token)\n\t\t\tif (token === entityToken) {\n\t\t\t\tif (tokenPosition > matchedPosition) {\n\t\t\t\t\tmatchedPosition = tokenPosition\n\t\t\t\t\tmatchedConfidence = CONFIDENCE_EXACT\n\t\t\t\t\tmatchedDetail = 'keyword'\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst aliasExact = mapping.aliases.some((alias) => alias.toLowerCase() === token)\n\t\t\tif (aliasExact) {\n\t\t\t\tif (tokenPosition > matchedPosition) {\n\t\t\t\t\tmatchedPosition = tokenPosition\n\t\t\t\t\tmatchedConfidence = CONFIDENCE_ALIAS\n\t\t\t\t\tmatchedDetail = 'alias'\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst fuzzy = matchAlias(token, mapping.aliases, similarity)\n\t\t\tif (fuzzy > 0 && tokenPosition > matchedPosition) {\n\t\t\t\tmatchedPosition = tokenPosition\n\t\t\t\tmatchedConfidence = fuzzy\n\t\t\t\tmatchedDetail = 'alias'\n\t\t\t}\n\t\t}\n\n\t\tif (matchedPosition >= 0) {\n\t\t\tkeywordMatches.push({\n\t\t\t\tmapping,\n\t\t\t\tposition: matchedPosition,\n\t\t\t\tconfidence: matchedConfidence,\n\t\t\t\tdetail: matchedDetail,\n\t\t\t})\n\t\t}\n\t}\n\n\tkeywordMatches.sort((a, b) => a.position - b.position)\n\n\tconst used = new Set<number>()\n\tconst filled = new Set<string>()\n\tconst entities: Entity[] = []\n\n\tfor (const match of keywordMatches) {\n\t\tlet bestIndex = -1\n\t\tlet bestDistance = Number.POSITIVE_INFINITY\n\t\tfor (let index = 0; index < numbers.length; index += 1) {\n\t\t\tif (used.has(index)) continue\n\t\t\tconst position = positions[index]\n\t\t\tif (position === undefined) continue\n\t\t\tconst distance = Math.abs(position - match.position)\n\t\t\tif (distance < bestDistance) {\n\t\t\t\tbestDistance = distance\n\t\t\t\tbestIndex = index\n\t\t\t}\n\t\t}\n\t\tif (bestIndex >= 0) {\n\t\t\tconst value = numbers[bestIndex]\n\t\t\tif (value !== undefined) {\n\t\t\t\tused.add(bestIndex)\n\t\t\t\tfilled.add(match.mapping.entity)\n\t\t\t\tentities.push({\n\t\t\t\t\tname: match.mapping.entity,\n\t\t\t\t\tvalue,\n\t\t\t\t\tprovenance: { category: 'extracted', detail: match.detail },\n\t\t\t\t\tconfidence: match.confidence,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tlet numberIndex = 0\n\tfor (const mapping of mappings) {\n\t\tif (filled.has(mapping.entity)) continue\n\t\twhile (numberIndex < numbers.length && used.has(numberIndex)) numberIndex += 1\n\t\tif (numberIndex >= numbers.length) break\n\t\tconst value = numbers[numberIndex]\n\t\tif (value !== undefined) {\n\t\t\tused.add(numberIndex)\n\t\t\tfilled.add(mapping.entity)\n\t\t\tentities.push({\n\t\t\t\tname: mapping.entity,\n\t\t\t\tvalue,\n\t\t\t\tprovenance: { category: 'extracted', detail: 'positional' },\n\t\t\t\tconfidence: CONFIDENCE_POSITIONAL,\n\t\t\t})\n\t\t}\n\t\tnumberIndex += 1\n\t}\n\n\treturn entities\n}\n\n// === Intent classification\n\n/**\n * Classify the action + domain intent of a text against caller-supplied\n * vocabularies.\n *\n * @remarks\n * `actions` maps a token to an action name — the first matching token in\n * `text` (left to right) wins, at `CONFIDENCE_EXACT`. `domains` maps a domain\n * name to its keyword list — the domain with the most matching tokens wins\n * (ties keep the earliest-declared domain), also at `CONFIDENCE_EXACT`.\n * Combined confidence (PINNED): both fire → their average; exactly one fires\n * → its value times `0.5`; neither → `0`. There is no built-in worldview and\n * no auto-classification from a registered template's own `domain` name — a\n * caller MUST list a template's domain among `domains` for it to classify.\n * No `floor` parameter: the confidence floor gate lives at the orchestrator's\n * `matchTemplate` step, never inside classification itself.\n *\n * @param text - The (normalized) text to classify\n * @param actions - The caller's token → action-name vocabulary\n * @param domains - The caller's domain-name → keyword-list vocabulary\n * @returns The classified intent\n *\n * @example\n * ```ts\n * import { classifyIntent } from '@src/core'\n *\n * classifyIntent('calculate my rate', { calculate: 'compute' }, { rating: ['rate'] })\n * // { action: 'compute', domain: 'rating', confidence: 1 }\n * classifyIntent('hello', {}, {}) // { action: '', domain: '', confidence: 0 }\n * ```\n */\nexport function classifyIntent(\n\ttext: string,\n\tactions: Readonly<Record<string, string>>,\n\tdomains: Readonly<Record<string, readonly string[]>>,\n): Intent {\n\tconst tokens = tokenize(text)\n\n\tlet action = ''\n\tlet actionConfidence = 0\n\tfor (const token of tokens) {\n\t\tconst mapped = actions[token]\n\t\tif (mapped !== undefined) {\n\t\t\taction = mapped\n\t\t\tactionConfidence = CONFIDENCE_EXACT\n\t\t\tbreak\n\t\t}\n\t}\n\n\tlet domain = ''\n\tlet domainConfidence = 0\n\tlet bestMatches = 0\n\tfor (const [name, keywords] of Object.entries(domains)) {\n\t\tconst lowerKeywords = keywords.map((keyword) => keyword.toLowerCase())\n\t\tlet matches = 0\n\t\tfor (const token of tokens) {\n\t\t\tif (lowerKeywords.includes(token)) matches += 1\n\t\t}\n\t\tif (matches > bestMatches) {\n\t\t\tbestMatches = matches\n\t\t\tdomain = name\n\t\t\tdomainConfidence = CONFIDENCE_EXACT\n\t\t}\n\t}\n\n\tconst confidence =\n\t\tactionConfidence > 0 && domainConfidence > 0\n\t\t\t? (actionConfidence + domainConfidence) / 2\n\t\t\t: Math.max(actionConfidence, domainConfidence) * 0.5\n\n\treturn { action, domain, confidence }\n}\n\n// === Fuzzy matching\n\n/**\n * Bigram (Dice coefficient) string similarity, case-insensitive.\n *\n * @param a - The first string\n * @param b - The second string\n * @returns A score in `[0, 1]` — `1` for an exact (case-insensitive) match,\n * `0` when either string is shorter than 2 characters and they are not equal\n *\n * @example\n * ```ts\n * import { scoreSimilarity } from '@src/core'\n *\n * scoreSimilarity('rate', 'rate') // 1\n * scoreSimilarity('rate', 'value') // 0 — no shared bigrams\n * ```\n */\nexport function scoreSimilarity(a: string, b: string): number {\n\tconst left = a.toLowerCase()\n\tconst right = b.toLowerCase()\n\tif (left === right) return 1\n\tif (left.length < 2 || right.length < 2) return 0\n\n\tconst bigrams = new Map<string, number>()\n\tfor (let index = 0; index < left.length - 1; index += 1) {\n\t\tconst bigram = left.slice(index, index + 2)\n\t\tbigrams.set(bigram, (bigrams.get(bigram) ?? 0) + 1)\n\t}\n\n\tlet matches = 0\n\tfor (let index = 0; index < right.length - 1; index += 1) {\n\t\tconst bigram = right.slice(index, index + 2)\n\t\tconst count = bigrams.get(bigram)\n\t\tif (count !== undefined && count > 0) {\n\t\t\tbigrams.set(bigram, count - 1)\n\t\t\tmatches += 1\n\t\t}\n\t}\n\n\treturn (2 * matches) / (left.length - 1 + (right.length - 1))\n}\n\n/**\n * The best `scoreSimilarity` a token achieves against a list of aliases,\n * gated by a threshold.\n *\n * @param token - The token to score\n * @param aliases - The alias phrases to score against\n * @param threshold - The minimum score to report (an explicit no-match below it)\n * @returns The best score when it meets `threshold`, else `0`\n *\n * @example\n * ```ts\n * import { matchAlias } from '@src/core'\n *\n * matchAlias('valu', ['value', 'amount'], 0.6) // ~0.86 — fuzzy hit on 'value'\n * matchAlias('xyz', ['value', 'amount'], 0.6) // 0 — no alias clears the threshold\n * ```\n */\nexport function matchAlias(token: string, aliases: readonly string[], threshold: number): number {\n\tlet best = 0\n\tfor (const alias of aliases) {\n\t\tconst score = scoreSimilarity(token, alias)\n\t\tif (score > best) best = score\n\t}\n\treturn best >= threshold ? best : 0\n}\n\n// === Digest\n\n/**\n * Render a value into a canonical, key-order-stable string — the pre-image\n * of `digestValue`.\n *\n * @remarks\n * Ported from the app's `raters` digest machinery (`app/core/raters/helpers.ts`)\n * — record keys sort before serialization so a re-ordered object canonicalizes\n * identically; arrays keep position order (position is meaningful).\n * Cycle-safe and total (AGENTS §14): `visited` tracks the object ancestors\n * along the CURRENT recursion path (not a global \"seen\" set, so the same\n * object reachable twice via non-cyclic sibling branches still canonicalizes\n * normally); revisiting an ancestor renders that node as the literal string\n * `'[cycle]'` instead of recursing — deterministic, never throws, never\n * overflows the call stack.\n *\n * @param value - The value to canonicalize\n * @param visited - The object ancestors along the current recursion path (internal; omit at the call site)\n * @returns The canonical string form\n *\n * @example\n * ```ts\n * import { canonicalize } from '@src/core'\n *\n * canonicalize({ b: 1, a: 2 }) === canonicalize({ a: 2, b: 1 }) // true\n * ```\n */\nexport function canonicalize(value: unknown, visited: ReadonlySet<object> = new Set()): string {\n\tif (Array.isArray(value)) {\n\t\tif (visited.has(value)) return JSON.stringify('[cycle]')\n\t\tconst nextVisited = new Set(visited)\n\t\tnextVisited.add(value)\n\t\treturn `[${value.map((entry) => canonicalize(entry, nextVisited)).join(',')}]`\n\t}\n\tif (isRecord(value)) {\n\t\tif (visited.has(value)) return JSON.stringify('[cycle]')\n\t\tconst nextVisited = new Set(visited)\n\t\tnextVisited.add(value)\n\t\tconst keys = Object.keys(value).sort()\n\t\treturn `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalize(value[key], nextVisited)}`).join(',')}}`\n\t}\n\treturn JSON.stringify(value) ?? 'null'\n}\n\n/**\n * Compute a canonical structural digest of a pure-JSON value — a key-order-\n * stable FNV-1a hash rendered as an 8-hex-digit string.\n *\n * @remarks\n * Pure ECMAScript, no host crypto (AGENTS §17.7) — the same algorithm as the\n * app's `digest`, ported into core so `Interpretation.digest` and the\n * versioned managers can hash without leaving strict core.\n *\n * @param value - The value to digest\n * @returns The 8-character hex digest\n *\n * @example\n * ```ts\n * import { digestValue } from '@src/core'\n *\n * digestValue({ a: 1 }) === digestValue({ a: 1 }) // true — deterministic\n * ```\n */\nexport function digestValue(value: unknown): string {\n\tconst canonical = canonicalize(value)\n\tlet hash = 0x811c9dc5\n\tfor (let index = 0; index < canonical.length; index += 1) {\n\t\thash ^= canonical.charCodeAt(index)\n\t\thash = Math.imul(hash, 0x01000193)\n\t}\n\treturn (hash >>> 0).toString(16).padStart(8, '0')\n}\n\n// === Template matching\n\n/**\n * Score how well a classified intent matches one template's domain + action.\n *\n * @param intent - The classified intent\n * @param template - The candidate template\n * @returns A score in `[0, 1]` — the mean of the domain match (`1`/`0`) and\n * the action match (`1`/`0`, `template.intents` containing `intent.action`)\n *\n * @example\n * ```ts\n * import { scoreTemplate } from '@src/core'\n *\n * scoreTemplate(\n * \t{ action: 'compute', domain: 'rating', confidence: 1 },\n * \t{ id: 't1', name: 'T', domain: 'rating', intents: ['compute'], mappings: [], defaults: [], computations: [], definition: { reasoning: 'symbolic', id: 't1', name: 'T', equations: [], variables: {} } },\n * ) // 1\n * ```\n */\nexport function scoreTemplate(intent: Intent, template: Template): number {\n\tconst domainScore = template.domain.toLowerCase() === intent.domain.toLowerCase() ? 1 : 0\n\tconst actionScore = template.intents.some(\n\t\t(candidate) => candidate.toLowerCase() === intent.action.toLowerCase(),\n\t)\n\t\t? 1\n\t\t: 0\n\treturn (domainScore + actionScore) / 2\n}\n\n/**\n * Find the best-scoring registered template for a classified intent, gated\n * by a confidence floor.\n *\n * @remarks\n * Explicit no-match (AGENTS-flagged scsr defect 2 — never an arbitrary\n * `templates[0]` fallback): an empty registry, or a best score strictly below\n * `floor`, both return `undefined`.\n *\n * @param intent - The classified intent\n * @param templates - The registered templates to score\n * @param floor - The minimum score a match must clear\n * @returns The best-scoring template, or `undefined` on no qualifying match\n *\n * @example\n * ```ts\n * import { matchTemplate } from '@src/core'\n *\n * matchTemplate({ action: '', domain: '', confidence: 0 }, [], 0.3) // undefined — empty registry\n * ```\n */\nexport function matchTemplate(\n\tintent: Intent,\n\ttemplates: readonly Template[],\n\tfloor: number,\n): Template | undefined {\n\tlet best: Template | undefined\n\tlet bestScore = -1\n\tfor (const template of templates) {\n\t\tconst score = scoreTemplate(intent, template)\n\t\tif (score > bestScore) {\n\t\t\tbestScore = score\n\t\t\tbest = template\n\t\t}\n\t}\n\treturn best !== undefined && bestScore >= floor ? best : undefined\n}\n\n// === Computed fields\n\n/**\n * Collect every variable name referenced by a symbolic expression tree, in\n * first-occurrence order.\n *\n * @param expression - The expression tree to scan\n * @returns The referenced variable names, deduplicated\n *\n * @example\n * ```ts\n * import { constant, operation, variable } from '@orkestrel/reason'\n * import { variablesOf } from '@src/core'\n *\n * variablesOf(operation('divide', variable('deductible'), constant(12))) // ['deductible']\n * ```\n */\nexport function variablesOf(expression: SymbolicExpression): readonly string[] {\n\tconst names: string[] = []\n\tconst seen = new Set<string>()\n\n\tfunction collect(node: SymbolicExpression): void {\n\t\tif (node.form === 'variable') {\n\t\t\tif (!seen.has(node.name)) {\n\t\t\t\tseen.add(node.name)\n\t\t\t\tnames.push(node.name)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (node.form === 'operation') {\n\t\t\tcollect(node.left)\n\t\t\tif (node.right !== undefined) collect(node.right)\n\t\t}\n\t}\n\n\tcollect(expression)\n\treturn names\n}\n\n/**\n * Evaluate a symbolic expression tree against resolved bindings.\n *\n * @remarks\n * THE critical leaf (design-pinned, engine-parity semantics): an absent\n * `right` operand on a binary operation defaults to `0` — matching\n * `SymbolicReasoner`'s internal `#evaluate` — and is always passed as an\n * EXPLICIT numeric operand, so the same tree evaluates identically here and\n * inside the engine. Each arithmetic step delegates to the reasons\n * `applyOperation` pure function, mapping the node's `.operator` field onto\n * its `operator` parameter. An unresolved input variable, or a non-finite\n * result (`NaN` from a divide-by-zero, or an overflowing `±Infinity`),\n * becomes a gap — `undefined`, never landing on a subject.\n *\n * @param expression - The expression tree to evaluate\n * @param bindings - The resolved variable bindings\n * @returns The evaluated number, or `undefined` on an unresolved input or a\n * non-finite result\n *\n * @example\n * ```ts\n * import { constant, operation, variable } from '@orkestrel/reason'\n * import { resolveExpression } from '@src/core'\n *\n * resolveExpression(operation('divide', variable('deductible'), constant(12)), { deductible: 6000 }) // 500\n * resolveExpression(operation('divide', constant(1), constant(0)), {}) // undefined — NaN gap\n * resolveExpression(variable('missing'), {}) // undefined — unresolved input\n * ```\n */\nexport function resolveExpression(\n\texpression: SymbolicExpression,\n\tbindings: Readonly<Record<string, number>>,\n): number | undefined {\n\tif (expression.form === 'constant') return expression.value\n\tif (expression.form === 'variable') return bindings[expression.name]\n\n\tconst left = resolveExpression(expression.left, bindings)\n\tif (left === undefined) return undefined\n\n\tconst right = expression.right === undefined ? 0 : resolveExpression(expression.right, bindings)\n\tif (right === undefined) return undefined\n\n\tconst result = applyOperation(expression.operator, left, right)\n\treturn isFiniteNumber(result) ? result : undefined\n}\n\n// === Reverse direction — structure to prose\n\n/**\n * Render a one-line, display-neutral description of a reasons `Subject`,\n * through an injected `Narrator`.\n *\n * @remarks\n * Complements — never duplicates — the raters `describe*` family (which\n * describes RATERS artifacts); this describes REASONS artifacts. Every field\n * renders via `narrator.label` + `narrator.value` (looked up under the\n * `'units'` phrase table, falling back to `'plain'`) — the wording is fully\n * lexicon-driven (AGENTS §21 mechanism-never-policy); `Definition` /\n * `ReasonResult` narration lives on `Narrator#describe` / `Narrator#narrate`\n * directly.\n *\n * @param subject - The subject to describe\n * @param narrator - The lexicon-driven renderer to render field labels/values/lines through\n * @returns A one-line description, the lexicon's `'subject.empty'` line when empty\n *\n * @example\n * ```ts\n * import { createNarrator, describeSubject } from '@src/core'\n *\n * describeSubject({ age: 25, income: 50000 }, createNarrator()) // 'with age: 25, income: 50000'\n * ```\n */\nexport function describeSubject(subject: Subject, narrator: NarratorInterface): string {\n\tconst keys = Object.keys(subject).sort()\n\tif (keys.length === 0) return narrator.line('subject.empty', {})\n\tconst parts = keys.map((key) => {\n\t\tconst unit = narrator.phrase('units', key, 'plain')\n\t\treturn `${narrator.label(key)}: ${narrator.value(unit, subject[key])}`\n\t})\n\treturn narrator.line('subject.fields', { fields: parts.join(', ') })\n}\n\n// === JSON intake\n\n/**\n * Parse a JSON string into a `Template`, or `undefined` on invalid JSON or a\n * shape that fails `isTemplate`.\n *\n * @remarks\n * The module's sole JSON boundary (design §4) — an `Interpretation` and the\n * versioned records are produced internally, never deserialized from\n * untrusted JSON; replay re-runs `interpret`, it does not deserialize a\n * stored result.\n *\n * @param value - The JSON text to parse\n * @returns The parsed template, or `undefined`\n *\n * @example\n * ```ts\n * import { parseTemplate } from '@src/core'\n *\n * parseTemplate('not json') // undefined\n * ```\n */\nexport function parseTemplate(value: string): Template | undefined {\n\treturn parseJSONAs(value, isTemplate)\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { Definition } from '@orkestrel/reason'\nimport type {\n\tDefinitionManagerEventMap,\n\tDefinitionManagerInterface,\n\tDefinitionManagerOptions,\n\tDefinitionRecord,\n\tManagerAddOptions,\n} from '../types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { InterpretError } from '../errors.js'\nimport { digestValue } from '../helpers.js'\n\n/**\n * The definition registry — a self-owning, versioned and content-hashed\n * record-holder for the reasons {@link Definition}s an interpretation produces.\n *\n * @remarks\n * Mirrors {@link TemplateManager}: `add` defaults each record id to the\n * definition's own `id`, derives `hash` from the definition CONTENT\n * (id-independent), and bumps `version` ONLY when that hash changes at a reused\n * id — an identical re-add keeps its version. The batch `remove(ids)` form is\n * all-or-nothing; `destroy()` is idempotent and every method afterwards throws\n * `InterpretError('DESTROYED', …)`.\n *\n * @example\n * ```ts\n * import { symbolicDefinition } from '@orkestrel/reason'\n * import { DefinitionManager } from '@src/core'\n *\n * const manager = new DefinitionManager()\n * const record = manager.add(symbolicDefinition('rate', 'Rate', []))\n * record.id // 'rate'\n * manager.add(symbolicDefinition('rate', 'Rate', [])).version // 1 — identical re-add, no bump\n * ```\n */\nexport class DefinitionManager implements DefinitionManagerInterface {\n\treadonly #records = new Map<string, DefinitionRecord>()\n\treadonly #emitter: Emitter<DefinitionManagerEventMap>\n\t#destroyed = false\n\n\tconstructor(options?: DefinitionManagerOptions) {\n\t\tthis.#emitter = new Emitter<DefinitionManagerEventMap>({\n\t\t\ton: options?.on,\n\t\t\terror: options?.error,\n\t\t})\n\t\tfor (const definition of options?.definitions ?? []) this.add(definition)\n\t}\n\n\tget emitter(): EmitterInterface<DefinitionManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget size(): number {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.size\n\t}\n\n\thas(id: string): boolean {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.has(id)\n\t}\n\n\tdefinition(id: string): DefinitionRecord | undefined {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.get(id)\n\t}\n\n\tdefinitions(): readonly DefinitionRecord[] {\n\t\tthis.#ensureAlive()\n\t\treturn [...this.#records.values()]\n\t}\n\n\tadd(definition: Definition, options?: ManagerAddOptions): DefinitionRecord {\n\t\tthis.#ensureAlive()\n\t\tconst id = options?.id ?? definition.id\n\t\tconst hash = digestValue(definition)\n\t\tconst existing = this.#records.get(id)\n\t\tconst version =\n\t\t\texisting === undefined ? 1 : existing.hash === hash ? existing.version : existing.version + 1\n\t\tconst record: DefinitionRecord = { id, definition, version, hash }\n\t\tthis.#records.set(id, record)\n\t\tthis.#emitter.emit('add', id)\n\t\treturn record\n\t}\n\n\t// Array overload first (AGENTS §9.2); the batch form is all-or-nothing.\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(target?: string | readonly string[]): boolean | void {\n\t\tthis.#ensureAlive()\n\t\tif (target === undefined) {\n\t\t\tfor (const id of this.#records.keys()) this.#emitter.emit('remove', id)\n\t\t\tthis.#records.clear()\n\t\t\treturn\n\t\t}\n\t\tif (typeof target === 'string') {\n\t\t\tconst removed = this.#records.delete(target)\n\t\t\tif (removed) this.#emitter.emit('remove', target)\n\t\t\treturn removed\n\t\t}\n\t\tfor (const id of target) if (!this.#records.has(id)) return false\n\t\tfor (const id of target) {\n\t\t\tthis.#records.delete(id)\n\t\t\tthis.#emitter.emit('remove', id)\n\t\t}\n\t\treturn true\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#records.clear()\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#ensureAlive(): void {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new InterpretError('DESTROYED', 'Definition manager has been destroyed')\n\t\t}\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { Subject } from '@orkestrel/reason'\nimport type {\n\tManagerAddOptions,\n\tSubjectManagerEventMap,\n\tSubjectManagerInterface,\n\tSubjectManagerOptions,\n\tSubjectRecord,\n} from '../types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { InterpretError } from '../errors.js'\nimport { digestValue } from '../helpers.js'\n\n/**\n * The subject registry — a self-owning, versioned and content-hashed\n * record-holder that mints its OWN record identity for every {@link Subject}\n * (a `Subject` carries no `id` field of its own).\n *\n * @remarks\n * The defect-7 fix: scsr keyed stored subjects by their definition's id, so\n * successive same-domain turns silently overwrote one shared subject. Here each\n * `add` mints a fresh `subject-{n}` id (deterministic per instance, no host\n * randomness — AGENTS §17.7) unless the caller overrides it via\n * `ManagerAddOptions.id`. `hash` is content-derived (id-independent) and\n * `version` bumps ONLY when the hash changes at a reused id. The batch\n * `remove(ids)` form is all-or-nothing; `destroy()` is idempotent and every\n * method afterwards throws `InterpretError('DESTROYED', …)`.\n *\n * @example\n * ```ts\n * import { SubjectManager } from '@src/core'\n *\n * const manager = new SubjectManager()\n * const first = manager.add({ age: 25 })\n * const second = manager.add({ age: 30 })\n * first.id !== second.id // true — each subject gets its own identity\n * ```\n */\nexport class SubjectManager implements SubjectManagerInterface {\n\treadonly #records = new Map<string, SubjectRecord>()\n\treadonly #emitter: Emitter<SubjectManagerEventMap>\n\t#counter = 0\n\t#destroyed = false\n\n\tconstructor(options?: SubjectManagerOptions) {\n\t\tthis.#emitter = new Emitter<SubjectManagerEventMap>({ on: options?.on, error: options?.error })\n\t\tfor (const subject of options?.subjects ?? []) this.add(subject)\n\t}\n\n\tget emitter(): EmitterInterface<SubjectManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget size(): number {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.size\n\t}\n\n\thas(id: string): boolean {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.has(id)\n\t}\n\n\tsubject(id: string): SubjectRecord | undefined {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.get(id)\n\t}\n\n\tsubjects(): readonly SubjectRecord[] {\n\t\tthis.#ensureAlive()\n\t\treturn [...this.#records.values()]\n\t}\n\n\tadd(subject: Subject, options?: ManagerAddOptions): SubjectRecord {\n\t\tthis.#ensureAlive()\n\t\tlet id = options?.id\n\t\tif (id === undefined) {\n\t\t\tid = `subject-${this.#counter}`\n\t\t\tthis.#counter += 1\n\t\t}\n\t\tconst hash = digestValue(subject)\n\t\tconst existing = this.#records.get(id)\n\t\tconst version =\n\t\t\texisting === undefined ? 1 : existing.hash === hash ? existing.version : existing.version + 1\n\t\tconst record: SubjectRecord = { id, subject, version, hash }\n\t\tthis.#records.set(id, record)\n\t\tthis.#emitter.emit('add', id)\n\t\treturn record\n\t}\n\n\t// Array overload first (AGENTS §9.2); the batch form is all-or-nothing.\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(target?: string | readonly string[]): boolean | void {\n\t\tthis.#ensureAlive()\n\t\tif (target === undefined) {\n\t\t\tfor (const id of this.#records.keys()) this.#emitter.emit('remove', id)\n\t\t\tthis.#records.clear()\n\t\t\treturn\n\t\t}\n\t\tif (typeof target === 'string') {\n\t\t\tconst removed = this.#records.delete(target)\n\t\t\tif (removed) this.#emitter.emit('remove', target)\n\t\t\treturn removed\n\t\t}\n\t\tfor (const id of target) if (!this.#records.has(id)) return false\n\t\tfor (const id of target) {\n\t\t\tthis.#records.delete(id)\n\t\t\tthis.#emitter.emit('remove', id)\n\t\t}\n\t\treturn true\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#records.clear()\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#ensureAlive(): void {\n\t\tif (this.#destroyed) throw new InterpretError('DESTROYED', 'Subject manager has been destroyed')\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tDefinitionManagerInterface,\n\tEntity,\n\tInterpretContextEventMap,\n\tInterpretContextInterface,\n\tInterpretContextOptions,\n\tInterpretation,\n\tSubjectManagerInterface,\n} from '../types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { DEFAULT_INTERPRET_HISTORY } from '../constants.js'\nimport { InterpretError } from '../errors.js'\nimport { DefinitionManager } from './DefinitionManager.js'\nimport { SubjectManager } from './SubjectManager.js'\n\n/**\n * Cross-turn interpretation context — a capped, replayable history of\n * completed {@link Interpretation}s plus the subject and definition registries\n * carry-over reads from.\n *\n * @remarks\n * `previous()` is a capped ring buffer (newest-last, oldest dropped once the\n * `history` cap is reached — `DEFAULT_INTERPRET_HISTORY` by default, ≥ 3\n * preserves the carry-over pin) rather than scsr's unbounded `previous` array.\n * `entities()` flattens every entity across the buffered history, most recent\n * last — the read a `Clarifier`'s same-domain carry-over consults. `add` pushes\n * one result and trims to the cap; `clear` resets the history and both\n * registries WITHOUT tearing the context down; `destroy()` is idempotent and\n * every method afterwards throws `InterpretError('DESTROYED', …)`.\n *\n * @example\n * ```ts\n * import { InterpretContext } from '@src/core'\n *\n * const context = new InterpretContext({ session: 's1', history: 8 })\n * context.session // 's1'\n * context.previous() // []\n * ```\n */\nexport class InterpretContext implements InterpretContextInterface {\n\treadonly #session?: string\n\treadonly #subjects: SubjectManagerInterface\n\treadonly #definitions: DefinitionManagerInterface\n\treadonly #history: number\n\treadonly #previous: Interpretation[] = []\n\treadonly #emitter: Emitter<InterpretContextEventMap>\n\t#destroyed = false\n\n\tconstructor(options?: InterpretContextOptions) {\n\t\tthis.#session = options?.session\n\t\tthis.#history = Math.max(0, options?.history ?? DEFAULT_INTERPRET_HISTORY)\n\t\tthis.#subjects = new SubjectManager()\n\t\tthis.#definitions = new DefinitionManager()\n\t\tthis.#emitter = new Emitter<InterpretContextEventMap>({\n\t\t\ton: options?.on,\n\t\t\terror: options?.error,\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<InterpretContextEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget session(): string | undefined {\n\t\tthis.#ensureAlive()\n\t\treturn this.#session\n\t}\n\n\tget subjects(): SubjectManagerInterface {\n\t\tthis.#ensureAlive()\n\t\treturn this.#subjects\n\t}\n\n\tget definitions(): DefinitionManagerInterface {\n\t\tthis.#ensureAlive()\n\t\treturn this.#definitions\n\t}\n\n\tprevious(): readonly Interpretation[] {\n\t\tthis.#ensureAlive()\n\t\treturn [...this.#previous]\n\t}\n\n\tentities(): readonly Entity[] {\n\t\tthis.#ensureAlive()\n\t\treturn this.#previous.flatMap((result) => [...result.entities])\n\t}\n\n\tadd(result: Interpretation): void {\n\t\tthis.#ensureAlive()\n\t\tthis.#previous.push(result)\n\t\twhile (this.#previous.length > this.#history) this.#previous.shift()\n\t\tthis.#emitter.emit('add', result.digest)\n\t}\n\n\tclear(): void {\n\t\tthis.#ensureAlive()\n\t\tthis.#previous.length = 0\n\t\tthis.#subjects.remove()\n\t\tthis.#definitions.remove()\n\t\tthis.#emitter.emit('clear')\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#previous.length = 0\n\t\tthis.#subjects.destroy()\n\t\tthis.#definitions.destroy()\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#ensureAlive(): void {\n\t\tif (this.#destroyed)\n\t\t\tthrow new InterpretError('DESTROYED', 'Interpret context has been destroyed')\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tManagerAddOptions,\n\tTemplate,\n\tTemplateManagerEventMap,\n\tTemplateManagerInterface,\n\tTemplateManagerOptions,\n\tTemplateRecord,\n} from '../types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { InterpretError } from '../errors.js'\nimport { digestValue } from '../helpers.js'\n\n/**\n * The template registry — a self-owning, versioned and content-hashed\n * record-holder for the {@link Template}s an `Interpret` orchestrator matches\n * against.\n *\n * @remarks\n * `size` (never `count` — the sole tally in scope) plus the AGENTS §9.1\n * singular/plural accessors (`template` / `templates`) and the §9.2 batch\n * `remove` overloads. `add` derives each record's `hash` from the template's\n * CONTENT (id-independent — the same template data hashes identically under\n * any record id) and bumps `version` ONLY when that hash changes: an identical\n * re-add keeps its version (unlike scsr, which bumped on every add). The\n * batch `remove(ids)` form is ALL-OR-NOTHING — any id absent from the registry\n * leaves the collection untouched and returns `false`. `destroy()` is\n * idempotent; every method afterwards throws `InterpretError('DESTROYED', …)`.\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { TemplateManager } from '@src/core'\n *\n * const manager = new TemplateManager()\n * const record = manager.add({\n * \tid: 't1',\n * \tname: 'Arithmetic',\n * \tdomain: 'arithmetic',\n * \tintents: ['calculate'],\n * \tmappings: [],\n * \tdefaults: [],\n * \tcomputations: [],\n * \tdefinition: quantitativeDefinition('t1', 'Arithmetic', [\n * \t\tfactorGroup('total', 'sum', [fieldFactor('value', 'value')]),\n * \t]),\n * })\n * record.version // 1\n * manager.size // 1\n * ```\n */\nexport class TemplateManager implements TemplateManagerInterface {\n\treadonly #records = new Map<string, TemplateRecord>()\n\treadonly #emitter: Emitter<TemplateManagerEventMap>\n\t#destroyed = false\n\n\tconstructor(options?: TemplateManagerOptions) {\n\t\tthis.#emitter = new Emitter<TemplateManagerEventMap>({ on: options?.on, error: options?.error })\n\t\tfor (const template of options?.templates ?? []) this.add(template)\n\t}\n\n\tget emitter(): EmitterInterface<TemplateManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget size(): number {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.size\n\t}\n\n\thas(id: string): boolean {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.has(id)\n\t}\n\n\ttemplate(id: string): TemplateRecord | undefined {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.get(id)\n\t}\n\n\ttemplates(): readonly TemplateRecord[] {\n\t\tthis.#ensureAlive()\n\t\treturn [...this.#records.values()]\n\t}\n\n\tadd(template: Template, options?: ManagerAddOptions): TemplateRecord {\n\t\tthis.#ensureAlive()\n\t\tconst id = options?.id ?? template.id\n\t\tconst hash = digestValue(template)\n\t\tconst existing = this.#records.get(id)\n\t\tconst version =\n\t\t\texisting === undefined ? 1 : existing.hash === hash ? existing.version : existing.version + 1\n\t\tconst record: TemplateRecord = { id, template, version, hash }\n\t\tthis.#records.set(id, record)\n\t\tthis.#emitter.emit('add', id)\n\t\treturn record\n\t}\n\n\t// Array overload first (AGENTS §9.2); the batch form is all-or-nothing.\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(target?: string | readonly string[]): boolean | void {\n\t\tthis.#ensureAlive()\n\t\tif (target === undefined) {\n\t\t\tfor (const id of this.#records.keys()) this.#emitter.emit('remove', id)\n\t\t\tthis.#records.clear()\n\t\t\treturn\n\t\t}\n\t\tif (typeof target === 'string') {\n\t\t\tconst removed = this.#records.delete(target)\n\t\t\tif (removed) this.#emitter.emit('remove', target)\n\t\t\treturn removed\n\t\t}\n\t\tfor (const id of target) if (!this.#records.has(id)) return false\n\t\tfor (const id of target) {\n\t\t\tthis.#records.delete(id)\n\t\t\tthis.#emitter.emit('remove', id)\n\t\t}\n\t\treturn true\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#records.clear()\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#ensureAlive(): void {\n\t\tif (this.#destroyed)\n\t\t\tthrow new InterpretError('DESTROYED', 'Template manager has been destroyed')\n\t}\n}\n","import type { FieldPath } from '@orkestrel/contract'\nimport type { Definition, ReasonResult } from '@orkestrel/reason'\nimport type { Lexicon, NarratorFormatter, NarratorInterface, NarratorOptions } from './types.js'\nimport { formatField } from '@orkestrel/reason'\nimport { DEFAULT_LEXICON } from './constants.js'\nimport { interpolateMessage } from './helpers.js'\n\n/**\n * A stateless, TOTAL, lexicon-driven rendering engine for the reverse\n * direction — the reverse-direction mirror of the forward `Formatter`'s\n * `verbs` seam (AGENTS §21 mechanism-never-policy).\n *\n * @remarks\n * Every wording decision is DATA — a caller-supplied `Lexicon` merged, per\n * sub-record (`phrases` / `labels` / `templates`), OVER `DEFAULT_LEXICON`.\n * Stateless and holds no resources: no emitter, no `destroy()` (deliberate —\n * there is nothing to release). Every method is total (never throws); a\n * lexicon or formatter miss degrades to its documented fallback rather than\n * a thrown error, and every lookup guards with `Object.hasOwn` so an\n * adversarial key (`toString`, `constructor`, `__proto__`) misses cleanly\n * instead of reading an inherited prototype member.\n *\n * @example\n * ```ts\n * import { Narrator } from '@src/core'\n *\n * const narrator = new Narrator({\n * \tlexicon: { phrases: { comparison: { equals: 'is' } } },\n * \tformatters: { money: (value) => `$${String(value)}` },\n * })\n * narrator.phrase('comparison', 'equals', 'equals') // 'is'\n * narrator.phrase('comparison', 'missing', 'equals') // 'equals' — fallback\n * narrator.value('money', 5) // '$5'\n * ```\n */\nexport class Narrator implements NarratorInterface {\n\treadonly #lexicon: Required<Lexicon>\n\treadonly #formatters: Readonly<Record<string, NarratorFormatter>>\n\n\tconstructor(options?: NarratorOptions) {\n\t\tthis.#lexicon = {\n\t\t\tphrases: { ...DEFAULT_LEXICON.phrases, ...options?.lexicon?.phrases },\n\t\t\tlabels: { ...DEFAULT_LEXICON.labels, ...options?.lexicon?.labels },\n\t\t\ttemplates: { ...DEFAULT_LEXICON.templates, ...options?.lexicon?.templates },\n\t\t}\n\t\tthis.#formatters = { ...options?.formatters }\n\t}\n\n\tphrase(table: string, key: string, fallback?: string): string {\n\t\tif (Object.hasOwn(this.#lexicon.phrases, table)) {\n\t\t\tconst row = this.#lexicon.phrases[table]\n\t\t\tif (row !== null && row !== undefined && Object.hasOwn(row, key)) {\n\t\t\t\tconst value = row[key]\n\t\t\t\tif (typeof value === 'string') return value\n\t\t\t}\n\t\t}\n\t\treturn fallback ?? key\n\t}\n\n\tlabel(field: FieldPath): string {\n\t\tconst key = formatField(field)\n\t\tif (Object.hasOwn(this.#lexicon.labels, key)) {\n\t\t\tconst value = this.#lexicon.labels[key]\n\t\t\tif (typeof value === 'string') return value\n\t\t}\n\t\treturn key\n\t}\n\n\tline(id: string, values: Readonly<Record<string, unknown>>): string {\n\t\tif (!Object.hasOwn(this.#lexicon.templates, id)) return ''\n\t\tconst template = this.#lexicon.templates[id]\n\t\treturn typeof template === 'string' ? interpolateMessage(template, values) : ''\n\t}\n\n\tvalue(unit: string, raw: unknown): string {\n\t\tif (Object.hasOwn(this.#formatters, unit)) {\n\t\t\tconst formatter = this.#formatters[unit]\n\t\t\tif (typeof formatter === 'function') {\n\t\t\t\ttry {\n\t\t\t\t\treturn formatter(raw)\n\t\t\t\t} catch {\n\t\t\t\t\treturn String(raw)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn String(raw)\n\t}\n\n\tdescribe(definition: Definition): string {\n\t\tswitch (definition.reasoning) {\n\t\t\tcase 'quantitative':\n\t\t\t\treturn this.line('definition.quantitative', {\n\t\t\t\t\tname: definition.name,\n\t\t\t\t\tcount: definition.groups.length,\n\t\t\t\t})\n\t\t\tcase 'logical':\n\t\t\t\treturn this.line('definition.logical', {\n\t\t\t\t\tname: definition.name,\n\t\t\t\t\tcount: definition.rules.length,\n\t\t\t\t\tstrategy: definition.strategy,\n\t\t\t\t})\n\t\t\tcase 'symbolic':\n\t\t\t\treturn this.line('definition.symbolic', {\n\t\t\t\t\tname: definition.name,\n\t\t\t\t\tcount: definition.equations.length,\n\t\t\t\t})\n\t\t\tcase 'inferential':\n\t\t\t\treturn this.line('definition.inferential', {\n\t\t\t\t\tname: definition.name,\n\t\t\t\t\tfacts: definition.facts.length,\n\t\t\t\t\tinferences: definition.inferences.length,\n\t\t\t\t\tstrategy: definition.strategy,\n\t\t\t\t})\n\t\t}\n\t}\n\n\tnarrate(result: ReasonResult): string {\n\t\tswitch (result.reasoning) {\n\t\t\tcase 'quantitative': {\n\t\t\t\tconst base = this.line('result.quantitative', { value: result.value, count: result.count })\n\t\t\t\tif (result.errors.length === 0) return base\n\t\t\t\tconst suffix = this.line('result.quantitative.failed', { errors: result.errors.join(', ') })\n\t\t\t\treturn `${base}${suffix}`\n\t\t\t}\n\t\t\tcase 'logical':\n\t\t\t\treturn this.line('result.logical', {\n\t\t\t\t\tstatus: result.conclusion ? 'met' : 'unmet',\n\t\t\t\t\tcount: result.count,\n\t\t\t\t})\n\t\t\tcase 'symbolic': {\n\t\t\t\tconst solved = Object.entries(result.solutions)\n\t\t\t\t\t.map(([key, value]) => `${key}=${value}`)\n\t\t\t\t\t.join(', ')\n\t\t\t\treturn this.line('result.symbolic', { solved })\n\t\t\t}\n\t\t\tcase 'inferential':\n\t\t\t\treturn this.line('result.inferential', { count: result.derived.length })\n\t\t}\n\t}\n}\n","import type {\n\tAmbiguity,\n\tClarifierInterface,\n\tClarifierOptions,\n\tClarifyResult,\n\tComputedField,\n\tEntity,\n\tIntent,\n\tInterpretContextInterface,\n\tTemplate,\n} from '../types.js'\nimport { isFiniteNumber } from '@orkestrel/contract'\nimport { formatField } from '@orkestrel/reason'\nimport {\n\tCONFIDENCE_CARRIED,\n\tCONFIDENCE_COMPUTED,\n\tCONFIDENCE_DEFAULT,\n\tDEFAULT_INTERPRET_FLOOR,\n} from '../constants.js'\nimport { resolveExpression, variablesOf } from '../helpers.js'\n\n/**\n * The `Clarifier` stage: resolves same-domain carry-over, template defaults,\n * and declaratively computed fields against an already-assigned entity set,\n * surfacing an {@link Ambiguity} for every required mapping that stays\n * unresolved.\n *\n * @remarks\n * Resolution order: fresh (already-assigned) entities always win; carry-over\n * fills a mapping only from the SAME domain's most recent prior turn (a\n * domain change drops carry-over entirely) and never overwrites a fresh\n * value; template defaults fill any field still unresolved after carry-over;\n * computed fields resolve in dependency (topological) order via\n * `resolveExpression` — an unresolved input, a non-finite result, or a\n * dependency cycle leaves the field a gap, never landing an entity. `floor`\n * (from {@link ClarifierOptions}, never hardcoded — AGENTS-flagged scsr\n * defect 4) gates whether a resolved entity's confidence counts as\n * \"resolved enough\" when raising ambiguities — a field with a value below\n * `floor` still raises its ambiguity.\n *\n * @example\n * ```ts\n * import { Clarifier } from '@src/core'\n *\n * const clarifier = new Clarifier({ floor: 0.3 })\n * clarifier.clarify(\n * \t[],\n * \t{\n * \t\tid: 't1',\n * \t\tname: 'Arithmetic',\n * \t\tdomain: 'arithmetic',\n * \t\tintents: ['calculate'],\n * \t\tmappings: [{ entity: 'value', aliases: [], field: 'value', required: true }],\n * \t\tdefaults: [],\n * \t\tcomputations: [],\n * \t\tdefinition: { reasoning: 'symbolic', id: 't1', name: 'Arithmetic', equations: [], variables: {} },\n * \t},\n * \tundefined,\n * \t{ action: 'calculate', domain: 'arithmetic', confidence: 1 },\n * ) // { entities: [], ambiguities: [{ field: 'value', ... }], complete: false }\n * ```\n */\nexport class Clarifier implements ClarifierInterface {\n\treadonly #floor: number\n\n\tconstructor(options?: ClarifierOptions) {\n\t\tthis.#floor = options?.floor ?? DEFAULT_INTERPRET_FLOOR\n\t}\n\n\tclarify(\n\t\tentities: readonly Entity[],\n\t\ttemplate: Template,\n\t\tcontext: InterpretContextInterface | undefined,\n\t\tintent: Intent,\n\t): ClarifyResult {\n\t\tconst resolved: Entity[] = [...entities]\n\t\tconst filledEntityNames = new Set(resolved.map((entity) => entity.name))\n\t\tconst filledFields = new Set(\n\t\t\tresolved.map((entity) => {\n\t\t\t\tconst mapping = template.mappings.find((candidate) => candidate.entity === entity.name)\n\t\t\t\treturn mapping === undefined ? entity.name : formatField(mapping.field)\n\t\t\t}),\n\t\t)\n\n\t\tthis.#carryOver(template, context, intent, filledEntityNames, filledFields, resolved)\n\t\tthis.#fillDefaults(template, filledFields, resolved)\n\t\tthis.#resolveComputations(template, filledFields, resolved)\n\n\t\tconst ambiguities = this.#collectAmbiguities(template, resolved)\n\n\t\treturn { entities: resolved, ambiguities, complete: ambiguities.length === 0 }\n\t}\n\n\t// Same-domain-only carry-over — a chaining pass over `context.previous()`\n\t// mutating the shared `resolved` accumulator (AGENTS §7: an algorithm step,\n\t// not a leaf).\n\t#carryOver(\n\t\ttemplate: Template,\n\t\tcontext: InterpretContextInterface | undefined,\n\t\tintent: Intent,\n\t\tfilledEntityNames: Set<string>,\n\t\tfilledFields: Set<string>,\n\t\tresolved: Entity[],\n\t): void {\n\t\tif (context === undefined) return\n\t\tconst sameDomain = context.previous().filter((prior) => prior.intent.domain === intent.domain)\n\t\tfor (const mapping of template.mappings) {\n\t\t\tif (filledEntityNames.has(mapping.entity)) continue\n\t\t\tfor (let index = sameDomain.length - 1; index >= 0; index -= 1) {\n\t\t\t\tconst prior = sameDomain[index]\n\t\t\t\tconst found = prior?.entities.find((entity) => entity.name === mapping.entity)\n\t\t\t\tif (found === undefined) continue\n\t\t\t\tresolved.push({\n\t\t\t\t\tname: mapping.entity,\n\t\t\t\t\tvalue: found.value,\n\t\t\t\t\tprovenance: { category: 'carried' },\n\t\t\t\t\tconfidence: CONFIDENCE_CARRIED,\n\t\t\t\t})\n\t\t\t\tfilledEntityNames.add(mapping.entity)\n\t\t\t\tfilledFields.add(formatField(mapping.field))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Fills every still-unresolved default field — never overwrites.\n\t#fillDefaults(template: Template, filledFields: Set<string>, resolved: Entity[]): void {\n\t\tfor (const fieldDefault of template.defaults) {\n\t\t\tconst key = formatField(fieldDefault.field)\n\t\t\tif (filledFields.has(key)) continue\n\t\t\tconst mapping = template.mappings.find((candidate) => formatField(candidate.field) === key)\n\t\t\tresolved.push({\n\t\t\t\tname: mapping?.entity ?? key,\n\t\t\t\tvalue: fieldDefault.value,\n\t\t\t\tprovenance: { category: 'default' },\n\t\t\t\tconfidence: CONFIDENCE_DEFAULT,\n\t\t\t})\n\t\t\tfilledFields.add(key)\n\t\t}\n\t}\n\n\t// Resolves computed fields in dependency order, seeding bindings from\n\t// every already-resolved numeric field (extracted/carried/default), then\n\t// growing bindings as each computed field lands.\n\t#resolveComputations(template: Template, filledFields: Set<string>, resolved: Entity[]): void {\n\t\tconst bindings: Record<string, number> = {}\n\t\tfor (const entity of resolved) {\n\t\t\tconst mapping = template.mappings.find((candidate) => candidate.entity === entity.name)\n\t\t\tconst field = mapping === undefined ? entity.name : formatField(mapping.field)\n\t\t\tif (isFiniteNumber(entity.value)) bindings[field] = entity.value\n\t\t}\n\n\t\tfor (const computation of this.#orderComputations(template.computations)) {\n\t\t\tconst key = formatField(computation.field)\n\t\t\tif (filledFields.has(key)) continue\n\t\t\tconst value = resolveExpression(computation.expression, bindings)\n\t\t\tif (value === undefined) continue\n\t\t\tconst mapping = template.mappings.find((candidate) => formatField(candidate.field) === key)\n\t\t\tresolved.push({\n\t\t\t\tname: mapping?.entity ?? key,\n\t\t\t\tvalue,\n\t\t\t\tprovenance: { category: 'computed' },\n\t\t\t\tconfidence: CONFIDENCE_COMPUTED,\n\t\t\t})\n\t\t\tfilledFields.add(key)\n\t\t\tbindings[key] = value\n\t\t}\n\t}\n\n\t// Kahn's-algorithm topological order over the computed fields' field-to-\n\t// field dependency graph (via `variablesOf`) — a dependency cycle simply\n\t// excludes every field it involves from the returned order, so a cyclic\n\t// field (and anything depending on it) resolves to a gap rather than an\n\t// arbitrary evaluation order. A compositional graph traversal, so it stays\n\t// a private orchestration step rather than a leaf (AGENTS §7 — mirrors the\n\t// `SymbolicReasoner#solve`/`#isolate` precedent).\n\t#orderComputations(computations: readonly ComputedField[]): readonly ComputedField[] {\n\t\tconst byField = new Map<string, ComputedField>()\n\t\tfor (const computation of computations) byField.set(formatField(computation.field), computation)\n\n\t\tconst dependents = new Map<string, string[]>()\n\t\tconst inDegree = new Map<string, number>()\n\t\tfor (const key of byField.keys()) inDegree.set(key, 0)\n\n\t\tfor (const [key, computation] of byField) {\n\t\t\tconst dependencies = variablesOf(computation.expression).filter((name) => byField.has(name))\n\t\t\tinDegree.set(key, dependencies.length)\n\t\t\tfor (const dependency of dependencies) {\n\t\t\t\tconst list = dependents.get(dependency) ?? []\n\t\t\t\tlist.push(key)\n\t\t\t\tdependents.set(dependency, list)\n\t\t\t}\n\t\t}\n\n\t\tconst queue: string[] = []\n\t\tfor (const [key, degree] of inDegree) if (degree === 0) queue.push(key)\n\n\t\tconst ordered: ComputedField[] = []\n\t\tlet cursor = 0\n\t\twhile (cursor < queue.length) {\n\t\t\tconst key = queue[cursor]\n\t\t\tcursor += 1\n\t\t\tif (key === undefined) continue\n\t\t\tconst computation = byField.get(key)\n\t\t\tif (computation !== undefined) ordered.push(computation)\n\t\t\tfor (const dependent of dependents.get(key) ?? []) {\n\t\t\t\tconst next = (inDegree.get(dependent) ?? 0) - 1\n\t\t\t\tinDegree.set(dependent, next)\n\t\t\t\tif (next === 0) queue.push(dependent)\n\t\t\t}\n\t\t}\n\n\t\treturn ordered\n\t}\n\n\t// One ambiguity per required mapping without a resolved-enough entity.\n\t#collectAmbiguities(template: Template, resolved: readonly Entity[]): Ambiguity[] {\n\t\tconst ambiguities: Ambiguity[] = []\n\t\tfor (const mapping of template.mappings) {\n\t\t\tif (mapping.required !== true) continue\n\t\t\tconst entity = resolved.find((candidate) => candidate.name === mapping.entity)\n\t\t\tconst resolvedEnough = entity !== undefined && entity.confidence >= this.#floor\n\t\t\tif (resolvedEnough) continue\n\t\t\tambiguities.push({\n\t\t\t\tfield: mapping.field,\n\t\t\t\tquestion: `What is your ${mapping.entity}?`,\n\t\t\t\tcandidates: [],\n\t\t\t\trequired: true,\n\t\t\t})\n\t\t}\n\t\treturn ambiguities\n\t}\n}\n","import type { ExtractorInterface, ExtractorOptions, ExtractResult } from '../types.js'\nimport { DEFAULT_ACTIONS, DEFAULT_DOMAINS } from '../constants.js'\nimport { classifyIntent, extractNumbers } from '../helpers.js'\n\n/**\n * The `Extractor` stage: template-agnostic intent classification plus raw\n * numeric-entity mining.\n *\n * @remarks\n * Deliberately never named `Parser` — the `contracts` module already owns\n * `Parser<T>`, so a class of that name would collide in type space (AGENTS\n * §21, design ledger 3). `extract` never sees a `Template`: numbers →\n * entity ASSIGNMENT is a separate orchestrator-owned step that runs only\n * after a template has matched (`assignEntities` in `helpers.ts`), not\n * inside this stage (the defect-3 fix — scsr's parser mined template-shaped\n * entities directly and only worked via an `instanceof` hack).\n *\n * @example\n * ```ts\n * import { Extractor } from '@src/core'\n *\n * const extractor = new Extractor({\n * \tactions: { calculate: 'compute' },\n * \tdomains: { rating: ['rate'] },\n * })\n * extractor.extract('calculate my rate at 85')\n * // { intent: { action: 'compute', domain: 'rating', confidence: 1 }, numbers: [85], complete: true }\n * ```\n */\nexport class Extractor implements ExtractorInterface {\n\treadonly #actions: Readonly<Record<string, string>>\n\treadonly #domains: Readonly<Record<string, readonly string[]>>\n\n\tconstructor(options?: ExtractorOptions) {\n\t\tthis.#actions = { ...DEFAULT_ACTIONS, ...options?.actions }\n\t\tthis.#domains = { ...DEFAULT_DOMAINS, ...options?.domains }\n\t}\n\n\textract(text: string): ExtractResult {\n\t\tconst numbers = extractNumbers(text)\n\t\tconst intent = classifyIntent(text, this.#actions, this.#domains)\n\t\treturn { intent, numbers, complete: numbers.length > 0 && intent.confidence > 0 }\n\t}\n}\n","import type {\n\tAmbiguity,\n\tEntity,\n\tFormatResult,\n\tFormatterInterface,\n\tFormatterOptions,\n\tIntent,\n\tTemplate,\n} from '../types.js'\nimport { formatField } from '@orkestrel/reason'\nimport { DEFAULT_VERBS } from '../constants.js'\n\n/**\n * The `Formatter` stage: renders the refined natural-language prompt for a\n * matched template.\n *\n * @remarks\n * Shape: `{verb} {template.name}` + ` with {label}: {value}, …` for every\n * non-default entity (via the core-root `formatField`) + `\n * (defaults: {label}: {value}, …)` for default-provenance entities + `\n * needed: {question} …` for every ambiguity. `verbs` maps `intent.action` to\n * its display verb; an action absent from the map falls back to the action\n * string itself. Every parameter is read — no ignored `context` argument\n * (AGENTS-flagged scsr defect 5).\n *\n * @example\n * ```ts\n * import { Formatter } from '@src/core'\n *\n * const formatter = new Formatter({ verbs: { calculate: 'Calculate' } })\n * formatter.format(\n * \t{ action: 'calculate', domain: 'arithmetic', confidence: 1 },\n * \t{\n * \t\tid: 't1',\n * \t\tname: 'Arithmetic',\n * \t\tdomain: 'arithmetic',\n * \t\tintents: ['calculate'],\n * \t\tmappings: [],\n * \t\tdefaults: [],\n * \t\tcomputations: [],\n * \t\tdefinition: { reasoning: 'symbolic', id: 't1', name: 'Arithmetic', equations: [], variables: {} },\n * \t},\n * \t[],\n * \t[],\n * ) // { prompt: 'Calculate Arithmetic' }\n * ```\n */\nexport class Formatter implements FormatterInterface {\n\treadonly #verbs: Readonly<Record<string, string>>\n\n\tconstructor(options?: FormatterOptions) {\n\t\tthis.#verbs = { ...DEFAULT_VERBS, ...options?.verbs }\n\t}\n\n\tformat(\n\t\tintent: Intent,\n\t\ttemplate: Template,\n\t\tentities: readonly Entity[],\n\t\tambiguities: readonly Ambiguity[],\n\t): FormatResult {\n\t\tconst verb = this.#verbs[intent.action] ?? intent.action\n\t\tconst render = (list: readonly Entity[]): string =>\n\t\t\tlist.map((entity) => `${formatField(entity.name)}: ${String(entity.value)}`).join(', ')\n\n\t\tlet prompt = `${verb} ${template.name}`\n\n\t\tconst resolved = entities.filter((entity) => entity.provenance.category !== 'default')\n\t\tif (resolved.length > 0) prompt += ` with ${render(resolved)}`\n\n\t\tconst defaults = entities.filter((entity) => entity.provenance.category === 'default')\n\t\tif (defaults.length > 0) prompt += ` (defaults: ${render(defaults)})`\n\n\t\tif (ambiguities.length > 0) {\n\t\t\tprompt += ` needed: ${ambiguities.map((ambiguity) => ambiguity.question).join(' ')}`\n\t\t}\n\n\t\treturn { prompt }\n\t}\n}\n","import type { Subject } from '@orkestrel/reason'\nimport type {\n\tEntity,\n\tFieldMapping,\n\tGenerateResult,\n\tGeneratorInterface,\n\tTemplate,\n} from '../types.js'\nimport { isFiniteNumber } from '@orkestrel/contract'\nimport { CONFIDENCE_COMPUTED } from '../constants.js'\nimport { deriveAggregateField, setField } from '../helpers.js'\n\n/**\n * The `Generator` stage: builds the final `Subject` from a fully resolved\n * entity set, plus its complete field audit.\n *\n * @remarks\n * `entity → field` via `template.mappings` (an `EntityMapping.entity` name\n * lookup); an entity whose name matches no mapping lands on the field named\n * by its OWN `name` — the shape `Clarifier` uses for its synthesized\n * default/computed entities, so one lookup rule serves both extraction-\n * mapped and template-data-derived fields. A single-element array value\n * unwraps to its scalar; a multi-element, ALL-numeric array value stays an\n * array AND additionally emits five aggregate fields (`Sum` / `Count` /\n * `Average` / `Minimum` / `Maximum`, provenance `computed`), each derived as\n * a SIBLING path beside the source field via `deriveAggregateField` — for an\n * array `FieldPath` (e.g. `['address', 'amounts']`) the aggregates nest\n * (`['address', 'amountsSum']`, ...); for a plain string field they stay\n * flat (`'amountsSum'`), matching the source field's own shape.\n * `confidence` is the mean of the input entities' own confidences (`0` for\n * an empty entity set). A `FieldMapping` is emitted for EVERY field that\n * lands on the subject, including defaults, computed fields, and aggregates\n * — scsr silently omitted defaults/computed from its audit trail; this\n * closes that gap. `GeneratorOptions` is a reserved extension seam — the\n * stage has no knobs yet, so construction takes no arguments until one\n * exists.\n *\n * @example\n * ```ts\n * import { Generator } from '@src/core'\n *\n * const generator = new Generator()\n * generator.generate(\n * \t[\n * \t\t{\n * \t\t\tname: 'value',\n * \t\t\tvalue: 42,\n * \t\t\tprovenance: { category: 'extracted', detail: 'collect' },\n * \t\t\tconfidence: 0.9,\n * \t\t},\n * \t],\n * \t{\n * \t\tid: 't1',\n * \t\tname: 'Arithmetic',\n * \t\tdomain: 'arithmetic',\n * \t\tintents: ['calculate'],\n * \t\tmappings: [{ entity: 'value', aliases: [], field: 'value' }],\n * \t\tdefaults: [],\n * \t\tcomputations: [],\n * \t\tdefinition: { reasoning: 'symbolic', id: 't1', name: 'Arithmetic', equations: [], variables: {} },\n * \t},\n * ) // { subject: { value: 42 }, mappings: [...], confidence: 0.9, ... }\n * ```\n */\nexport class Generator implements GeneratorInterface {\n\tgenerate(entities: readonly Entity[], template: Template): GenerateResult {\n\t\tlet subject: Subject = {}\n\t\tconst mappings: FieldMapping[] = []\n\n\t\tfor (const entity of entities) {\n\t\t\tconst mapping = template.mappings.find((candidate) => candidate.entity === entity.name)\n\t\t\tconst field = mapping === undefined ? entity.name : mapping.field\n\t\t\tconst value = entity.value\n\n\t\t\tif (Array.isArray(value) && value.length === 1) {\n\t\t\t\tconst scalar = value[0]\n\t\t\t\tsubject = setField(subject, field, scalar)\n\t\t\t\tmappings.push({\n\t\t\t\t\tfield,\n\t\t\t\t\tentity: entity.name,\n\t\t\t\t\tvalue: scalar,\n\t\t\t\t\tprovenance: entity.provenance,\n\t\t\t\t\tconfidence: entity.confidence,\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (Array.isArray(value) && value.length > 1) {\n\t\t\t\tconst numeric: number[] = []\n\t\t\t\tfor (const item of value) {\n\t\t\t\t\tif (!isFiniteNumber(item)) break\n\t\t\t\t\tnumeric.push(item)\n\t\t\t\t}\n\t\t\t\tif (numeric.length === value.length) {\n\t\t\t\t\tsubject = setField(subject, field, value)\n\t\t\t\t\tmappings.push({\n\t\t\t\t\t\tfield,\n\t\t\t\t\t\tentity: entity.name,\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t\tprovenance: entity.provenance,\n\t\t\t\t\t\tconfidence: entity.confidence,\n\t\t\t\t\t})\n\t\t\t\t\tconst sum = numeric.reduce((total, item) => total + item, 0)\n\t\t\t\t\tconst minimum = numeric.reduce((min, item) => (item < min ? item : min), numeric[0])\n\t\t\t\t\tconst maximum = numeric.reduce((max, item) => (item > max ? item : max), numeric[0])\n\t\t\t\t\tconst aggregates = [\n\t\t\t\t\t\t[deriveAggregateField(field, 'Sum'), sum],\n\t\t\t\t\t\t[deriveAggregateField(field, 'Count'), numeric.length],\n\t\t\t\t\t\t[deriveAggregateField(field, 'Average'), sum / numeric.length],\n\t\t\t\t\t\t[deriveAggregateField(field, 'Minimum'), minimum],\n\t\t\t\t\t\t[deriveAggregateField(field, 'Maximum'), maximum],\n\t\t\t\t\t] as const\n\t\t\t\t\tfor (const [aggregateField, aggregateValue] of aggregates) {\n\t\t\t\t\t\tsubject = setField(subject, aggregateField, aggregateValue)\n\t\t\t\t\t\tmappings.push({\n\t\t\t\t\t\t\tfield: aggregateField,\n\t\t\t\t\t\t\tvalue: aggregateValue,\n\t\t\t\t\t\t\tprovenance: { category: 'computed' },\n\t\t\t\t\t\t\tconfidence: CONFIDENCE_COMPUTED,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsubject = setField(subject, field, value)\n\t\t\tmappings.push({\n\t\t\t\tfield,\n\t\t\t\tentity: entity.name,\n\t\t\t\tvalue,\n\t\t\t\tprovenance: entity.provenance,\n\t\t\t\tconfidence: entity.confidence,\n\t\t\t})\n\t\t}\n\n\t\tconst confidence =\n\t\t\tentities.length === 0\n\t\t\t\t? 0\n\t\t\t\t: entities.reduce((total, entity) => total + entity.confidence, 0) / entities.length\n\n\t\treturn { subject, definition: template.definition, mappings, confidence }\n\t}\n}\n","import type {\n\tNormalizeResult,\n\tNormalizerInterface,\n\tNormalizerOptions,\n\tTextChange,\n} from '../types.js'\nimport { DEFAULT_ABBREVIATIONS, DEFAULT_CONTRACTIONS, DEFAULT_CORRECTIONS } from '../constants.js'\nimport { applyReplacements, collapseWhitespace, escapeRegExp } from '../helpers.js'\n\n/**\n * The `Normalizer` stage: applies contraction, abbreviation, and correction\n * substitutions in order, then collapses whitespace.\n *\n * @remarks\n * Each caller map is merged OVER the neutral built-in default for its slot —\n * `text` is never mutated (AGENTS §11). Every substitution actually applied\n * (one entry per matching map KEY, not per occurrence) is recorded on the\n * result's `changes`, in `contractions → abbreviations → corrections` order,\n * so the audit trail explains every character difference between `text` and\n * `NormalizeResult.text` (the final whitespace collapse carries no entry of\n * its own — it is structural cleanup, not a substitution).\n *\n * @example\n * ```ts\n * import { Normalizer } from '@src/core'\n *\n * const normalizer = new Normalizer({ contractions: { \"can't\": 'cannot' } })\n * normalizer.normalize(\"can't stop\")\n * // { text: 'cannot stop', changes: [{ from: \"can't\", to: 'cannot' }] }\n * ```\n */\nexport class Normalizer implements NormalizerInterface {\n\treadonly #contractions: Readonly<Record<string, string>>\n\treadonly #abbreviations: Readonly<Record<string, string>>\n\treadonly #corrections: Readonly<Record<string, string>>\n\n\tconstructor(options?: NormalizerOptions) {\n\t\tthis.#contractions = { ...DEFAULT_CONTRACTIONS, ...options?.contractions }\n\t\tthis.#abbreviations = { ...DEFAULT_ABBREVIATIONS, ...options?.abbreviations }\n\t\tthis.#corrections = { ...DEFAULT_CORRECTIONS, ...options?.corrections }\n\t}\n\n\tnormalize(text: string): NormalizeResult {\n\t\tconst changes: TextChange[] = []\n\t\tlet working = text\n\t\tfor (const map of [this.#contractions, this.#abbreviations, this.#corrections]) {\n\t\t\tconst applied = this.#applyStage(working, map)\n\t\t\tworking = applied.text\n\t\t\tchanges.push(...applied.changes)\n\t\t}\n\t\treturn { text: collapseWhitespace(working), changes }\n\t}\n\n\t// One substitution pass over `map`, recording only the keys that actually\n\t// matched. A chaining pass over the leaf `applyReplacements`, so it stays a\n\t// private orchestration step rather than a leaf of its own (AGENTS §7).\n\t#applyStage(\n\t\ttext: string,\n\t\tmap: Readonly<Record<string, string>>,\n\t): { text: string; changes: readonly TextChange[] } {\n\t\tlet working = text\n\t\tconst changes: TextChange[] = []\n\t\tfor (const [from, to] of Object.entries(map)) {\n\t\t\tconst pattern = new RegExp(`\\\\b${escapeRegExp(from)}\\\\b`, 'i')\n\t\t\tif (pattern.test(working)) {\n\t\t\t\tworking = applyReplacements(working, { [from]: to })\n\t\t\t\tchanges.push({ from, to })\n\t\t\t}\n\t\t}\n\t\treturn { text: working, changes }\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { Definition, ReasonResult } from '@orkestrel/reason'\nimport type {\n\tAmbiguity,\n\tClarifierInterface,\n\tClarifyResult,\n\tEntity,\n\tExtractorInterface,\n\tExtractResult,\n\tFormatResult,\n\tFormatterInterface,\n\tGenerateResult,\n\tGeneratorInterface,\n\tIntent,\n\tInterpretContextInterface,\n\tInterpretErrorCode,\n\tInterpretEventMap,\n\tInterpretInterface,\n\tInterpretOptions,\n\tInterpretStage,\n\tInterpretation,\n\tNarratorInterface,\n\tNormalizeResult,\n\tNormalizerInterface,\n\tStageFailure,\n\tStageRecord,\n\tTemplate,\n} from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { DEFAULT_INTERPRET_FLOOR, DEFAULT_INTERPRET_SIMILARITY } from './constants.js'\nimport { InterpretError } from './errors.js'\nimport { assignEntities, digestValue, matchTemplate } from './helpers.js'\nimport { InterpretContext } from './managers/InterpretContext.js'\nimport { TemplateManager } from './managers/TemplateManager.js'\nimport { Narrator } from './Narrator.js'\nimport { Clarifier } from './stages/Clarifier.js'\nimport { Extractor } from './stages/Extractor.js'\nimport { Formatter } from './stages/Formatter.js'\nimport { Generator } from './stages/Generator.js'\nimport { Normalizer } from './stages/Normalizer.js'\n\n/**\n * The interpretation orchestrator — the sole public entry point of the\n * `interprets` module, mirroring the reasons `Reason` orchestrator shape.\n *\n * @remarks\n * `interpret()` is genuinely SYNCHRONOUS (scsr's was fake-async with zero\n * `await`s) and runs a fixed five-stage pipeline —\n * `[normalize, extract, clarify, format, generate]` — each producing one\n * {@link StageRecord}. Between `extract` and `clarify` the orchestrator matches\n * the classified {@link Intent} against its registered {@link Template}s and,\n * on a match, assigns the extracted numbers to that template's mappings\n * (`assignEntities`) — a template-owned step, not a sixth stage. No match, or a\n * matched template whose intent confidence falls below the configured `floor`,\n * yields an explicit, auditable INCOMPLETE result (a `field: 'intent'`\n * ambiguity, absent subject/definition) rather than scsr's arbitrary\n * `templates[0]` fallback. A stage THROW is caught, marked on its record AND on\n * `failures`, emitted as `error`, and still yields a visible incomplete result\n * — never a silent fallback. Every result carries a `digest` over its original\n * text plus the matched template id/version and the built subject/definition,\n * so re-running the same text against the same template version reproduces the\n * same digest (the replay contract). `describe` / `narrate` are the reverse\n * direction (structure → prose). `destroy()` is idempotent, tears down the\n * registry and context, then destroys the emitter LAST (AGENTS §13); every\n * method afterwards except the {@link emitter} getter throws\n * `InterpretError('DESTROYED', …)`.\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { Interpret, Extractor } from '@src/core'\n *\n * const interpret = new Interpret({\n * \textractor: new Extractor({ actions: { calculate: 'calculate' }, domains: { arithmetic: ['arithmetic'] } }),\n * \ttemplates: [\n * \t\t{\n * \t\t\tid: 't1',\n * \t\t\tname: 'Arithmetic',\n * \t\t\tdomain: 'arithmetic',\n * \t\t\tintents: ['calculate'],\n * \t\t\tmappings: [{ entity: 'value', aliases: [], field: 'value' }],\n * \t\t\tdefaults: [],\n * \t\t\tcomputations: [],\n * \t\t\tdefinition: quantitativeDefinition('t1', 'Arithmetic', [\n * \t\t\t\tfactorGroup('total', 'sum', [fieldFactor('value', 'value')]),\n * \t\t\t]),\n * \t\t},\n * \t],\n * })\n * interpret.interpret('calculate arithmetic 42').subject // { value: 42 }\n * ```\n */\nexport class Interpret implements InterpretInterface {\n\treadonly #templates: TemplateManager\n\treadonly #context: InterpretContextInterface\n\treadonly #normalizer: NormalizerInterface\n\treadonly #extractor: ExtractorInterface\n\treadonly #clarifier: ClarifierInterface\n\treadonly #formatter: FormatterInterface\n\treadonly #generator: GeneratorInterface\n\treadonly #similarity: number\n\treadonly #floor: number\n\treadonly #narrator: NarratorInterface\n\treadonly #emitter: Emitter<InterpretEventMap>\n\t#destroyed = false\n\n\tconstructor(options?: InterpretOptions) {\n\t\tthis.#similarity = options?.similarity ?? DEFAULT_INTERPRET_SIMILARITY\n\t\tthis.#floor = options?.floor ?? DEFAULT_INTERPRET_FLOOR\n\t\tthis.#templates = new TemplateManager({ templates: options?.templates })\n\t\tthis.#context = options?.context ?? new InterpretContext({ history: options?.history })\n\t\tthis.#normalizer = options?.normalizer ?? new Normalizer()\n\t\tthis.#extractor = options?.extractor ?? new Extractor()\n\t\tthis.#clarifier = options?.clarifier ?? new Clarifier({ floor: this.#floor })\n\t\tthis.#formatter = options?.formatter ?? new Formatter()\n\t\tthis.#generator = options?.generator ?? new Generator()\n\t\tthis.#narrator = new Narrator({ lexicon: options?.lexicon, formatters: options?.formatters })\n\t\tthis.#emitter = new Emitter<InterpretEventMap>({ on: options?.on, error: options?.error })\n\t}\n\n\tget emitter(): EmitterInterface<InterpretEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tinterpret(text: string): Interpretation {\n\t\tthis.#ensureAlive()\n\t\tconst stages: StageRecord[] = []\n\n\t\tlet normalized: NormalizeResult\n\t\ttry {\n\t\t\tnormalized = this.#normalizer.normalize(text)\n\t\t} catch (error) {\n\t\t\treturn this.#abort(\n\t\t\t\ttext,\n\t\t\t\ttext,\n\t\t\t\t{ action: '', domain: '', confidence: 0 },\n\t\t\t\t[],\n\t\t\t\t[],\n\t\t\t\tstages,\n\t\t\t\t'normalize',\n\t\t\t\t'NORMALIZE_FAILED',\n\t\t\t\ttext,\n\t\t\t\terror,\n\t\t\t\t['extract', 'clarify', 'format', 'generate'],\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t)\n\t\t}\n\t\tstages.push({ stage: 'normalize', input: text, output: normalized, failed: false })\n\n\t\tlet extract: ExtractResult\n\t\ttry {\n\t\t\textract = this.#extractor.extract(normalized.text)\n\t\t} catch (error) {\n\t\t\treturn this.#abort(\n\t\t\t\ttext,\n\t\t\t\tnormalized.text,\n\t\t\t\t{ action: '', domain: '', confidence: 0 },\n\t\t\t\t[],\n\t\t\t\t[],\n\t\t\t\tstages,\n\t\t\t\t'extract',\n\t\t\t\t'EXTRACT_FAILED',\n\t\t\t\tnormalized.text,\n\t\t\t\terror,\n\t\t\t\t['clarify', 'format', 'generate'],\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t)\n\t\t}\n\t\tstages.push({ stage: 'extract', input: normalized.text, output: extract, failed: false })\n\n\t\tconst intent = extract.intent\n\t\tconst templates = this.#templates.templates().map((record) => record.template)\n\t\tconst matched = matchTemplate(intent, templates, this.#floor)\n\n\t\tif (matched === undefined) {\n\t\t\treturn this.#gate(\n\t\t\t\ttext,\n\t\t\t\tnormalized.text,\n\t\t\t\tintent,\n\t\t\t\t[],\n\t\t\t\tstages,\n\t\t\t\t'NO_TEMPLATE',\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t)\n\t\t}\n\n\t\tconst assigned = assignEntities(\n\t\t\textract.numbers,\n\t\t\tmatched.mappings,\n\t\t\tnormalized.text,\n\t\t\tthis.#similarity,\n\t\t)\n\t\tconst record = this.#templates.template(matched.id)\n\t\tconst version = record?.version\n\n\t\tif (intent.confidence < this.#floor) {\n\t\t\treturn this.#gate(\n\t\t\t\ttext,\n\t\t\t\tnormalized.text,\n\t\t\t\tintent,\n\t\t\t\tassigned,\n\t\t\t\tstages,\n\t\t\t\t'LOW_CONFIDENCE',\n\t\t\t\tmatched.id,\n\t\t\t\tversion,\n\t\t\t)\n\t\t}\n\n\t\tlet clarified: ClarifyResult\n\t\ttry {\n\t\t\tclarified = this.#clarifier.clarify(assigned, matched, this.#context, intent)\n\t\t} catch (error) {\n\t\t\treturn this.#abort(\n\t\t\t\ttext,\n\t\t\t\tnormalized.text,\n\t\t\t\tintent,\n\t\t\t\tassigned,\n\t\t\t\t[],\n\t\t\t\tstages,\n\t\t\t\t'clarify',\n\t\t\t\t'CLARIFY_FAILED',\n\t\t\t\tassigned,\n\t\t\t\terror,\n\t\t\t\t['format', 'generate'],\n\t\t\t\tmatched.id,\n\t\t\t\tversion,\n\t\t\t)\n\t\t}\n\t\tstages.push({ stage: 'clarify', input: assigned, output: clarified, failed: false })\n\n\t\tconst formatInput = { intent, entities: clarified.entities, ambiguities: clarified.ambiguities }\n\t\tlet formatted: FormatResult\n\t\ttry {\n\t\t\tformatted = this.#formatter.format(intent, matched, clarified.entities, clarified.ambiguities)\n\t\t} catch (error) {\n\t\t\treturn this.#abort(\n\t\t\t\ttext,\n\t\t\t\tnormalized.text,\n\t\t\t\tintent,\n\t\t\t\tclarified.entities,\n\t\t\t\tclarified.ambiguities,\n\t\t\t\tstages,\n\t\t\t\t'format',\n\t\t\t\t'FORMAT_FAILED',\n\t\t\t\tformatInput,\n\t\t\t\terror,\n\t\t\t\t['generate'],\n\t\t\t\tmatched.id,\n\t\t\t\tversion,\n\t\t\t)\n\t\t}\n\t\tstages.push({ stage: 'format', input: formatInput, output: formatted, failed: false })\n\n\t\tlet generated: GenerateResult\n\t\ttry {\n\t\t\tgenerated = this.#generator.generate(clarified.entities, matched)\n\t\t} catch (error) {\n\t\t\treturn this.#abort(\n\t\t\t\ttext,\n\t\t\t\tnormalized.text,\n\t\t\t\tintent,\n\t\t\t\tclarified.entities,\n\t\t\t\tclarified.ambiguities,\n\t\t\t\tstages,\n\t\t\t\t'generate',\n\t\t\t\t'GENERATE_FAILED',\n\t\t\t\tclarified.entities,\n\t\t\t\terror,\n\t\t\t\t[],\n\t\t\t\tmatched.id,\n\t\t\t\tversion,\n\t\t\t)\n\t\t}\n\t\tstages.push({ stage: 'generate', input: clarified.entities, output: generated, failed: false })\n\n\t\tconst digest = digestValue({\n\t\t\ttext,\n\t\t\ttemplateId: matched.id,\n\t\t\ttemplateVersion: version,\n\t\t\tsubject: generated.subject,\n\t\t\tdefinition: generated.definition,\n\t\t})\n\t\tconst result: Interpretation = {\n\t\t\ttext,\n\t\t\tnormalized: normalized.text,\n\t\t\tintent,\n\t\t\tentities: clarified.entities,\n\t\t\tsubject: generated.subject,\n\t\t\tdefinition: generated.definition,\n\t\t\tmappings: generated.mappings,\n\t\t\tambiguities: clarified.ambiguities,\n\t\t\tprompt: formatted.prompt,\n\t\t\tstages,\n\t\t\tfailures: [],\n\t\t\tcomplete: clarified.complete,\n\t\t\tconfidence: generated.confidence,\n\t\t\tdigest,\n\t\t}\n\n\t\tthis.#context.subjects.add(generated.subject)\n\t\tthis.#context.definitions.add(generated.definition, { id: generated.definition.id })\n\t\tthis.#context.add(result)\n\t\tthis.#emitter.emit('interpret', result)\n\t\treturn result\n\t}\n\n\tregister(template: Template): void {\n\t\tthis.#ensureAlive()\n\t\tthis.#templates.add(template, { id: template.id })\n\t\tthis.#emitter.emit('register', template.id)\n\t}\n\n\tunregister(id: string): boolean {\n\t\tthis.#ensureAlive()\n\t\treturn this.#templates.remove(id)\n\t}\n\n\ttemplate(id: string): Template | undefined {\n\t\tthis.#ensureAlive()\n\t\treturn this.#templates.template(id)?.template\n\t}\n\n\ttemplates(): readonly Template[] {\n\t\tthis.#ensureAlive()\n\t\treturn this.#templates.templates().map((record) => record.template)\n\t}\n\n\tdescribe(definition: Definition): string {\n\t\tthis.#ensureAlive()\n\t\treturn this.#narrator.describe(definition)\n\t}\n\n\tnarrate(result: ReasonResult): string {\n\t\tthis.#ensureAlive()\n\t\treturn this.#narrator.narrate(result)\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#templates.destroy()\n\t\tthis.#context.destroy()\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// A NO_TEMPLATE / LOW_CONFIDENCE match gate — an explicit incomplete result\n\t// carrying a `field: 'intent'` ambiguity whose candidates are the registered\n\t// domain names, plus the matching StageFailure. No `error` emit — a gate is\n\t// a deliberate incomplete outcome, not a stage throw.\n\t#gate(\n\t\ttext: string,\n\t\tnormalized: string,\n\t\tintent: Intent,\n\t\tentities: readonly Entity[],\n\t\tstages: StageRecord[],\n\t\tcode: 'NO_TEMPLATE' | 'LOW_CONFIDENCE',\n\t\ttemplateId: string | undefined,\n\t\ttemplateVersion: number | undefined,\n\t): Interpretation {\n\t\tconst domains = [\n\t\t\t...new Set(this.#templates.templates().map((record) => record.template.domain)),\n\t\t]\n\t\tconst ambiguity: Ambiguity = {\n\t\t\tfield: 'intent',\n\t\t\tquestion:\n\t\t\t\tcode === 'NO_TEMPLATE'\n\t\t\t\t\t? 'Which domain and action did you mean?'\n\t\t\t\t\t: 'Which did you mean? The intent was too weak to act on.',\n\t\t\tcandidates: domains,\n\t\t\trequired: true,\n\t\t}\n\t\tconst failure: StageFailure = {\n\t\t\tstage: 'clarify',\n\t\t\tcode,\n\t\t\tmessage:\n\t\t\t\tcode === 'NO_TEMPLATE'\n\t\t\t\t\t? 'No registered template matched the classified intent'\n\t\t\t\t\t: 'Classified intent confidence fell below the configured floor',\n\t\t}\n\t\treturn this.#assemble(\n\t\t\ttext,\n\t\t\tnormalized,\n\t\t\tintent,\n\t\t\tentities,\n\t\t\t[ambiguity],\n\t\t\tstages,\n\t\t\t[failure],\n\t\t\t['clarify', 'format', 'generate'],\n\t\t\ttemplateId,\n\t\t\ttemplateVersion,\n\t\t)\n\t}\n\n\t// A stage THROW — mark the failed stage's record, emit `error` with the raw\n\t// thrown value, and assemble a visible incomplete result. The one site the\n\t// thrown value is rendered to a message (folded here, its sole use).\n\t#abort(\n\t\ttext: string,\n\t\tnormalized: string,\n\t\tintent: Intent,\n\t\tentities: readonly Entity[],\n\t\tambiguities: readonly Ambiguity[],\n\t\tstages: StageRecord[],\n\t\tstage: InterpretStage,\n\t\tcode: InterpretErrorCode,\n\t\tinput: unknown,\n\t\terror: unknown,\n\t\tremaining: readonly InterpretStage[],\n\t\ttemplateId: string | undefined,\n\t\ttemplateVersion: number | undefined,\n\t): Interpretation {\n\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\tstages.push({ stage, input, output: undefined, failed: true, error: message })\n\t\tthis.#emitter.emit('error', error)\n\t\treturn this.#assemble(\n\t\t\ttext,\n\t\t\tnormalized,\n\t\t\tintent,\n\t\t\tentities,\n\t\t\tambiguities,\n\t\t\tstages,\n\t\t\t[{ stage, code, message }],\n\t\t\tremaining,\n\t\t\ttemplateId,\n\t\t\ttemplateVersion,\n\t\t)\n\t}\n\n\t// Assemble a visible incomplete result: pad the un-run stages with skipped\n\t// records so `stages` always holds exactly five, digest over the known\n\t// pre-image, record the result in context, and emit `interpret` (an\n\t// incomplete run is still a completed CALL — visibility is the point).\n\t#assemble(\n\t\ttext: string,\n\t\tnormalized: string,\n\t\tintent: Intent,\n\t\tentities: readonly Entity[],\n\t\tambiguities: readonly Ambiguity[],\n\t\tstages: StageRecord[],\n\t\tfailures: readonly StageFailure[],\n\t\tremaining: readonly InterpretStage[],\n\t\ttemplateId: string | undefined,\n\t\ttemplateVersion: number | undefined,\n\t): Interpretation {\n\t\tfor (const stage of remaining) {\n\t\t\tstages.push({ stage, input: undefined, output: undefined, failed: false })\n\t\t}\n\t\tconst digest = digestValue({\n\t\t\ttext,\n\t\t\ttemplateId,\n\t\t\ttemplateVersion,\n\t\t\tsubject: undefined,\n\t\t\tdefinition: undefined,\n\t\t})\n\t\tconst result: Interpretation = {\n\t\t\ttext,\n\t\t\tnormalized,\n\t\t\tintent,\n\t\t\tentities,\n\t\t\tmappings: [],\n\t\t\tambiguities,\n\t\t\tprompt: '',\n\t\t\tstages,\n\t\t\tfailures: [...failures],\n\t\t\tcomplete: false,\n\t\t\tconfidence: 0,\n\t\t\tdigest,\n\t\t}\n\t\tthis.#context.add(result)\n\t\tthis.#emitter.emit('interpret', result)\n\t\treturn result\n\t}\n\n\t#ensureAlive(): void {\n\t\tif (this.#destroyed) throw new InterpretError('DESTROYED', 'Interpret has been destroyed')\n\t}\n}\n","import type {\n\tClarifierInterface,\n\tClarifierOptions,\n\tDefinitionManagerInterface,\n\tDefinitionManagerOptions,\n\tExtractorInterface,\n\tExtractorOptions,\n\tFormatterInterface,\n\tFormatterOptions,\n\tGeneratorInterface,\n\tGeneratorOptions,\n\tInterpretContextInterface,\n\tInterpretContextOptions,\n\tInterpretInterface,\n\tInterpretOptions,\n\tNarratorInterface,\n\tNarratorOptions,\n\tNormalizerInterface,\n\tNormalizerOptions,\n\tSubjectManagerInterface,\n\tSubjectManagerOptions,\n\tTemplate,\n\tTemplateManagerInterface,\n\tTemplateManagerOptions,\n} from './types.js'\nimport { InterpretError } from './errors.js'\nimport { isTemplate } from './validators.js'\nimport { Interpret } from './Interpret.js'\nimport { Narrator } from './Narrator.js'\nimport { InterpretContext } from './managers/InterpretContext.js'\nimport { TemplateManager } from './managers/TemplateManager.js'\nimport { SubjectManager } from './managers/SubjectManager.js'\nimport { DefinitionManager } from './managers/DefinitionManager.js'\nimport { Clarifier } from './stages/Clarifier.js'\nimport { Extractor } from './stages/Extractor.js'\nimport { Formatter } from './stages/Formatter.js'\nimport { Generator } from './stages/Generator.js'\nimport { Normalizer } from './stages/Normalizer.js'\n\n/**\n * Create an interpretation orchestrator.\n *\n * @remarks\n * `interpret()` is genuinely synchronous and runs the fixed five-stage\n * pipeline `[normalize, extract, clarify, format, generate]`. Every stage\n * slot (`normalizer` / `extractor` / `clarifier` / `formatter` / `generator`)\n * is bring-your-own — a supplied implementation is used as-is, else the\n * built-in stage is constructed from the matching per-stage options.\n *\n * @param options - Optional templates, context, stage implementations, the\n * `similarity` / `floor` axes, and emitter hooks\n * @returns A working {@link InterpretInterface}\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { createInterpret } from '@src/core'\n *\n * const interpret = createInterpret({\n * \textractor: { extract: () => ({ intent: { action: 'calculate', domain: 'arithmetic', confidence: 1 }, numbers: [42], complete: true }) },\n * \ttemplates: [\n * \t\t{\n * \t\t\tid: 't1',\n * \t\t\tname: 'Arithmetic',\n * \t\t\tdomain: 'arithmetic',\n * \t\t\tintents: ['calculate'],\n * \t\t\tmappings: [{ entity: 'value', aliases: [], field: 'value' }],\n * \t\t\tdefaults: [],\n * \t\t\tcomputations: [],\n * \t\t\tdefinition: quantitativeDefinition('t1', 'Arithmetic', [\n * \t\t\t\tfactorGroup('total', 'sum', [fieldFactor('value', 'value')]),\n * \t\t\t]),\n * \t\t},\n * \t],\n * })\n * interpret.interpret('calculate arithmetic 42').subject // { value: 42 }\n * ```\n */\nexport function createInterpret(options?: InterpretOptions): InterpretInterface {\n\treturn new Interpret(options)\n}\n\n/**\n * Create a text normalizer.\n *\n * @param options - Optional contraction / abbreviation / correction maps,\n * merged over the neutral built-in defaults\n * @returns A stateless {@link NormalizerInterface}\n *\n * @example\n * ```ts\n * import { createNormalizer } from '@src/core'\n *\n * createNormalizer().normalize(\"it's cold\") // { text: 'it is cold', changes: [{ from: \"it's\", to: 'it is' }] }\n * ```\n */\nexport function createNormalizer(options?: NormalizerOptions): NormalizerInterface {\n\treturn new Normalizer(options)\n}\n\n/**\n * Create a template-agnostic intent classifier and number extractor.\n *\n * @param options - Optional caller `actions` / `domains` vocabularies\n * @returns A stateless {@link ExtractorInterface}\n *\n * @example\n * ```ts\n * import { createExtractor } from '@src/core'\n *\n * const extractor = createExtractor({\n * \tactions: { calculate: 'calculate' },\n * \tdomains: { arithmetic: ['arithmetic'] },\n * })\n * extractor.extract('calculate arithmetic 42').numbers // [42]\n * ```\n */\nexport function createExtractor(options?: ExtractorOptions): ExtractorInterface {\n\treturn new Extractor(options)\n}\n\n/**\n * Create a clarifier — carry-over, defaults, and computed-field resolution\n * against an assigned entity set.\n *\n * @param options - Optional confidence `floor` for raised ambiguities\n * @returns A stateless {@link ClarifierInterface}\n *\n * @example\n * ```ts\n * import { createClarifier } from '@src/core'\n *\n * const clarifier = createClarifier({ floor: 0.5 })\n * ```\n */\nexport function createClarifier(options?: ClarifierOptions): ClarifierInterface {\n\treturn new Clarifier(options)\n}\n\n/**\n * Create a prompt formatter.\n *\n * @param options - Optional caller intent-verb phrasing map\n * @returns A stateless {@link FormatterInterface}\n *\n * @example\n * ```ts\n * import { createFormatter } from '@src/core'\n *\n * const formatter = createFormatter({ verbs: { calculate: 'Calculate' } })\n * ```\n */\nexport function createFormatter(options?: FormatterOptions): FormatterInterface {\n\treturn new Formatter(options)\n}\n\n/**\n * Create a subject/definition generator.\n *\n * @param options - Currently an empty extension seam\n * @returns A stateless {@link GeneratorInterface}\n *\n * @example\n * ```ts\n * import { createGenerator } from '@src/core'\n *\n * const generator = createGenerator()\n * ```\n */\nexport function createGenerator(_options?: GeneratorOptions): GeneratorInterface {\n\treturn new Generator()\n}\n\n/**\n * Create a template registry.\n *\n * @param options - Optional initial seed collection\n * @returns A working {@link TemplateManagerInterface}\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { createTemplate, createTemplateManager } from '@src/core'\n *\n * const template = createTemplate({\n * \tid: 't1', name: 'Arithmetic', domain: 'arithmetic', intents: ['calculate'],\n * \tmappings: [{ entity: 'value', aliases: [], field: 'value' }], defaults: [], computations: [],\n * \tdefinition: quantitativeDefinition('t1', 'Arithmetic', [factorGroup('total', 'sum', [fieldFactor('value', 'value')])]),\n * })\n * const templates = createTemplateManager({ templates: [template] })\n * templates.size // 1\n * ```\n */\nexport function createTemplateManager(options?: TemplateManagerOptions): TemplateManagerInterface {\n\treturn new TemplateManager(options)\n}\n\n/**\n * Create a subject registry.\n *\n * @remarks\n * Mints its own record ids on `add` when none is supplied — a `Subject`\n * carries no `id` field of its own.\n *\n * @param options - Optional initial seed collection\n * @returns A working {@link SubjectManagerInterface}\n *\n * @example\n * ```ts\n * import { createSubjectManager } from '@src/core'\n *\n * const subjects = createSubjectManager({ subjects: [{ value: 1 }] })\n * subjects.size // 1\n * ```\n */\nexport function createSubjectManager(options?: SubjectManagerOptions): SubjectManagerInterface {\n\treturn new SubjectManager(options)\n}\n\n/**\n * Create a definition registry.\n *\n * @param options - Optional initial seed collection\n * @returns A working {@link DefinitionManagerInterface}\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { createDefinitionManager } from '@src/core'\n *\n * const definitions = createDefinitionManager({\n * \tdefinitions: [quantitativeDefinition('d1', 'D1', [factorGroup('total', 'sum', [fieldFactor('value', 'value')])])],\n * })\n * definitions.size // 1\n * ```\n */\nexport function createDefinitionManager(\n\toptions?: DefinitionManagerOptions,\n): DefinitionManagerInterface {\n\treturn new DefinitionManager(options)\n}\n\n/**\n * Create a cross-turn interpretation context.\n *\n * @param options - Optional `session` label and `history` ring-buffer cap\n * @returns A working {@link InterpretContextInterface}\n *\n * @example\n * ```ts\n * import { createInterpretContext } from '@src/core'\n *\n * const context = createInterpretContext({ session: 'turn-1', history: 4 })\n * context.previous() // []\n * ```\n */\nexport function createInterpretContext(\n\toptions?: InterpretContextOptions,\n): InterpretContextInterface {\n\treturn new InterpretContext(options)\n}\n\n/**\n * Build and validate one interpretation template from plain data.\n *\n * @remarks\n * The factory/coercer pair for template intake (AGENTS §4.6.1): this throws\n * on malformed data, while `parseTemplate` returns `undefined`. Data failing\n * {@link isTemplate} throws `InterpretError('INVALID_TEMPLATE', …)`.\n *\n * @param data - The candidate template data\n * @returns The same data, now known to satisfy {@link Template}\n * @throws {@link InterpretError} `INVALID_TEMPLATE` when `data` fails validation\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { createTemplate } from '@src/core'\n *\n * const template = createTemplate({\n * \tid: 't1', name: 'Arithmetic', domain: 'arithmetic', intents: ['calculate'],\n * \tmappings: [{ entity: 'value', aliases: [], field: 'value' }], defaults: [], computations: [],\n * \tdefinition: quantitativeDefinition('t1', 'Arithmetic', [factorGroup('total', 'sum', [fieldFactor('value', 'value')])]),\n * })\n * template.id // 't1'\n * ```\n */\nexport function createTemplate(data: Template): Template {\n\tif (!isTemplate(data)) {\n\t\tthrow new InterpretError('INVALID_TEMPLATE', 'Template data failed validation')\n\t}\n\treturn data\n}\n\n/**\n * Create a lexicon-driven reverse-direction rendering engine.\n *\n * @remarks\n * Stateless — `phrase` / `label` / `line` / `value` are total lookups into a\n * caller `Lexicon` merged over `DEFAULT_LEXICON`, and `describe` / `narrate`\n * compose them over a reasons `Definition` / `ReasonResult`.\n *\n * @param options - Optional `lexicon` and `formatters` map\n * @returns A stateless {@link NarratorInterface}\n *\n * @example\n * ```ts\n * import { createNarrator } from '@src/core'\n *\n * const narrator = createNarrator({ lexicon: { templates: { 'subject.empty': 'nothing here' } } })\n * narrator.line('subject.empty', {}) // 'nothing here'\n * ```\n */\nexport function createNarrator(options?: NarratorOptions): NarratorInterface {\n\treturn new Narrator(options)\n}\n"],"mappings":";;;;;;;;;;;;;AAkBA,IAAa,+BAA+B;;;;;;AAO5C,IAAa,0BAA0B;;AAGvC,IAAa,4BAA4B;;AAGzC,IAAa,eAAe;;AAG5B,IAAa,mBAAmB;;AAGhC,IAAa,mB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ter","#destroyed","#session","#subjects","#definitions","#history","#previous","#emitter","#ensureAlive","#destroyed","#records","#emitter","#ensureAlive","#destroyed","#lexicon","#formatters","#floor","#carryOver","#fillDefaults","#resolveComputations","#collectAmbiguities","#orderComputations","#actions","#domains","#verbs","#contractions","#abbreviations","#corrections","#applyStage","#templates","#context","#normalizer","#extractor","#clarifier","#formatter","#generator","#similarity","#floor","#narrator","#emitter","#ensureAlive","#abort","#gate","#destroyed","#assemble"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/managers/DefinitionManager.ts","../../../src/core/managers/SubjectManager.ts","../../../src/core/managers/InterpretContext.ts","../../../src/core/managers/TemplateManager.ts","../../../src/core/Narrator.ts","../../../src/core/stages/Clarifier.ts","../../../src/core/stages/Extractor.ts","../../../src/core/stages/Formatter.ts","../../../src/core/stages/Generator.ts","../../../src/core/stages/Normalizer.ts","../../../src/core/Interpret.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { Lexicon } from './types.js'\n\n// Frozen default data for the interprets module (AGENTS §5 — constants are\n// UPPER_SNAKE_CASE data, the sole home for module-scope literal defaults).\n// Every vocabulary map here is intentionally NEUTRAL and small — domain\n// worldview (insurance verbs, en-US misspelling corrections, business\n// domains) is the caller's business, supplied via options (AGENTS-flagged\n// scsr defect: a \"generic\" core module baked in ~100 hardcoded corrections).\n\n/**\n * Default `similarity` for `createInterpret` / `matchAlias` — the fuzzy\n * alias-match score threshold (0..1).\n *\n * @remarks\n * Domain-qualified (not a bare `DEFAULT_SIMILARITY`) so the name stays free\n * of collision on the shared `@src/core` barrel, mirroring the\n * `DEFAULT_REASON_BAIL` precedent.\n */\nexport const DEFAULT_INTERPRET_SIMILARITY = 0.8\n\n/**\n * Default `floor` for `createInterpret` / `matchTemplate` — the minimum\n * intent confidence a template match (or the classified intent itself) must\n * clear.\n */\nexport const DEFAULT_INTERPRET_FLOOR = 0.3\n\n/** Default `history` cap for an `InterpretContext`'s `previous()` ring buffer. */\nexport const DEFAULT_INTERPRET_HISTORY = 16\n\n/** Default `id` for an `Interpret` orchestrator. */\nexport const INTERPRET_ID = 'interpret'\n\n/** Confidence assigned to an exact keyword-proximity entity match. */\nexport const CONFIDENCE_EXACT = 1\n\n/** Confidence assigned to an exact alias-phrase entity match. */\nexport const CONFIDENCE_ALIAS = 0.9\n\n/** Confidence assigned when a single entity mapping collects every extracted number. */\nexport const CONFIDENCE_COLLECT = 0.9\n\n/** Confidence assigned to a positional (order-based) entity match fallback. */\nexport const CONFIDENCE_POSITIONAL = 0.7\n\n/** Confidence assigned to a same-domain carried-over field. */\nexport const CONFIDENCE_CARRIED = 0.7\n\n/** Confidence assigned to a template default fill. */\nexport const CONFIDENCE_DEFAULT = 1\n\n/** Confidence assigned to a successfully resolved computed field. */\nexport const CONFIDENCE_COMPUTED = 0.9\n\n/**\n * The numeric-entity extraction pattern shared by `extractNumbers` and\n * `assignEntities` — an optional leading `$`, thousands-comma-grouped digits,\n * an optional decimal fraction, and an optional trailing `%`.\n *\n * @remarks\n * Carries the global flag, so every call site builds a fresh `RegExp` from\n * `.source` / `.flags` (mirrors the core-root `PLACEHOLDER_PATTERN` pattern)\n * rather than sharing this instance's mutable `lastIndex` across scans.\n */\nexport const NUMBER_PATTERN = /(?:\\$\\s*)?(\\d+(?:,\\d{3})*(?:\\.\\d+)?)\\s*%?/g\n\n/**\n * Prototype-pollution-unsafe field-path segments — `setField` refuses to\n * write ANY path containing one, returning its input unchanged.\n */\nexport const UNSAFE_FIELD_SEGMENTS: readonly string[] = Object.freeze([\n\t'__proto__',\n\t'prototype',\n\t'constructor',\n])\n\n/**\n * Neutral built-in contraction expansions for `Normalizer` — small on\n * purpose; callers merge their own map over this one.\n */\nexport const DEFAULT_CONTRACTIONS: Readonly<Record<string, string>> = Object.freeze({\n\t\"can't\": 'cannot',\n\t\"won't\": 'will not',\n\t\"it's\": 'it is',\n\t\"don't\": 'do not',\n})\n\n/** Neutral built-in abbreviation expansions for `Normalizer` — empty by default. */\nexport const DEFAULT_ABBREVIATIONS: Readonly<Record<string, string>> = Object.freeze({})\n\n/** Neutral built-in misspelling corrections for `Normalizer` — empty by default. */\nexport const DEFAULT_CORRECTIONS: Readonly<Record<string, string>> = Object.freeze({})\n\n/** Neutral built-in action-verb vocabulary for `Extractor#extract`'s intent classification — empty by default. */\nexport const DEFAULT_ACTIONS: Readonly<Record<string, string>> = Object.freeze({})\n\n/** Neutral built-in domain-keyword vocabulary for `Extractor#extract`'s intent classification — empty by default. */\nexport const DEFAULT_DOMAINS: Readonly<Record<string, readonly string[]>> = Object.freeze({})\n\n/** Neutral built-in intent-verb phrasing for `Formatter#format` — empty by default. */\nexport const DEFAULT_VERBS: Readonly<Record<string, string>> = Object.freeze({})\n\n/**\n * The neutral default `Lexicon` a `Narrator` merges caller data over.\n *\n * @remarks\n * `phrases` and `labels` are empty — there is no built-in vocabulary or\n * label overrides (AGENTS §21 mechanism-never-policy). `templates` carries\n * the structural, display-neutral strings the reverse helpers formerly\n * hardcoded, keyed by\n * `{table}.{reasoning}` for the four reasons kinds, `result.quantitative.failed`\n * for the quantitative-result failure suffix, and `subject.fields` /\n * `subject.empty` for `describeSubject`. Every string is a plain\n * @orkestrel/template `fillTemplate` template — `{{name}}`-style placeholders\n * resolved against the caller-supplied `values` record.\n */\nexport const DEFAULT_LEXICON: Lexicon = Object.freeze({\n\tphrases: Object.freeze({}),\n\tlabels: Object.freeze({}),\n\ttemplates: Object.freeze({\n\t\t'definition.quantitative': '{{name}}: {{count}} factor group(s)',\n\t\t'definition.logical': '{{name}}: {{count}} rule(s), strategy {{strategy}}',\n\t\t'definition.symbolic': '{{name}}: solve {{count}} equation(s)',\n\t\t'definition.inferential':\n\t\t\t'{{name}}: {{facts}} fact(s)/{{inferences}} inference(s), {{strategy}}',\n\t\t'result.quantitative': 'scored {{value}} across {{count}} group(s)',\n\t\t'result.quantitative.failed': '; failed: {{errors}}',\n\t\t'result.logical': '{{status}}: {{count}} rule(s)',\n\t\t'result.symbolic': 'solved {{solved}}',\n\t\t'result.inferential': 'derived {{count}} fact(s)',\n\t\t'subject.fields': 'with {{fields}}',\n\t\t'subject.empty': 'with no fields',\n\t}),\n})\n","import type { InterpretErrorCode } from './types.js'\n\n// AGENTS §12: misuse of the interprets layer `throw`s an `InterpretError`\n// carrying a machine-readable `code`, so a `catch` branches on `error.code`.\n\n/**\n * An error thrown by the interprets layer.\n *\n * @remarks\n * Thrown for: an injected stage implementation throwing during its phase\n * (`NORMALIZE_FAILED` / `EXTRACT_FAILED` / `CLARIFY_FAILED` /\n * `FORMAT_FAILED` / `GENERATE_FAILED`), `createTemplate` handed data that\n * fails `isTemplate` (`INVALID_TEMPLATE`), and any use of a destroyed\n * `Interpret` / manager / context (`DESTROYED`). `NO_TEMPLATE` and\n * `LOW_CONFIDENCE` never throw — they surface as a visible incomplete\n * {@link Interpretation} instead (never an arbitrary fallback template).\n * `context`, when present, carries the offending stage / template id.\n */\nexport class InterpretError extends Error {\n\treadonly code: InterpretErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: InterpretErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'InterpretError'\n\t\tthis.code = code\n\t\tthis.context = context\n\t}\n}\n\n/**\n * Narrow an unknown caught value to an {@link InterpretError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is an {@link InterpretError}\n *\n * @example\n * ```ts\n * import { isInterpretError } from '@src/core'\n *\n * try {\n * \tinterpret.template('missing')\n * } catch (error) {\n * \tif (isInterpretError(error) && error.code === 'DESTROYED') return\n * }\n * ```\n */\nexport function isInterpretError(value: unknown): value is InterpretError {\n\treturn value instanceof InterpretError\n}\n","import type { ComputedField, EntityMapping, FieldDefault, Template } from './types.js'\nimport { arrayOf, isBoolean, isString, notOf, recordOf, unionOf } from '@orkestrel/contract'\nimport { isDefinition, isFieldPath, isSymbolicExpression } from '@orkestrel/reason'\n\n// AGENTS §14: every guard here is a TOTAL function — adversarial input (junk,\n// hostile prototypes, cyclic/deep nesting) returns `false`, never throws.\n// Every record guard is EXACT (`recordOf`): an extra key fails. `isTemplate`\n// composes reasons' exported `isSymbolicExpression` (already recursive\n// through `lazyOf`) and `isDefinition` rather than minting local duplicates —\n// a second `isSymbolicExpression` would collide under the shared `@src/core`\n// barrel's `export *` (TypeScript silently drops BOTH conflicting star\n// re-exports), breaking reasons' own guard and failing the AGENTS §22 parity\n// gate. `interprets` therefore owns no recursive expression guard of its own.\n\n/**\n * Determine whether a value is an {@link EntityMapping} — a literal\n * alias-phrase extraction rule pointing at a subject field.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed entity mapping\n *\n * @example\n * ```ts\n * import { isEntityMapping } from '@src/core'\n *\n * isEntityMapping({ entity: 'age', aliases: ['years old'], field: 'age' }) // true\n * isEntityMapping({ entity: 'age', aliases: [/\\d+/], field: 'age' }) // false — RegExp alias\n * ```\n */\nexport function isEntityMapping(value: unknown): value is EntityMapping {\n\treturn recordOf(\n\t\t{\n\t\t\tentity: isString,\n\t\t\taliases: arrayOf(isString),\n\t\t\tfield: isFieldPath,\n\t\t\trequired: isBoolean,\n\t\t},\n\t\t['required'],\n\t)(value)\n}\n\n/**\n * Determine whether a value is a {@link FieldDefault} — a fallback value a\n * {@link Template} fills onto an unresolved field.\n *\n * @remarks\n * `value` is unconstrained (any value, including `null` or `undefined`) as\n * long as the key is present — the trivially-true guard `notOf(unionOf())`\n * mirrors the reasons `Check.value` precedent.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed field default\n *\n * @example\n * ```ts\n * import { isFieldDefault } from '@src/core'\n *\n * isFieldDefault({ field: 'term', value: 12 }) // true\n * isFieldDefault({ field: 'term' }) // false — value missing\n * ```\n */\nexport function isFieldDefault(value: unknown): value is FieldDefault {\n\treturn recordOf({ field: isFieldPath, value: notOf(unionOf()) })(value)\n}\n\n/**\n * Determine whether a value is a {@link ComputedField} — a declaratively\n * computed field carrying a reasons {@link SymbolicExpression} tree.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed computed field\n *\n * @example\n * ```ts\n * import { constant, operation, variable } from '@orkestrel/reason'\n * import { isComputedField } from '@src/core'\n *\n * isComputedField({\n * \tfield: 'monthly',\n * \texpression: operation('divide', variable('deductible'), constant(12)),\n * }) // true\n * isComputedField({ field: 'monthly', expression: { form: 'variable' } }) // false — name missing\n * ```\n */\nexport function isComputedField(value: unknown): value is ComputedField {\n\treturn recordOf({ field: isFieldPath, expression: isSymbolicExpression })(value)\n}\n\n/**\n * Determine whether a value is a {@link Template} — a named, versionable\n * interpretation template.\n *\n * @remarks\n * `definition` is validated with reasons' `isDefinition` — a `Template`'s\n * definition is already expressed in terrain reasons vocabulary, so no\n * parallel interprets-owned definition guard exists.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed template\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { isTemplate } from '@src/core'\n *\n * isTemplate({\n * \tid: 't1',\n * \tname: 'Arithmetic',\n * \tdomain: 'arithmetic',\n * \tintents: ['calculate'],\n * \tmappings: [],\n * \tdefaults: [],\n * \tcomputations: [],\n * \tdefinition: quantitativeDefinition('t1', 'Arithmetic', [\n * \t\tfactorGroup('total', 'sum', [fieldFactor('value', 'value')]),\n * \t]),\n * }) // true\n * isTemplate({ id: 't1' }) // false — most fields missing\n * ```\n */\nexport function isTemplate(value: unknown): value is Template {\n\treturn recordOf({\n\t\tid: isString,\n\t\tname: isString,\n\t\tdomain: isString,\n\t\tintents: arrayOf(isString),\n\t\tmappings: arrayOf(isEntityMapping),\n\t\tdefaults: arrayOf(isFieldDefault),\n\t\tcomputations: arrayOf(isComputedField),\n\t\tdefinition: isDefinition,\n\t})(value)\n}\n","import type { FieldPath } from '@orkestrel/contract'\nimport type { Subject, SymbolicExpression } from '@orkestrel/reason'\nimport type { Entity, EntityMapping, Intent, NarratorInterface, Template } from './types.js'\nimport { isFiniteNumber, isRecord, parseJSONAs } from '@orkestrel/contract'\nimport { applyOperation } from '@orkestrel/reason'\nimport {\n\tCONFIDENCE_ALIAS,\n\tCONFIDENCE_COLLECT,\n\tCONFIDENCE_EXACT,\n\tCONFIDENCE_POSITIONAL,\n\tNUMBER_PATTERN,\n\tUNSAFE_FIELD_SEGMENTS,\n} from './constants.js'\nimport { isTemplate } from './validators.js'\n\n// The interprets pure-leaf inventory (AGENTS §5/§7) — every function here is\n// a referentially-transparent computation with no instance state, exported\n// and independently unit-testable. Stateful orchestration (the five-stage\n// pipeline, entity assignment sequencing, template registration) lives on the\n// `Interpret` orchestrator and its stage classes, never here.\n\n// === Regex safety\n\n/**\n * Escape every regex metacharacter in `text` so it matches literally when\n * compiled into a `RegExp`.\n *\n * @param text - The literal text to escape\n * @returns `text` with every regex metacharacter backslash-escaped\n *\n * @example\n * ```ts\n * import { escapeRegExp } from '@src/core'\n *\n * escapeRegExp('a.b*c') // 'a\\\\.b\\\\*c'\n * new RegExp(escapeRegExp('a.b*c')).test('a.b*c') // true\n * ```\n */\nexport function escapeRegExp(text: string): string {\n\treturn text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n// === Field paths — safe copy-on-write writes\n\n/**\n * Copy-on-write write a value at a (possibly nested) field path on a subject.\n *\n * @remarks\n * Never mutates `subject` — every level a `field` array descends through is\n * freshly copied, so the input and every intermediate record stay untouched\n * (AGENTS §11). Prototype-pollution-safe: a `field` containing `__proto__`,\n * `prototype`, or `constructor` at ANY segment (checked against\n * `UNSAFE_FIELD_SEGMENTS`) is refused as a no-op, returning `subject`\n * unchanged. A non-record value already sitting at an intermediate segment is\n * replaced by a fresh record rather than descended into.\n *\n * @param subject - The subject to derive from\n * @param field - The (possibly nested) field path to write\n * @param value - The value to write\n * @returns A fresh subject with `value` written at `field`, or `subject`\n * unchanged when `field` carries an unsafe segment\n *\n * @example\n * ```ts\n * import { setField } from '@src/core'\n *\n * setField({ age: 25 }, 'age', 30) // { age: 30 }\n * setField({}, ['address', 'city'], 'Reno') // { address: { city: 'Reno' } }\n * setField({}, ['__proto__', 'polluted'], true) // {} — refused, unchanged\n * ```\n */\n/**\n * Derive the sibling field path for a computed aggregate of `field` — the\n * suffix is appended to `field`'s OWN last segment, so the aggregate nests\n * beside the source field rather than flattening past it.\n *\n * @remarks\n * For an array {@link FieldPath} (e.g. `['address', 'amounts']`) with suffix\n * `'Sum'` the result is `['address', 'amountsSum']` — nested beside\n * `address.amounts`. For a plain string field the result stays a flat string\n * (`'amounts'` → `'amountsSum'`), matching the existing single-key behavior.\n *\n * @param field - The source field path\n * @param suffix - The aggregate suffix (`'Sum'`, `'Count'`, `'Average'`, `'Minimum'`, `'Maximum'`)\n * @returns The sibling field path for the aggregate\n *\n * @example\n * ```ts\n * import { deriveAggregateField } from '@src/core'\n *\n * deriveAggregateField(['address', 'amounts'], 'Sum') // ['address', 'amountsSum']\n * deriveAggregateField('amounts', 'Sum') // 'amountsSum'\n * ```\n */\nexport function deriveAggregateField(field: FieldPath, suffix: string): FieldPath {\n\tif (Array.isArray(field)) {\n\t\tconst last = field[field.length - 1]\n\t\treturn [...field.slice(0, -1), `${last}${suffix}`]\n\t}\n\treturn `${field}${suffix}`\n}\n\nexport function setField(subject: Subject, field: FieldPath, value: unknown): Subject {\n\tconst path = Array.isArray(field) ? field : [field]\n\tif (path.length === 0) return subject\n\tif (path.some((segment) => UNSAFE_FIELD_SEGMENTS.includes(segment))) return subject\n\tconst [key, ...rest] = path\n\tif (key === undefined) return subject\n\tif (rest.length === 0) return { ...subject, [key]: value }\n\tconst child = subject[key]\n\tconst nested = isRecord(child) ? child : {}\n\treturn { ...subject, [key]: setField(nested, rest, value) }\n}\n\n// === Normalization\n\n/**\n * Replace every whole-word occurrence of a map's keys with their values.\n *\n * @remarks\n * Word-boundary safe (`in` never matches inside `information`) and\n * case-insensitive; each key is regex-escaped via the core-root\n * `escapeRegExp` before compiling, so a caller-supplied phrase containing\n * regex metacharacters is matched literally. Multiple keys apply in\n * `Object.entries` order — the `Normalizer` stage sequences its three maps\n * (contractions, abbreviations, corrections) with three separate calls.\n *\n * @param text - The text to substitute within\n * @param map - The `{ from: to }` substitution map\n * @returns `text` with every whole-word match replaced\n *\n * @example\n * ```ts\n * import { applyReplacements } from '@src/core'\n *\n * applyReplacements(\"can't stop\", { \"can't\": 'cannot' }) // 'cannot stop'\n * applyReplacements('information', { in: 'IN' }) // 'information' — word-boundary safe\n * ```\n */\nexport function applyReplacements(text: string, map: Readonly<Record<string, string>>): string {\n\tlet result = text\n\tfor (const [from, to] of Object.entries(map)) {\n\t\tconst pattern = new RegExp(`\\\\b${escapeRegExp(from)}\\\\b`, 'gi')\n\t\tresult = result.replace(pattern, to)\n\t}\n\treturn result\n}\n\n/**\n * Collapse every run of whitespace to a single space and trim the ends.\n *\n * @param text - The text to collapse\n * @returns The collapsed text\n *\n * @example\n * ```ts\n * import { collapseWhitespace } from '@src/core'\n *\n * collapseWhitespace(' a b\\t c ') // 'a b c'\n * ```\n */\nexport function collapseWhitespace(text: string): string {\n\treturn text.replace(/\\s+/g, ' ').trim()\n}\n\n// === Tokenization (internal plumbing shared by extraction & classification)\n\n/**\n * Split text into lowercase tokens, stripping punctuation outside a small\n * numeric/currency-safe allowlist.\n *\n * @remarks\n * Shared by `classifyIntent` and `assignEntities` — pure ECMAScript\n * (no locale-aware `Intl` segmentation), so multi-byte / astral text tokenizes\n * on ASCII word boundaries only.\n *\n * @param text - The text to tokenize\n * @returns The lowercase tokens, punctuation-stripped, empty tokens dropped\n *\n * @example\n * ```ts\n * import { tokenize } from '@src/core'\n *\n * tokenize('The rate is 85%.') // ['the', 'rate', 'is', '85%']\n * ```\n */\nexport function tokenize(text: string): readonly string[] {\n\treturn text\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9\\s./%$'-]/g, ' ')\n\t\t.split(/\\s+/)\n\t\t.filter((token) => token.length > 0)\n}\n\n// === Extraction\n\n/**\n * Mine every numeric literal from text — optional leading `$`, thousands\n * commas, an optional decimal fraction, an optional trailing `%`.\n *\n * @remarks\n * Numbers-only: this is the module's entire extraction contract (AGENTS\n * §21 mechanism-never-policy) — no date, text-entity, or negation parsing.\n *\n * @param text - The text to scan\n * @returns Every extracted number, in left-to-right order\n *\n * @example\n * ```ts\n * import { extractNumbers } from '@src/core'\n *\n * extractNumbers('income was $50,000, age 25') // [50000, 25]\n * ```\n */\nexport function extractNumbers(text: string): readonly number[] {\n\tconst pattern = new RegExp(NUMBER_PATTERN.source, NUMBER_PATTERN.flags)\n\tconst numbers: number[] = []\n\tlet match = pattern.exec(text)\n\twhile (match !== null) {\n\t\tconst raw = match[1]\n\t\tif (raw !== undefined) {\n\t\t\tconst value = Number(raw.replace(/,/g, ''))\n\t\t\tif (Number.isFinite(value)) numbers.push(value)\n\t\t}\n\t\tmatch = pattern.exec(text)\n\t}\n\treturn numbers\n}\n\n/**\n * Assign already-extracted numbers to a matched template's entity mappings.\n *\n * @remarks\n * Strategy, in order: (1) a SINGLE mapping collects every number (an array\n * when more than one, a scalar otherwise) at `CONFIDENCE_COLLECT`. Otherwise,\n * per mapping, the rightmost token in the text that equals the entity name\n * (`CONFIDENCE_EXACT`), an alias exactly (`CONFIDENCE_ALIAS`), or an alias\n * fuzzily (via `matchAlias`, confidence = its returned score) becomes a\n * keyword anchor; anchors sort left-to-right and each claims its nearest\n * unused number by text position. (3) Any mapping still unfilled claims the\n * next unused number positionally, at `CONFIDENCE_POSITIONAL`. Every entity\n * carries provenance `category: 'extracted'` with `detail` naming the\n * strategy that filled it (`'collect' | 'keyword' | 'alias' | 'positional'`).\n * Runs ONLY after a template has matched (an orchestrator-owned step, never\n * inside `Extractor`, which stays template-agnostic).\n *\n * @param numbers - The numbers already extracted from `text` via `extractNumbers`\n * @param mappings - The matched template's entity mappings\n * @param text - The same text `numbers` was extracted from (for keyword proximity)\n * @param similarity - The fuzzy alias-match score threshold (0..1)\n * @returns The assigned entities, one per filled mapping\n *\n * @example\n * ```ts\n * import { assignEntities } from '@src/core'\n *\n * const mappings = [\n * \t{ entity: 'age', aliases: ['years old'], field: 'age' },\n * \t{ entity: 'score', aliases: ['credit score'], field: 'score' },\n * ]\n * assignEntities([25, 720], mappings, '25 year old with score 720', 0.8)\n * // [{ name: 'age', value: 25, ... }, { name: 'score', value: 720, ... }]\n * ```\n */\nexport function assignEntities(\n\tnumbers: readonly number[],\n\tmappings: readonly EntityMapping[],\n\ttext: string,\n\tsimilarity: number,\n): readonly Entity[] {\n\tif (mappings.length === 0 || numbers.length === 0) return []\n\n\tif (mappings.length === 1) {\n\t\tconst mapping = mappings[0]\n\t\tif (mapping === undefined) return []\n\t\treturn [\n\t\t\t{\n\t\t\t\tname: mapping.entity,\n\t\t\t\tvalue: numbers.length === 1 ? numbers[0] : numbers,\n\t\t\t\tprovenance: { category: 'extracted', detail: 'collect' },\n\t\t\t\tconfidence: CONFIDENCE_COLLECT,\n\t\t\t},\n\t\t]\n\t}\n\n\tconst tokens = tokenize(text)\n\tconst lowerText = text.toLowerCase()\n\n\tconst positions: number[] = []\n\tconst positionPattern = new RegExp(NUMBER_PATTERN.source, NUMBER_PATTERN.flags)\n\tlet positionMatch = positionPattern.exec(text)\n\twhile (positionMatch !== null) {\n\t\tpositions.push(positionMatch.index)\n\t\tpositionMatch = positionPattern.exec(text)\n\t}\n\n\tconst keywordMatches: {\n\t\tmapping: EntityMapping\n\t\tposition: number\n\t\tconfidence: number\n\t\tdetail: 'keyword' | 'alias'\n\t}[] = []\n\n\tfor (const mapping of mappings) {\n\t\tlet matchedPosition = -1\n\t\tlet matchedConfidence = 0\n\t\tlet matchedDetail: 'keyword' | 'alias' = 'keyword'\n\t\tconst entityToken = mapping.entity.toLowerCase()\n\n\t\tfor (const token of tokens) {\n\t\t\tconst tokenPosition = lowerText.indexOf(token)\n\t\t\tif (token === entityToken) {\n\t\t\t\tif (tokenPosition > matchedPosition) {\n\t\t\t\t\tmatchedPosition = tokenPosition\n\t\t\t\t\tmatchedConfidence = CONFIDENCE_EXACT\n\t\t\t\t\tmatchedDetail = 'keyword'\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst aliasExact = mapping.aliases.some((alias) => alias.toLowerCase() === token)\n\t\t\tif (aliasExact) {\n\t\t\t\tif (tokenPosition > matchedPosition) {\n\t\t\t\t\tmatchedPosition = tokenPosition\n\t\t\t\t\tmatchedConfidence = CONFIDENCE_ALIAS\n\t\t\t\t\tmatchedDetail = 'alias'\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst fuzzy = matchAlias(token, mapping.aliases, similarity)\n\t\t\tif (fuzzy > 0 && tokenPosition > matchedPosition) {\n\t\t\t\tmatchedPosition = tokenPosition\n\t\t\t\tmatchedConfidence = fuzzy\n\t\t\t\tmatchedDetail = 'alias'\n\t\t\t}\n\t\t}\n\n\t\tif (matchedPosition >= 0) {\n\t\t\tkeywordMatches.push({\n\t\t\t\tmapping,\n\t\t\t\tposition: matchedPosition,\n\t\t\t\tconfidence: matchedConfidence,\n\t\t\t\tdetail: matchedDetail,\n\t\t\t})\n\t\t}\n\t}\n\n\tkeywordMatches.sort((a, b) => a.position - b.position)\n\n\tconst used = new Set<number>()\n\tconst filled = new Set<string>()\n\tconst entities: Entity[] = []\n\n\tfor (const match of keywordMatches) {\n\t\tlet bestIndex = -1\n\t\tlet bestDistance = Number.POSITIVE_INFINITY\n\t\tfor (let index = 0; index < numbers.length; index += 1) {\n\t\t\tif (used.has(index)) continue\n\t\t\tconst position = positions[index]\n\t\t\tif (position === undefined) continue\n\t\t\tconst distance = Math.abs(position - match.position)\n\t\t\tif (distance < bestDistance) {\n\t\t\t\tbestDistance = distance\n\t\t\t\tbestIndex = index\n\t\t\t}\n\t\t}\n\t\tif (bestIndex >= 0) {\n\t\t\tconst value = numbers[bestIndex]\n\t\t\tif (value !== undefined) {\n\t\t\t\tused.add(bestIndex)\n\t\t\t\tfilled.add(match.mapping.entity)\n\t\t\t\tentities.push({\n\t\t\t\t\tname: match.mapping.entity,\n\t\t\t\t\tvalue,\n\t\t\t\t\tprovenance: { category: 'extracted', detail: match.detail },\n\t\t\t\t\tconfidence: match.confidence,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tlet numberIndex = 0\n\tfor (const mapping of mappings) {\n\t\tif (filled.has(mapping.entity)) continue\n\t\twhile (numberIndex < numbers.length && used.has(numberIndex)) numberIndex += 1\n\t\tif (numberIndex >= numbers.length) break\n\t\tconst value = numbers[numberIndex]\n\t\tif (value !== undefined) {\n\t\t\tused.add(numberIndex)\n\t\t\tfilled.add(mapping.entity)\n\t\t\tentities.push({\n\t\t\t\tname: mapping.entity,\n\t\t\t\tvalue,\n\t\t\t\tprovenance: { category: 'extracted', detail: 'positional' },\n\t\t\t\tconfidence: CONFIDENCE_POSITIONAL,\n\t\t\t})\n\t\t}\n\t\tnumberIndex += 1\n\t}\n\n\treturn entities\n}\n\n// === Intent classification\n\n/**\n * Classify the action + domain intent of a text against caller-supplied\n * vocabularies.\n *\n * @remarks\n * `actions` maps a token to an action name — the first matching token in\n * `text` (left to right) wins, at `CONFIDENCE_EXACT`. `domains` maps a domain\n * name to its keyword list — the domain with the most matching tokens wins\n * (ties keep the earliest-declared domain), also at `CONFIDENCE_EXACT`.\n * Combined confidence (PINNED): both fire → their average; exactly one fires\n * → its value times `0.5`; neither → `0`. There is no built-in worldview and\n * no auto-classification from a registered template's own `domain` name — a\n * caller MUST list a template's domain among `domains` for it to classify.\n * No `floor` parameter: the confidence floor gate lives at the orchestrator's\n * `matchTemplate` step, never inside classification itself.\n *\n * @param text - The (normalized) text to classify\n * @param actions - The caller's token → action-name vocabulary\n * @param domains - The caller's domain-name → keyword-list vocabulary\n * @returns The classified intent\n *\n * @example\n * ```ts\n * import { classifyIntent } from '@src/core'\n *\n * classifyIntent('calculate my rate', { calculate: 'compute' }, { rating: ['rate'] })\n * // { action: 'compute', domain: 'rating', confidence: 1 }\n * classifyIntent('hello', {}, {}) // { action: '', domain: '', confidence: 0 }\n * ```\n */\nexport function classifyIntent(\n\ttext: string,\n\tactions: Readonly<Record<string, string>>,\n\tdomains: Readonly<Record<string, readonly string[]>>,\n): Intent {\n\tconst tokens = tokenize(text)\n\n\tlet action = ''\n\tlet actionConfidence = 0\n\tfor (const token of tokens) {\n\t\tconst mapped = actions[token]\n\t\tif (mapped !== undefined) {\n\t\t\taction = mapped\n\t\t\tactionConfidence = CONFIDENCE_EXACT\n\t\t\tbreak\n\t\t}\n\t}\n\n\tlet domain = ''\n\tlet domainConfidence = 0\n\tlet bestMatches = 0\n\tfor (const [name, keywords] of Object.entries(domains)) {\n\t\tconst lowerKeywords = keywords.map((keyword) => keyword.toLowerCase())\n\t\tlet matches = 0\n\t\tfor (const token of tokens) {\n\t\t\tif (lowerKeywords.includes(token)) matches += 1\n\t\t}\n\t\tif (matches > bestMatches) {\n\t\t\tbestMatches = matches\n\t\t\tdomain = name\n\t\t\tdomainConfidence = CONFIDENCE_EXACT\n\t\t}\n\t}\n\n\tconst confidence =\n\t\tactionConfidence > 0 && domainConfidence > 0\n\t\t\t? (actionConfidence + domainConfidence) / 2\n\t\t\t: Math.max(actionConfidence, domainConfidence) * 0.5\n\n\treturn { action, domain, confidence }\n}\n\n// === Fuzzy matching\n\n/**\n * Bigram (Dice coefficient) string similarity, case-insensitive.\n *\n * @param a - The first string\n * @param b - The second string\n * @returns A score in `[0, 1]` — `1` for an exact (case-insensitive) match,\n * `0` when either string is shorter than 2 characters and they are not equal\n *\n * @example\n * ```ts\n * import { scoreSimilarity } from '@src/core'\n *\n * scoreSimilarity('rate', 'rate') // 1\n * scoreSimilarity('rate', 'value') // 0 — no shared bigrams\n * ```\n */\nexport function scoreSimilarity(a: string, b: string): number {\n\tconst left = a.toLowerCase()\n\tconst right = b.toLowerCase()\n\tif (left === right) return 1\n\tif (left.length < 2 || right.length < 2) return 0\n\n\tconst bigrams = new Map<string, number>()\n\tfor (let index = 0; index < left.length - 1; index += 1) {\n\t\tconst bigram = left.slice(index, index + 2)\n\t\tbigrams.set(bigram, (bigrams.get(bigram) ?? 0) + 1)\n\t}\n\n\tlet matches = 0\n\tfor (let index = 0; index < right.length - 1; index += 1) {\n\t\tconst bigram = right.slice(index, index + 2)\n\t\tconst count = bigrams.get(bigram)\n\t\tif (count !== undefined && count > 0) {\n\t\t\tbigrams.set(bigram, count - 1)\n\t\t\tmatches += 1\n\t\t}\n\t}\n\n\treturn (2 * matches) / (left.length - 1 + (right.length - 1))\n}\n\n/**\n * The best `scoreSimilarity` a token achieves against a list of aliases,\n * gated by a threshold.\n *\n * @param token - The token to score\n * @param aliases - The alias phrases to score against\n * @param threshold - The minimum score to report (an explicit no-match below it)\n * @returns The best score when it meets `threshold`, else `0`\n *\n * @example\n * ```ts\n * import { matchAlias } from '@src/core'\n *\n * matchAlias('valu', ['value', 'amount'], 0.6) // ~0.86 — fuzzy hit on 'value'\n * matchAlias('xyz', ['value', 'amount'], 0.6) // 0 — no alias clears the threshold\n * ```\n */\nexport function matchAlias(token: string, aliases: readonly string[], threshold: number): number {\n\tlet best = 0\n\tfor (const alias of aliases) {\n\t\tconst score = scoreSimilarity(token, alias)\n\t\tif (score > best) best = score\n\t}\n\treturn best >= threshold ? best : 0\n}\n\n// === Digest\n\n/**\n * Render a value into a canonical, key-order-stable string — the pre-image\n * of `digestValue`.\n *\n * @remarks\n * Ported from the app's `raters` digest machinery (`app/core/raters/helpers.ts`)\n * — record keys sort before serialization so a re-ordered object canonicalizes\n * identically; arrays keep position order (position is meaningful).\n * Cycle-safe and total (AGENTS §14): `visited` tracks the object ancestors\n * along the CURRENT recursion path (not a global \"seen\" set, so the same\n * object reachable twice via non-cyclic sibling branches still canonicalizes\n * normally); revisiting an ancestor renders that node as the literal string\n * `'[cycle]'` instead of recursing — deterministic, never throws, never\n * overflows the call stack.\n *\n * @param value - The value to canonicalize\n * @param visited - The object ancestors along the current recursion path (internal; omit at the call site)\n * @returns The canonical string form\n *\n * @example\n * ```ts\n * import { canonicalize } from '@src/core'\n *\n * canonicalize({ b: 1, a: 2 }) === canonicalize({ a: 2, b: 1 }) // true\n * ```\n */\nexport function canonicalize(value: unknown, visited: ReadonlySet<object> = new Set()): string {\n\tif (Array.isArray(value)) {\n\t\tif (visited.has(value)) return JSON.stringify('[cycle]')\n\t\tconst nextVisited = new Set(visited)\n\t\tnextVisited.add(value)\n\t\treturn `[${value.map((entry) => canonicalize(entry, nextVisited)).join(',')}]`\n\t}\n\tif (isRecord(value)) {\n\t\tif (visited.has(value)) return JSON.stringify('[cycle]')\n\t\tconst nextVisited = new Set(visited)\n\t\tnextVisited.add(value)\n\t\tconst keys = Object.keys(value).sort()\n\t\treturn `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalize(value[key], nextVisited)}`).join(',')}}`\n\t}\n\treturn JSON.stringify(value) ?? 'null'\n}\n\n/**\n * Compute a canonical structural digest of a pure-JSON value — a key-order-\n * stable FNV-1a hash rendered as an 8-hex-digit string.\n *\n * @remarks\n * Pure ECMAScript, no host crypto (AGENTS §17.7) — the same algorithm as the\n * app's `digest`, ported into core so `Interpretation.digest` and the\n * versioned managers can hash without leaving strict core.\n *\n * @param value - The value to digest\n * @returns The 8-character hex digest\n *\n * @example\n * ```ts\n * import { digestValue } from '@src/core'\n *\n * digestValue({ a: 1 }) === digestValue({ a: 1 }) // true — deterministic\n * ```\n */\nexport function digestValue(value: unknown): string {\n\tconst canonical = canonicalize(value)\n\tlet hash = 0x811c9dc5\n\tfor (let index = 0; index < canonical.length; index += 1) {\n\t\thash ^= canonical.charCodeAt(index)\n\t\thash = Math.imul(hash, 0x01000193)\n\t}\n\treturn (hash >>> 0).toString(16).padStart(8, '0')\n}\n\n// === Template matching\n\n/**\n * Score how well a classified intent matches one template's domain + action.\n *\n * @param intent - The classified intent\n * @param template - The candidate template\n * @returns A score in `[0, 1]` — the mean of the domain match (`1`/`0`) and\n * the action match (`1`/`0`, `template.intents` containing `intent.action`)\n *\n * @example\n * ```ts\n * import { scoreTemplate } from '@src/core'\n *\n * scoreTemplate(\n * \t{ action: 'compute', domain: 'rating', confidence: 1 },\n * \t{ id: 't1', name: 'T', domain: 'rating', intents: ['compute'], mappings: [], defaults: [], computations: [], definition: { reasoning: 'symbolic', id: 't1', name: 'T', equations: [], variables: {} } },\n * ) // 1\n * ```\n */\nexport function scoreTemplate(intent: Intent, template: Template): number {\n\tconst domainScore = template.domain.toLowerCase() === intent.domain.toLowerCase() ? 1 : 0\n\tconst actionScore = template.intents.some(\n\t\t(candidate) => candidate.toLowerCase() === intent.action.toLowerCase(),\n\t)\n\t\t? 1\n\t\t: 0\n\treturn (domainScore + actionScore) / 2\n}\n\n/**\n * Find the best-scoring registered template for a classified intent, gated\n * by a confidence floor.\n *\n * @remarks\n * Explicit no-match (AGENTS-flagged scsr defect 2 — never an arbitrary\n * `templates[0]` fallback): an empty registry, or a best score strictly below\n * `floor`, both return `undefined`.\n *\n * @param intent - The classified intent\n * @param templates - The registered templates to score\n * @param floor - The minimum score a match must clear\n * @returns The best-scoring template, or `undefined` on no qualifying match\n *\n * @example\n * ```ts\n * import { matchTemplate } from '@src/core'\n *\n * matchTemplate({ action: '', domain: '', confidence: 0 }, [], 0.3) // undefined — empty registry\n * ```\n */\nexport function matchTemplate(\n\tintent: Intent,\n\ttemplates: readonly Template[],\n\tfloor: number,\n): Template | undefined {\n\tlet best: Template | undefined\n\tlet bestScore = -1\n\tfor (const template of templates) {\n\t\tconst score = scoreTemplate(intent, template)\n\t\tif (score > bestScore) {\n\t\t\tbestScore = score\n\t\t\tbest = template\n\t\t}\n\t}\n\treturn best !== undefined && bestScore >= floor ? best : undefined\n}\n\n// === Computed fields\n\n/**\n * Collect every variable name referenced by a symbolic expression tree, in\n * first-occurrence order.\n *\n * @param expression - The expression tree to scan\n * @returns The referenced variable names, deduplicated\n *\n * @example\n * ```ts\n * import { constant, operation, variable } from '@orkestrel/reason'\n * import { variablesOf } from '@src/core'\n *\n * variablesOf(operation('divide', variable('deductible'), constant(12))) // ['deductible']\n * ```\n */\nexport function variablesOf(expression: SymbolicExpression): readonly string[] {\n\tconst names: string[] = []\n\tconst seen = new Set<string>()\n\n\tfunction collect(node: SymbolicExpression): void {\n\t\tif (node.form === 'variable') {\n\t\t\tif (!seen.has(node.name)) {\n\t\t\t\tseen.add(node.name)\n\t\t\t\tnames.push(node.name)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (node.form === 'operation') {\n\t\t\tcollect(node.left)\n\t\t\tif (node.right !== undefined) collect(node.right)\n\t\t}\n\t}\n\n\tcollect(expression)\n\treturn names\n}\n\n/**\n * Evaluate a symbolic expression tree against resolved bindings.\n *\n * @remarks\n * THE critical leaf (design-pinned, engine-parity semantics): an absent\n * `right` operand on a binary operation defaults to `0` — matching\n * `SymbolicReasoner`'s internal `#evaluate` — and is always passed as an\n * EXPLICIT numeric operand, so the same tree evaluates identically here and\n * inside the engine. Each arithmetic step delegates to the reasons\n * `applyOperation` pure function, mapping the node's `.operator` field onto\n * its `operator` parameter. An unresolved input variable, or a non-finite\n * result (`NaN` from a divide-by-zero, or an overflowing `±Infinity`),\n * becomes a gap — `undefined`, never landing on a subject.\n *\n * @param expression - The expression tree to evaluate\n * @param bindings - The resolved variable bindings\n * @returns The evaluated number, or `undefined` on an unresolved input or a\n * non-finite result\n *\n * @example\n * ```ts\n * import { constant, operation, variable } from '@orkestrel/reason'\n * import { resolveExpression } from '@src/core'\n *\n * resolveExpression(operation('divide', variable('deductible'), constant(12)), { deductible: 6000 }) // 500\n * resolveExpression(operation('divide', constant(1), constant(0)), {}) // undefined — NaN gap\n * resolveExpression(variable('missing'), {}) // undefined — unresolved input\n * ```\n */\nexport function resolveExpression(\n\texpression: SymbolicExpression,\n\tbindings: Readonly<Record<string, number>>,\n): number | undefined {\n\tif (expression.form === 'constant') return expression.value\n\tif (expression.form === 'variable') return bindings[expression.name]\n\n\tconst left = resolveExpression(expression.left, bindings)\n\tif (left === undefined) return undefined\n\n\tconst right = expression.right === undefined ? 0 : resolveExpression(expression.right, bindings)\n\tif (right === undefined) return undefined\n\n\tconst result = applyOperation(expression.operator, left, right)\n\treturn isFiniteNumber(result) ? result : undefined\n}\n\n// === Reverse direction — structure to prose\n\n/**\n * Render a one-line, display-neutral description of a reasons `Subject`,\n * through an injected `Narrator`.\n *\n * @remarks\n * Complements — never duplicates — the raters `describe*` family (which\n * describes RATERS artifacts); this describes REASONS artifacts. Every field\n * renders via `narrator.label` + `narrator.value` (looked up under the\n * `'units'` phrase table, falling back to `'plain'`) — the wording is fully\n * lexicon-driven (AGENTS §21 mechanism-never-policy); `Definition` /\n * `ReasonResult` narration lives on `Narrator#describe` / `Narrator#narrate`\n * directly.\n *\n * @param subject - The subject to describe\n * @param narrator - The lexicon-driven renderer to render field labels/values/lines through\n * @returns A one-line description, the lexicon's `'subject.empty'` line when empty\n *\n * @example\n * ```ts\n * import { createNarrator, describeSubject } from '@src/core'\n *\n * describeSubject({ age: 25, income: 50000 }, createNarrator()) // 'with age: 25, income: 50000'\n * ```\n */\nexport function describeSubject(subject: Subject, narrator: NarratorInterface): string {\n\tconst keys = Object.keys(subject).sort()\n\tif (keys.length === 0) return narrator.line('subject.empty', {})\n\tconst parts = keys.map((key) => {\n\t\tconst unit = narrator.phrase('units', key, 'plain')\n\t\treturn `${narrator.label(key)}: ${narrator.value(unit, subject[key])}`\n\t})\n\treturn narrator.line('subject.fields', { fields: parts.join(', ') })\n}\n\n// === JSON intake\n\n/**\n * Parse a JSON string into a `Template`, or `undefined` on invalid JSON or a\n * shape that fails `isTemplate`.\n *\n * @remarks\n * The module's sole JSON boundary (design §4) — an `Interpretation` and the\n * versioned records are produced internally, never deserialized from\n * untrusted JSON; replay re-runs `interpret`, it does not deserialize a\n * stored result.\n *\n * @param value - The JSON text to parse\n * @returns The parsed template, or `undefined`\n *\n * @example\n * ```ts\n * import { parseTemplate } from '@src/core'\n *\n * parseTemplate('not json') // undefined\n * ```\n */\nexport function parseTemplate(value: string): Template | undefined {\n\treturn parseJSONAs(value, isTemplate)\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { Definition } from '@orkestrel/reason'\nimport type {\n\tDefinitionManagerEventMap,\n\tDefinitionManagerInterface,\n\tDefinitionManagerOptions,\n\tDefinitionRecord,\n\tManagerAddOptions,\n} from '../types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { InterpretError } from '../errors.js'\nimport { digestValue } from '../helpers.js'\n\n/**\n * The definition registry — a self-owning, versioned and content-hashed\n * record-holder for the reasons {@link Definition}s an interpretation produces.\n *\n * @remarks\n * Mirrors {@link TemplateManager}: `add` defaults each record id to the\n * definition's own `id`, derives `hash` from the definition CONTENT\n * (id-independent), and bumps `version` ONLY when that hash changes at a reused\n * id — an identical re-add keeps its version. The batch `remove(ids)` form is\n * all-or-nothing; `destroy()` is idempotent and every method afterwards throws\n * `InterpretError('DESTROYED', …)`.\n *\n * @example\n * ```ts\n * import { symbolicDefinition } from '@orkestrel/reason'\n * import { DefinitionManager } from '@src/core'\n *\n * const manager = new DefinitionManager()\n * const record = manager.add(symbolicDefinition('rate', 'Rate', []))\n * record.id // 'rate'\n * manager.add(symbolicDefinition('rate', 'Rate', [])).version // 1 — identical re-add, no bump\n * ```\n */\nexport class DefinitionManager implements DefinitionManagerInterface {\n\treadonly #records = new Map<string, DefinitionRecord>()\n\treadonly #emitter: Emitter<DefinitionManagerEventMap>\n\t#destroyed = false\n\n\tconstructor(options?: DefinitionManagerOptions) {\n\t\tthis.#emitter = new Emitter<DefinitionManagerEventMap>({\n\t\t\ton: options?.on,\n\t\t\terror: options?.error,\n\t\t})\n\t\tfor (const definition of options?.definitions ?? []) this.add(definition)\n\t}\n\n\tget emitter(): EmitterInterface<DefinitionManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget size(): number {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.size\n\t}\n\n\thas(id: string): boolean {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.has(id)\n\t}\n\n\tdefinition(id: string): DefinitionRecord | undefined {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.get(id)\n\t}\n\n\tdefinitions(): readonly DefinitionRecord[] {\n\t\tthis.#ensureAlive()\n\t\treturn [...this.#records.values()]\n\t}\n\n\tadd(definition: Definition, options?: ManagerAddOptions): DefinitionRecord {\n\t\tthis.#ensureAlive()\n\t\tconst id = options?.id ?? definition.id\n\t\tconst hash = digestValue(definition)\n\t\tconst existing = this.#records.get(id)\n\t\tconst version =\n\t\t\texisting === undefined ? 1 : existing.hash === hash ? existing.version : existing.version + 1\n\t\tconst record: DefinitionRecord = { id, definition, version, hash }\n\t\tthis.#records.set(id, record)\n\t\tthis.#emitter.emit('add', id)\n\t\treturn record\n\t}\n\n\t// Array overload first (AGENTS §9.2); the batch form is all-or-nothing.\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(target?: string | readonly string[]): boolean | void {\n\t\tthis.#ensureAlive()\n\t\tif (target === undefined) {\n\t\t\tfor (const id of this.#records.keys()) this.#emitter.emit('remove', id)\n\t\t\tthis.#records.clear()\n\t\t\treturn\n\t\t}\n\t\tif (typeof target === 'string') {\n\t\t\tconst removed = this.#records.delete(target)\n\t\t\tif (removed) this.#emitter.emit('remove', target)\n\t\t\treturn removed\n\t\t}\n\t\tfor (const id of target) if (!this.#records.has(id)) return false\n\t\tfor (const id of target) {\n\t\t\tthis.#records.delete(id)\n\t\t\tthis.#emitter.emit('remove', id)\n\t\t}\n\t\treturn true\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#records.clear()\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#ensureAlive(): void {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new InterpretError('DESTROYED', 'Definition manager has been destroyed')\n\t\t}\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { Subject } from '@orkestrel/reason'\nimport type {\n\tManagerAddOptions,\n\tSubjectManagerEventMap,\n\tSubjectManagerInterface,\n\tSubjectManagerOptions,\n\tSubjectRecord,\n} from '../types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { InterpretError } from '../errors.js'\nimport { digestValue } from '../helpers.js'\n\n/**\n * The subject registry — a self-owning, versioned and content-hashed\n * record-holder that mints its OWN record identity for every {@link Subject}\n * (a `Subject` carries no `id` field of its own).\n *\n * @remarks\n * The defect-7 fix: scsr keyed stored subjects by their definition's id, so\n * successive same-domain turns silently overwrote one shared subject. Here each\n * `add` mints a fresh `subject-{n}` id (deterministic per instance, no host\n * randomness — AGENTS §17.7) unless the caller overrides it via\n * `ManagerAddOptions.id`. `hash` is content-derived (id-independent) and\n * `version` bumps ONLY when the hash changes at a reused id. The batch\n * `remove(ids)` form is all-or-nothing; `destroy()` is idempotent and every\n * method afterwards throws `InterpretError('DESTROYED', …)`.\n *\n * @example\n * ```ts\n * import { SubjectManager } from '@src/core'\n *\n * const manager = new SubjectManager()\n * const first = manager.add({ age: 25 })\n * const second = manager.add({ age: 30 })\n * first.id !== second.id // true — each subject gets its own identity\n * ```\n */\nexport class SubjectManager implements SubjectManagerInterface {\n\treadonly #records = new Map<string, SubjectRecord>()\n\treadonly #emitter: Emitter<SubjectManagerEventMap>\n\t#counter = 0\n\t#destroyed = false\n\n\tconstructor(options?: SubjectManagerOptions) {\n\t\tthis.#emitter = new Emitter<SubjectManagerEventMap>({ on: options?.on, error: options?.error })\n\t\tfor (const subject of options?.subjects ?? []) this.add(subject)\n\t}\n\n\tget emitter(): EmitterInterface<SubjectManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget size(): number {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.size\n\t}\n\n\thas(id: string): boolean {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.has(id)\n\t}\n\n\tsubject(id: string): SubjectRecord | undefined {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.get(id)\n\t}\n\n\tsubjects(): readonly SubjectRecord[] {\n\t\tthis.#ensureAlive()\n\t\treturn [...this.#records.values()]\n\t}\n\n\tadd(subject: Subject, options?: ManagerAddOptions): SubjectRecord {\n\t\tthis.#ensureAlive()\n\t\tlet id = options?.id\n\t\tif (id === undefined) {\n\t\t\tid = `subject-${this.#counter}`\n\t\t\tthis.#counter += 1\n\t\t}\n\t\tconst hash = digestValue(subject)\n\t\tconst existing = this.#records.get(id)\n\t\tconst version =\n\t\t\texisting === undefined ? 1 : existing.hash === hash ? existing.version : existing.version + 1\n\t\tconst record: SubjectRecord = { id, subject, version, hash }\n\t\tthis.#records.set(id, record)\n\t\tthis.#emitter.emit('add', id)\n\t\treturn record\n\t}\n\n\t// Array overload first (AGENTS §9.2); the batch form is all-or-nothing.\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(target?: string | readonly string[]): boolean | void {\n\t\tthis.#ensureAlive()\n\t\tif (target === undefined) {\n\t\t\tfor (const id of this.#records.keys()) this.#emitter.emit('remove', id)\n\t\t\tthis.#records.clear()\n\t\t\treturn\n\t\t}\n\t\tif (typeof target === 'string') {\n\t\t\tconst removed = this.#records.delete(target)\n\t\t\tif (removed) this.#emitter.emit('remove', target)\n\t\t\treturn removed\n\t\t}\n\t\tfor (const id of target) if (!this.#records.has(id)) return false\n\t\tfor (const id of target) {\n\t\t\tthis.#records.delete(id)\n\t\t\tthis.#emitter.emit('remove', id)\n\t\t}\n\t\treturn true\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#records.clear()\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#ensureAlive(): void {\n\t\tif (this.#destroyed) throw new InterpretError('DESTROYED', 'Subject manager has been destroyed')\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tDefinitionManagerInterface,\n\tEntity,\n\tInterpretContextEventMap,\n\tInterpretContextInterface,\n\tInterpretContextOptions,\n\tInterpretation,\n\tSubjectManagerInterface,\n} from '../types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { DEFAULT_INTERPRET_HISTORY } from '../constants.js'\nimport { InterpretError } from '../errors.js'\nimport { DefinitionManager } from './DefinitionManager.js'\nimport { SubjectManager } from './SubjectManager.js'\n\n/**\n * Cross-turn interpretation context — a capped, replayable history of\n * completed {@link Interpretation}s plus the subject and definition registries\n * carry-over reads from.\n *\n * @remarks\n * `previous()` is a capped ring buffer (newest-last, oldest dropped once the\n * `history` cap is reached — `DEFAULT_INTERPRET_HISTORY` by default, ≥ 3\n * preserves the carry-over pin) rather than scsr's unbounded `previous` array.\n * `entities()` flattens every entity across the buffered history, most recent\n * last — the read a `Clarifier`'s same-domain carry-over consults. `add` pushes\n * one result and trims to the cap; `clear` resets the history and both\n * registries WITHOUT tearing the context down; `destroy()` is idempotent and\n * every method afterwards throws `InterpretError('DESTROYED', …)`.\n *\n * @example\n * ```ts\n * import { InterpretContext } from '@src/core'\n *\n * const context = new InterpretContext({ session: 's1', history: 8 })\n * context.session // 's1'\n * context.previous() // []\n * ```\n */\nexport class InterpretContext implements InterpretContextInterface {\n\treadonly #session?: string\n\treadonly #subjects: SubjectManagerInterface\n\treadonly #definitions: DefinitionManagerInterface\n\treadonly #history: number\n\treadonly #previous: Interpretation[] = []\n\treadonly #emitter: Emitter<InterpretContextEventMap>\n\t#destroyed = false\n\n\tconstructor(options?: InterpretContextOptions) {\n\t\tthis.#session = options?.session\n\t\tthis.#history = Math.max(0, options?.history ?? DEFAULT_INTERPRET_HISTORY)\n\t\tthis.#subjects = new SubjectManager()\n\t\tthis.#definitions = new DefinitionManager()\n\t\tthis.#emitter = new Emitter<InterpretContextEventMap>({\n\t\t\ton: options?.on,\n\t\t\terror: options?.error,\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<InterpretContextEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget session(): string | undefined {\n\t\tthis.#ensureAlive()\n\t\treturn this.#session\n\t}\n\n\tget subjects(): SubjectManagerInterface {\n\t\tthis.#ensureAlive()\n\t\treturn this.#subjects\n\t}\n\n\tget definitions(): DefinitionManagerInterface {\n\t\tthis.#ensureAlive()\n\t\treturn this.#definitions\n\t}\n\n\tprevious(): readonly Interpretation[] {\n\t\tthis.#ensureAlive()\n\t\treturn [...this.#previous]\n\t}\n\n\tentities(): readonly Entity[] {\n\t\tthis.#ensureAlive()\n\t\treturn this.#previous.flatMap((result) => [...result.entities])\n\t}\n\n\tadd(result: Interpretation): void {\n\t\tthis.#ensureAlive()\n\t\tthis.#previous.push(result)\n\t\twhile (this.#previous.length > this.#history) this.#previous.shift()\n\t\tthis.#emitter.emit('add', result.digest)\n\t}\n\n\tclear(): void {\n\t\tthis.#ensureAlive()\n\t\tthis.#previous.length = 0\n\t\tthis.#subjects.remove()\n\t\tthis.#definitions.remove()\n\t\tthis.#emitter.emit('clear')\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#previous.length = 0\n\t\tthis.#subjects.destroy()\n\t\tthis.#definitions.destroy()\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#ensureAlive(): void {\n\t\tif (this.#destroyed)\n\t\t\tthrow new InterpretError('DESTROYED', 'Interpret context has been destroyed')\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tManagerAddOptions,\n\tTemplate,\n\tTemplateManagerEventMap,\n\tTemplateManagerInterface,\n\tTemplateManagerOptions,\n\tTemplateRecord,\n} from '../types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { InterpretError } from '../errors.js'\nimport { digestValue } from '../helpers.js'\n\n/**\n * The template registry — a self-owning, versioned and content-hashed\n * record-holder for the {@link Template}s an `Interpret` orchestrator matches\n * against.\n *\n * @remarks\n * `size` (never `count` — the sole tally in scope) plus the AGENTS §9.1\n * singular/plural accessors (`template` / `templates`) and the §9.2 batch\n * `remove` overloads. `add` derives each record's `hash` from the template's\n * CONTENT (id-independent — the same template data hashes identically under\n * any record id) and bumps `version` ONLY when that hash changes: an identical\n * re-add keeps its version (unlike scsr, which bumped on every add). The\n * batch `remove(ids)` form is ALL-OR-NOTHING — any id absent from the registry\n * leaves the collection untouched and returns `false`. `destroy()` is\n * idempotent; every method afterwards throws `InterpretError('DESTROYED', …)`.\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { TemplateManager } from '@src/core'\n *\n * const manager = new TemplateManager()\n * const record = manager.add({\n * \tid: 't1',\n * \tname: 'Arithmetic',\n * \tdomain: 'arithmetic',\n * \tintents: ['calculate'],\n * \tmappings: [],\n * \tdefaults: [],\n * \tcomputations: [],\n * \tdefinition: quantitativeDefinition('t1', 'Arithmetic', [\n * \t\tfactorGroup('total', 'sum', [fieldFactor('value', 'value')]),\n * \t]),\n * })\n * record.version // 1\n * manager.size // 1\n * ```\n */\nexport class TemplateManager implements TemplateManagerInterface {\n\treadonly #records = new Map<string, TemplateRecord>()\n\treadonly #emitter: Emitter<TemplateManagerEventMap>\n\t#destroyed = false\n\n\tconstructor(options?: TemplateManagerOptions) {\n\t\tthis.#emitter = new Emitter<TemplateManagerEventMap>({ on: options?.on, error: options?.error })\n\t\tfor (const template of options?.templates ?? []) this.add(template)\n\t}\n\n\tget emitter(): EmitterInterface<TemplateManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget size(): number {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.size\n\t}\n\n\thas(id: string): boolean {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.has(id)\n\t}\n\n\ttemplate(id: string): TemplateRecord | undefined {\n\t\tthis.#ensureAlive()\n\t\treturn this.#records.get(id)\n\t}\n\n\ttemplates(): readonly TemplateRecord[] {\n\t\tthis.#ensureAlive()\n\t\treturn [...this.#records.values()]\n\t}\n\n\tadd(template: Template, options?: ManagerAddOptions): TemplateRecord {\n\t\tthis.#ensureAlive()\n\t\tconst id = options?.id ?? template.id\n\t\tconst hash = digestValue(template)\n\t\tconst existing = this.#records.get(id)\n\t\tconst version =\n\t\t\texisting === undefined ? 1 : existing.hash === hash ? existing.version : existing.version + 1\n\t\tconst record: TemplateRecord = { id, template, version, hash }\n\t\tthis.#records.set(id, record)\n\t\tthis.#emitter.emit('add', id)\n\t\treturn record\n\t}\n\n\t// Array overload first (AGENTS §9.2); the batch form is all-or-nothing.\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(target?: string | readonly string[]): boolean | void {\n\t\tthis.#ensureAlive()\n\t\tif (target === undefined) {\n\t\t\tfor (const id of this.#records.keys()) this.#emitter.emit('remove', id)\n\t\t\tthis.#records.clear()\n\t\t\treturn\n\t\t}\n\t\tif (typeof target === 'string') {\n\t\t\tconst removed = this.#records.delete(target)\n\t\t\tif (removed) this.#emitter.emit('remove', target)\n\t\t\treturn removed\n\t\t}\n\t\tfor (const id of target) if (!this.#records.has(id)) return false\n\t\tfor (const id of target) {\n\t\t\tthis.#records.delete(id)\n\t\t\tthis.#emitter.emit('remove', id)\n\t\t}\n\t\treturn true\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#records.clear()\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#ensureAlive(): void {\n\t\tif (this.#destroyed)\n\t\t\tthrow new InterpretError('DESTROYED', 'Template manager has been destroyed')\n\t}\n}\n","import type { FieldPath } from '@orkestrel/contract'\nimport type { Definition, ReasonResult } from '@orkestrel/reason'\nimport type { Lexicon, NarratorFormatter, NarratorInterface, NarratorOptions } from './types.js'\nimport { formatField } from '@orkestrel/reason'\nimport { fillTemplate } from '@orkestrel/template'\nimport { DEFAULT_LEXICON } from './constants.js'\n\n/**\n * A stateless, TOTAL, lexicon-driven rendering engine for the reverse\n * direction — the reverse-direction mirror of the forward `Formatter`'s\n * `verbs` seam (AGENTS §21 mechanism-never-policy).\n *\n * @remarks\n * Every wording decision is DATA — a caller-supplied `Lexicon` merged, per\n * sub-record (`phrases` / `labels` / `templates`), OVER `DEFAULT_LEXICON`.\n * Stateless and holds no resources: no emitter, no `destroy()` (deliberate —\n * there is nothing to release). Every method is total (never throws); a\n * lexicon or formatter miss degrades to its documented fallback rather than\n * a thrown error, and every lookup guards with `Object.hasOwn` so an\n * adversarial key (`toString`, `constructor`, `__proto__`) misses cleanly\n * instead of reading an inherited prototype member.\n *\n * @example\n * ```ts\n * import { Narrator } from '@src/core'\n *\n * const narrator = new Narrator({\n * \tlexicon: { phrases: { comparison: { equals: 'is' } } },\n * \tformatters: { money: (value) => `$${String(value)}` },\n * })\n * narrator.phrase('comparison', 'equals', 'equals') // 'is'\n * narrator.phrase('comparison', 'missing', 'equals') // 'equals' — fallback\n * narrator.value('money', 5) // '$5'\n * ```\n */\nexport class Narrator implements NarratorInterface {\n\treadonly #lexicon: Required<Lexicon>\n\treadonly #formatters: Readonly<Record<string, NarratorFormatter>>\n\n\tconstructor(options?: NarratorOptions) {\n\t\tthis.#lexicon = {\n\t\t\tphrases: { ...DEFAULT_LEXICON.phrases, ...options?.lexicon?.phrases },\n\t\t\tlabels: { ...DEFAULT_LEXICON.labels, ...options?.lexicon?.labels },\n\t\t\ttemplates: { ...DEFAULT_LEXICON.templates, ...options?.lexicon?.templates },\n\t\t}\n\t\tthis.#formatters = { ...options?.formatters }\n\t}\n\n\tphrase(table: string, key: string, fallback?: string): string {\n\t\tif (Object.hasOwn(this.#lexicon.phrases, table)) {\n\t\t\tconst row = this.#lexicon.phrases[table]\n\t\t\tif (row !== null && row !== undefined && Object.hasOwn(row, key)) {\n\t\t\t\tconst value = row[key]\n\t\t\t\tif (typeof value === 'string') return value\n\t\t\t}\n\t\t}\n\t\treturn fallback ?? key\n\t}\n\n\tlabel(field: FieldPath): string {\n\t\tconst key = formatField(field)\n\t\tif (Object.hasOwn(this.#lexicon.labels, key)) {\n\t\t\tconst value = this.#lexicon.labels[key]\n\t\t\tif (typeof value === 'string') return value\n\t\t}\n\t\treturn key\n\t}\n\n\tline(id: string, values: Readonly<Record<string, unknown>>): string {\n\t\tif (!Object.hasOwn(this.#lexicon.templates, id)) return ''\n\t\tconst template = this.#lexicon.templates[id]\n\t\treturn typeof template === 'string' ? fillTemplate(template, values, { missing: 'empty' }) : ''\n\t}\n\n\tvalue(unit: string, raw: unknown): string {\n\t\tif (Object.hasOwn(this.#formatters, unit)) {\n\t\t\tconst formatter = this.#formatters[unit]\n\t\t\tif (typeof formatter === 'function') {\n\t\t\t\ttry {\n\t\t\t\t\treturn formatter(raw)\n\t\t\t\t} catch {\n\t\t\t\t\treturn String(raw)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn String(raw)\n\t}\n\n\tdescribe(definition: Definition): string {\n\t\tswitch (definition.reasoning) {\n\t\t\tcase 'quantitative':\n\t\t\t\treturn this.line('definition.quantitative', {\n\t\t\t\t\tname: definition.name,\n\t\t\t\t\tcount: definition.groups.length,\n\t\t\t\t})\n\t\t\tcase 'logical':\n\t\t\t\treturn this.line('definition.logical', {\n\t\t\t\t\tname: definition.name,\n\t\t\t\t\tcount: definition.rules.length,\n\t\t\t\t\tstrategy: definition.strategy,\n\t\t\t\t})\n\t\t\tcase 'symbolic':\n\t\t\t\treturn this.line('definition.symbolic', {\n\t\t\t\t\tname: definition.name,\n\t\t\t\t\tcount: definition.equations.length,\n\t\t\t\t})\n\t\t\tcase 'inferential':\n\t\t\t\treturn this.line('definition.inferential', {\n\t\t\t\t\tname: definition.name,\n\t\t\t\t\tfacts: definition.facts.length,\n\t\t\t\t\tinferences: definition.inferences.length,\n\t\t\t\t\tstrategy: definition.strategy,\n\t\t\t\t})\n\t\t}\n\t}\n\n\tnarrate(result: ReasonResult): string {\n\t\tswitch (result.reasoning) {\n\t\t\tcase 'quantitative': {\n\t\t\t\tconst base = this.line('result.quantitative', { value: result.value, count: result.count })\n\t\t\t\tif (result.errors.length === 0) return base\n\t\t\t\tconst suffix = this.line('result.quantitative.failed', { errors: result.errors.join(', ') })\n\t\t\t\treturn `${base}${suffix}`\n\t\t\t}\n\t\t\tcase 'logical':\n\t\t\t\treturn this.line('result.logical', {\n\t\t\t\t\tstatus: result.conclusion ? 'met' : 'unmet',\n\t\t\t\t\tcount: result.count,\n\t\t\t\t})\n\t\t\tcase 'symbolic': {\n\t\t\t\tconst solved = Object.entries(result.solutions)\n\t\t\t\t\t.map(([key, value]) => `${key}=${value}`)\n\t\t\t\t\t.join(', ')\n\t\t\t\treturn this.line('result.symbolic', { solved })\n\t\t\t}\n\t\t\tcase 'inferential':\n\t\t\t\treturn this.line('result.inferential', { count: result.derived.length })\n\t\t}\n\t}\n}\n","import type {\n\tAmbiguity,\n\tClarifierInterface,\n\tClarifierOptions,\n\tClarifyResult,\n\tComputedField,\n\tEntity,\n\tIntent,\n\tInterpretContextInterface,\n\tTemplate,\n} from '../types.js'\nimport { isFiniteNumber } from '@orkestrel/contract'\nimport { formatField } from '@orkestrel/reason'\nimport {\n\tCONFIDENCE_CARRIED,\n\tCONFIDENCE_COMPUTED,\n\tCONFIDENCE_DEFAULT,\n\tDEFAULT_INTERPRET_FLOOR,\n} from '../constants.js'\nimport { resolveExpression, variablesOf } from '../helpers.js'\n\n/**\n * The `Clarifier` stage: resolves same-domain carry-over, template defaults,\n * and declaratively computed fields against an already-assigned entity set,\n * surfacing an {@link Ambiguity} for every required mapping that stays\n * unresolved.\n *\n * @remarks\n * Resolution order: fresh (already-assigned) entities always win; carry-over\n * fills a mapping only from the SAME domain's most recent prior turn (a\n * domain change drops carry-over entirely) and never overwrites a fresh\n * value; template defaults fill any field still unresolved after carry-over;\n * computed fields resolve in dependency (topological) order via\n * `resolveExpression` — an unresolved input, a non-finite result, or a\n * dependency cycle leaves the field a gap, never landing an entity. `floor`\n * (from {@link ClarifierOptions}, never hardcoded — AGENTS-flagged scsr\n * defect 4) gates whether a resolved entity's confidence counts as\n * \"resolved enough\" when raising ambiguities — a field with a value below\n * `floor` still raises its ambiguity.\n *\n * @example\n * ```ts\n * import { Clarifier } from '@src/core'\n *\n * const clarifier = new Clarifier({ floor: 0.3 })\n * clarifier.clarify(\n * \t[],\n * \t{\n * \t\tid: 't1',\n * \t\tname: 'Arithmetic',\n * \t\tdomain: 'arithmetic',\n * \t\tintents: ['calculate'],\n * \t\tmappings: [{ entity: 'value', aliases: [], field: 'value', required: true }],\n * \t\tdefaults: [],\n * \t\tcomputations: [],\n * \t\tdefinition: { reasoning: 'symbolic', id: 't1', name: 'Arithmetic', equations: [], variables: {} },\n * \t},\n * \tundefined,\n * \t{ action: 'calculate', domain: 'arithmetic', confidence: 1 },\n * ) // { entities: [], ambiguities: [{ field: 'value', ... }], complete: false }\n * ```\n */\nexport class Clarifier implements ClarifierInterface {\n\treadonly #floor: number\n\n\tconstructor(options?: ClarifierOptions) {\n\t\tthis.#floor = options?.floor ?? DEFAULT_INTERPRET_FLOOR\n\t}\n\n\tclarify(\n\t\tentities: readonly Entity[],\n\t\ttemplate: Template,\n\t\tcontext: InterpretContextInterface | undefined,\n\t\tintent: Intent,\n\t): ClarifyResult {\n\t\tconst resolved: Entity[] = [...entities]\n\t\tconst filledEntityNames = new Set(resolved.map((entity) => entity.name))\n\t\tconst filledFields = new Set(\n\t\t\tresolved.map((entity) => {\n\t\t\t\tconst mapping = template.mappings.find((candidate) => candidate.entity === entity.name)\n\t\t\t\treturn mapping === undefined ? entity.name : formatField(mapping.field)\n\t\t\t}),\n\t\t)\n\n\t\tthis.#carryOver(template, context, intent, filledEntityNames, filledFields, resolved)\n\t\tthis.#fillDefaults(template, filledFields, resolved)\n\t\tthis.#resolveComputations(template, filledFields, resolved)\n\n\t\tconst ambiguities = this.#collectAmbiguities(template, resolved)\n\n\t\treturn { entities: resolved, ambiguities, complete: ambiguities.length === 0 }\n\t}\n\n\t// Same-domain-only carry-over — a chaining pass over `context.previous()`\n\t// mutating the shared `resolved` accumulator (AGENTS §7: an algorithm step,\n\t// not a leaf).\n\t#carryOver(\n\t\ttemplate: Template,\n\t\tcontext: InterpretContextInterface | undefined,\n\t\tintent: Intent,\n\t\tfilledEntityNames: Set<string>,\n\t\tfilledFields: Set<string>,\n\t\tresolved: Entity[],\n\t): void {\n\t\tif (context === undefined) return\n\t\tconst sameDomain = context.previous().filter((prior) => prior.intent.domain === intent.domain)\n\t\tfor (const mapping of template.mappings) {\n\t\t\tif (filledEntityNames.has(mapping.entity)) continue\n\t\t\tfor (let index = sameDomain.length - 1; index >= 0; index -= 1) {\n\t\t\t\tconst prior = sameDomain[index]\n\t\t\t\tconst found = prior?.entities.find((entity) => entity.name === mapping.entity)\n\t\t\t\tif (found === undefined) continue\n\t\t\t\tresolved.push({\n\t\t\t\t\tname: mapping.entity,\n\t\t\t\t\tvalue: found.value,\n\t\t\t\t\tprovenance: { category: 'carried' },\n\t\t\t\t\tconfidence: CONFIDENCE_CARRIED,\n\t\t\t\t})\n\t\t\t\tfilledEntityNames.add(mapping.entity)\n\t\t\t\tfilledFields.add(formatField(mapping.field))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Fills every still-unresolved default field — never overwrites.\n\t#fillDefaults(template: Template, filledFields: Set<string>, resolved: Entity[]): void {\n\t\tfor (const fieldDefault of template.defaults) {\n\t\t\tconst key = formatField(fieldDefault.field)\n\t\t\tif (filledFields.has(key)) continue\n\t\t\tconst mapping = template.mappings.find((candidate) => formatField(candidate.field) === key)\n\t\t\tresolved.push({\n\t\t\t\tname: mapping?.entity ?? key,\n\t\t\t\tvalue: fieldDefault.value,\n\t\t\t\tprovenance: { category: 'default' },\n\t\t\t\tconfidence: CONFIDENCE_DEFAULT,\n\t\t\t})\n\t\t\tfilledFields.add(key)\n\t\t}\n\t}\n\n\t// Resolves computed fields in dependency order, seeding bindings from\n\t// every already-resolved numeric field (extracted/carried/default), then\n\t// growing bindings as each computed field lands.\n\t#resolveComputations(template: Template, filledFields: Set<string>, resolved: Entity[]): void {\n\t\tconst bindings: Record<string, number> = {}\n\t\tfor (const entity of resolved) {\n\t\t\tconst mapping = template.mappings.find((candidate) => candidate.entity === entity.name)\n\t\t\tconst field = mapping === undefined ? entity.name : formatField(mapping.field)\n\t\t\tif (isFiniteNumber(entity.value)) bindings[field] = entity.value\n\t\t}\n\n\t\tfor (const computation of this.#orderComputations(template.computations)) {\n\t\t\tconst key = formatField(computation.field)\n\t\t\tif (filledFields.has(key)) continue\n\t\t\tconst value = resolveExpression(computation.expression, bindings)\n\t\t\tif (value === undefined) continue\n\t\t\tconst mapping = template.mappings.find((candidate) => formatField(candidate.field) === key)\n\t\t\tresolved.push({\n\t\t\t\tname: mapping?.entity ?? key,\n\t\t\t\tvalue,\n\t\t\t\tprovenance: { category: 'computed' },\n\t\t\t\tconfidence: CONFIDENCE_COMPUTED,\n\t\t\t})\n\t\t\tfilledFields.add(key)\n\t\t\tbindings[key] = value\n\t\t}\n\t}\n\n\t// Kahn's-algorithm topological order over the computed fields' field-to-\n\t// field dependency graph (via `variablesOf`) — a dependency cycle simply\n\t// excludes every field it involves from the returned order, so a cyclic\n\t// field (and anything depending on it) resolves to a gap rather than an\n\t// arbitrary evaluation order. A compositional graph traversal, so it stays\n\t// a private orchestration step rather than a leaf (AGENTS §7 — mirrors the\n\t// `SymbolicReasoner#solve`/`#isolate` precedent).\n\t#orderComputations(computations: readonly ComputedField[]): readonly ComputedField[] {\n\t\tconst byField = new Map<string, ComputedField>()\n\t\tfor (const computation of computations) byField.set(formatField(computation.field), computation)\n\n\t\tconst dependents = new Map<string, string[]>()\n\t\tconst inDegree = new Map<string, number>()\n\t\tfor (const key of byField.keys()) inDegree.set(key, 0)\n\n\t\tfor (const [key, computation] of byField) {\n\t\t\tconst dependencies = variablesOf(computation.expression).filter((name) => byField.has(name))\n\t\t\tinDegree.set(key, dependencies.length)\n\t\t\tfor (const dependency of dependencies) {\n\t\t\t\tconst list = dependents.get(dependency) ?? []\n\t\t\t\tlist.push(key)\n\t\t\t\tdependents.set(dependency, list)\n\t\t\t}\n\t\t}\n\n\t\tconst queue: string[] = []\n\t\tfor (const [key, degree] of inDegree) if (degree === 0) queue.push(key)\n\n\t\tconst ordered: ComputedField[] = []\n\t\tlet cursor = 0\n\t\twhile (cursor < queue.length) {\n\t\t\tconst key = queue[cursor]\n\t\t\tcursor += 1\n\t\t\tif (key === undefined) continue\n\t\t\tconst computation = byField.get(key)\n\t\t\tif (computation !== undefined) ordered.push(computation)\n\t\t\tfor (const dependent of dependents.get(key) ?? []) {\n\t\t\t\tconst next = (inDegree.get(dependent) ?? 0) - 1\n\t\t\t\tinDegree.set(dependent, next)\n\t\t\t\tif (next === 0) queue.push(dependent)\n\t\t\t}\n\t\t}\n\n\t\treturn ordered\n\t}\n\n\t// One ambiguity per required mapping without a resolved-enough entity.\n\t#collectAmbiguities(template: Template, resolved: readonly Entity[]): Ambiguity[] {\n\t\tconst ambiguities: Ambiguity[] = []\n\t\tfor (const mapping of template.mappings) {\n\t\t\tif (mapping.required !== true) continue\n\t\t\tconst entity = resolved.find((candidate) => candidate.name === mapping.entity)\n\t\t\tconst resolvedEnough = entity !== undefined && entity.confidence >= this.#floor\n\t\t\tif (resolvedEnough) continue\n\t\t\tambiguities.push({\n\t\t\t\tfield: mapping.field,\n\t\t\t\tquestion: `What is your ${mapping.entity}?`,\n\t\t\t\tcandidates: [],\n\t\t\t\trequired: true,\n\t\t\t})\n\t\t}\n\t\treturn ambiguities\n\t}\n}\n","import type { ExtractorInterface, ExtractorOptions, ExtractResult } from '../types.js'\nimport { DEFAULT_ACTIONS, DEFAULT_DOMAINS } from '../constants.js'\nimport { classifyIntent, extractNumbers } from '../helpers.js'\n\n/**\n * The `Extractor` stage: template-agnostic intent classification plus raw\n * numeric-entity mining.\n *\n * @remarks\n * Deliberately never named `Parser` — the `contracts` module already owns\n * `Parser<T>`, so a class of that name would collide in type space (AGENTS\n * §21, design ledger 3). `extract` never sees a `Template`: numbers →\n * entity ASSIGNMENT is a separate orchestrator-owned step that runs only\n * after a template has matched (`assignEntities` in `helpers.ts`), not\n * inside this stage (the defect-3 fix — scsr's parser mined template-shaped\n * entities directly and only worked via an `instanceof` hack).\n *\n * @example\n * ```ts\n * import { Extractor } from '@src/core'\n *\n * const extractor = new Extractor({\n * \tactions: { calculate: 'compute' },\n * \tdomains: { rating: ['rate'] },\n * })\n * extractor.extract('calculate my rate at 85')\n * // { intent: { action: 'compute', domain: 'rating', confidence: 1 }, numbers: [85], complete: true }\n * ```\n */\nexport class Extractor implements ExtractorInterface {\n\treadonly #actions: Readonly<Record<string, string>>\n\treadonly #domains: Readonly<Record<string, readonly string[]>>\n\n\tconstructor(options?: ExtractorOptions) {\n\t\tthis.#actions = { ...DEFAULT_ACTIONS, ...options?.actions }\n\t\tthis.#domains = { ...DEFAULT_DOMAINS, ...options?.domains }\n\t}\n\n\textract(text: string): ExtractResult {\n\t\tconst numbers = extractNumbers(text)\n\t\tconst intent = classifyIntent(text, this.#actions, this.#domains)\n\t\treturn { intent, numbers, complete: numbers.length > 0 && intent.confidence > 0 }\n\t}\n}\n","import type {\n\tAmbiguity,\n\tEntity,\n\tFormatResult,\n\tFormatterInterface,\n\tFormatterOptions,\n\tIntent,\n\tTemplate,\n} from '../types.js'\nimport { formatField } from '@orkestrel/reason'\nimport { DEFAULT_VERBS } from '../constants.js'\n\n/**\n * The `Formatter` stage: renders the refined natural-language prompt for a\n * matched template.\n *\n * @remarks\n * Shape: `{verb} {template.name}` + ` with {label}: {value}, …` for every\n * non-default entity (via the core-root `formatField`) + `\n * (defaults: {label}: {value}, …)` for default-provenance entities + `\n * needed: {question} …` for every ambiguity. `verbs` maps `intent.action` to\n * its display verb; an action absent from the map falls back to the action\n * string itself. Every parameter is read — no ignored `context` argument\n * (AGENTS-flagged scsr defect 5).\n *\n * @example\n * ```ts\n * import { Formatter } from '@src/core'\n *\n * const formatter = new Formatter({ verbs: { calculate: 'Calculate' } })\n * formatter.format(\n * \t{ action: 'calculate', domain: 'arithmetic', confidence: 1 },\n * \t{\n * \t\tid: 't1',\n * \t\tname: 'Arithmetic',\n * \t\tdomain: 'arithmetic',\n * \t\tintents: ['calculate'],\n * \t\tmappings: [],\n * \t\tdefaults: [],\n * \t\tcomputations: [],\n * \t\tdefinition: { reasoning: 'symbolic', id: 't1', name: 'Arithmetic', equations: [], variables: {} },\n * \t},\n * \t[],\n * \t[],\n * ) // { prompt: 'Calculate Arithmetic' }\n * ```\n */\nexport class Formatter implements FormatterInterface {\n\treadonly #verbs: Readonly<Record<string, string>>\n\n\tconstructor(options?: FormatterOptions) {\n\t\tthis.#verbs = { ...DEFAULT_VERBS, ...options?.verbs }\n\t}\n\n\tformat(\n\t\tintent: Intent,\n\t\ttemplate: Template,\n\t\tentities: readonly Entity[],\n\t\tambiguities: readonly Ambiguity[],\n\t): FormatResult {\n\t\tconst verb = this.#verbs[intent.action] ?? intent.action\n\t\tconst render = (list: readonly Entity[]): string =>\n\t\t\tlist.map((entity) => `${formatField(entity.name)}: ${String(entity.value)}`).join(', ')\n\n\t\tlet prompt = `${verb} ${template.name}`\n\n\t\tconst resolved = entities.filter((entity) => entity.provenance.category !== 'default')\n\t\tif (resolved.length > 0) prompt += ` with ${render(resolved)}`\n\n\t\tconst defaults = entities.filter((entity) => entity.provenance.category === 'default')\n\t\tif (defaults.length > 0) prompt += ` (defaults: ${render(defaults)})`\n\n\t\tif (ambiguities.length > 0) {\n\t\t\tprompt += ` needed: ${ambiguities.map((ambiguity) => ambiguity.question).join(' ')}`\n\t\t}\n\n\t\treturn { prompt }\n\t}\n}\n","import type { Subject } from '@orkestrel/reason'\nimport type {\n\tEntity,\n\tFieldMapping,\n\tGenerateResult,\n\tGeneratorInterface,\n\tTemplate,\n} from '../types.js'\nimport { isFiniteNumber } from '@orkestrel/contract'\nimport { CONFIDENCE_COMPUTED } from '../constants.js'\nimport { deriveAggregateField, setField } from '../helpers.js'\n\n/**\n * The `Generator` stage: builds the final `Subject` from a fully resolved\n * entity set, plus its complete field audit.\n *\n * @remarks\n * `entity → field` via `template.mappings` (an `EntityMapping.entity` name\n * lookup); an entity whose name matches no mapping lands on the field named\n * by its OWN `name` — the shape `Clarifier` uses for its synthesized\n * default/computed entities, so one lookup rule serves both extraction-\n * mapped and template-data-derived fields. A single-element array value\n * unwraps to its scalar; a multi-element, ALL-numeric array value stays an\n * array AND additionally emits five aggregate fields (`Sum` / `Count` /\n * `Average` / `Minimum` / `Maximum`, provenance `computed`), each derived as\n * a SIBLING path beside the source field via `deriveAggregateField` — for an\n * array `FieldPath` (e.g. `['address', 'amounts']`) the aggregates nest\n * (`['address', 'amountsSum']`, ...); for a plain string field they stay\n * flat (`'amountsSum'`), matching the source field's own shape.\n * `confidence` is the mean of the input entities' own confidences (`0` for\n * an empty entity set). A `FieldMapping` is emitted for EVERY field that\n * lands on the subject, including defaults, computed fields, and aggregates\n * — scsr silently omitted defaults/computed from its audit trail; this\n * closes that gap. `GeneratorOptions` is a reserved extension seam — the\n * stage has no knobs yet, so construction takes no arguments until one\n * exists.\n *\n * @example\n * ```ts\n * import { Generator } from '@src/core'\n *\n * const generator = new Generator()\n * generator.generate(\n * \t[\n * \t\t{\n * \t\t\tname: 'value',\n * \t\t\tvalue: 42,\n * \t\t\tprovenance: { category: 'extracted', detail: 'collect' },\n * \t\t\tconfidence: 0.9,\n * \t\t},\n * \t],\n * \t{\n * \t\tid: 't1',\n * \t\tname: 'Arithmetic',\n * \t\tdomain: 'arithmetic',\n * \t\tintents: ['calculate'],\n * \t\tmappings: [{ entity: 'value', aliases: [], field: 'value' }],\n * \t\tdefaults: [],\n * \t\tcomputations: [],\n * \t\tdefinition: { reasoning: 'symbolic', id: 't1', name: 'Arithmetic', equations: [], variables: {} },\n * \t},\n * ) // { subject: { value: 42 }, mappings: [...], confidence: 0.9, ... }\n * ```\n */\nexport class Generator implements GeneratorInterface {\n\tgenerate(entities: readonly Entity[], template: Template): GenerateResult {\n\t\tlet subject: Subject = {}\n\t\tconst mappings: FieldMapping[] = []\n\n\t\tfor (const entity of entities) {\n\t\t\tconst mapping = template.mappings.find((candidate) => candidate.entity === entity.name)\n\t\t\tconst field = mapping === undefined ? entity.name : mapping.field\n\t\t\tconst value = entity.value\n\n\t\t\tif (Array.isArray(value) && value.length === 1) {\n\t\t\t\tconst scalar = value[0]\n\t\t\t\tsubject = setField(subject, field, scalar)\n\t\t\t\tmappings.push({\n\t\t\t\t\tfield,\n\t\t\t\t\tentity: entity.name,\n\t\t\t\t\tvalue: scalar,\n\t\t\t\t\tprovenance: entity.provenance,\n\t\t\t\t\tconfidence: entity.confidence,\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (Array.isArray(value) && value.length > 1) {\n\t\t\t\tconst numeric: number[] = []\n\t\t\t\tfor (const item of value) {\n\t\t\t\t\tif (!isFiniteNumber(item)) break\n\t\t\t\t\tnumeric.push(item)\n\t\t\t\t}\n\t\t\t\tif (numeric.length === value.length) {\n\t\t\t\t\tsubject = setField(subject, field, value)\n\t\t\t\t\tmappings.push({\n\t\t\t\t\t\tfield,\n\t\t\t\t\t\tentity: entity.name,\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t\tprovenance: entity.provenance,\n\t\t\t\t\t\tconfidence: entity.confidence,\n\t\t\t\t\t})\n\t\t\t\t\tconst sum = numeric.reduce((total, item) => total + item, 0)\n\t\t\t\t\tconst minimum = numeric.reduce((min, item) => (item < min ? item : min), numeric[0])\n\t\t\t\t\tconst maximum = numeric.reduce((max, item) => (item > max ? item : max), numeric[0])\n\t\t\t\t\tconst aggregates = [\n\t\t\t\t\t\t[deriveAggregateField(field, 'Sum'), sum],\n\t\t\t\t\t\t[deriveAggregateField(field, 'Count'), numeric.length],\n\t\t\t\t\t\t[deriveAggregateField(field, 'Average'), sum / numeric.length],\n\t\t\t\t\t\t[deriveAggregateField(field, 'Minimum'), minimum],\n\t\t\t\t\t\t[deriveAggregateField(field, 'Maximum'), maximum],\n\t\t\t\t\t] as const\n\t\t\t\t\tfor (const [aggregateField, aggregateValue] of aggregates) {\n\t\t\t\t\t\tsubject = setField(subject, aggregateField, aggregateValue)\n\t\t\t\t\t\tmappings.push({\n\t\t\t\t\t\t\tfield: aggregateField,\n\t\t\t\t\t\t\tvalue: aggregateValue,\n\t\t\t\t\t\t\tprovenance: { category: 'computed' },\n\t\t\t\t\t\t\tconfidence: CONFIDENCE_COMPUTED,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsubject = setField(subject, field, value)\n\t\t\tmappings.push({\n\t\t\t\tfield,\n\t\t\t\tentity: entity.name,\n\t\t\t\tvalue,\n\t\t\t\tprovenance: entity.provenance,\n\t\t\t\tconfidence: entity.confidence,\n\t\t\t})\n\t\t}\n\n\t\tconst confidence =\n\t\t\tentities.length === 0\n\t\t\t\t? 0\n\t\t\t\t: entities.reduce((total, entity) => total + entity.confidence, 0) / entities.length\n\n\t\treturn { subject, definition: template.definition, mappings, confidence }\n\t}\n}\n","import type {\n\tNormalizeResult,\n\tNormalizerInterface,\n\tNormalizerOptions,\n\tTextChange,\n} from '../types.js'\nimport { DEFAULT_ABBREVIATIONS, DEFAULT_CONTRACTIONS, DEFAULT_CORRECTIONS } from '../constants.js'\nimport { applyReplacements, collapseWhitespace, escapeRegExp } from '../helpers.js'\n\n/**\n * The `Normalizer` stage: applies contraction, abbreviation, and correction\n * substitutions in order, then collapses whitespace.\n *\n * @remarks\n * Each caller map is merged OVER the neutral built-in default for its slot —\n * `text` is never mutated (AGENTS §11). Every substitution actually applied\n * (one entry per matching map KEY, not per occurrence) is recorded on the\n * result's `changes`, in `contractions → abbreviations → corrections` order,\n * so the audit trail explains every character difference between `text` and\n * `NormalizeResult.text` (the final whitespace collapse carries no entry of\n * its own — it is structural cleanup, not a substitution).\n *\n * @example\n * ```ts\n * import { Normalizer } from '@src/core'\n *\n * const normalizer = new Normalizer({ contractions: { \"can't\": 'cannot' } })\n * normalizer.normalize(\"can't stop\")\n * // { text: 'cannot stop', changes: [{ from: \"can't\", to: 'cannot' }] }\n * ```\n */\nexport class Normalizer implements NormalizerInterface {\n\treadonly #contractions: Readonly<Record<string, string>>\n\treadonly #abbreviations: Readonly<Record<string, string>>\n\treadonly #corrections: Readonly<Record<string, string>>\n\n\tconstructor(options?: NormalizerOptions) {\n\t\tthis.#contractions = { ...DEFAULT_CONTRACTIONS, ...options?.contractions }\n\t\tthis.#abbreviations = { ...DEFAULT_ABBREVIATIONS, ...options?.abbreviations }\n\t\tthis.#corrections = { ...DEFAULT_CORRECTIONS, ...options?.corrections }\n\t}\n\n\tnormalize(text: string): NormalizeResult {\n\t\tconst changes: TextChange[] = []\n\t\tlet working = text\n\t\tfor (const map of [this.#contractions, this.#abbreviations, this.#corrections]) {\n\t\t\tconst applied = this.#applyStage(working, map)\n\t\t\tworking = applied.text\n\t\t\tchanges.push(...applied.changes)\n\t\t}\n\t\treturn { text: collapseWhitespace(working), changes }\n\t}\n\n\t// One substitution pass over `map`, recording only the keys that actually\n\t// matched. A chaining pass over the leaf `applyReplacements`, so it stays a\n\t// private orchestration step rather than a leaf of its own (AGENTS §7).\n\t#applyStage(\n\t\ttext: string,\n\t\tmap: Readonly<Record<string, string>>,\n\t): { text: string; changes: readonly TextChange[] } {\n\t\tlet working = text\n\t\tconst changes: TextChange[] = []\n\t\tfor (const [from, to] of Object.entries(map)) {\n\t\t\tconst pattern = new RegExp(`\\\\b${escapeRegExp(from)}\\\\b`, 'i')\n\t\t\tif (pattern.test(working)) {\n\t\t\t\tworking = applyReplacements(working, { [from]: to })\n\t\t\t\tchanges.push({ from, to })\n\t\t\t}\n\t\t}\n\t\treturn { text: working, changes }\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { Definition, ReasonResult } from '@orkestrel/reason'\nimport type {\n\tAmbiguity,\n\tClarifierInterface,\n\tClarifyResult,\n\tEntity,\n\tExtractorInterface,\n\tExtractResult,\n\tFormatResult,\n\tFormatterInterface,\n\tGenerateResult,\n\tGeneratorInterface,\n\tIntent,\n\tInterpretContextInterface,\n\tInterpretErrorCode,\n\tInterpretEventMap,\n\tInterpretInterface,\n\tInterpretOptions,\n\tInterpretStage,\n\tInterpretation,\n\tNarratorInterface,\n\tNormalizeResult,\n\tNormalizerInterface,\n\tStageFailure,\n\tStageRecord,\n\tTemplate,\n} from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { DEFAULT_INTERPRET_FLOOR, DEFAULT_INTERPRET_SIMILARITY } from './constants.js'\nimport { InterpretError } from './errors.js'\nimport { assignEntities, digestValue, matchTemplate } from './helpers.js'\nimport { InterpretContext } from './managers/InterpretContext.js'\nimport { TemplateManager } from './managers/TemplateManager.js'\nimport { Narrator } from './Narrator.js'\nimport { Clarifier } from './stages/Clarifier.js'\nimport { Extractor } from './stages/Extractor.js'\nimport { Formatter } from './stages/Formatter.js'\nimport { Generator } from './stages/Generator.js'\nimport { Normalizer } from './stages/Normalizer.js'\n\n/**\n * The interpretation orchestrator — the sole public entry point of the\n * `interprets` module, mirroring the reasons `Reason` orchestrator shape.\n *\n * @remarks\n * `interpret()` is genuinely SYNCHRONOUS (scsr's was fake-async with zero\n * `await`s) and runs a fixed five-stage pipeline —\n * `[normalize, extract, clarify, format, generate]` — each producing one\n * {@link StageRecord}. Between `extract` and `clarify` the orchestrator matches\n * the classified {@link Intent} against its registered {@link Template}s and,\n * on a match, assigns the extracted numbers to that template's mappings\n * (`assignEntities`) — a template-owned step, not a sixth stage. No match, or a\n * matched template whose intent confidence falls below the configured `floor`,\n * yields an explicit, auditable INCOMPLETE result (a `field: 'intent'`\n * ambiguity, absent subject/definition) rather than scsr's arbitrary\n * `templates[0]` fallback. A stage THROW is caught, marked on its record AND on\n * `failures`, emitted as `error`, and still yields a visible incomplete result\n * — never a silent fallback. Every result carries a `digest` over its original\n * text plus the matched template id/version and the built subject/definition,\n * so re-running the same text against the same template version reproduces the\n * same digest (the replay contract). `describe` / `narrate` are the reverse\n * direction (structure → prose). `destroy()` is idempotent, tears down the\n * registry and context, then destroys the emitter LAST (AGENTS §13); every\n * method afterwards except the {@link emitter} getter throws\n * `InterpretError('DESTROYED', …)`.\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { Interpret, Extractor } from '@src/core'\n *\n * const interpret = new Interpret({\n * \textractor: new Extractor({ actions: { calculate: 'calculate' }, domains: { arithmetic: ['arithmetic'] } }),\n * \ttemplates: [\n * \t\t{\n * \t\t\tid: 't1',\n * \t\t\tname: 'Arithmetic',\n * \t\t\tdomain: 'arithmetic',\n * \t\t\tintents: ['calculate'],\n * \t\t\tmappings: [{ entity: 'value', aliases: [], field: 'value' }],\n * \t\t\tdefaults: [],\n * \t\t\tcomputations: [],\n * \t\t\tdefinition: quantitativeDefinition('t1', 'Arithmetic', [\n * \t\t\t\tfactorGroup('total', 'sum', [fieldFactor('value', 'value')]),\n * \t\t\t]),\n * \t\t},\n * \t],\n * })\n * interpret.interpret('calculate arithmetic 42').subject // { value: 42 }\n * ```\n */\nexport class Interpret implements InterpretInterface {\n\treadonly #templates: TemplateManager\n\treadonly #context: InterpretContextInterface\n\treadonly #normalizer: NormalizerInterface\n\treadonly #extractor: ExtractorInterface\n\treadonly #clarifier: ClarifierInterface\n\treadonly #formatter: FormatterInterface\n\treadonly #generator: GeneratorInterface\n\treadonly #similarity: number\n\treadonly #floor: number\n\treadonly #narrator: NarratorInterface\n\treadonly #emitter: Emitter<InterpretEventMap>\n\t#destroyed = false\n\n\tconstructor(options?: InterpretOptions) {\n\t\tthis.#similarity = options?.similarity ?? DEFAULT_INTERPRET_SIMILARITY\n\t\tthis.#floor = options?.floor ?? DEFAULT_INTERPRET_FLOOR\n\t\tthis.#templates = new TemplateManager({ templates: options?.templates })\n\t\tthis.#context = options?.context ?? new InterpretContext({ history: options?.history })\n\t\tthis.#normalizer = options?.normalizer ?? new Normalizer()\n\t\tthis.#extractor = options?.extractor ?? new Extractor()\n\t\tthis.#clarifier = options?.clarifier ?? new Clarifier({ floor: this.#floor })\n\t\tthis.#formatter = options?.formatter ?? new Formatter()\n\t\tthis.#generator = options?.generator ?? new Generator()\n\t\tthis.#narrator = new Narrator({ lexicon: options?.lexicon, formatters: options?.formatters })\n\t\tthis.#emitter = new Emitter<InterpretEventMap>({ on: options?.on, error: options?.error })\n\t}\n\n\tget emitter(): EmitterInterface<InterpretEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tinterpret(text: string): Interpretation {\n\t\tthis.#ensureAlive()\n\t\tconst stages: StageRecord[] = []\n\n\t\tlet normalized: NormalizeResult\n\t\ttry {\n\t\t\tnormalized = this.#normalizer.normalize(text)\n\t\t} catch (error) {\n\t\t\treturn this.#abort(\n\t\t\t\ttext,\n\t\t\t\ttext,\n\t\t\t\t{ action: '', domain: '', confidence: 0 },\n\t\t\t\t[],\n\t\t\t\t[],\n\t\t\t\tstages,\n\t\t\t\t'normalize',\n\t\t\t\t'NORMALIZE_FAILED',\n\t\t\t\ttext,\n\t\t\t\terror,\n\t\t\t\t['extract', 'clarify', 'format', 'generate'],\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t)\n\t\t}\n\t\tstages.push({ stage: 'normalize', input: text, output: normalized, failed: false })\n\n\t\tlet extract: ExtractResult\n\t\ttry {\n\t\t\textract = this.#extractor.extract(normalized.text)\n\t\t} catch (error) {\n\t\t\treturn this.#abort(\n\t\t\t\ttext,\n\t\t\t\tnormalized.text,\n\t\t\t\t{ action: '', domain: '', confidence: 0 },\n\t\t\t\t[],\n\t\t\t\t[],\n\t\t\t\tstages,\n\t\t\t\t'extract',\n\t\t\t\t'EXTRACT_FAILED',\n\t\t\t\tnormalized.text,\n\t\t\t\terror,\n\t\t\t\t['clarify', 'format', 'generate'],\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t)\n\t\t}\n\t\tstages.push({ stage: 'extract', input: normalized.text, output: extract, failed: false })\n\n\t\tconst intent = extract.intent\n\t\tconst templates = this.#templates.templates().map((record) => record.template)\n\t\tconst matched = matchTemplate(intent, templates, this.#floor)\n\n\t\tif (matched === undefined) {\n\t\t\treturn this.#gate(\n\t\t\t\ttext,\n\t\t\t\tnormalized.text,\n\t\t\t\tintent,\n\t\t\t\t[],\n\t\t\t\tstages,\n\t\t\t\t'NO_TEMPLATE',\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t)\n\t\t}\n\n\t\tconst assigned = assignEntities(\n\t\t\textract.numbers,\n\t\t\tmatched.mappings,\n\t\t\tnormalized.text,\n\t\t\tthis.#similarity,\n\t\t)\n\t\tconst record = this.#templates.template(matched.id)\n\t\tconst version = record?.version\n\n\t\tif (intent.confidence < this.#floor) {\n\t\t\treturn this.#gate(\n\t\t\t\ttext,\n\t\t\t\tnormalized.text,\n\t\t\t\tintent,\n\t\t\t\tassigned,\n\t\t\t\tstages,\n\t\t\t\t'LOW_CONFIDENCE',\n\t\t\t\tmatched.id,\n\t\t\t\tversion,\n\t\t\t)\n\t\t}\n\n\t\tlet clarified: ClarifyResult\n\t\ttry {\n\t\t\tclarified = this.#clarifier.clarify(assigned, matched, this.#context, intent)\n\t\t} catch (error) {\n\t\t\treturn this.#abort(\n\t\t\t\ttext,\n\t\t\t\tnormalized.text,\n\t\t\t\tintent,\n\t\t\t\tassigned,\n\t\t\t\t[],\n\t\t\t\tstages,\n\t\t\t\t'clarify',\n\t\t\t\t'CLARIFY_FAILED',\n\t\t\t\tassigned,\n\t\t\t\terror,\n\t\t\t\t['format', 'generate'],\n\t\t\t\tmatched.id,\n\t\t\t\tversion,\n\t\t\t)\n\t\t}\n\t\tstages.push({ stage: 'clarify', input: assigned, output: clarified, failed: false })\n\n\t\tconst formatInput = { intent, entities: clarified.entities, ambiguities: clarified.ambiguities }\n\t\tlet formatted: FormatResult\n\t\ttry {\n\t\t\tformatted = this.#formatter.format(intent, matched, clarified.entities, clarified.ambiguities)\n\t\t} catch (error) {\n\t\t\treturn this.#abort(\n\t\t\t\ttext,\n\t\t\t\tnormalized.text,\n\t\t\t\tintent,\n\t\t\t\tclarified.entities,\n\t\t\t\tclarified.ambiguities,\n\t\t\t\tstages,\n\t\t\t\t'format',\n\t\t\t\t'FORMAT_FAILED',\n\t\t\t\tformatInput,\n\t\t\t\terror,\n\t\t\t\t['generate'],\n\t\t\t\tmatched.id,\n\t\t\t\tversion,\n\t\t\t)\n\t\t}\n\t\tstages.push({ stage: 'format', input: formatInput, output: formatted, failed: false })\n\n\t\tlet generated: GenerateResult\n\t\ttry {\n\t\t\tgenerated = this.#generator.generate(clarified.entities, matched)\n\t\t} catch (error) {\n\t\t\treturn this.#abort(\n\t\t\t\ttext,\n\t\t\t\tnormalized.text,\n\t\t\t\tintent,\n\t\t\t\tclarified.entities,\n\t\t\t\tclarified.ambiguities,\n\t\t\t\tstages,\n\t\t\t\t'generate',\n\t\t\t\t'GENERATE_FAILED',\n\t\t\t\tclarified.entities,\n\t\t\t\terror,\n\t\t\t\t[],\n\t\t\t\tmatched.id,\n\t\t\t\tversion,\n\t\t\t)\n\t\t}\n\t\tstages.push({ stage: 'generate', input: clarified.entities, output: generated, failed: false })\n\n\t\tconst digest = digestValue({\n\t\t\ttext,\n\t\t\ttemplateId: matched.id,\n\t\t\ttemplateVersion: version,\n\t\t\tsubject: generated.subject,\n\t\t\tdefinition: generated.definition,\n\t\t})\n\t\tconst result: Interpretation = {\n\t\t\ttext,\n\t\t\tnormalized: normalized.text,\n\t\t\tintent,\n\t\t\tentities: clarified.entities,\n\t\t\tsubject: generated.subject,\n\t\t\tdefinition: generated.definition,\n\t\t\tmappings: generated.mappings,\n\t\t\tambiguities: clarified.ambiguities,\n\t\t\tprompt: formatted.prompt,\n\t\t\tstages,\n\t\t\tfailures: [],\n\t\t\tcomplete: clarified.complete,\n\t\t\tconfidence: generated.confidence,\n\t\t\tdigest,\n\t\t}\n\n\t\tthis.#context.subjects.add(generated.subject)\n\t\tthis.#context.definitions.add(generated.definition, { id: generated.definition.id })\n\t\tthis.#context.add(result)\n\t\tthis.#emitter.emit('interpret', result)\n\t\treturn result\n\t}\n\n\tregister(template: Template): void {\n\t\tthis.#ensureAlive()\n\t\tthis.#templates.add(template, { id: template.id })\n\t\tthis.#emitter.emit('register', template.id)\n\t}\n\n\tunregister(id: string): boolean {\n\t\tthis.#ensureAlive()\n\t\treturn this.#templates.remove(id)\n\t}\n\n\ttemplate(id: string): Template | undefined {\n\t\tthis.#ensureAlive()\n\t\treturn this.#templates.template(id)?.template\n\t}\n\n\ttemplates(): readonly Template[] {\n\t\tthis.#ensureAlive()\n\t\treturn this.#templates.templates().map((record) => record.template)\n\t}\n\n\tdescribe(definition: Definition): string {\n\t\tthis.#ensureAlive()\n\t\treturn this.#narrator.describe(definition)\n\t}\n\n\tnarrate(result: ReasonResult): string {\n\t\tthis.#ensureAlive()\n\t\treturn this.#narrator.narrate(result)\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#templates.destroy()\n\t\tthis.#context.destroy()\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// A NO_TEMPLATE / LOW_CONFIDENCE match gate — an explicit incomplete result\n\t// carrying a `field: 'intent'` ambiguity whose candidates are the registered\n\t// domain names, plus the matching StageFailure. No `error` emit — a gate is\n\t// a deliberate incomplete outcome, not a stage throw.\n\t#gate(\n\t\ttext: string,\n\t\tnormalized: string,\n\t\tintent: Intent,\n\t\tentities: readonly Entity[],\n\t\tstages: StageRecord[],\n\t\tcode: 'NO_TEMPLATE' | 'LOW_CONFIDENCE',\n\t\ttemplateId: string | undefined,\n\t\ttemplateVersion: number | undefined,\n\t): Interpretation {\n\t\tconst domains = [\n\t\t\t...new Set(this.#templates.templates().map((record) => record.template.domain)),\n\t\t]\n\t\tconst ambiguity: Ambiguity = {\n\t\t\tfield: 'intent',\n\t\t\tquestion:\n\t\t\t\tcode === 'NO_TEMPLATE'\n\t\t\t\t\t? 'Which domain and action did you mean?'\n\t\t\t\t\t: 'Which did you mean? The intent was too weak to act on.',\n\t\t\tcandidates: domains,\n\t\t\trequired: true,\n\t\t}\n\t\tconst failure: StageFailure = {\n\t\t\tstage: 'clarify',\n\t\t\tcode,\n\t\t\tmessage:\n\t\t\t\tcode === 'NO_TEMPLATE'\n\t\t\t\t\t? 'No registered template matched the classified intent'\n\t\t\t\t\t: 'Classified intent confidence fell below the configured floor',\n\t\t}\n\t\treturn this.#assemble(\n\t\t\ttext,\n\t\t\tnormalized,\n\t\t\tintent,\n\t\t\tentities,\n\t\t\t[ambiguity],\n\t\t\tstages,\n\t\t\t[failure],\n\t\t\t['clarify', 'format', 'generate'],\n\t\t\ttemplateId,\n\t\t\ttemplateVersion,\n\t\t)\n\t}\n\n\t// A stage THROW — mark the failed stage's record, emit `error` with the raw\n\t// thrown value, and assemble a visible incomplete result. The one site the\n\t// thrown value is rendered to a message (folded here, its sole use).\n\t#abort(\n\t\ttext: string,\n\t\tnormalized: string,\n\t\tintent: Intent,\n\t\tentities: readonly Entity[],\n\t\tambiguities: readonly Ambiguity[],\n\t\tstages: StageRecord[],\n\t\tstage: InterpretStage,\n\t\tcode: InterpretErrorCode,\n\t\tinput: unknown,\n\t\terror: unknown,\n\t\tremaining: readonly InterpretStage[],\n\t\ttemplateId: string | undefined,\n\t\ttemplateVersion: number | undefined,\n\t): Interpretation {\n\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\tstages.push({ stage, input, output: undefined, failed: true, error: message })\n\t\tthis.#emitter.emit('error', error)\n\t\treturn this.#assemble(\n\t\t\ttext,\n\t\t\tnormalized,\n\t\t\tintent,\n\t\t\tentities,\n\t\t\tambiguities,\n\t\t\tstages,\n\t\t\t[{ stage, code, message }],\n\t\t\tremaining,\n\t\t\ttemplateId,\n\t\t\ttemplateVersion,\n\t\t)\n\t}\n\n\t// Assemble a visible incomplete result: pad the un-run stages with skipped\n\t// records so `stages` always holds exactly five, digest over the known\n\t// pre-image, record the result in context, and emit `interpret` (an\n\t// incomplete run is still a completed CALL — visibility is the point).\n\t#assemble(\n\t\ttext: string,\n\t\tnormalized: string,\n\t\tintent: Intent,\n\t\tentities: readonly Entity[],\n\t\tambiguities: readonly Ambiguity[],\n\t\tstages: StageRecord[],\n\t\tfailures: readonly StageFailure[],\n\t\tremaining: readonly InterpretStage[],\n\t\ttemplateId: string | undefined,\n\t\ttemplateVersion: number | undefined,\n\t): Interpretation {\n\t\tfor (const stage of remaining) {\n\t\t\tstages.push({ stage, input: undefined, output: undefined, failed: false })\n\t\t}\n\t\tconst digest = digestValue({\n\t\t\ttext,\n\t\t\ttemplateId,\n\t\t\ttemplateVersion,\n\t\t\tsubject: undefined,\n\t\t\tdefinition: undefined,\n\t\t})\n\t\tconst result: Interpretation = {\n\t\t\ttext,\n\t\t\tnormalized,\n\t\t\tintent,\n\t\t\tentities,\n\t\t\tmappings: [],\n\t\t\tambiguities,\n\t\t\tprompt: '',\n\t\t\tstages,\n\t\t\tfailures: [...failures],\n\t\t\tcomplete: false,\n\t\t\tconfidence: 0,\n\t\t\tdigest,\n\t\t}\n\t\tthis.#context.add(result)\n\t\tthis.#emitter.emit('interpret', result)\n\t\treturn result\n\t}\n\n\t#ensureAlive(): void {\n\t\tif (this.#destroyed) throw new InterpretError('DESTROYED', 'Interpret has been destroyed')\n\t}\n}\n","import type {\n\tClarifierInterface,\n\tClarifierOptions,\n\tDefinitionManagerInterface,\n\tDefinitionManagerOptions,\n\tExtractorInterface,\n\tExtractorOptions,\n\tFormatterInterface,\n\tFormatterOptions,\n\tGeneratorInterface,\n\tGeneratorOptions,\n\tInterpretContextInterface,\n\tInterpretContextOptions,\n\tInterpretInterface,\n\tInterpretOptions,\n\tNarratorInterface,\n\tNarratorOptions,\n\tNormalizerInterface,\n\tNormalizerOptions,\n\tSubjectManagerInterface,\n\tSubjectManagerOptions,\n\tTemplate,\n\tTemplateManagerInterface,\n\tTemplateManagerOptions,\n} from './types.js'\nimport { InterpretError } from './errors.js'\nimport { isTemplate } from './validators.js'\nimport { Interpret } from './Interpret.js'\nimport { Narrator } from './Narrator.js'\nimport { InterpretContext } from './managers/InterpretContext.js'\nimport { TemplateManager } from './managers/TemplateManager.js'\nimport { SubjectManager } from './managers/SubjectManager.js'\nimport { DefinitionManager } from './managers/DefinitionManager.js'\nimport { Clarifier } from './stages/Clarifier.js'\nimport { Extractor } from './stages/Extractor.js'\nimport { Formatter } from './stages/Formatter.js'\nimport { Generator } from './stages/Generator.js'\nimport { Normalizer } from './stages/Normalizer.js'\n\n/**\n * Create an interpretation orchestrator.\n *\n * @remarks\n * `interpret()` is genuinely synchronous and runs the fixed five-stage\n * pipeline `[normalize, extract, clarify, format, generate]`. Every stage\n * slot (`normalizer` / `extractor` / `clarifier` / `formatter` / `generator`)\n * is bring-your-own — a supplied implementation is used as-is, else the\n * built-in stage is constructed from the matching per-stage options.\n *\n * @param options - Optional templates, context, stage implementations, the\n * `similarity` / `floor` axes, and emitter hooks\n * @returns A working {@link InterpretInterface}\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { createInterpret } from '@src/core'\n *\n * const interpret = createInterpret({\n * \textractor: { extract: () => ({ intent: { action: 'calculate', domain: 'arithmetic', confidence: 1 }, numbers: [42], complete: true }) },\n * \ttemplates: [\n * \t\t{\n * \t\t\tid: 't1',\n * \t\t\tname: 'Arithmetic',\n * \t\t\tdomain: 'arithmetic',\n * \t\t\tintents: ['calculate'],\n * \t\t\tmappings: [{ entity: 'value', aliases: [], field: 'value' }],\n * \t\t\tdefaults: [],\n * \t\t\tcomputations: [],\n * \t\t\tdefinition: quantitativeDefinition('t1', 'Arithmetic', [\n * \t\t\t\tfactorGroup('total', 'sum', [fieldFactor('value', 'value')]),\n * \t\t\t]),\n * \t\t},\n * \t],\n * })\n * interpret.interpret('calculate arithmetic 42').subject // { value: 42 }\n * ```\n */\nexport function createInterpret(options?: InterpretOptions): InterpretInterface {\n\treturn new Interpret(options)\n}\n\n/**\n * Create a text normalizer.\n *\n * @param options - Optional contraction / abbreviation / correction maps,\n * merged over the neutral built-in defaults\n * @returns A stateless {@link NormalizerInterface}\n *\n * @example\n * ```ts\n * import { createNormalizer } from '@src/core'\n *\n * createNormalizer().normalize(\"it's cold\") // { text: 'it is cold', changes: [{ from: \"it's\", to: 'it is' }] }\n * ```\n */\nexport function createNormalizer(options?: NormalizerOptions): NormalizerInterface {\n\treturn new Normalizer(options)\n}\n\n/**\n * Create a template-agnostic intent classifier and number extractor.\n *\n * @param options - Optional caller `actions` / `domains` vocabularies\n * @returns A stateless {@link ExtractorInterface}\n *\n * @example\n * ```ts\n * import { createExtractor } from '@src/core'\n *\n * const extractor = createExtractor({\n * \tactions: { calculate: 'calculate' },\n * \tdomains: { arithmetic: ['arithmetic'] },\n * })\n * extractor.extract('calculate arithmetic 42').numbers // [42]\n * ```\n */\nexport function createExtractor(options?: ExtractorOptions): ExtractorInterface {\n\treturn new Extractor(options)\n}\n\n/**\n * Create a clarifier — carry-over, defaults, and computed-field resolution\n * against an assigned entity set.\n *\n * @param options - Optional confidence `floor` for raised ambiguities\n * @returns A stateless {@link ClarifierInterface}\n *\n * @example\n * ```ts\n * import { createClarifier } from '@src/core'\n *\n * const clarifier = createClarifier({ floor: 0.5 })\n * ```\n */\nexport function createClarifier(options?: ClarifierOptions): ClarifierInterface {\n\treturn new Clarifier(options)\n}\n\n/**\n * Create a prompt formatter.\n *\n * @param options - Optional caller intent-verb phrasing map\n * @returns A stateless {@link FormatterInterface}\n *\n * @example\n * ```ts\n * import { createFormatter } from '@src/core'\n *\n * const formatter = createFormatter({ verbs: { calculate: 'Calculate' } })\n * ```\n */\nexport function createFormatter(options?: FormatterOptions): FormatterInterface {\n\treturn new Formatter(options)\n}\n\n/**\n * Create a subject/definition generator.\n *\n * @param options - Currently an empty extension seam\n * @returns A stateless {@link GeneratorInterface}\n *\n * @example\n * ```ts\n * import { createGenerator } from '@src/core'\n *\n * const generator = createGenerator()\n * ```\n */\nexport function createGenerator(_options?: GeneratorOptions): GeneratorInterface {\n\treturn new Generator()\n}\n\n/**\n * Create a template registry.\n *\n * @param options - Optional initial seed collection\n * @returns A working {@link TemplateManagerInterface}\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { createTemplate, createTemplateManager } from '@src/core'\n *\n * const template = createTemplate({\n * \tid: 't1', name: 'Arithmetic', domain: 'arithmetic', intents: ['calculate'],\n * \tmappings: [{ entity: 'value', aliases: [], field: 'value' }], defaults: [], computations: [],\n * \tdefinition: quantitativeDefinition('t1', 'Arithmetic', [factorGroup('total', 'sum', [fieldFactor('value', 'value')])]),\n * })\n * const templates = createTemplateManager({ templates: [template] })\n * templates.size // 1\n * ```\n */\nexport function createTemplateManager(options?: TemplateManagerOptions): TemplateManagerInterface {\n\treturn new TemplateManager(options)\n}\n\n/**\n * Create a subject registry.\n *\n * @remarks\n * Mints its own record ids on `add` when none is supplied — a `Subject`\n * carries no `id` field of its own.\n *\n * @param options - Optional initial seed collection\n * @returns A working {@link SubjectManagerInterface}\n *\n * @example\n * ```ts\n * import { createSubjectManager } from '@src/core'\n *\n * const subjects = createSubjectManager({ subjects: [{ value: 1 }] })\n * subjects.size // 1\n * ```\n */\nexport function createSubjectManager(options?: SubjectManagerOptions): SubjectManagerInterface {\n\treturn new SubjectManager(options)\n}\n\n/**\n * Create a definition registry.\n *\n * @param options - Optional initial seed collection\n * @returns A working {@link DefinitionManagerInterface}\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { createDefinitionManager } from '@src/core'\n *\n * const definitions = createDefinitionManager({\n * \tdefinitions: [quantitativeDefinition('d1', 'D1', [factorGroup('total', 'sum', [fieldFactor('value', 'value')])])],\n * })\n * definitions.size // 1\n * ```\n */\nexport function createDefinitionManager(\n\toptions?: DefinitionManagerOptions,\n): DefinitionManagerInterface {\n\treturn new DefinitionManager(options)\n}\n\n/**\n * Create a cross-turn interpretation context.\n *\n * @param options - Optional `session` label and `history` ring-buffer cap\n * @returns A working {@link InterpretContextInterface}\n *\n * @example\n * ```ts\n * import { createInterpretContext } from '@src/core'\n *\n * const context = createInterpretContext({ session: 'turn-1', history: 4 })\n * context.previous() // []\n * ```\n */\nexport function createInterpretContext(\n\toptions?: InterpretContextOptions,\n): InterpretContextInterface {\n\treturn new InterpretContext(options)\n}\n\n/**\n * Build and validate one interpretation template from plain data.\n *\n * @remarks\n * The factory/coercer pair for template intake (AGENTS §4.6.1): this throws\n * on malformed data, while `parseTemplate` returns `undefined`. Data failing\n * {@link isTemplate} throws `InterpretError('INVALID_TEMPLATE', …)`.\n *\n * @param data - The candidate template data\n * @returns The same data, now known to satisfy {@link Template}\n * @throws {@link InterpretError} `INVALID_TEMPLATE` when `data` fails validation\n *\n * @example\n * ```ts\n * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'\n * import { createTemplate } from '@src/core'\n *\n * const template = createTemplate({\n * \tid: 't1', name: 'Arithmetic', domain: 'arithmetic', intents: ['calculate'],\n * \tmappings: [{ entity: 'value', aliases: [], field: 'value' }], defaults: [], computations: [],\n * \tdefinition: quantitativeDefinition('t1', 'Arithmetic', [factorGroup('total', 'sum', [fieldFactor('value', 'value')])]),\n * })\n * template.id // 't1'\n * ```\n */\nexport function createTemplate(data: Template): Template {\n\tif (!isTemplate(data)) {\n\t\tthrow new InterpretError('INVALID_TEMPLATE', 'Template data failed validation')\n\t}\n\treturn data\n}\n\n/**\n * Create a lexicon-driven reverse-direction rendering engine.\n *\n * @remarks\n * Stateless — `phrase` / `label` / `line` / `value` are total lookups into a\n * caller `Lexicon` merged over `DEFAULT_LEXICON`, and `describe` / `narrate`\n * compose them over a reasons `Definition` / `ReasonResult`.\n *\n * @param options - Optional `lexicon` and `formatters` map\n * @returns A stateless {@link NarratorInterface}\n *\n * @example\n * ```ts\n * import { createNarrator } from '@src/core'\n *\n * const narrator = createNarrator({ lexicon: { templates: { 'subject.empty': 'nothing here' } } })\n * narrator.line('subject.empty', {}) // 'nothing here'\n * ```\n */\nexport function createNarrator(options?: NarratorOptions): NarratorInterface {\n\treturn new Narrator(options)\n}\n"],"mappings":";;;;;;;;;;;;;;AAkBA,IAAa,+BAA+B;;;;;;AAO5C,IAAa,0BAA0B;;AAGvC,IAAa,4BAA4B;;AAGzC,IAAa,eAAe;;AAG5B,IAAa,mBAAmB;;AAGhC,IAAa,mBAAmB;;AAGhC,IAAa,qBAAqB;;AAGlC,IAAa,wBAAwB;;AAGrC,IAAa,qBAAqB;;AAGlC,IAAa,qBAAqB;;AAGlC,IAAa,sBAAsB;;;;;;;;;;;AAYnC,IAAa,iBAAiB;;;;;AAM9B,IAAa,wBAA2C,OAAO,OAAO;CACrE;CACA;CACA;AACD,CAAC;;;;;AAMD,IAAa,uBAAyD,OAAO,OAAO;CACnF,SAAS;CACT,SAAS;CACT,QAAQ;CACR,SAAS;AACV,CAAC;;AAGD,IAAa,wBAA0D,OAAO,OAAO,CAAC,CAAC;;AAGvF,IAAa,sBAAwD,OAAO,OAAO,CAAC,CAAC;;AAGrF,IAAa,kBAAoD,OAAO,OAAO,CAAC,CAAC;;AAGjF,IAAa,kBAA+D,OAAO,OAAO,CAAC,CAAC;;AAG5F,IAAa,gBAAkD,OAAO,OAAO,CAAC,CAAC;;;;;;;;;;;;;;;AAgB/E,IAAa,kBAA2B,OAAO,OAAO;CACrD,SAAS,OAAO,OAAO,CAAC,CAAC;CACzB,QAAQ,OAAO,OAAO,CAAC,CAAC;CACxB,WAAW,OAAO,OAAO;EACxB,2BAA2B;EAC3B,sBAAsB;EACtB,uBAAuB;EACvB,0BACC;EACD,uBAAuB;EACvB,8BAA8B;EAC9B,kBAAkB;EAClB,mBAAmB;EACnB,sBAAsB;EACtB,kBAAkB;EAClB,iBAAiB;CAClB,CAAC;AACF,CAAC;;;;;;;;;;;;;;;;ACnHD,IAAa,iBAAb,cAAoC,MAAM;CACzC;CACA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