@orkestrel/interpret 0.0.1 → 0.0.3

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