@orkestrel/interpret 0.0.3 → 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.
@@ -0,0 +1,2605 @@
1
+ import { arrayOf, isBoolean, isFiniteNumber, isRecord, isString, notOf, parseJSONAs, recordOf, unionOf } from "@orkestrel/contract";
2
+ import { applyOperation, formatField, isDefinition, isFieldPath, isSymbolicExpression } from "@orkestrel/reason";
3
+ import { Emitter } from "@orkestrel/emitter";
4
+ import { fillTemplate } from "@orkestrel/template";
5
+ //#region src/core/constants.ts
6
+ /**
7
+ * Default `similarity` for `createInterpret` / `matchAlias` — the fuzzy
8
+ * alias-match score threshold (0..1).
9
+ *
10
+ * @remarks
11
+ * Domain-qualified (not a bare `DEFAULT_SIMILARITY`) so the name stays free
12
+ * of collision on the shared `@src/core` barrel, mirroring the
13
+ * `DEFAULT_REASON_BAIL` precedent.
14
+ */
15
+ var DEFAULT_INTERPRET_SIMILARITY = .8;
16
+ /**
17
+ * Default `floor` for `createInterpret` / `matchTemplate` — the minimum
18
+ * intent confidence a template match (or the classified intent itself) must
19
+ * clear.
20
+ */
21
+ var DEFAULT_INTERPRET_FLOOR = .3;
22
+ /** Default `history` cap for an `InterpretContext`'s `previous()` ring buffer. */
23
+ var DEFAULT_INTERPRET_HISTORY = 16;
24
+ /** Default `id` for an `Interpret` orchestrator. */
25
+ var INTERPRET_ID = "interpret";
26
+ /** Confidence assigned to an exact keyword-proximity entity match. */
27
+ var CONFIDENCE_EXACT = 1;
28
+ /** Confidence assigned to an exact alias-phrase entity match. */
29
+ var CONFIDENCE_ALIAS = .9;
30
+ /** Confidence assigned when a single entity mapping collects every extracted number. */
31
+ var CONFIDENCE_COLLECT = .9;
32
+ /** Confidence assigned to a positional (order-based) entity match fallback. */
33
+ var CONFIDENCE_POSITIONAL = .7;
34
+ /** Confidence assigned to a same-domain carried-over field. */
35
+ var CONFIDENCE_CARRIED = .7;
36
+ /** Confidence assigned to a template default fill. */
37
+ var CONFIDENCE_DEFAULT = 1;
38
+ /** Confidence assigned to a successfully resolved computed field. */
39
+ var CONFIDENCE_COMPUTED = .9;
40
+ /**
41
+ * The numeric-entity extraction pattern shared by `extractNumbers` and
42
+ * `assignEntities` — an optional leading `$`, thousands-comma-grouped digits,
43
+ * an optional decimal fraction, and an optional trailing `%`.
44
+ *
45
+ * @remarks
46
+ * Carries the global flag, so every call site builds a fresh `RegExp` from
47
+ * `.source` / `.flags` (mirrors the core-root `PLACEHOLDER_PATTERN` pattern)
48
+ * rather than sharing this instance's mutable `lastIndex` across scans.
49
+ */
50
+ var NUMBER_PATTERN = /(?:\$\s*)?(\d+(?:,\d{3})*(?:\.\d+)?)\s*%?/g;
51
+ /**
52
+ * Prototype-pollution-unsafe field-path segments — `setField` refuses to
53
+ * write ANY path containing one, returning its input unchanged.
54
+ */
55
+ var UNSAFE_FIELD_SEGMENTS = Object.freeze([
56
+ "__proto__",
57
+ "prototype",
58
+ "constructor"
59
+ ]);
60
+ /**
61
+ * Neutral built-in contraction expansions for `Normalizer` — small on
62
+ * purpose; callers merge their own map over this one.
63
+ */
64
+ var DEFAULT_CONTRACTIONS = Object.freeze({
65
+ "can't": "cannot",
66
+ "won't": "will not",
67
+ "it's": "it is",
68
+ "don't": "do not"
69
+ });
70
+ /** Neutral built-in abbreviation expansions for `Normalizer` — empty by default. */
71
+ var DEFAULT_ABBREVIATIONS = Object.freeze({});
72
+ /** Neutral built-in misspelling corrections for `Normalizer` — empty by default. */
73
+ var DEFAULT_CORRECTIONS = Object.freeze({});
74
+ /** Neutral built-in action-verb vocabulary for `Extractor#extract`'s intent classification — empty by default. */
75
+ var DEFAULT_ACTIONS = Object.freeze({});
76
+ /** Neutral built-in domain-keyword vocabulary for `Extractor#extract`'s intent classification — empty by default. */
77
+ var DEFAULT_DOMAINS = Object.freeze({});
78
+ /** Neutral built-in intent-verb phrasing for `Formatter#format` — empty by default. */
79
+ var DEFAULT_VERBS = Object.freeze({});
80
+ /**
81
+ * The neutral default `Lexicon` a `Narrator` merges caller data over.
82
+ *
83
+ * @remarks
84
+ * `phrases` and `labels` are empty — there is no built-in vocabulary or
85
+ * label overrides (AGENTS §21 mechanism-never-policy). `templates` carries
86
+ * the structural, display-neutral strings the reverse helpers formerly
87
+ * hardcoded, keyed by
88
+ * `{table}.{reasoning}` for the four reasons kinds, `result.quantitative.failed`
89
+ * for the quantitative-result failure suffix, and `subject.fields` /
90
+ * `subject.empty` for `describeSubject`. Every string is a plain
91
+ * @orkestrel/template `fillTemplate` template — `{{name}}`-style placeholders
92
+ * resolved against the caller-supplied `values` record.
93
+ */
94
+ var DEFAULT_LEXICON = Object.freeze({
95
+ phrases: Object.freeze({}),
96
+ labels: Object.freeze({}),
97
+ templates: Object.freeze({
98
+ "definition.quantitative": "{{name}}: {{count}} factor group(s)",
99
+ "definition.logical": "{{name}}: {{count}} rule(s), strategy {{strategy}}",
100
+ "definition.symbolic": "{{name}}: solve {{count}} equation(s)",
101
+ "definition.inferential": "{{name}}: {{facts}} fact(s)/{{inferences}} inference(s), {{strategy}}",
102
+ "result.quantitative": "scored {{value}} across {{count}} group(s)",
103
+ "result.quantitative.failed": "; failed: {{errors}}",
104
+ "result.logical": "{{status}}: {{count}} rule(s)",
105
+ "result.symbolic": "solved {{solved}}",
106
+ "result.inferential": "derived {{count}} fact(s)",
107
+ "subject.fields": "with {{fields}}",
108
+ "subject.empty": "with no fields"
109
+ })
110
+ });
111
+ //#endregion
112
+ //#region src/core/errors.ts
113
+ /**
114
+ * An error thrown by the interprets layer.
115
+ *
116
+ * @remarks
117
+ * Thrown for: an injected stage implementation throwing during its phase
118
+ * (`NORMALIZE_FAILED` / `EXTRACT_FAILED` / `CLARIFY_FAILED` /
119
+ * `FORMAT_FAILED` / `GENERATE_FAILED`), `createTemplate` handed data that
120
+ * fails `isTemplate` (`INVALID_TEMPLATE`), and any use of a destroyed
121
+ * `Interpret` / manager / context (`DESTROYED`). `NO_TEMPLATE` and
122
+ * `LOW_CONFIDENCE` never throw — they surface as a visible incomplete
123
+ * {@link Interpretation} instead (never an arbitrary fallback template).
124
+ * `context`, when present, carries the offending stage / template id.
125
+ */
126
+ var InterpretError = class extends Error {
127
+ code;
128
+ context;
129
+ constructor(code, message, context) {
130
+ super(message);
131
+ this.name = "InterpretError";
132
+ this.code = code;
133
+ this.context = context;
134
+ }
135
+ };
136
+ /**
137
+ * Narrow an unknown caught value to an {@link InterpretError}.
138
+ *
139
+ * @param value - The value to test (typically a `catch` binding)
140
+ * @returns `true` when `value` is an {@link InterpretError}
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * import { isInterpretError } from '@src/core'
145
+ *
146
+ * try {
147
+ * interpret.template('missing')
148
+ * } catch (error) {
149
+ * if (isInterpretError(error) && error.code === 'DESTROYED') return
150
+ * }
151
+ * ```
152
+ */
153
+ function isInterpretError(value) {
154
+ return value instanceof InterpretError;
155
+ }
156
+ //#endregion
157
+ //#region src/core/validators.ts
158
+ /**
159
+ * Determine whether a value is an {@link EntityMapping} — a literal
160
+ * alias-phrase extraction rule pointing at a subject field.
161
+ *
162
+ * @param value - The value to test
163
+ * @returns `true` when `value` is a well-formed entity mapping
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * import { isEntityMapping } from '@src/core'
168
+ *
169
+ * isEntityMapping({ entity: 'age', aliases: ['years old'], field: 'age' }) // true
170
+ * isEntityMapping({ entity: 'age', aliases: [/\d+/], field: 'age' }) // false — RegExp alias
171
+ * ```
172
+ */
173
+ function isEntityMapping(value) {
174
+ return recordOf({
175
+ entity: isString,
176
+ aliases: arrayOf(isString),
177
+ field: isFieldPath,
178
+ required: isBoolean
179
+ }, ["required"])(value);
180
+ }
181
+ /**
182
+ * Determine whether a value is a {@link FieldDefault} — a fallback value a
183
+ * {@link Template} fills onto an unresolved field.
184
+ *
185
+ * @remarks
186
+ * `value` is unconstrained (any value, including `null` or `undefined`) as
187
+ * long as the key is present — the trivially-true guard `notOf(unionOf())`
188
+ * mirrors the reasons `Check.value` precedent.
189
+ *
190
+ * @param value - The value to test
191
+ * @returns `true` when `value` is a well-formed field default
192
+ *
193
+ * @example
194
+ * ```ts
195
+ * import { isFieldDefault } from '@src/core'
196
+ *
197
+ * isFieldDefault({ field: 'term', value: 12 }) // true
198
+ * isFieldDefault({ field: 'term' }) // false — value missing
199
+ * ```
200
+ */
201
+ function isFieldDefault(value) {
202
+ return recordOf({
203
+ field: isFieldPath,
204
+ value: notOf(unionOf())
205
+ })(value);
206
+ }
207
+ /**
208
+ * Determine whether a value is a {@link ComputedField} — a declaratively
209
+ * computed field carrying a reasons {@link SymbolicExpression} tree.
210
+ *
211
+ * @param value - The value to test
212
+ * @returns `true` when `value` is a well-formed computed field
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * import { constant, operation, variable } from '@orkestrel/reason'
217
+ * import { isComputedField } from '@src/core'
218
+ *
219
+ * isComputedField({
220
+ * field: 'monthly',
221
+ * expression: operation('divide', variable('deductible'), constant(12)),
222
+ * }) // true
223
+ * isComputedField({ field: 'monthly', expression: { form: 'variable' } }) // false — name missing
224
+ * ```
225
+ */
226
+ function isComputedField(value) {
227
+ return recordOf({
228
+ field: isFieldPath,
229
+ expression: isSymbolicExpression
230
+ })(value);
231
+ }
232
+ /**
233
+ * Determine whether a value is a {@link Template} — a named, versionable
234
+ * interpretation template.
235
+ *
236
+ * @remarks
237
+ * `definition` is validated with reasons' `isDefinition` — a `Template`'s
238
+ * definition is already expressed in terrain reasons vocabulary, so no
239
+ * parallel interprets-owned definition guard exists.
240
+ *
241
+ * @param value - The value to test
242
+ * @returns `true` when `value` is a well-formed template
243
+ *
244
+ * @example
245
+ * ```ts
246
+ * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
247
+ * import { isTemplate } from '@src/core'
248
+ *
249
+ * isTemplate({
250
+ * id: 't1',
251
+ * name: 'Arithmetic',
252
+ * domain: 'arithmetic',
253
+ * intents: ['calculate'],
254
+ * mappings: [],
255
+ * defaults: [],
256
+ * computations: [],
257
+ * definition: quantitativeDefinition('t1', 'Arithmetic', [
258
+ * factorGroup('total', 'sum', [fieldFactor('value', 'value')]),
259
+ * ]),
260
+ * }) // true
261
+ * isTemplate({ id: 't1' }) // false — most fields missing
262
+ * ```
263
+ */
264
+ function isTemplate(value) {
265
+ return recordOf({
266
+ id: isString,
267
+ name: isString,
268
+ domain: isString,
269
+ intents: arrayOf(isString),
270
+ mappings: arrayOf(isEntityMapping),
271
+ defaults: arrayOf(isFieldDefault),
272
+ computations: arrayOf(isComputedField),
273
+ definition: isDefinition
274
+ })(value);
275
+ }
276
+ //#endregion
277
+ //#region src/core/helpers.ts
278
+ /**
279
+ * Escape every regex metacharacter in `text` so it matches literally when
280
+ * compiled into a `RegExp`.
281
+ *
282
+ * @param text - The literal text to escape
283
+ * @returns `text` with every regex metacharacter backslash-escaped
284
+ *
285
+ * @example
286
+ * ```ts
287
+ * import { escapeRegExp } from '@src/core'
288
+ *
289
+ * escapeRegExp('a.b*c') // 'a\\.b\\*c'
290
+ * new RegExp(escapeRegExp('a.b*c')).test('a.b*c') // true
291
+ * ```
292
+ */
293
+ function escapeRegExp(text) {
294
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
295
+ }
296
+ /**
297
+ * Copy-on-write write a value at a (possibly nested) field path on a subject.
298
+ *
299
+ * @remarks
300
+ * Never mutates `subject` — every level a `field` array descends through is
301
+ * freshly copied, so the input and every intermediate record stay untouched
302
+ * (AGENTS §11). Prototype-pollution-safe: a `field` containing `__proto__`,
303
+ * `prototype`, or `constructor` at ANY segment (checked against
304
+ * `UNSAFE_FIELD_SEGMENTS`) is refused as a no-op, returning `subject`
305
+ * unchanged. A non-record value already sitting at an intermediate segment is
306
+ * replaced by a fresh record rather than descended into.
307
+ *
308
+ * @param subject - The subject to derive from
309
+ * @param field - The (possibly nested) field path to write
310
+ * @param value - The value to write
311
+ * @returns A fresh subject with `value` written at `field`, or `subject`
312
+ * unchanged when `field` carries an unsafe segment
313
+ *
314
+ * @example
315
+ * ```ts
316
+ * import { setField } from '@src/core'
317
+ *
318
+ * setField({ age: 25 }, 'age', 30) // { age: 30 }
319
+ * setField({}, ['address', 'city'], 'Reno') // { address: { city: 'Reno' } }
320
+ * setField({}, ['__proto__', 'polluted'], true) // {} — refused, unchanged
321
+ * ```
322
+ */
323
+ /**
324
+ * Derive the sibling field path for a computed aggregate of `field` — the
325
+ * suffix is appended to `field`'s OWN last segment, so the aggregate nests
326
+ * beside the source field rather than flattening past it.
327
+ *
328
+ * @remarks
329
+ * For an array {@link FieldPath} (e.g. `['address', 'amounts']`) with suffix
330
+ * `'Sum'` the result is `['address', 'amountsSum']` — nested beside
331
+ * `address.amounts`. For a plain string field the result stays a flat string
332
+ * (`'amounts'` → `'amountsSum'`), matching the existing single-key behavior.
333
+ *
334
+ * @param field - The source field path
335
+ * @param suffix - The aggregate suffix (`'Sum'`, `'Count'`, `'Average'`, `'Minimum'`, `'Maximum'`)
336
+ * @returns The sibling field path for the aggregate
337
+ *
338
+ * @example
339
+ * ```ts
340
+ * import { deriveAggregateField } from '@src/core'
341
+ *
342
+ * deriveAggregateField(['address', 'amounts'], 'Sum') // ['address', 'amountsSum']
343
+ * deriveAggregateField('amounts', 'Sum') // 'amountsSum'
344
+ * ```
345
+ */
346
+ function deriveAggregateField(field, suffix) {
347
+ if (Array.isArray(field)) {
348
+ const last = field[field.length - 1];
349
+ return [...field.slice(0, -1), `${last}${suffix}`];
350
+ }
351
+ return `${field}${suffix}`;
352
+ }
353
+ function setField(subject, field, value) {
354
+ const path = Array.isArray(field) ? field : [field];
355
+ if (path.length === 0) return subject;
356
+ if (path.some((segment) => UNSAFE_FIELD_SEGMENTS.includes(segment))) return subject;
357
+ const [key, ...rest] = path;
358
+ if (key === void 0) return subject;
359
+ if (rest.length === 0) return {
360
+ ...subject,
361
+ [key]: value
362
+ };
363
+ const child = subject[key];
364
+ const nested = isRecord(child) ? child : {};
365
+ return {
366
+ ...subject,
367
+ [key]: setField(nested, rest, value)
368
+ };
369
+ }
370
+ /**
371
+ * Replace every whole-word occurrence of a map's keys with their values.
372
+ *
373
+ * @remarks
374
+ * Word-boundary safe (`in` never matches inside `information`) and
375
+ * case-insensitive; each key is regex-escaped via the core-root
376
+ * `escapeRegExp` before compiling, so a caller-supplied phrase containing
377
+ * regex metacharacters is matched literally. Multiple keys apply in
378
+ * `Object.entries` order — the `Normalizer` stage sequences its three maps
379
+ * (contractions, abbreviations, corrections) with three separate calls.
380
+ *
381
+ * @param text - The text to substitute within
382
+ * @param map - The `{ from: to }` substitution map
383
+ * @returns `text` with every whole-word match replaced
384
+ *
385
+ * @example
386
+ * ```ts
387
+ * import { applyReplacements } from '@src/core'
388
+ *
389
+ * applyReplacements("can't stop", { "can't": 'cannot' }) // 'cannot stop'
390
+ * applyReplacements('information', { in: 'IN' }) // 'information' — word-boundary safe
391
+ * ```
392
+ */
393
+ function applyReplacements(text, map) {
394
+ let result = text;
395
+ for (const [from, to] of Object.entries(map)) {
396
+ const pattern = new RegExp(`\\b${escapeRegExp(from)}\\b`, "gi");
397
+ result = result.replace(pattern, to);
398
+ }
399
+ return result;
400
+ }
401
+ /**
402
+ * Collapse every run of whitespace to a single space and trim the ends.
403
+ *
404
+ * @param text - The text to collapse
405
+ * @returns The collapsed text
406
+ *
407
+ * @example
408
+ * ```ts
409
+ * import { collapseWhitespace } from '@src/core'
410
+ *
411
+ * collapseWhitespace(' a b\t c ') // 'a b c'
412
+ * ```
413
+ */
414
+ function collapseWhitespace(text) {
415
+ return text.replace(/\s+/g, " ").trim();
416
+ }
417
+ /**
418
+ * Split text into lowercase tokens, stripping punctuation outside a small
419
+ * numeric/currency-safe allowlist.
420
+ *
421
+ * @remarks
422
+ * Shared by `classifyIntent` and `assignEntities` — pure ECMAScript
423
+ * (no locale-aware `Intl` segmentation), so multi-byte / astral text tokenizes
424
+ * on ASCII word boundaries only.
425
+ *
426
+ * @param text - The text to tokenize
427
+ * @returns The lowercase tokens, punctuation-stripped, empty tokens dropped
428
+ *
429
+ * @example
430
+ * ```ts
431
+ * import { tokenize } from '@src/core'
432
+ *
433
+ * tokenize('The rate is 85%.') // ['the', 'rate', 'is', '85%']
434
+ * ```
435
+ */
436
+ function tokenize(text) {
437
+ return text.toLowerCase().replace(/[^a-z0-9\s./%$'-]/g, " ").split(/\s+/).filter((token) => token.length > 0);
438
+ }
439
+ /**
440
+ * Mine every numeric literal from text — optional leading `$`, thousands
441
+ * commas, an optional decimal fraction, an optional trailing `%`.
442
+ *
443
+ * @remarks
444
+ * Numbers-only: this is the module's entire extraction contract (AGENTS
445
+ * §21 mechanism-never-policy) — no date, text-entity, or negation parsing.
446
+ *
447
+ * @param text - The text to scan
448
+ * @returns Every extracted number, in left-to-right order
449
+ *
450
+ * @example
451
+ * ```ts
452
+ * import { extractNumbers } from '@src/core'
453
+ *
454
+ * extractNumbers('income was $50,000, age 25') // [50000, 25]
455
+ * ```
456
+ */
457
+ function extractNumbers(text) {
458
+ const pattern = new RegExp(NUMBER_PATTERN.source, NUMBER_PATTERN.flags);
459
+ const numbers = [];
460
+ let match = pattern.exec(text);
461
+ while (match !== null) {
462
+ const raw = match[1];
463
+ if (raw !== void 0) {
464
+ const value = Number(raw.replace(/,/g, ""));
465
+ if (Number.isFinite(value)) numbers.push(value);
466
+ }
467
+ match = pattern.exec(text);
468
+ }
469
+ return numbers;
470
+ }
471
+ /**
472
+ * Assign already-extracted numbers to a matched template's entity mappings.
473
+ *
474
+ * @remarks
475
+ * Strategy, in order: (1) a SINGLE mapping collects every number (an array
476
+ * when more than one, a scalar otherwise) at `CONFIDENCE_COLLECT`. Otherwise,
477
+ * per mapping, the rightmost token in the text that equals the entity name
478
+ * (`CONFIDENCE_EXACT`), an alias exactly (`CONFIDENCE_ALIAS`), or an alias
479
+ * fuzzily (via `matchAlias`, confidence = its returned score) becomes a
480
+ * keyword anchor; anchors sort left-to-right and each claims its nearest
481
+ * unused number by text position. (3) Any mapping still unfilled claims the
482
+ * next unused number positionally, at `CONFIDENCE_POSITIONAL`. Every entity
483
+ * carries provenance `category: 'extracted'` with `detail` naming the
484
+ * strategy that filled it (`'collect' | 'keyword' | 'alias' | 'positional'`).
485
+ * Runs ONLY after a template has matched (an orchestrator-owned step, never
486
+ * inside `Extractor`, which stays template-agnostic).
487
+ *
488
+ * @param numbers - The numbers already extracted from `text` via `extractNumbers`
489
+ * @param mappings - The matched template's entity mappings
490
+ * @param text - The same text `numbers` was extracted from (for keyword proximity)
491
+ * @param similarity - The fuzzy alias-match score threshold (0..1)
492
+ * @returns The assigned entities, one per filled mapping
493
+ *
494
+ * @example
495
+ * ```ts
496
+ * import { assignEntities } from '@src/core'
497
+ *
498
+ * const mappings = [
499
+ * { entity: 'age', aliases: ['years old'], field: 'age' },
500
+ * { entity: 'score', aliases: ['credit score'], field: 'score' },
501
+ * ]
502
+ * assignEntities([25, 720], mappings, '25 year old with score 720', 0.8)
503
+ * // [{ name: 'age', value: 25, ... }, { name: 'score', value: 720, ... }]
504
+ * ```
505
+ */
506
+ function assignEntities(numbers, mappings, text, similarity) {
507
+ if (mappings.length === 0 || numbers.length === 0) return [];
508
+ if (mappings.length === 1) {
509
+ const mapping = mappings[0];
510
+ if (mapping === void 0) return [];
511
+ return [{
512
+ name: mapping.entity,
513
+ value: numbers.length === 1 ? numbers[0] : numbers,
514
+ provenance: {
515
+ category: "extracted",
516
+ detail: "collect"
517
+ },
518
+ confidence: CONFIDENCE_COLLECT
519
+ }];
520
+ }
521
+ const tokens = tokenize(text);
522
+ const lowerText = text.toLowerCase();
523
+ const positions = [];
524
+ const positionPattern = new RegExp(NUMBER_PATTERN.source, NUMBER_PATTERN.flags);
525
+ let positionMatch = positionPattern.exec(text);
526
+ while (positionMatch !== null) {
527
+ positions.push(positionMatch.index);
528
+ positionMatch = positionPattern.exec(text);
529
+ }
530
+ const keywordMatches = [];
531
+ for (const mapping of mappings) {
532
+ let matchedPosition = -1;
533
+ let matchedConfidence = 0;
534
+ let matchedDetail = "keyword";
535
+ const entityToken = mapping.entity.toLowerCase();
536
+ for (const token of tokens) {
537
+ const tokenPosition = lowerText.indexOf(token);
538
+ if (token === entityToken) {
539
+ if (tokenPosition > matchedPosition) {
540
+ matchedPosition = tokenPosition;
541
+ matchedConfidence = 1;
542
+ matchedDetail = "keyword";
543
+ }
544
+ continue;
545
+ }
546
+ if (mapping.aliases.some((alias) => alias.toLowerCase() === token)) {
547
+ if (tokenPosition > matchedPosition) {
548
+ matchedPosition = tokenPosition;
549
+ matchedConfidence = CONFIDENCE_ALIAS;
550
+ matchedDetail = "alias";
551
+ }
552
+ continue;
553
+ }
554
+ const fuzzy = matchAlias(token, mapping.aliases, similarity);
555
+ if (fuzzy > 0 && tokenPosition > matchedPosition) {
556
+ matchedPosition = tokenPosition;
557
+ matchedConfidence = fuzzy;
558
+ matchedDetail = "alias";
559
+ }
560
+ }
561
+ if (matchedPosition >= 0) keywordMatches.push({
562
+ mapping,
563
+ position: matchedPosition,
564
+ confidence: matchedConfidence,
565
+ detail: matchedDetail
566
+ });
567
+ }
568
+ keywordMatches.sort((a, b) => a.position - b.position);
569
+ const used = /* @__PURE__ */ new Set();
570
+ const filled = /* @__PURE__ */ new Set();
571
+ const entities = [];
572
+ for (const match of keywordMatches) {
573
+ let bestIndex = -1;
574
+ let bestDistance = Number.POSITIVE_INFINITY;
575
+ for (let index = 0; index < numbers.length; index += 1) {
576
+ if (used.has(index)) continue;
577
+ const position = positions[index];
578
+ if (position === void 0) continue;
579
+ const distance = Math.abs(position - match.position);
580
+ if (distance < bestDistance) {
581
+ bestDistance = distance;
582
+ bestIndex = index;
583
+ }
584
+ }
585
+ if (bestIndex >= 0) {
586
+ const value = numbers[bestIndex];
587
+ if (value !== void 0) {
588
+ used.add(bestIndex);
589
+ filled.add(match.mapping.entity);
590
+ entities.push({
591
+ name: match.mapping.entity,
592
+ value,
593
+ provenance: {
594
+ category: "extracted",
595
+ detail: match.detail
596
+ },
597
+ confidence: match.confidence
598
+ });
599
+ }
600
+ }
601
+ }
602
+ let numberIndex = 0;
603
+ for (const mapping of mappings) {
604
+ if (filled.has(mapping.entity)) continue;
605
+ while (numberIndex < numbers.length && used.has(numberIndex)) numberIndex += 1;
606
+ if (numberIndex >= numbers.length) break;
607
+ const value = numbers[numberIndex];
608
+ if (value !== void 0) {
609
+ used.add(numberIndex);
610
+ filled.add(mapping.entity);
611
+ entities.push({
612
+ name: mapping.entity,
613
+ value,
614
+ provenance: {
615
+ category: "extracted",
616
+ detail: "positional"
617
+ },
618
+ confidence: CONFIDENCE_POSITIONAL
619
+ });
620
+ }
621
+ numberIndex += 1;
622
+ }
623
+ return entities;
624
+ }
625
+ /**
626
+ * Classify the action + domain intent of a text against caller-supplied
627
+ * vocabularies.
628
+ *
629
+ * @remarks
630
+ * `actions` maps a token to an action name — the first matching token in
631
+ * `text` (left to right) wins, at `CONFIDENCE_EXACT`. `domains` maps a domain
632
+ * name to its keyword list — the domain with the most matching tokens wins
633
+ * (ties keep the earliest-declared domain), also at `CONFIDENCE_EXACT`.
634
+ * Combined confidence (PINNED): both fire → their average; exactly one fires
635
+ * → its value times `0.5`; neither → `0`. There is no built-in worldview and
636
+ * no auto-classification from a registered template's own `domain` name — a
637
+ * caller MUST list a template's domain among `domains` for it to classify.
638
+ * No `floor` parameter: the confidence floor gate lives at the orchestrator's
639
+ * `matchTemplate` step, never inside classification itself.
640
+ *
641
+ * @param text - The (normalized) text to classify
642
+ * @param actions - The caller's token → action-name vocabulary
643
+ * @param domains - The caller's domain-name → keyword-list vocabulary
644
+ * @returns The classified intent
645
+ *
646
+ * @example
647
+ * ```ts
648
+ * import { classifyIntent } from '@src/core'
649
+ *
650
+ * classifyIntent('calculate my rate', { calculate: 'compute' }, { rating: ['rate'] })
651
+ * // { action: 'compute', domain: 'rating', confidence: 1 }
652
+ * classifyIntent('hello', {}, {}) // { action: '', domain: '', confidence: 0 }
653
+ * ```
654
+ */
655
+ function classifyIntent(text, actions, domains) {
656
+ const tokens = tokenize(text);
657
+ let action = "";
658
+ let actionConfidence = 0;
659
+ for (const token of tokens) {
660
+ const mapped = actions[token];
661
+ if (mapped !== void 0) {
662
+ action = mapped;
663
+ actionConfidence = 1;
664
+ break;
665
+ }
666
+ }
667
+ let domain = "";
668
+ let domainConfidence = 0;
669
+ let bestMatches = 0;
670
+ for (const [name, keywords] of Object.entries(domains)) {
671
+ const lowerKeywords = keywords.map((keyword) => keyword.toLowerCase());
672
+ let matches = 0;
673
+ for (const token of tokens) if (lowerKeywords.includes(token)) matches += 1;
674
+ if (matches > bestMatches) {
675
+ bestMatches = matches;
676
+ domain = name;
677
+ domainConfidence = 1;
678
+ }
679
+ }
680
+ const confidence = actionConfidence > 0 && domainConfidence > 0 ? (actionConfidence + domainConfidence) / 2 : Math.max(actionConfidence, domainConfidence) * .5;
681
+ return {
682
+ action,
683
+ domain,
684
+ confidence
685
+ };
686
+ }
687
+ /**
688
+ * Bigram (Dice coefficient) string similarity, case-insensitive.
689
+ *
690
+ * @param a - The first string
691
+ * @param b - The second string
692
+ * @returns A score in `[0, 1]` — `1` for an exact (case-insensitive) match,
693
+ * `0` when either string is shorter than 2 characters and they are not equal
694
+ *
695
+ * @example
696
+ * ```ts
697
+ * import { scoreSimilarity } from '@src/core'
698
+ *
699
+ * scoreSimilarity('rate', 'rate') // 1
700
+ * scoreSimilarity('rate', 'value') // 0 — no shared bigrams
701
+ * ```
702
+ */
703
+ function scoreSimilarity(a, b) {
704
+ const left = a.toLowerCase();
705
+ const right = b.toLowerCase();
706
+ if (left === right) return 1;
707
+ if (left.length < 2 || right.length < 2) return 0;
708
+ const bigrams = /* @__PURE__ */ new Map();
709
+ for (let index = 0; index < left.length - 1; index += 1) {
710
+ const bigram = left.slice(index, index + 2);
711
+ bigrams.set(bigram, (bigrams.get(bigram) ?? 0) + 1);
712
+ }
713
+ let matches = 0;
714
+ for (let index = 0; index < right.length - 1; index += 1) {
715
+ const bigram = right.slice(index, index + 2);
716
+ const count = bigrams.get(bigram);
717
+ if (count !== void 0 && count > 0) {
718
+ bigrams.set(bigram, count - 1);
719
+ matches += 1;
720
+ }
721
+ }
722
+ return 2 * matches / (left.length - 1 + (right.length - 1));
723
+ }
724
+ /**
725
+ * The best `scoreSimilarity` a token achieves against a list of aliases,
726
+ * gated by a threshold.
727
+ *
728
+ * @param token - The token to score
729
+ * @param aliases - The alias phrases to score against
730
+ * @param threshold - The minimum score to report (an explicit no-match below it)
731
+ * @returns The best score when it meets `threshold`, else `0`
732
+ *
733
+ * @example
734
+ * ```ts
735
+ * import { matchAlias } from '@src/core'
736
+ *
737
+ * matchAlias('valu', ['value', 'amount'], 0.6) // ~0.86 — fuzzy hit on 'value'
738
+ * matchAlias('xyz', ['value', 'amount'], 0.6) // 0 — no alias clears the threshold
739
+ * ```
740
+ */
741
+ function matchAlias(token, aliases, threshold) {
742
+ let best = 0;
743
+ for (const alias of aliases) {
744
+ const score = scoreSimilarity(token, alias);
745
+ if (score > best) best = score;
746
+ }
747
+ return best >= threshold ? best : 0;
748
+ }
749
+ /**
750
+ * Render a value into a canonical, key-order-stable string — the pre-image
751
+ * of `digestValue`.
752
+ *
753
+ * @remarks
754
+ * Ported from the app's `raters` digest machinery (`app/core/raters/helpers.ts`)
755
+ * — record keys sort before serialization so a re-ordered object canonicalizes
756
+ * identically; arrays keep position order (position is meaningful).
757
+ * Cycle-safe and total (AGENTS §14): `visited` tracks the object ancestors
758
+ * along the CURRENT recursion path (not a global "seen" set, so the same
759
+ * object reachable twice via non-cyclic sibling branches still canonicalizes
760
+ * normally); revisiting an ancestor renders that node as the literal string
761
+ * `'[cycle]'` instead of recursing — deterministic, never throws, never
762
+ * overflows the call stack.
763
+ *
764
+ * @param value - The value to canonicalize
765
+ * @param visited - The object ancestors along the current recursion path (internal; omit at the call site)
766
+ * @returns The canonical string form
767
+ *
768
+ * @example
769
+ * ```ts
770
+ * import { canonicalize } from '@src/core'
771
+ *
772
+ * canonicalize({ b: 1, a: 2 }) === canonicalize({ a: 2, b: 1 }) // true
773
+ * ```
774
+ */
775
+ function canonicalize(value, visited = /* @__PURE__ */ new Set()) {
776
+ if (Array.isArray(value)) {
777
+ if (visited.has(value)) return JSON.stringify("[cycle]");
778
+ const nextVisited = new Set(visited);
779
+ nextVisited.add(value);
780
+ return `[${value.map((entry) => canonicalize(entry, nextVisited)).join(",")}]`;
781
+ }
782
+ if (isRecord(value)) {
783
+ if (visited.has(value)) return JSON.stringify("[cycle]");
784
+ const nextVisited = new Set(visited);
785
+ nextVisited.add(value);
786
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalize(value[key], nextVisited)}`).join(",")}}`;
787
+ }
788
+ return JSON.stringify(value) ?? "null";
789
+ }
790
+ /**
791
+ * Compute a canonical structural digest of a pure-JSON value — a key-order-
792
+ * stable FNV-1a hash rendered as an 8-hex-digit string.
793
+ *
794
+ * @remarks
795
+ * Pure ECMAScript, no host crypto (AGENTS §17.7) — the same algorithm as the
796
+ * app's `digest`, ported into core so `Interpretation.digest` and the
797
+ * versioned managers can hash without leaving strict core.
798
+ *
799
+ * @param value - The value to digest
800
+ * @returns The 8-character hex digest
801
+ *
802
+ * @example
803
+ * ```ts
804
+ * import { digestValue } from '@src/core'
805
+ *
806
+ * digestValue({ a: 1 }) === digestValue({ a: 1 }) // true — deterministic
807
+ * ```
808
+ */
809
+ function digestValue(value) {
810
+ const canonical = canonicalize(value);
811
+ let hash = 2166136261;
812
+ for (let index = 0; index < canonical.length; index += 1) {
813
+ hash ^= canonical.charCodeAt(index);
814
+ hash = Math.imul(hash, 16777619);
815
+ }
816
+ return (hash >>> 0).toString(16).padStart(8, "0");
817
+ }
818
+ /**
819
+ * Score how well a classified intent matches one template's domain + action.
820
+ *
821
+ * @param intent - The classified intent
822
+ * @param template - The candidate template
823
+ * @returns A score in `[0, 1]` — the mean of the domain match (`1`/`0`) and
824
+ * the action match (`1`/`0`, `template.intents` containing `intent.action`)
825
+ *
826
+ * @example
827
+ * ```ts
828
+ * import { scoreTemplate } from '@src/core'
829
+ *
830
+ * scoreTemplate(
831
+ * { action: 'compute', domain: 'rating', confidence: 1 },
832
+ * { id: 't1', name: 'T', domain: 'rating', intents: ['compute'], mappings: [], defaults: [], computations: [], definition: { reasoning: 'symbolic', id: 't1', name: 'T', equations: [], variables: {} } },
833
+ * ) // 1
834
+ * ```
835
+ */
836
+ function scoreTemplate(intent, template) {
837
+ return ((template.domain.toLowerCase() === intent.domain.toLowerCase() ? 1 : 0) + (template.intents.some((candidate) => candidate.toLowerCase() === intent.action.toLowerCase()) ? 1 : 0)) / 2;
838
+ }
839
+ /**
840
+ * Find the best-scoring registered template for a classified intent, gated
841
+ * by a confidence floor.
842
+ *
843
+ * @remarks
844
+ * Explicit no-match (AGENTS-flagged scsr defect 2 — never an arbitrary
845
+ * `templates[0]` fallback): an empty registry, or a best score strictly below
846
+ * `floor`, both return `undefined`.
847
+ *
848
+ * @param intent - The classified intent
849
+ * @param templates - The registered templates to score
850
+ * @param floor - The minimum score a match must clear
851
+ * @returns The best-scoring template, or `undefined` on no qualifying match
852
+ *
853
+ * @example
854
+ * ```ts
855
+ * import { matchTemplate } from '@src/core'
856
+ *
857
+ * matchTemplate({ action: '', domain: '', confidence: 0 }, [], 0.3) // undefined — empty registry
858
+ * ```
859
+ */
860
+ function matchTemplate(intent, templates, floor) {
861
+ let best;
862
+ let bestScore = -1;
863
+ for (const template of templates) {
864
+ const score = scoreTemplate(intent, template);
865
+ if (score > bestScore) {
866
+ bestScore = score;
867
+ best = template;
868
+ }
869
+ }
870
+ return best !== void 0 && bestScore >= floor ? best : void 0;
871
+ }
872
+ /**
873
+ * Collect every variable name referenced by a symbolic expression tree, in
874
+ * first-occurrence order.
875
+ *
876
+ * @param expression - The expression tree to scan
877
+ * @returns The referenced variable names, deduplicated
878
+ *
879
+ * @example
880
+ * ```ts
881
+ * import { constant, operation, variable } from '@orkestrel/reason'
882
+ * import { variablesOf } from '@src/core'
883
+ *
884
+ * variablesOf(operation('divide', variable('deductible'), constant(12))) // ['deductible']
885
+ * ```
886
+ */
887
+ function variablesOf(expression) {
888
+ const names = [];
889
+ const seen = /* @__PURE__ */ new Set();
890
+ function collect(node) {
891
+ if (node.form === "variable") {
892
+ if (!seen.has(node.name)) {
893
+ seen.add(node.name);
894
+ names.push(node.name);
895
+ }
896
+ return;
897
+ }
898
+ if (node.form === "operation") {
899
+ collect(node.left);
900
+ if (node.right !== void 0) collect(node.right);
901
+ }
902
+ }
903
+ collect(expression);
904
+ return names;
905
+ }
906
+ /**
907
+ * Evaluate a symbolic expression tree against resolved bindings.
908
+ *
909
+ * @remarks
910
+ * THE critical leaf (design-pinned, engine-parity semantics): an absent
911
+ * `right` operand on a binary operation defaults to `0` — matching
912
+ * `SymbolicReasoner`'s internal `#evaluate` — and is always passed as an
913
+ * EXPLICIT numeric operand, so the same tree evaluates identically here and
914
+ * inside the engine. Each arithmetic step delegates to the reasons
915
+ * `applyOperation` pure function, mapping the node's `.operator` field onto
916
+ * its `operator` parameter. An unresolved input variable, or a non-finite
917
+ * result (`NaN` from a divide-by-zero, or an overflowing `±Infinity`),
918
+ * becomes a gap — `undefined`, never landing on a subject.
919
+ *
920
+ * @param expression - The expression tree to evaluate
921
+ * @param bindings - The resolved variable bindings
922
+ * @returns The evaluated number, or `undefined` on an unresolved input or a
923
+ * non-finite result
924
+ *
925
+ * @example
926
+ * ```ts
927
+ * import { constant, operation, variable } from '@orkestrel/reason'
928
+ * import { resolveExpression } from '@src/core'
929
+ *
930
+ * resolveExpression(operation('divide', variable('deductible'), constant(12)), { deductible: 6000 }) // 500
931
+ * resolveExpression(operation('divide', constant(1), constant(0)), {}) // undefined — NaN gap
932
+ * resolveExpression(variable('missing'), {}) // undefined — unresolved input
933
+ * ```
934
+ */
935
+ function resolveExpression(expression, bindings) {
936
+ if (expression.form === "constant") return expression.value;
937
+ if (expression.form === "variable") return bindings[expression.name];
938
+ const left = resolveExpression(expression.left, bindings);
939
+ if (left === void 0) return void 0;
940
+ const right = expression.right === void 0 ? 0 : resolveExpression(expression.right, bindings);
941
+ if (right === void 0) return void 0;
942
+ const result = applyOperation(expression.operator, left, right);
943
+ return isFiniteNumber(result) ? result : void 0;
944
+ }
945
+ /**
946
+ * Render a one-line, display-neutral description of a reasons `Subject`,
947
+ * through an injected `Narrator`.
948
+ *
949
+ * @remarks
950
+ * Complements — never duplicates — the raters `describe*` family (which
951
+ * describes RATERS artifacts); this describes REASONS artifacts. Every field
952
+ * renders via `narrator.label` + `narrator.value` (looked up under the
953
+ * `'units'` phrase table, falling back to `'plain'`) — the wording is fully
954
+ * lexicon-driven (AGENTS §21 mechanism-never-policy); `Definition` /
955
+ * `ReasonResult` narration lives on `Narrator#describe` / `Narrator#narrate`
956
+ * directly.
957
+ *
958
+ * @param subject - The subject to describe
959
+ * @param narrator - The lexicon-driven renderer to render field labels/values/lines through
960
+ * @returns A one-line description, the lexicon's `'subject.empty'` line when empty
961
+ *
962
+ * @example
963
+ * ```ts
964
+ * import { createNarrator, describeSubject } from '@src/core'
965
+ *
966
+ * describeSubject({ age: 25, income: 50000 }, createNarrator()) // 'with age: 25, income: 50000'
967
+ * ```
968
+ */
969
+ function describeSubject(subject, narrator) {
970
+ const keys = Object.keys(subject).sort();
971
+ if (keys.length === 0) return narrator.line("subject.empty", {});
972
+ const parts = keys.map((key) => {
973
+ const unit = narrator.phrase("units", key, "plain");
974
+ return `${narrator.label(key)}: ${narrator.value(unit, subject[key])}`;
975
+ });
976
+ return narrator.line("subject.fields", { fields: parts.join(", ") });
977
+ }
978
+ /**
979
+ * Parse a JSON string into a `Template`, or `undefined` on invalid JSON or a
980
+ * shape that fails `isTemplate`.
981
+ *
982
+ * @remarks
983
+ * The module's sole JSON boundary (design §4) — an `Interpretation` and the
984
+ * versioned records are produced internally, never deserialized from
985
+ * untrusted JSON; replay re-runs `interpret`, it does not deserialize a
986
+ * stored result.
987
+ *
988
+ * @param value - The JSON text to parse
989
+ * @returns The parsed template, or `undefined`
990
+ *
991
+ * @example
992
+ * ```ts
993
+ * import { parseTemplate } from '@src/core'
994
+ *
995
+ * parseTemplate('not json') // undefined
996
+ * ```
997
+ */
998
+ function parseTemplate(value) {
999
+ return parseJSONAs(value, isTemplate);
1000
+ }
1001
+ //#endregion
1002
+ //#region src/core/managers/DefinitionManager.ts
1003
+ /**
1004
+ * The definition registry — a self-owning, versioned and content-hashed
1005
+ * record-holder for the reasons {@link Definition}s an interpretation produces.
1006
+ *
1007
+ * @remarks
1008
+ * Mirrors {@link TemplateManager}: `add` defaults each record id to the
1009
+ * definition's own `id`, derives `hash` from the definition CONTENT
1010
+ * (id-independent), and bumps `version` ONLY when that hash changes at a reused
1011
+ * id — an identical re-add keeps its version. The batch `remove(ids)` form is
1012
+ * all-or-nothing; `destroy()` is idempotent and every method afterwards throws
1013
+ * `InterpretError('DESTROYED', …)`.
1014
+ *
1015
+ * @example
1016
+ * ```ts
1017
+ * import { symbolicDefinition } from '@orkestrel/reason'
1018
+ * import { DefinitionManager } from '@src/core'
1019
+ *
1020
+ * const manager = new DefinitionManager()
1021
+ * const record = manager.add(symbolicDefinition('rate', 'Rate', []))
1022
+ * record.id // 'rate'
1023
+ * manager.add(symbolicDefinition('rate', 'Rate', [])).version // 1 — identical re-add, no bump
1024
+ * ```
1025
+ */
1026
+ var DefinitionManager = class {
1027
+ #records = /* @__PURE__ */ new Map();
1028
+ #emitter;
1029
+ #destroyed = false;
1030
+ constructor(options) {
1031
+ this.#emitter = new Emitter({
1032
+ on: options?.on,
1033
+ error: options?.error
1034
+ });
1035
+ for (const definition of options?.definitions ?? []) this.add(definition);
1036
+ }
1037
+ get emitter() {
1038
+ return this.#emitter;
1039
+ }
1040
+ get size() {
1041
+ this.#ensureAlive();
1042
+ return this.#records.size;
1043
+ }
1044
+ has(id) {
1045
+ this.#ensureAlive();
1046
+ return this.#records.has(id);
1047
+ }
1048
+ definition(id) {
1049
+ this.#ensureAlive();
1050
+ return this.#records.get(id);
1051
+ }
1052
+ definitions() {
1053
+ this.#ensureAlive();
1054
+ return [...this.#records.values()];
1055
+ }
1056
+ add(definition, options) {
1057
+ this.#ensureAlive();
1058
+ const id = options?.id ?? definition.id;
1059
+ const hash = digestValue(definition);
1060
+ const existing = this.#records.get(id);
1061
+ const record = {
1062
+ id,
1063
+ definition,
1064
+ version: existing === void 0 ? 1 : existing.hash === hash ? existing.version : existing.version + 1,
1065
+ hash
1066
+ };
1067
+ this.#records.set(id, record);
1068
+ this.#emitter.emit("add", id);
1069
+ return record;
1070
+ }
1071
+ remove(target) {
1072
+ this.#ensureAlive();
1073
+ if (target === void 0) {
1074
+ for (const id of this.#records.keys()) this.#emitter.emit("remove", id);
1075
+ this.#records.clear();
1076
+ return;
1077
+ }
1078
+ if (typeof target === "string") {
1079
+ const removed = this.#records.delete(target);
1080
+ if (removed) this.#emitter.emit("remove", target);
1081
+ return removed;
1082
+ }
1083
+ for (const id of target) if (!this.#records.has(id)) return false;
1084
+ for (const id of target) {
1085
+ this.#records.delete(id);
1086
+ this.#emitter.emit("remove", id);
1087
+ }
1088
+ return true;
1089
+ }
1090
+ destroy() {
1091
+ if (this.#destroyed) return;
1092
+ this.#records.clear();
1093
+ this.#destroyed = true;
1094
+ this.#emitter.emit("destroy");
1095
+ this.#emitter.destroy();
1096
+ }
1097
+ #ensureAlive() {
1098
+ if (this.#destroyed) throw new InterpretError("DESTROYED", "Definition manager has been destroyed");
1099
+ }
1100
+ };
1101
+ //#endregion
1102
+ //#region src/core/managers/SubjectManager.ts
1103
+ /**
1104
+ * The subject registry — a self-owning, versioned and content-hashed
1105
+ * record-holder that mints its OWN record identity for every {@link Subject}
1106
+ * (a `Subject` carries no `id` field of its own).
1107
+ *
1108
+ * @remarks
1109
+ * The defect-7 fix: scsr keyed stored subjects by their definition's id, so
1110
+ * successive same-domain turns silently overwrote one shared subject. Here each
1111
+ * `add` mints a fresh `subject-{n}` id (deterministic per instance, no host
1112
+ * randomness — AGENTS §17.7) unless the caller overrides it via
1113
+ * `ManagerAddOptions.id`. `hash` is content-derived (id-independent) and
1114
+ * `version` bumps ONLY when the hash changes at a reused id. The batch
1115
+ * `remove(ids)` form is all-or-nothing; `destroy()` is idempotent and every
1116
+ * method afterwards throws `InterpretError('DESTROYED', …)`.
1117
+ *
1118
+ * @example
1119
+ * ```ts
1120
+ * import { SubjectManager } from '@src/core'
1121
+ *
1122
+ * const manager = new SubjectManager()
1123
+ * const first = manager.add({ age: 25 })
1124
+ * const second = manager.add({ age: 30 })
1125
+ * first.id !== second.id // true — each subject gets its own identity
1126
+ * ```
1127
+ */
1128
+ var SubjectManager = class {
1129
+ #records = /* @__PURE__ */ new Map();
1130
+ #emitter;
1131
+ #counter = 0;
1132
+ #destroyed = false;
1133
+ constructor(options) {
1134
+ this.#emitter = new Emitter({
1135
+ on: options?.on,
1136
+ error: options?.error
1137
+ });
1138
+ for (const subject of options?.subjects ?? []) this.add(subject);
1139
+ }
1140
+ get emitter() {
1141
+ return this.#emitter;
1142
+ }
1143
+ get size() {
1144
+ this.#ensureAlive();
1145
+ return this.#records.size;
1146
+ }
1147
+ has(id) {
1148
+ this.#ensureAlive();
1149
+ return this.#records.has(id);
1150
+ }
1151
+ subject(id) {
1152
+ this.#ensureAlive();
1153
+ return this.#records.get(id);
1154
+ }
1155
+ subjects() {
1156
+ this.#ensureAlive();
1157
+ return [...this.#records.values()];
1158
+ }
1159
+ add(subject, options) {
1160
+ this.#ensureAlive();
1161
+ let id = options?.id;
1162
+ if (id === void 0) {
1163
+ id = `subject-${this.#counter}`;
1164
+ this.#counter += 1;
1165
+ }
1166
+ const hash = digestValue(subject);
1167
+ const existing = this.#records.get(id);
1168
+ const version = existing === void 0 ? 1 : existing.hash === hash ? existing.version : existing.version + 1;
1169
+ const record = {
1170
+ id,
1171
+ subject,
1172
+ version,
1173
+ hash
1174
+ };
1175
+ this.#records.set(id, record);
1176
+ this.#emitter.emit("add", id);
1177
+ return record;
1178
+ }
1179
+ remove(target) {
1180
+ this.#ensureAlive();
1181
+ if (target === void 0) {
1182
+ for (const id of this.#records.keys()) this.#emitter.emit("remove", id);
1183
+ this.#records.clear();
1184
+ return;
1185
+ }
1186
+ if (typeof target === "string") {
1187
+ const removed = this.#records.delete(target);
1188
+ if (removed) this.#emitter.emit("remove", target);
1189
+ return removed;
1190
+ }
1191
+ for (const id of target) if (!this.#records.has(id)) return false;
1192
+ for (const id of target) {
1193
+ this.#records.delete(id);
1194
+ this.#emitter.emit("remove", id);
1195
+ }
1196
+ return true;
1197
+ }
1198
+ destroy() {
1199
+ if (this.#destroyed) return;
1200
+ this.#records.clear();
1201
+ this.#destroyed = true;
1202
+ this.#emitter.emit("destroy");
1203
+ this.#emitter.destroy();
1204
+ }
1205
+ #ensureAlive() {
1206
+ if (this.#destroyed) throw new InterpretError("DESTROYED", "Subject manager has been destroyed");
1207
+ }
1208
+ };
1209
+ //#endregion
1210
+ //#region src/core/managers/InterpretContext.ts
1211
+ /**
1212
+ * Cross-turn interpretation context — a capped, replayable history of
1213
+ * completed {@link Interpretation}s plus the subject and definition registries
1214
+ * carry-over reads from.
1215
+ *
1216
+ * @remarks
1217
+ * `previous()` is a capped ring buffer (newest-last, oldest dropped once the
1218
+ * `history` cap is reached — `DEFAULT_INTERPRET_HISTORY` by default, ≥ 3
1219
+ * preserves the carry-over pin) rather than scsr's unbounded `previous` array.
1220
+ * `entities()` flattens every entity across the buffered history, most recent
1221
+ * last — the read a `Clarifier`'s same-domain carry-over consults. `add` pushes
1222
+ * one result and trims to the cap; `clear` resets the history and both
1223
+ * registries WITHOUT tearing the context down; `destroy()` is idempotent and
1224
+ * every method afterwards throws `InterpretError('DESTROYED', …)`.
1225
+ *
1226
+ * @example
1227
+ * ```ts
1228
+ * import { InterpretContext } from '@src/core'
1229
+ *
1230
+ * const context = new InterpretContext({ session: 's1', history: 8 })
1231
+ * context.session // 's1'
1232
+ * context.previous() // []
1233
+ * ```
1234
+ */
1235
+ var InterpretContext = class {
1236
+ #session;
1237
+ #subjects;
1238
+ #definitions;
1239
+ #history;
1240
+ #previous = [];
1241
+ #emitter;
1242
+ #destroyed = false;
1243
+ constructor(options) {
1244
+ this.#session = options?.session;
1245
+ this.#history = Math.max(0, options?.history ?? 16);
1246
+ this.#subjects = new SubjectManager();
1247
+ this.#definitions = new DefinitionManager();
1248
+ this.#emitter = new Emitter({
1249
+ on: options?.on,
1250
+ error: options?.error
1251
+ });
1252
+ }
1253
+ get emitter() {
1254
+ return this.#emitter;
1255
+ }
1256
+ get session() {
1257
+ this.#ensureAlive();
1258
+ return this.#session;
1259
+ }
1260
+ get subjects() {
1261
+ this.#ensureAlive();
1262
+ return this.#subjects;
1263
+ }
1264
+ get definitions() {
1265
+ this.#ensureAlive();
1266
+ return this.#definitions;
1267
+ }
1268
+ previous() {
1269
+ this.#ensureAlive();
1270
+ return [...this.#previous];
1271
+ }
1272
+ entities() {
1273
+ this.#ensureAlive();
1274
+ return this.#previous.flatMap((result) => [...result.entities]);
1275
+ }
1276
+ add(result) {
1277
+ this.#ensureAlive();
1278
+ this.#previous.push(result);
1279
+ while (this.#previous.length > this.#history) this.#previous.shift();
1280
+ this.#emitter.emit("add", result.digest);
1281
+ }
1282
+ clear() {
1283
+ this.#ensureAlive();
1284
+ this.#previous.length = 0;
1285
+ this.#subjects.remove();
1286
+ this.#definitions.remove();
1287
+ this.#emitter.emit("clear");
1288
+ }
1289
+ destroy() {
1290
+ if (this.#destroyed) return;
1291
+ this.#previous.length = 0;
1292
+ this.#subjects.destroy();
1293
+ this.#definitions.destroy();
1294
+ this.#destroyed = true;
1295
+ this.#emitter.emit("destroy");
1296
+ this.#emitter.destroy();
1297
+ }
1298
+ #ensureAlive() {
1299
+ if (this.#destroyed) throw new InterpretError("DESTROYED", "Interpret context has been destroyed");
1300
+ }
1301
+ };
1302
+ //#endregion
1303
+ //#region src/core/managers/TemplateManager.ts
1304
+ /**
1305
+ * The template registry — a self-owning, versioned and content-hashed
1306
+ * record-holder for the {@link Template}s an `Interpret` orchestrator matches
1307
+ * against.
1308
+ *
1309
+ * @remarks
1310
+ * `size` (never `count` — the sole tally in scope) plus the AGENTS §9.1
1311
+ * singular/plural accessors (`template` / `templates`) and the §9.2 batch
1312
+ * `remove` overloads. `add` derives each record's `hash` from the template's
1313
+ * CONTENT (id-independent — the same template data hashes identically under
1314
+ * any record id) and bumps `version` ONLY when that hash changes: an identical
1315
+ * re-add keeps its version (unlike scsr, which bumped on every add). The
1316
+ * batch `remove(ids)` form is ALL-OR-NOTHING — any id absent from the registry
1317
+ * leaves the collection untouched and returns `false`. `destroy()` is
1318
+ * idempotent; every method afterwards throws `InterpretError('DESTROYED', …)`.
1319
+ *
1320
+ * @example
1321
+ * ```ts
1322
+ * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
1323
+ * import { TemplateManager } from '@src/core'
1324
+ *
1325
+ * const manager = new TemplateManager()
1326
+ * const record = manager.add({
1327
+ * id: 't1',
1328
+ * name: 'Arithmetic',
1329
+ * domain: 'arithmetic',
1330
+ * intents: ['calculate'],
1331
+ * mappings: [],
1332
+ * defaults: [],
1333
+ * computations: [],
1334
+ * definition: quantitativeDefinition('t1', 'Arithmetic', [
1335
+ * factorGroup('total', 'sum', [fieldFactor('value', 'value')]),
1336
+ * ]),
1337
+ * })
1338
+ * record.version // 1
1339
+ * manager.size // 1
1340
+ * ```
1341
+ */
1342
+ var TemplateManager = class {
1343
+ #records = /* @__PURE__ */ new Map();
1344
+ #emitter;
1345
+ #destroyed = false;
1346
+ constructor(options) {
1347
+ this.#emitter = new Emitter({
1348
+ on: options?.on,
1349
+ error: options?.error
1350
+ });
1351
+ for (const template of options?.templates ?? []) this.add(template);
1352
+ }
1353
+ get emitter() {
1354
+ return this.#emitter;
1355
+ }
1356
+ get size() {
1357
+ this.#ensureAlive();
1358
+ return this.#records.size;
1359
+ }
1360
+ has(id) {
1361
+ this.#ensureAlive();
1362
+ return this.#records.has(id);
1363
+ }
1364
+ template(id) {
1365
+ this.#ensureAlive();
1366
+ return this.#records.get(id);
1367
+ }
1368
+ templates() {
1369
+ this.#ensureAlive();
1370
+ return [...this.#records.values()];
1371
+ }
1372
+ add(template, options) {
1373
+ this.#ensureAlive();
1374
+ const id = options?.id ?? template.id;
1375
+ const hash = digestValue(template);
1376
+ const existing = this.#records.get(id);
1377
+ const record = {
1378
+ id,
1379
+ template,
1380
+ version: existing === void 0 ? 1 : existing.hash === hash ? existing.version : existing.version + 1,
1381
+ hash
1382
+ };
1383
+ this.#records.set(id, record);
1384
+ this.#emitter.emit("add", id);
1385
+ return record;
1386
+ }
1387
+ remove(target) {
1388
+ this.#ensureAlive();
1389
+ if (target === void 0) {
1390
+ for (const id of this.#records.keys()) this.#emitter.emit("remove", id);
1391
+ this.#records.clear();
1392
+ return;
1393
+ }
1394
+ if (typeof target === "string") {
1395
+ const removed = this.#records.delete(target);
1396
+ if (removed) this.#emitter.emit("remove", target);
1397
+ return removed;
1398
+ }
1399
+ for (const id of target) if (!this.#records.has(id)) return false;
1400
+ for (const id of target) {
1401
+ this.#records.delete(id);
1402
+ this.#emitter.emit("remove", id);
1403
+ }
1404
+ return true;
1405
+ }
1406
+ destroy() {
1407
+ if (this.#destroyed) return;
1408
+ this.#records.clear();
1409
+ this.#destroyed = true;
1410
+ this.#emitter.emit("destroy");
1411
+ this.#emitter.destroy();
1412
+ }
1413
+ #ensureAlive() {
1414
+ if (this.#destroyed) throw new InterpretError("DESTROYED", "Template manager has been destroyed");
1415
+ }
1416
+ };
1417
+ //#endregion
1418
+ //#region src/core/Narrator.ts
1419
+ /**
1420
+ * A stateless, TOTAL, lexicon-driven rendering engine for the reverse
1421
+ * direction — the reverse-direction mirror of the forward `Formatter`'s
1422
+ * `verbs` seam (AGENTS §21 mechanism-never-policy).
1423
+ *
1424
+ * @remarks
1425
+ * Every wording decision is DATA — a caller-supplied `Lexicon` merged, per
1426
+ * sub-record (`phrases` / `labels` / `templates`), OVER `DEFAULT_LEXICON`.
1427
+ * Stateless and holds no resources: no emitter, no `destroy()` (deliberate —
1428
+ * there is nothing to release). Every method is total (never throws); a
1429
+ * lexicon or formatter miss degrades to its documented fallback rather than
1430
+ * a thrown error, and every lookup guards with `Object.hasOwn` so an
1431
+ * adversarial key (`toString`, `constructor`, `__proto__`) misses cleanly
1432
+ * instead of reading an inherited prototype member.
1433
+ *
1434
+ * @example
1435
+ * ```ts
1436
+ * import { Narrator } from '@src/core'
1437
+ *
1438
+ * const narrator = new Narrator({
1439
+ * lexicon: { phrases: { comparison: { equals: 'is' } } },
1440
+ * formatters: { money: (value) => `$${String(value)}` },
1441
+ * })
1442
+ * narrator.phrase('comparison', 'equals', 'equals') // 'is'
1443
+ * narrator.phrase('comparison', 'missing', 'equals') // 'equals' — fallback
1444
+ * narrator.value('money', 5) // '$5'
1445
+ * ```
1446
+ */
1447
+ var Narrator = class {
1448
+ #lexicon;
1449
+ #formatters;
1450
+ constructor(options) {
1451
+ this.#lexicon = {
1452
+ phrases: {
1453
+ ...DEFAULT_LEXICON.phrases,
1454
+ ...options?.lexicon?.phrases
1455
+ },
1456
+ labels: {
1457
+ ...DEFAULT_LEXICON.labels,
1458
+ ...options?.lexicon?.labels
1459
+ },
1460
+ templates: {
1461
+ ...DEFAULT_LEXICON.templates,
1462
+ ...options?.lexicon?.templates
1463
+ }
1464
+ };
1465
+ this.#formatters = { ...options?.formatters };
1466
+ }
1467
+ phrase(table, key, fallback) {
1468
+ if (Object.hasOwn(this.#lexicon.phrases, table)) {
1469
+ const row = this.#lexicon.phrases[table];
1470
+ if (row !== null && row !== void 0 && Object.hasOwn(row, key)) {
1471
+ const value = row[key];
1472
+ if (typeof value === "string") return value;
1473
+ }
1474
+ }
1475
+ return fallback ?? key;
1476
+ }
1477
+ label(field) {
1478
+ const key = formatField(field);
1479
+ if (Object.hasOwn(this.#lexicon.labels, key)) {
1480
+ const value = this.#lexicon.labels[key];
1481
+ if (typeof value === "string") return value;
1482
+ }
1483
+ return key;
1484
+ }
1485
+ line(id, values) {
1486
+ if (!Object.hasOwn(this.#lexicon.templates, id)) return "";
1487
+ const template = this.#lexicon.templates[id];
1488
+ return typeof template === "string" ? fillTemplate(template, values, { missing: "empty" }) : "";
1489
+ }
1490
+ value(unit, raw) {
1491
+ if (Object.hasOwn(this.#formatters, unit)) {
1492
+ const formatter = this.#formatters[unit];
1493
+ if (typeof formatter === "function") try {
1494
+ return formatter(raw);
1495
+ } catch {
1496
+ return String(raw);
1497
+ }
1498
+ }
1499
+ return String(raw);
1500
+ }
1501
+ describe(definition) {
1502
+ switch (definition.reasoning) {
1503
+ case "quantitative": return this.line("definition.quantitative", {
1504
+ name: definition.name,
1505
+ count: definition.groups.length
1506
+ });
1507
+ case "logical": return this.line("definition.logical", {
1508
+ name: definition.name,
1509
+ count: definition.rules.length,
1510
+ strategy: definition.strategy
1511
+ });
1512
+ case "symbolic": return this.line("definition.symbolic", {
1513
+ name: definition.name,
1514
+ count: definition.equations.length
1515
+ });
1516
+ case "inferential": return this.line("definition.inferential", {
1517
+ name: definition.name,
1518
+ facts: definition.facts.length,
1519
+ inferences: definition.inferences.length,
1520
+ strategy: definition.strategy
1521
+ });
1522
+ }
1523
+ }
1524
+ narrate(result) {
1525
+ switch (result.reasoning) {
1526
+ case "quantitative": {
1527
+ const base = this.line("result.quantitative", {
1528
+ value: result.value,
1529
+ count: result.count
1530
+ });
1531
+ if (result.errors.length === 0) return base;
1532
+ return `${base}${this.line("result.quantitative.failed", { errors: result.errors.join(", ") })}`;
1533
+ }
1534
+ case "logical": return this.line("result.logical", {
1535
+ status: result.conclusion ? "met" : "unmet",
1536
+ count: result.count
1537
+ });
1538
+ case "symbolic": {
1539
+ const solved = Object.entries(result.solutions).map(([key, value]) => `${key}=${value}`).join(", ");
1540
+ return this.line("result.symbolic", { solved });
1541
+ }
1542
+ case "inferential": return this.line("result.inferential", { count: result.derived.length });
1543
+ }
1544
+ }
1545
+ };
1546
+ //#endregion
1547
+ //#region src/core/stages/Clarifier.ts
1548
+ /**
1549
+ * The `Clarifier` stage: resolves same-domain carry-over, template defaults,
1550
+ * and declaratively computed fields against an already-assigned entity set,
1551
+ * surfacing an {@link Ambiguity} for every required mapping that stays
1552
+ * unresolved.
1553
+ *
1554
+ * @remarks
1555
+ * Resolution order: fresh (already-assigned) entities always win; carry-over
1556
+ * fills a mapping only from the SAME domain's most recent prior turn (a
1557
+ * domain change drops carry-over entirely) and never overwrites a fresh
1558
+ * value; template defaults fill any field still unresolved after carry-over;
1559
+ * computed fields resolve in dependency (topological) order via
1560
+ * `resolveExpression` — an unresolved input, a non-finite result, or a
1561
+ * dependency cycle leaves the field a gap, never landing an entity. `floor`
1562
+ * (from {@link ClarifierOptions}, never hardcoded — AGENTS-flagged scsr
1563
+ * defect 4) gates whether a resolved entity's confidence counts as
1564
+ * "resolved enough" when raising ambiguities — a field with a value below
1565
+ * `floor` still raises its ambiguity.
1566
+ *
1567
+ * @example
1568
+ * ```ts
1569
+ * import { Clarifier } from '@src/core'
1570
+ *
1571
+ * const clarifier = new Clarifier({ floor: 0.3 })
1572
+ * clarifier.clarify(
1573
+ * [],
1574
+ * {
1575
+ * id: 't1',
1576
+ * name: 'Arithmetic',
1577
+ * domain: 'arithmetic',
1578
+ * intents: ['calculate'],
1579
+ * mappings: [{ entity: 'value', aliases: [], field: 'value', required: true }],
1580
+ * defaults: [],
1581
+ * computations: [],
1582
+ * definition: { reasoning: 'symbolic', id: 't1', name: 'Arithmetic', equations: [], variables: {} },
1583
+ * },
1584
+ * undefined,
1585
+ * { action: 'calculate', domain: 'arithmetic', confidence: 1 },
1586
+ * ) // { entities: [], ambiguities: [{ field: 'value', ... }], complete: false }
1587
+ * ```
1588
+ */
1589
+ var Clarifier = class {
1590
+ #floor;
1591
+ constructor(options) {
1592
+ this.#floor = options?.floor ?? .3;
1593
+ }
1594
+ clarify(entities, template, context, intent) {
1595
+ const resolved = [...entities];
1596
+ const filledEntityNames = new Set(resolved.map((entity) => entity.name));
1597
+ const filledFields = new Set(resolved.map((entity) => {
1598
+ const mapping = template.mappings.find((candidate) => candidate.entity === entity.name);
1599
+ return mapping === void 0 ? entity.name : formatField(mapping.field);
1600
+ }));
1601
+ this.#carryOver(template, context, intent, filledEntityNames, filledFields, resolved);
1602
+ this.#fillDefaults(template, filledFields, resolved);
1603
+ this.#resolveComputations(template, filledFields, resolved);
1604
+ const ambiguities = this.#collectAmbiguities(template, resolved);
1605
+ return {
1606
+ entities: resolved,
1607
+ ambiguities,
1608
+ complete: ambiguities.length === 0
1609
+ };
1610
+ }
1611
+ #carryOver(template, context, intent, filledEntityNames, filledFields, resolved) {
1612
+ if (context === void 0) return;
1613
+ const sameDomain = context.previous().filter((prior) => prior.intent.domain === intent.domain);
1614
+ for (const mapping of template.mappings) {
1615
+ if (filledEntityNames.has(mapping.entity)) continue;
1616
+ for (let index = sameDomain.length - 1; index >= 0; index -= 1) {
1617
+ const found = sameDomain[index]?.entities.find((entity) => entity.name === mapping.entity);
1618
+ if (found === void 0) continue;
1619
+ resolved.push({
1620
+ name: mapping.entity,
1621
+ value: found.value,
1622
+ provenance: { category: "carried" },
1623
+ confidence: CONFIDENCE_CARRIED
1624
+ });
1625
+ filledEntityNames.add(mapping.entity);
1626
+ filledFields.add(formatField(mapping.field));
1627
+ break;
1628
+ }
1629
+ }
1630
+ }
1631
+ #fillDefaults(template, filledFields, resolved) {
1632
+ for (const fieldDefault of template.defaults) {
1633
+ const key = formatField(fieldDefault.field);
1634
+ if (filledFields.has(key)) continue;
1635
+ const mapping = template.mappings.find((candidate) => formatField(candidate.field) === key);
1636
+ resolved.push({
1637
+ name: mapping?.entity ?? key,
1638
+ value: fieldDefault.value,
1639
+ provenance: { category: "default" },
1640
+ confidence: 1
1641
+ });
1642
+ filledFields.add(key);
1643
+ }
1644
+ }
1645
+ #resolveComputations(template, filledFields, resolved) {
1646
+ const bindings = {};
1647
+ for (const entity of resolved) {
1648
+ const mapping = template.mappings.find((candidate) => candidate.entity === entity.name);
1649
+ const field = mapping === void 0 ? entity.name : formatField(mapping.field);
1650
+ if (isFiniteNumber(entity.value)) bindings[field] = entity.value;
1651
+ }
1652
+ for (const computation of this.#orderComputations(template.computations)) {
1653
+ const key = formatField(computation.field);
1654
+ if (filledFields.has(key)) continue;
1655
+ const value = resolveExpression(computation.expression, bindings);
1656
+ if (value === void 0) continue;
1657
+ const mapping = template.mappings.find((candidate) => formatField(candidate.field) === key);
1658
+ resolved.push({
1659
+ name: mapping?.entity ?? key,
1660
+ value,
1661
+ provenance: { category: "computed" },
1662
+ confidence: CONFIDENCE_COMPUTED
1663
+ });
1664
+ filledFields.add(key);
1665
+ bindings[key] = value;
1666
+ }
1667
+ }
1668
+ #orderComputations(computations) {
1669
+ const byField = /* @__PURE__ */ new Map();
1670
+ for (const computation of computations) byField.set(formatField(computation.field), computation);
1671
+ const dependents = /* @__PURE__ */ new Map();
1672
+ const inDegree = /* @__PURE__ */ new Map();
1673
+ for (const key of byField.keys()) inDegree.set(key, 0);
1674
+ for (const [key, computation] of byField) {
1675
+ const dependencies = variablesOf(computation.expression).filter((name) => byField.has(name));
1676
+ inDegree.set(key, dependencies.length);
1677
+ for (const dependency of dependencies) {
1678
+ const list = dependents.get(dependency) ?? [];
1679
+ list.push(key);
1680
+ dependents.set(dependency, list);
1681
+ }
1682
+ }
1683
+ const queue = [];
1684
+ for (const [key, degree] of inDegree) if (degree === 0) queue.push(key);
1685
+ const ordered = [];
1686
+ let cursor = 0;
1687
+ while (cursor < queue.length) {
1688
+ const key = queue[cursor];
1689
+ cursor += 1;
1690
+ if (key === void 0) continue;
1691
+ const computation = byField.get(key);
1692
+ if (computation !== void 0) ordered.push(computation);
1693
+ for (const dependent of dependents.get(key) ?? []) {
1694
+ const next = (inDegree.get(dependent) ?? 0) - 1;
1695
+ inDegree.set(dependent, next);
1696
+ if (next === 0) queue.push(dependent);
1697
+ }
1698
+ }
1699
+ return ordered;
1700
+ }
1701
+ #collectAmbiguities(template, resolved) {
1702
+ const ambiguities = [];
1703
+ for (const mapping of template.mappings) {
1704
+ if (mapping.required !== true) continue;
1705
+ const entity = resolved.find((candidate) => candidate.name === mapping.entity);
1706
+ if (entity !== void 0 && entity.confidence >= this.#floor) continue;
1707
+ ambiguities.push({
1708
+ field: mapping.field,
1709
+ question: `What is your ${mapping.entity}?`,
1710
+ candidates: [],
1711
+ required: true
1712
+ });
1713
+ }
1714
+ return ambiguities;
1715
+ }
1716
+ };
1717
+ //#endregion
1718
+ //#region src/core/stages/Extractor.ts
1719
+ /**
1720
+ * The `Extractor` stage: template-agnostic intent classification plus raw
1721
+ * numeric-entity mining.
1722
+ *
1723
+ * @remarks
1724
+ * Deliberately never named `Parser` — the `contracts` module already owns
1725
+ * `Parser<T>`, so a class of that name would collide in type space (AGENTS
1726
+ * §21, design ledger 3). `extract` never sees a `Template`: numbers →
1727
+ * entity ASSIGNMENT is a separate orchestrator-owned step that runs only
1728
+ * after a template has matched (`assignEntities` in `helpers.ts`), not
1729
+ * inside this stage (the defect-3 fix — scsr's parser mined template-shaped
1730
+ * entities directly and only worked via an `instanceof` hack).
1731
+ *
1732
+ * @example
1733
+ * ```ts
1734
+ * import { Extractor } from '@src/core'
1735
+ *
1736
+ * const extractor = new Extractor({
1737
+ * actions: { calculate: 'compute' },
1738
+ * domains: { rating: ['rate'] },
1739
+ * })
1740
+ * extractor.extract('calculate my rate at 85')
1741
+ * // { intent: { action: 'compute', domain: 'rating', confidence: 1 }, numbers: [85], complete: true }
1742
+ * ```
1743
+ */
1744
+ var Extractor = class {
1745
+ #actions;
1746
+ #domains;
1747
+ constructor(options) {
1748
+ this.#actions = {
1749
+ ...DEFAULT_ACTIONS,
1750
+ ...options?.actions
1751
+ };
1752
+ this.#domains = {
1753
+ ...DEFAULT_DOMAINS,
1754
+ ...options?.domains
1755
+ };
1756
+ }
1757
+ extract(text) {
1758
+ const numbers = extractNumbers(text);
1759
+ const intent = classifyIntent(text, this.#actions, this.#domains);
1760
+ return {
1761
+ intent,
1762
+ numbers,
1763
+ complete: numbers.length > 0 && intent.confidence > 0
1764
+ };
1765
+ }
1766
+ };
1767
+ //#endregion
1768
+ //#region src/core/stages/Formatter.ts
1769
+ /**
1770
+ * The `Formatter` stage: renders the refined natural-language prompt for a
1771
+ * matched template.
1772
+ *
1773
+ * @remarks
1774
+ * Shape: `{verb} {template.name}` + ` with {label}: {value}, …` for every
1775
+ * non-default entity (via the core-root `formatField`) + `
1776
+ * (defaults: {label}: {value}, …)` for default-provenance entities + `
1777
+ * needed: {question} …` for every ambiguity. `verbs` maps `intent.action` to
1778
+ * its display verb; an action absent from the map falls back to the action
1779
+ * string itself. Every parameter is read — no ignored `context` argument
1780
+ * (AGENTS-flagged scsr defect 5).
1781
+ *
1782
+ * @example
1783
+ * ```ts
1784
+ * import { Formatter } from '@src/core'
1785
+ *
1786
+ * const formatter = new Formatter({ verbs: { calculate: 'Calculate' } })
1787
+ * formatter.format(
1788
+ * { action: 'calculate', domain: 'arithmetic', confidence: 1 },
1789
+ * {
1790
+ * id: 't1',
1791
+ * name: 'Arithmetic',
1792
+ * domain: 'arithmetic',
1793
+ * intents: ['calculate'],
1794
+ * mappings: [],
1795
+ * defaults: [],
1796
+ * computations: [],
1797
+ * definition: { reasoning: 'symbolic', id: 't1', name: 'Arithmetic', equations: [], variables: {} },
1798
+ * },
1799
+ * [],
1800
+ * [],
1801
+ * ) // { prompt: 'Calculate Arithmetic' }
1802
+ * ```
1803
+ */
1804
+ var Formatter = class {
1805
+ #verbs;
1806
+ constructor(options) {
1807
+ this.#verbs = {
1808
+ ...DEFAULT_VERBS,
1809
+ ...options?.verbs
1810
+ };
1811
+ }
1812
+ format(intent, template, entities, ambiguities) {
1813
+ const verb = this.#verbs[intent.action] ?? intent.action;
1814
+ const render = (list) => list.map((entity) => `${formatField(entity.name)}: ${String(entity.value)}`).join(", ");
1815
+ let prompt = `${verb} ${template.name}`;
1816
+ const resolved = entities.filter((entity) => entity.provenance.category !== "default");
1817
+ if (resolved.length > 0) prompt += ` with ${render(resolved)}`;
1818
+ const defaults = entities.filter((entity) => entity.provenance.category === "default");
1819
+ if (defaults.length > 0) prompt += ` (defaults: ${render(defaults)})`;
1820
+ if (ambiguities.length > 0) prompt += ` needed: ${ambiguities.map((ambiguity) => ambiguity.question).join(" ")}`;
1821
+ return { prompt };
1822
+ }
1823
+ };
1824
+ //#endregion
1825
+ //#region src/core/stages/Generator.ts
1826
+ /**
1827
+ * The `Generator` stage: builds the final `Subject` from a fully resolved
1828
+ * entity set, plus its complete field audit.
1829
+ *
1830
+ * @remarks
1831
+ * `entity → field` via `template.mappings` (an `EntityMapping.entity` name
1832
+ * lookup); an entity whose name matches no mapping lands on the field named
1833
+ * by its OWN `name` — the shape `Clarifier` uses for its synthesized
1834
+ * default/computed entities, so one lookup rule serves both extraction-
1835
+ * mapped and template-data-derived fields. A single-element array value
1836
+ * unwraps to its scalar; a multi-element, ALL-numeric array value stays an
1837
+ * array AND additionally emits five aggregate fields (`Sum` / `Count` /
1838
+ * `Average` / `Minimum` / `Maximum`, provenance `computed`), each derived as
1839
+ * a SIBLING path beside the source field via `deriveAggregateField` — for an
1840
+ * array `FieldPath` (e.g. `['address', 'amounts']`) the aggregates nest
1841
+ * (`['address', 'amountsSum']`, ...); for a plain string field they stay
1842
+ * flat (`'amountsSum'`), matching the source field's own shape.
1843
+ * `confidence` is the mean of the input entities' own confidences (`0` for
1844
+ * an empty entity set). A `FieldMapping` is emitted for EVERY field that
1845
+ * lands on the subject, including defaults, computed fields, and aggregates
1846
+ * — scsr silently omitted defaults/computed from its audit trail; this
1847
+ * closes that gap. `GeneratorOptions` is a reserved extension seam — the
1848
+ * stage has no knobs yet, so construction takes no arguments until one
1849
+ * exists.
1850
+ *
1851
+ * @example
1852
+ * ```ts
1853
+ * import { Generator } from '@src/core'
1854
+ *
1855
+ * const generator = new Generator()
1856
+ * generator.generate(
1857
+ * [
1858
+ * {
1859
+ * name: 'value',
1860
+ * value: 42,
1861
+ * provenance: { category: 'extracted', detail: 'collect' },
1862
+ * confidence: 0.9,
1863
+ * },
1864
+ * ],
1865
+ * {
1866
+ * id: 't1',
1867
+ * name: 'Arithmetic',
1868
+ * domain: 'arithmetic',
1869
+ * intents: ['calculate'],
1870
+ * mappings: [{ entity: 'value', aliases: [], field: 'value' }],
1871
+ * defaults: [],
1872
+ * computations: [],
1873
+ * definition: { reasoning: 'symbolic', id: 't1', name: 'Arithmetic', equations: [], variables: {} },
1874
+ * },
1875
+ * ) // { subject: { value: 42 }, mappings: [...], confidence: 0.9, ... }
1876
+ * ```
1877
+ */
1878
+ var Generator = class {
1879
+ generate(entities, template) {
1880
+ let subject = {};
1881
+ const mappings = [];
1882
+ for (const entity of entities) {
1883
+ const mapping = template.mappings.find((candidate) => candidate.entity === entity.name);
1884
+ const field = mapping === void 0 ? entity.name : mapping.field;
1885
+ const value = entity.value;
1886
+ if (Array.isArray(value) && value.length === 1) {
1887
+ const scalar = value[0];
1888
+ subject = setField(subject, field, scalar);
1889
+ mappings.push({
1890
+ field,
1891
+ entity: entity.name,
1892
+ value: scalar,
1893
+ provenance: entity.provenance,
1894
+ confidence: entity.confidence
1895
+ });
1896
+ continue;
1897
+ }
1898
+ if (Array.isArray(value) && value.length > 1) {
1899
+ const numeric = [];
1900
+ for (const item of value) {
1901
+ if (!isFiniteNumber(item)) break;
1902
+ numeric.push(item);
1903
+ }
1904
+ if (numeric.length === value.length) {
1905
+ subject = setField(subject, field, value);
1906
+ mappings.push({
1907
+ field,
1908
+ entity: entity.name,
1909
+ value,
1910
+ provenance: entity.provenance,
1911
+ confidence: entity.confidence
1912
+ });
1913
+ const sum = numeric.reduce((total, item) => total + item, 0);
1914
+ const minimum = numeric.reduce((min, item) => item < min ? item : min, numeric[0]);
1915
+ const maximum = numeric.reduce((max, item) => item > max ? item : max, numeric[0]);
1916
+ const aggregates = [
1917
+ [deriveAggregateField(field, "Sum"), sum],
1918
+ [deriveAggregateField(field, "Count"), numeric.length],
1919
+ [deriveAggregateField(field, "Average"), sum / numeric.length],
1920
+ [deriveAggregateField(field, "Minimum"), minimum],
1921
+ [deriveAggregateField(field, "Maximum"), maximum]
1922
+ ];
1923
+ for (const [aggregateField, aggregateValue] of aggregates) {
1924
+ subject = setField(subject, aggregateField, aggregateValue);
1925
+ mappings.push({
1926
+ field: aggregateField,
1927
+ value: aggregateValue,
1928
+ provenance: { category: "computed" },
1929
+ confidence: CONFIDENCE_COMPUTED
1930
+ });
1931
+ }
1932
+ continue;
1933
+ }
1934
+ }
1935
+ subject = setField(subject, field, value);
1936
+ mappings.push({
1937
+ field,
1938
+ entity: entity.name,
1939
+ value,
1940
+ provenance: entity.provenance,
1941
+ confidence: entity.confidence
1942
+ });
1943
+ }
1944
+ const confidence = entities.length === 0 ? 0 : entities.reduce((total, entity) => total + entity.confidence, 0) / entities.length;
1945
+ return {
1946
+ subject,
1947
+ definition: template.definition,
1948
+ mappings,
1949
+ confidence
1950
+ };
1951
+ }
1952
+ };
1953
+ //#endregion
1954
+ //#region src/core/stages/Normalizer.ts
1955
+ /**
1956
+ * The `Normalizer` stage: applies contraction, abbreviation, and correction
1957
+ * substitutions in order, then collapses whitespace.
1958
+ *
1959
+ * @remarks
1960
+ * Each caller map is merged OVER the neutral built-in default for its slot —
1961
+ * `text` is never mutated (AGENTS §11). Every substitution actually applied
1962
+ * (one entry per matching map KEY, not per occurrence) is recorded on the
1963
+ * result's `changes`, in `contractions → abbreviations → corrections` order,
1964
+ * so the audit trail explains every character difference between `text` and
1965
+ * `NormalizeResult.text` (the final whitespace collapse carries no entry of
1966
+ * its own — it is structural cleanup, not a substitution).
1967
+ *
1968
+ * @example
1969
+ * ```ts
1970
+ * import { Normalizer } from '@src/core'
1971
+ *
1972
+ * const normalizer = new Normalizer({ contractions: { "can't": 'cannot' } })
1973
+ * normalizer.normalize("can't stop")
1974
+ * // { text: 'cannot stop', changes: [{ from: "can't", to: 'cannot' }] }
1975
+ * ```
1976
+ */
1977
+ var Normalizer = class {
1978
+ #contractions;
1979
+ #abbreviations;
1980
+ #corrections;
1981
+ constructor(options) {
1982
+ this.#contractions = {
1983
+ ...DEFAULT_CONTRACTIONS,
1984
+ ...options?.contractions
1985
+ };
1986
+ this.#abbreviations = {
1987
+ ...DEFAULT_ABBREVIATIONS,
1988
+ ...options?.abbreviations
1989
+ };
1990
+ this.#corrections = {
1991
+ ...DEFAULT_CORRECTIONS,
1992
+ ...options?.corrections
1993
+ };
1994
+ }
1995
+ normalize(text) {
1996
+ const changes = [];
1997
+ let working = text;
1998
+ for (const map of [
1999
+ this.#contractions,
2000
+ this.#abbreviations,
2001
+ this.#corrections
2002
+ ]) {
2003
+ const applied = this.#applyStage(working, map);
2004
+ working = applied.text;
2005
+ changes.push(...applied.changes);
2006
+ }
2007
+ return {
2008
+ text: collapseWhitespace(working),
2009
+ changes
2010
+ };
2011
+ }
2012
+ #applyStage(text, map) {
2013
+ let working = text;
2014
+ const changes = [];
2015
+ for (const [from, to] of Object.entries(map)) if (new RegExp(`\\b${escapeRegExp(from)}\\b`, "i").test(working)) {
2016
+ working = applyReplacements(working, { [from]: to });
2017
+ changes.push({
2018
+ from,
2019
+ to
2020
+ });
2021
+ }
2022
+ return {
2023
+ text: working,
2024
+ changes
2025
+ };
2026
+ }
2027
+ };
2028
+ //#endregion
2029
+ //#region src/core/Interpret.ts
2030
+ /**
2031
+ * The interpretation orchestrator — the sole public entry point of the
2032
+ * `interprets` module, mirroring the reasons `Reason` orchestrator shape.
2033
+ *
2034
+ * @remarks
2035
+ * `interpret()` is genuinely SYNCHRONOUS (scsr's was fake-async with zero
2036
+ * `await`s) and runs a fixed five-stage pipeline —
2037
+ * `[normalize, extract, clarify, format, generate]` — each producing one
2038
+ * {@link StageRecord}. Between `extract` and `clarify` the orchestrator matches
2039
+ * the classified {@link Intent} against its registered {@link Template}s and,
2040
+ * on a match, assigns the extracted numbers to that template's mappings
2041
+ * (`assignEntities`) — a template-owned step, not a sixth stage. No match, or a
2042
+ * matched template whose intent confidence falls below the configured `floor`,
2043
+ * yields an explicit, auditable INCOMPLETE result (a `field: 'intent'`
2044
+ * ambiguity, absent subject/definition) rather than scsr's arbitrary
2045
+ * `templates[0]` fallback. A stage THROW is caught, marked on its record AND on
2046
+ * `failures`, emitted as `error`, and still yields a visible incomplete result
2047
+ * — never a silent fallback. Every result carries a `digest` over its original
2048
+ * text plus the matched template id/version and the built subject/definition,
2049
+ * so re-running the same text against the same template version reproduces the
2050
+ * same digest (the replay contract). `describe` / `narrate` are the reverse
2051
+ * direction (structure → prose). `destroy()` is idempotent, tears down the
2052
+ * registry and context, then destroys the emitter LAST (AGENTS §13); every
2053
+ * method afterwards except the {@link emitter} getter throws
2054
+ * `InterpretError('DESTROYED', …)`.
2055
+ *
2056
+ * @example
2057
+ * ```ts
2058
+ * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
2059
+ * import { Interpret, Extractor } from '@src/core'
2060
+ *
2061
+ * const interpret = new Interpret({
2062
+ * extractor: new Extractor({ actions: { calculate: 'calculate' }, domains: { arithmetic: ['arithmetic'] } }),
2063
+ * templates: [
2064
+ * {
2065
+ * id: 't1',
2066
+ * name: 'Arithmetic',
2067
+ * domain: 'arithmetic',
2068
+ * intents: ['calculate'],
2069
+ * mappings: [{ entity: 'value', aliases: [], field: 'value' }],
2070
+ * defaults: [],
2071
+ * computations: [],
2072
+ * definition: quantitativeDefinition('t1', 'Arithmetic', [
2073
+ * factorGroup('total', 'sum', [fieldFactor('value', 'value')]),
2074
+ * ]),
2075
+ * },
2076
+ * ],
2077
+ * })
2078
+ * interpret.interpret('calculate arithmetic 42').subject // { value: 42 }
2079
+ * ```
2080
+ */
2081
+ var Interpret = class {
2082
+ #templates;
2083
+ #context;
2084
+ #normalizer;
2085
+ #extractor;
2086
+ #clarifier;
2087
+ #formatter;
2088
+ #generator;
2089
+ #similarity;
2090
+ #floor;
2091
+ #narrator;
2092
+ #emitter;
2093
+ #destroyed = false;
2094
+ constructor(options) {
2095
+ this.#similarity = options?.similarity ?? .8;
2096
+ this.#floor = options?.floor ?? .3;
2097
+ this.#templates = new TemplateManager({ templates: options?.templates });
2098
+ this.#context = options?.context ?? new InterpretContext({ history: options?.history });
2099
+ this.#normalizer = options?.normalizer ?? new Normalizer();
2100
+ this.#extractor = options?.extractor ?? new Extractor();
2101
+ this.#clarifier = options?.clarifier ?? new Clarifier({ floor: this.#floor });
2102
+ this.#formatter = options?.formatter ?? new Formatter();
2103
+ this.#generator = options?.generator ?? new Generator();
2104
+ this.#narrator = new Narrator({
2105
+ lexicon: options?.lexicon,
2106
+ formatters: options?.formatters
2107
+ });
2108
+ this.#emitter = new Emitter({
2109
+ on: options?.on,
2110
+ error: options?.error
2111
+ });
2112
+ }
2113
+ get emitter() {
2114
+ return this.#emitter;
2115
+ }
2116
+ interpret(text) {
2117
+ this.#ensureAlive();
2118
+ const stages = [];
2119
+ let normalized;
2120
+ try {
2121
+ normalized = this.#normalizer.normalize(text);
2122
+ } catch (error) {
2123
+ return this.#abort(text, text, {
2124
+ action: "",
2125
+ domain: "",
2126
+ confidence: 0
2127
+ }, [], [], stages, "normalize", "NORMALIZE_FAILED", text, error, [
2128
+ "extract",
2129
+ "clarify",
2130
+ "format",
2131
+ "generate"
2132
+ ], void 0, void 0);
2133
+ }
2134
+ stages.push({
2135
+ stage: "normalize",
2136
+ input: text,
2137
+ output: normalized,
2138
+ failed: false
2139
+ });
2140
+ let extract;
2141
+ try {
2142
+ extract = this.#extractor.extract(normalized.text);
2143
+ } catch (error) {
2144
+ return this.#abort(text, normalized.text, {
2145
+ action: "",
2146
+ domain: "",
2147
+ confidence: 0
2148
+ }, [], [], stages, "extract", "EXTRACT_FAILED", normalized.text, error, [
2149
+ "clarify",
2150
+ "format",
2151
+ "generate"
2152
+ ], void 0, void 0);
2153
+ }
2154
+ stages.push({
2155
+ stage: "extract",
2156
+ input: normalized.text,
2157
+ output: extract,
2158
+ failed: false
2159
+ });
2160
+ const intent = extract.intent;
2161
+ const matched = matchTemplate(intent, this.#templates.templates().map((record) => record.template), this.#floor);
2162
+ if (matched === void 0) return this.#gate(text, normalized.text, intent, [], stages, "NO_TEMPLATE", void 0, void 0);
2163
+ const assigned = assignEntities(extract.numbers, matched.mappings, normalized.text, this.#similarity);
2164
+ const version = this.#templates.template(matched.id)?.version;
2165
+ if (intent.confidence < this.#floor) return this.#gate(text, normalized.text, intent, assigned, stages, "LOW_CONFIDENCE", matched.id, version);
2166
+ let clarified;
2167
+ try {
2168
+ clarified = this.#clarifier.clarify(assigned, matched, this.#context, intent);
2169
+ } catch (error) {
2170
+ return this.#abort(text, normalized.text, intent, assigned, [], stages, "clarify", "CLARIFY_FAILED", assigned, error, ["format", "generate"], matched.id, version);
2171
+ }
2172
+ stages.push({
2173
+ stage: "clarify",
2174
+ input: assigned,
2175
+ output: clarified,
2176
+ failed: false
2177
+ });
2178
+ const formatInput = {
2179
+ intent,
2180
+ entities: clarified.entities,
2181
+ ambiguities: clarified.ambiguities
2182
+ };
2183
+ let formatted;
2184
+ try {
2185
+ formatted = this.#formatter.format(intent, matched, clarified.entities, clarified.ambiguities);
2186
+ } catch (error) {
2187
+ return this.#abort(text, normalized.text, intent, clarified.entities, clarified.ambiguities, stages, "format", "FORMAT_FAILED", formatInput, error, ["generate"], matched.id, version);
2188
+ }
2189
+ stages.push({
2190
+ stage: "format",
2191
+ input: formatInput,
2192
+ output: formatted,
2193
+ failed: false
2194
+ });
2195
+ let generated;
2196
+ try {
2197
+ generated = this.#generator.generate(clarified.entities, matched);
2198
+ } catch (error) {
2199
+ return this.#abort(text, normalized.text, intent, clarified.entities, clarified.ambiguities, stages, "generate", "GENERATE_FAILED", clarified.entities, error, [], matched.id, version);
2200
+ }
2201
+ stages.push({
2202
+ stage: "generate",
2203
+ input: clarified.entities,
2204
+ output: generated,
2205
+ failed: false
2206
+ });
2207
+ const digest = digestValue({
2208
+ text,
2209
+ templateId: matched.id,
2210
+ templateVersion: version,
2211
+ subject: generated.subject,
2212
+ definition: generated.definition
2213
+ });
2214
+ const result = {
2215
+ text,
2216
+ normalized: normalized.text,
2217
+ intent,
2218
+ entities: clarified.entities,
2219
+ subject: generated.subject,
2220
+ definition: generated.definition,
2221
+ mappings: generated.mappings,
2222
+ ambiguities: clarified.ambiguities,
2223
+ prompt: formatted.prompt,
2224
+ stages,
2225
+ failures: [],
2226
+ complete: clarified.complete,
2227
+ confidence: generated.confidence,
2228
+ digest
2229
+ };
2230
+ this.#context.subjects.add(generated.subject);
2231
+ this.#context.definitions.add(generated.definition, { id: generated.definition.id });
2232
+ this.#context.add(result);
2233
+ this.#emitter.emit("interpret", result);
2234
+ return result;
2235
+ }
2236
+ register(template) {
2237
+ this.#ensureAlive();
2238
+ this.#templates.add(template, { id: template.id });
2239
+ this.#emitter.emit("register", template.id);
2240
+ }
2241
+ unregister(id) {
2242
+ this.#ensureAlive();
2243
+ return this.#templates.remove(id);
2244
+ }
2245
+ template(id) {
2246
+ this.#ensureAlive();
2247
+ return this.#templates.template(id)?.template;
2248
+ }
2249
+ templates() {
2250
+ this.#ensureAlive();
2251
+ return this.#templates.templates().map((record) => record.template);
2252
+ }
2253
+ describe(definition) {
2254
+ this.#ensureAlive();
2255
+ return this.#narrator.describe(definition);
2256
+ }
2257
+ narrate(result) {
2258
+ this.#ensureAlive();
2259
+ return this.#narrator.narrate(result);
2260
+ }
2261
+ destroy() {
2262
+ if (this.#destroyed) return;
2263
+ this.#templates.destroy();
2264
+ this.#context.destroy();
2265
+ this.#destroyed = true;
2266
+ this.#emitter.emit("destroy");
2267
+ this.#emitter.destroy();
2268
+ }
2269
+ #gate(text, normalized, intent, entities, stages, code, templateId, templateVersion) {
2270
+ const domains = [...new Set(this.#templates.templates().map((record) => record.template.domain))];
2271
+ const ambiguity = {
2272
+ field: "intent",
2273
+ question: code === "NO_TEMPLATE" ? "Which domain and action did you mean?" : "Which did you mean? The intent was too weak to act on.",
2274
+ candidates: domains,
2275
+ required: true
2276
+ };
2277
+ const failure = {
2278
+ stage: "clarify",
2279
+ code,
2280
+ message: code === "NO_TEMPLATE" ? "No registered template matched the classified intent" : "Classified intent confidence fell below the configured floor"
2281
+ };
2282
+ return this.#assemble(text, normalized, intent, entities, [ambiguity], stages, [failure], [
2283
+ "clarify",
2284
+ "format",
2285
+ "generate"
2286
+ ], templateId, templateVersion);
2287
+ }
2288
+ #abort(text, normalized, intent, entities, ambiguities, stages, stage, code, input, error, remaining, templateId, templateVersion) {
2289
+ const message = error instanceof Error ? error.message : String(error);
2290
+ stages.push({
2291
+ stage,
2292
+ input,
2293
+ output: void 0,
2294
+ failed: true,
2295
+ error: message
2296
+ });
2297
+ this.#emitter.emit("error", error);
2298
+ return this.#assemble(text, normalized, intent, entities, ambiguities, stages, [{
2299
+ stage,
2300
+ code,
2301
+ message
2302
+ }], remaining, templateId, templateVersion);
2303
+ }
2304
+ #assemble(text, normalized, intent, entities, ambiguities, stages, failures, remaining, templateId, templateVersion) {
2305
+ for (const stage of remaining) stages.push({
2306
+ stage,
2307
+ input: void 0,
2308
+ output: void 0,
2309
+ failed: false
2310
+ });
2311
+ const digest = digestValue({
2312
+ text,
2313
+ templateId,
2314
+ templateVersion,
2315
+ subject: void 0,
2316
+ definition: void 0
2317
+ });
2318
+ const result = {
2319
+ text,
2320
+ normalized,
2321
+ intent,
2322
+ entities,
2323
+ mappings: [],
2324
+ ambiguities,
2325
+ prompt: "",
2326
+ stages,
2327
+ failures: [...failures],
2328
+ complete: false,
2329
+ confidence: 0,
2330
+ digest
2331
+ };
2332
+ this.#context.add(result);
2333
+ this.#emitter.emit("interpret", result);
2334
+ return result;
2335
+ }
2336
+ #ensureAlive() {
2337
+ if (this.#destroyed) throw new InterpretError("DESTROYED", "Interpret has been destroyed");
2338
+ }
2339
+ };
2340
+ //#endregion
2341
+ //#region src/core/factories.ts
2342
+ /**
2343
+ * Create an interpretation orchestrator.
2344
+ *
2345
+ * @remarks
2346
+ * `interpret()` is genuinely synchronous and runs the fixed five-stage
2347
+ * pipeline `[normalize, extract, clarify, format, generate]`. Every stage
2348
+ * slot (`normalizer` / `extractor` / `clarifier` / `formatter` / `generator`)
2349
+ * is bring-your-own — a supplied implementation is used as-is, else the
2350
+ * built-in stage is constructed from the matching per-stage options.
2351
+ *
2352
+ * @param options - Optional templates, context, stage implementations, the
2353
+ * `similarity` / `floor` axes, and emitter hooks
2354
+ * @returns A working {@link InterpretInterface}
2355
+ *
2356
+ * @example
2357
+ * ```ts
2358
+ * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
2359
+ * import { createInterpret } from '@src/core'
2360
+ *
2361
+ * const interpret = createInterpret({
2362
+ * extractor: { extract: () => ({ intent: { action: 'calculate', domain: 'arithmetic', confidence: 1 }, numbers: [42], complete: true }) },
2363
+ * templates: [
2364
+ * {
2365
+ * id: 't1',
2366
+ * name: 'Arithmetic',
2367
+ * domain: 'arithmetic',
2368
+ * intents: ['calculate'],
2369
+ * mappings: [{ entity: 'value', aliases: [], field: 'value' }],
2370
+ * defaults: [],
2371
+ * computations: [],
2372
+ * definition: quantitativeDefinition('t1', 'Arithmetic', [
2373
+ * factorGroup('total', 'sum', [fieldFactor('value', 'value')]),
2374
+ * ]),
2375
+ * },
2376
+ * ],
2377
+ * })
2378
+ * interpret.interpret('calculate arithmetic 42').subject // { value: 42 }
2379
+ * ```
2380
+ */
2381
+ function createInterpret(options) {
2382
+ return new Interpret(options);
2383
+ }
2384
+ /**
2385
+ * Create a text normalizer.
2386
+ *
2387
+ * @param options - Optional contraction / abbreviation / correction maps,
2388
+ * merged over the neutral built-in defaults
2389
+ * @returns A stateless {@link NormalizerInterface}
2390
+ *
2391
+ * @example
2392
+ * ```ts
2393
+ * import { createNormalizer } from '@src/core'
2394
+ *
2395
+ * createNormalizer().normalize("it's cold") // { text: 'it is cold', changes: [{ from: "it's", to: 'it is' }] }
2396
+ * ```
2397
+ */
2398
+ function createNormalizer(options) {
2399
+ return new Normalizer(options);
2400
+ }
2401
+ /**
2402
+ * Create a template-agnostic intent classifier and number extractor.
2403
+ *
2404
+ * @param options - Optional caller `actions` / `domains` vocabularies
2405
+ * @returns A stateless {@link ExtractorInterface}
2406
+ *
2407
+ * @example
2408
+ * ```ts
2409
+ * import { createExtractor } from '@src/core'
2410
+ *
2411
+ * const extractor = createExtractor({
2412
+ * actions: { calculate: 'calculate' },
2413
+ * domains: { arithmetic: ['arithmetic'] },
2414
+ * })
2415
+ * extractor.extract('calculate arithmetic 42').numbers // [42]
2416
+ * ```
2417
+ */
2418
+ function createExtractor(options) {
2419
+ return new Extractor(options);
2420
+ }
2421
+ /**
2422
+ * Create a clarifier — carry-over, defaults, and computed-field resolution
2423
+ * against an assigned entity set.
2424
+ *
2425
+ * @param options - Optional confidence `floor` for raised ambiguities
2426
+ * @returns A stateless {@link ClarifierInterface}
2427
+ *
2428
+ * @example
2429
+ * ```ts
2430
+ * import { createClarifier } from '@src/core'
2431
+ *
2432
+ * const clarifier = createClarifier({ floor: 0.5 })
2433
+ * ```
2434
+ */
2435
+ function createClarifier(options) {
2436
+ return new Clarifier(options);
2437
+ }
2438
+ /**
2439
+ * Create a prompt formatter.
2440
+ *
2441
+ * @param options - Optional caller intent-verb phrasing map
2442
+ * @returns A stateless {@link FormatterInterface}
2443
+ *
2444
+ * @example
2445
+ * ```ts
2446
+ * import { createFormatter } from '@src/core'
2447
+ *
2448
+ * const formatter = createFormatter({ verbs: { calculate: 'Calculate' } })
2449
+ * ```
2450
+ */
2451
+ function createFormatter(options) {
2452
+ return new Formatter(options);
2453
+ }
2454
+ /**
2455
+ * Create a subject/definition generator.
2456
+ *
2457
+ * @param options - Currently an empty extension seam
2458
+ * @returns A stateless {@link GeneratorInterface}
2459
+ *
2460
+ * @example
2461
+ * ```ts
2462
+ * import { createGenerator } from '@src/core'
2463
+ *
2464
+ * const generator = createGenerator()
2465
+ * ```
2466
+ */
2467
+ function createGenerator(_options) {
2468
+ return new Generator();
2469
+ }
2470
+ /**
2471
+ * Create a template registry.
2472
+ *
2473
+ * @param options - Optional initial seed collection
2474
+ * @returns A working {@link TemplateManagerInterface}
2475
+ *
2476
+ * @example
2477
+ * ```ts
2478
+ * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
2479
+ * import { createTemplate, createTemplateManager } from '@src/core'
2480
+ *
2481
+ * const template = createTemplate({
2482
+ * id: 't1', name: 'Arithmetic', domain: 'arithmetic', intents: ['calculate'],
2483
+ * mappings: [{ entity: 'value', aliases: [], field: 'value' }], defaults: [], computations: [],
2484
+ * definition: quantitativeDefinition('t1', 'Arithmetic', [factorGroup('total', 'sum', [fieldFactor('value', 'value')])]),
2485
+ * })
2486
+ * const templates = createTemplateManager({ templates: [template] })
2487
+ * templates.size // 1
2488
+ * ```
2489
+ */
2490
+ function createTemplateManager(options) {
2491
+ return new TemplateManager(options);
2492
+ }
2493
+ /**
2494
+ * Create a subject registry.
2495
+ *
2496
+ * @remarks
2497
+ * Mints its own record ids on `add` when none is supplied — a `Subject`
2498
+ * carries no `id` field of its own.
2499
+ *
2500
+ * @param options - Optional initial seed collection
2501
+ * @returns A working {@link SubjectManagerInterface}
2502
+ *
2503
+ * @example
2504
+ * ```ts
2505
+ * import { createSubjectManager } from '@src/core'
2506
+ *
2507
+ * const subjects = createSubjectManager({ subjects: [{ value: 1 }] })
2508
+ * subjects.size // 1
2509
+ * ```
2510
+ */
2511
+ function createSubjectManager(options) {
2512
+ return new SubjectManager(options);
2513
+ }
2514
+ /**
2515
+ * Create a definition registry.
2516
+ *
2517
+ * @param options - Optional initial seed collection
2518
+ * @returns A working {@link DefinitionManagerInterface}
2519
+ *
2520
+ * @example
2521
+ * ```ts
2522
+ * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
2523
+ * import { createDefinitionManager } from '@src/core'
2524
+ *
2525
+ * const definitions = createDefinitionManager({
2526
+ * definitions: [quantitativeDefinition('d1', 'D1', [factorGroup('total', 'sum', [fieldFactor('value', 'value')])])],
2527
+ * })
2528
+ * definitions.size // 1
2529
+ * ```
2530
+ */
2531
+ function createDefinitionManager(options) {
2532
+ return new DefinitionManager(options);
2533
+ }
2534
+ /**
2535
+ * Create a cross-turn interpretation context.
2536
+ *
2537
+ * @param options - Optional `session` label and `history` ring-buffer cap
2538
+ * @returns A working {@link InterpretContextInterface}
2539
+ *
2540
+ * @example
2541
+ * ```ts
2542
+ * import { createInterpretContext } from '@src/core'
2543
+ *
2544
+ * const context = createInterpretContext({ session: 'turn-1', history: 4 })
2545
+ * context.previous() // []
2546
+ * ```
2547
+ */
2548
+ function createInterpretContext(options) {
2549
+ return new InterpretContext(options);
2550
+ }
2551
+ /**
2552
+ * Build and validate one interpretation template from plain data.
2553
+ *
2554
+ * @remarks
2555
+ * The factory/coercer pair for template intake (AGENTS §4.6.1): this throws
2556
+ * on malformed data, while `parseTemplate` returns `undefined`. Data failing
2557
+ * {@link isTemplate} throws `InterpretError('INVALID_TEMPLATE', …)`.
2558
+ *
2559
+ * @param data - The candidate template data
2560
+ * @returns The same data, now known to satisfy {@link Template}
2561
+ * @throws {@link InterpretError} `INVALID_TEMPLATE` when `data` fails validation
2562
+ *
2563
+ * @example
2564
+ * ```ts
2565
+ * import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
2566
+ * import { createTemplate } from '@src/core'
2567
+ *
2568
+ * const template = createTemplate({
2569
+ * id: 't1', name: 'Arithmetic', domain: 'arithmetic', intents: ['calculate'],
2570
+ * mappings: [{ entity: 'value', aliases: [], field: 'value' }], defaults: [], computations: [],
2571
+ * definition: quantitativeDefinition('t1', 'Arithmetic', [factorGroup('total', 'sum', [fieldFactor('value', 'value')])]),
2572
+ * })
2573
+ * template.id // 't1'
2574
+ * ```
2575
+ */
2576
+ function createTemplate(data) {
2577
+ if (!isTemplate(data)) throw new InterpretError("INVALID_TEMPLATE", "Template data failed validation");
2578
+ return data;
2579
+ }
2580
+ /**
2581
+ * Create a lexicon-driven reverse-direction rendering engine.
2582
+ *
2583
+ * @remarks
2584
+ * Stateless — `phrase` / `label` / `line` / `value` are total lookups into a
2585
+ * caller `Lexicon` merged over `DEFAULT_LEXICON`, and `describe` / `narrate`
2586
+ * compose them over a reasons `Definition` / `ReasonResult`.
2587
+ *
2588
+ * @param options - Optional `lexicon` and `formatters` map
2589
+ * @returns A stateless {@link NarratorInterface}
2590
+ *
2591
+ * @example
2592
+ * ```ts
2593
+ * import { createNarrator } from '@src/core'
2594
+ *
2595
+ * const narrator = createNarrator({ lexicon: { templates: { 'subject.empty': 'nothing here' } } })
2596
+ * narrator.line('subject.empty', {}) // 'nothing here'
2597
+ * ```
2598
+ */
2599
+ function createNarrator(options) {
2600
+ return new Narrator(options);
2601
+ }
2602
+ //#endregion
2603
+ export { CONFIDENCE_ALIAS, CONFIDENCE_CARRIED, CONFIDENCE_COLLECT, CONFIDENCE_COMPUTED, CONFIDENCE_DEFAULT, CONFIDENCE_EXACT, CONFIDENCE_POSITIONAL, Clarifier, DEFAULT_ABBREVIATIONS, DEFAULT_ACTIONS, DEFAULT_CONTRACTIONS, DEFAULT_CORRECTIONS, DEFAULT_DOMAINS, DEFAULT_INTERPRET_FLOOR, DEFAULT_INTERPRET_HISTORY, DEFAULT_INTERPRET_SIMILARITY, DEFAULT_LEXICON, DEFAULT_VERBS, DefinitionManager, Extractor, Formatter, Generator, INTERPRET_ID, Interpret, InterpretContext, InterpretError, NUMBER_PATTERN, Narrator, Normalizer, SubjectManager, TemplateManager, UNSAFE_FIELD_SEGMENTS, applyReplacements, assignEntities, canonicalize, classifyIntent, collapseWhitespace, createClarifier, createDefinitionManager, createExtractor, createFormatter, createGenerator, createInterpret, createInterpretContext, createNarrator, createNormalizer, createSubjectManager, createTemplate, createTemplateManager, deriveAggregateField, describeSubject, digestValue, escapeRegExp, extractNumbers, isComputedField, isEntityMapping, isFieldDefault, isInterpretError, isTemplate, matchAlias, matchTemplate, parseTemplate, resolveExpression, scoreSimilarity, scoreTemplate, setField, tokenize, variablesOf };
2604
+
2605
+ //# sourceMappingURL=index.js.map