@orkestrel/rater 0.0.24 → 0.0.26

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.
@@ -149,49 +149,14 @@ function isRatingDefinition(value) {
149
149
  ])(value);
150
150
  }
151
151
  /**
152
- * Determines whether a value is an open result-side {@link Evidence} object.
153
- *
154
- * @remarks
155
- * Optional `field` is checked as a `FieldPath`, `label` as a string,
156
- * `comparison` as a `Comparison`, and `state` as a `CheckState`, each when defined.
157
- * Unknown members, prototypes, and class instances are admitted. Arrays are
158
- * refused. `expected` and `actual` are `unknown`, so this guard does not read or
159
- * check them and a borrowed result is never narrowed on them; either member may
160
- * also be absent because `objectOf` reads declared members rather than
161
- * requiring or enumerating own keys.
162
- *
163
- * @param value - The value to test
164
- * @returns True if every checked `Evidence` member conforms; false otherwise
165
- *
166
- * @example
167
- * ```ts
168
- * import { isEvidence } from '@orkestrel/rater'
169
- *
170
- * isEvidence({ field: 'age', comparison: 'above', expected: 18, actual: 25, state: 'met' }) // true
171
- * ```
172
- */
173
- function isEvidence(value) {
174
- return (0, _orkestrel_contract.objectOf)({
175
- field: _orkestrel_reason.isFieldPath,
176
- label: _orkestrel_contract.isString,
177
- comparison: _orkestrel_reason.isComparison,
178
- state: _orkestrel_reason.isCheckState
179
- }, [
180
- "field",
181
- "label",
182
- "comparison",
183
- "state"
184
- ])(value);
185
- }
186
- /**
187
152
  * Determines whether a value is an open {@link WorksheetFactor} result object.
188
153
  *
189
154
  * @remarks
190
- * `id`, the optional authored text, `applied`, an optional plain-number
191
- * `value`, and each `Evidence` entry are checked. Unknown members, prototypes,
192
- * and class instances are admitted and left unchecked, because a borrowed
193
- * result implementation may add them. Arrays are refused. Optional members may
194
- * be absent or read as `undefined`.
155
+ * `id`, the optional authored text, `applied`, `fallback`, the optional plain-number
156
+ * `value` and `raw`, and each `CheckResult` entry are checked. `actual` is `unknown`, so
157
+ * this guard does not read it. Unknown members, prototypes, and class instances are
158
+ * admitted and left unchecked, because a borrowed result implementation may add them. Arrays
159
+ * are refused. Optional members may be absent or read as `undefined`.
195
160
  *
196
161
  * @param value - The value to test
197
162
  * @returns True if every published worksheet-factor member conforms; false otherwise
@@ -200,7 +165,7 @@ function isEvidence(value) {
200
165
  * ```ts
201
166
  * import { isWorksheetFactor } from '@orkestrel/rater'
202
167
  *
203
- * isWorksheetFactor({ id: 'base', applied: true, value: 100, evidence: [] }) // true
168
+ * isWorksheetFactor({ id: 'base', applied: true, value: 100, fallback: false, checks: [] }) // true
204
169
  * ```
205
170
  */
206
171
  function isWorksheetFactor(value) {
@@ -210,18 +175,21 @@ function isWorksheetFactor(value) {
210
175
  description: _orkestrel_contract.isString,
211
176
  applied: _orkestrel_contract.isBoolean,
212
177
  value: _orkestrel_contract.isNumber,
213
- evidence: (0, _orkestrel_contract.arrayOf)(isEvidence)
178
+ raw: _orkestrel_contract.isNumber,
179
+ fallback: _orkestrel_contract.isBoolean,
180
+ checks: (0, _orkestrel_contract.arrayOf)(_orkestrel_reason.isCheckResult)
214
181
  }, [
215
182
  "name",
216
183
  "description",
217
- "value"
184
+ "value",
185
+ "raw"
218
186
  ])(value);
219
187
  }
220
188
  /**
221
189
  * Determines whether a value is an open {@link WorksheetGroup} result object.
222
190
  *
223
191
  * @remarks
224
- * `id`, the optional authored text, `applied`, a plain-number `value`, and each
192
+ * `id`, the optional authored text, `applied`, an optional plain-number `value`, and each
225
193
  * `WorksheetFactor` entry are checked. Unknown members, prototypes, and class
226
194
  * instances are admitted and left unchecked, because a borrowed result
227
195
  * implementation may add them. Arrays are refused. Optional members may be
@@ -245,13 +213,17 @@ function isWorksheetGroup(value) {
245
213
  applied: _orkestrel_contract.isBoolean,
246
214
  value: _orkestrel_contract.isNumber,
247
215
  factors: (0, _orkestrel_contract.arrayOf)(isWorksheetFactor)
248
- }, ["name", "description"])(value);
216
+ }, [
217
+ "name",
218
+ "description",
219
+ "value"
220
+ ])(value);
249
221
  }
250
222
  /**
251
223
  * Determines whether a value is an open {@link Step} result object.
252
224
  *
253
225
  * @remarks
254
- * `stage` is checked through `isWorksheetStage`, `id`, `name`, and `expression` when
226
+ * `stage` is checked through `isWorksheetStage`, `id` and `name` when
255
227
  * defined, and `value` as a plain number. Unknown members, prototypes, and
256
228
  * class instances are admitted and left unchecked, because a borrowed result
257
229
  * implementation may add them. Arrays are refused. Optional members may be
@@ -272,13 +244,8 @@ function isStep(value) {
272
244
  stage: isWorksheetStage,
273
245
  id: _orkestrel_contract.isString,
274
246
  name: _orkestrel_contract.isString,
275
- value: _orkestrel_contract.isNumber,
276
- expression: _orkestrel_contract.isString
277
- }, [
278
- "id",
279
- "name",
280
- "expression"
281
- ])(value);
247
+ value: _orkestrel_contract.isNumber
248
+ }, ["id", "name"])(value);
282
249
  }
283
250
  /**
284
251
  * Determines whether a value is an open {@link Worksheet} result object.
@@ -286,7 +253,7 @@ function isStep(value) {
286
253
  * @remarks
287
254
  * Identity, `aggregation` through reason's `isAggregation`, an optional
288
255
  * plain-number `precision`, a plain-number `value`, the nested groups and steps,
289
- * `trace`, `errors`, and `success` are checked. Unknown members, prototypes, and
256
+ * `trace`, `refusals` through reason's `isReasonRefusal`, and `success` are checked. Unknown members, prototypes, and
290
257
  * class instances are admitted and left unchecked, because a borrowed result
291
258
  * implementation may add them. Arrays are refused. Optional members may be
292
259
  * absent or read as `undefined`.
@@ -298,7 +265,7 @@ function isStep(value) {
298
265
  * ```ts
299
266
  * import { isWorksheet } from '@orkestrel/rater'
300
267
  *
301
- * isWorksheet({ id: 'quote', name: 'Quote', aggregation: 'sum', value: 0, groups: [], steps: [], trace: [], errors: [], success: true, faults: [], repairs: [], defaulted: [] }) // true
268
+ * isWorksheet({ id: 'quote', name: 'Quote', aggregation: 'sum', value: 0, groups: [], steps: [], trace: [], refusals: [], success: true, faults: [], repairs: [], defaulted: [] }) // true
302
269
  * ```
303
270
  */
304
271
  function isWorksheet(value) {
@@ -311,7 +278,7 @@ function isWorksheet(value) {
311
278
  groups: (0, _orkestrel_contract.arrayOf)(isWorksheetGroup),
312
279
  steps: (0, _orkestrel_contract.arrayOf)(isStep),
313
280
  trace: (0, _orkestrel_contract.arrayOf)(_orkestrel_contract.isString),
314
- errors: (0, _orkestrel_contract.arrayOf)(_orkestrel_contract.isString),
281
+ refusals: (0, _orkestrel_contract.arrayOf)(_orkestrel_reason.isReasonRefusal),
315
282
  success: _orkestrel_contract.isBoolean,
316
283
  faults: (0, _orkestrel_contract.arrayOf)(_orkestrel_contract.isAuditFault),
317
284
  repairs: (0, _orkestrel_contract.arrayOf)(_orkestrel_contract.isAuditFault),
@@ -338,7 +305,7 @@ function isWorksheet(value) {
338
305
  * ```ts
339
306
  * import { isLineResult } from '@orkestrel/rater'
340
307
  *
341
- * isLineResult({ id: 'base', name: 'Base', worksheet: { id: 'base', name: 'Base', aggregation: 'sum', value: 0, groups: [], steps: [], trace: [], errors: [], success: false } }) // true
308
+ * isLineResult({ id: 'base', name: 'Base', worksheet: { id: 'base', name: 'Base', aggregation: 'sum', value: 0, groups: [], steps: [], trace: [], refusals: [], success: false } }) // true
342
309
  * ```
343
310
  */
344
311
  function isLineResult(value) {
@@ -368,7 +335,7 @@ function isLineResult(value) {
368
335
  * ```ts
369
336
  * import { isRatingResult } from '@orkestrel/rater'
370
337
  *
371
- * isRatingResult({ lines: [], success: true, errors: [], faults: [], repairs: [], defaulted: [] }) // true
338
+ * isRatingResult({ lines: [], success: true, refusals: [], faults: [], repairs: [], defaulted: [] }) // true
372
339
  * ```
373
340
  */
374
341
  function isRatingResult(value) {
@@ -376,7 +343,7 @@ function isRatingResult(value) {
376
343
  lines: (0, _orkestrel_contract.arrayOf)(isLineResult),
377
344
  total: _orkestrel_contract.isNumber,
378
345
  success: _orkestrel_contract.isBoolean,
379
- errors: (0, _orkestrel_contract.arrayOf)(_orkestrel_contract.isString),
346
+ refusals: (0, _orkestrel_contract.arrayOf)(_orkestrel_reason.isReasonRefusal),
380
347
  faults: (0, _orkestrel_contract.arrayOf)(_orkestrel_contract.isAuditFault),
381
348
  repairs: (0, _orkestrel_contract.arrayOf)(_orkestrel_contract.isAuditFault),
382
349
  defaulted: (0, _orkestrel_contract.arrayOf)(_orkestrel_reason.isFieldPath)
@@ -439,66 +406,11 @@ function buildRatingDefinition(id, name, lines, overrides) {
439
406
  };
440
407
  }
441
408
  /**
442
- * Builds an {@link Evidence} row from an evaluated {@link Check}.
443
- *
444
- * @param check - The authored check
445
- * @param actual - The resolved subject value
446
- * @param state - The check's state; absent when the check was not evaluated
447
- * @param labels - Optional field-to-label overrides, keyed by dot-joined field
448
- * @returns A fresh evidence row
449
- *
450
- * @example
451
- * ```ts
452
- * import { createCheck } from '@orkestrel/reason'
453
- * import { buildEvidence } from '@orkestrel/rater'
454
- *
455
- * const entry = createCheck('age', 'above', 18)
456
- * buildEvidence(entry, 25, 'met') // { field: 'age', comparison: 'above', expected: 18, actual: 25, state: 'met' }
457
- * ```
458
- */
459
- function buildEvidence(check, actual, state, labels) {
460
- const field = (0, _orkestrel_reason.formatField)(check.field);
461
- const label = labels !== void 0 && Object.hasOwn(labels, field) ? labels[field] : void 0;
462
- return {
463
- field: check.field,
464
- ...label === void 0 ? {} : { label },
465
- comparison: check.operator,
466
- expected: check.value,
467
- actual,
468
- ...state === void 0 ? {} : { state }
469
- };
470
- }
471
- /**
472
- * Builds one evidence row per authored check of a quantitative factor, joined
473
- * to that check's evaluated result.
474
- *
475
- * @param checks - The factor's authored checks
476
- * @param results - The corresponding {@link CheckResult}s, in the same order
477
- * @param labels - Optional field-to-label overrides, keyed by dot-joined field
478
- * @returns A fresh list of evidence rows, one per authored check
479
- *
480
- * @example
481
- * ```ts
482
- * import { createCheck } from '@orkestrel/reason'
483
- * import { buildEvidenceRows } from '@orkestrel/rater'
484
- *
485
- * const checks = [createCheck('age', 'above', 18)]
486
- * buildEvidenceRows(checks, [{ field: 'age', state: 'met', actual: 25 }])
487
- * ```
488
- */
489
- function buildEvidenceRows(checks, results, labels) {
490
- return (checks ?? []).map((check, index) => {
491
- const result = results?.[index];
492
- return buildEvidence(check, result?.actual, result?.state, labels);
493
- });
494
- }
495
- /**
496
409
  * Joins one authored quantitative factor to its evaluated {@link FactorResult}.
497
410
  *
498
411
  * @param definition - The authored factor
499
412
  * @param results - The group's factor results
500
- * @param labels - Optional field-to-label overrides, keyed by dot-joined field
501
- * @returns A fresh worksheet factor
413
+ * @returns A fresh worksheet factor, its `checks` empty for a factor that never ran
502
414
  *
503
415
  * @example
504
416
  * ```ts
@@ -506,10 +418,10 @@ function buildEvidenceRows(checks, results, labels) {
506
418
  * import { buildWorksheetFactor } from '@orkestrel/rater'
507
419
  *
508
420
  * const factor = createFieldFactor('seats', 'seats')
509
- * buildWorksheetFactor(factor, [{ id: 'seats', applied: true, value: 10 }])
421
+ * buildWorksheetFactor(factor, [{ id: 'seats', applied: true, value: 10, fallback: false }])
510
422
  * ```
511
423
  */
512
- function buildWorksheetFactor(definition, results, labels) {
424
+ function buildWorksheetFactor(definition, results) {
513
425
  const result = results.find((entry) => entry.id === definition.id);
514
426
  return {
515
427
  id: definition.id,
@@ -517,7 +429,10 @@ function buildWorksheetFactor(definition, results, labels) {
517
429
  ...definition.description === void 0 ? {} : { description: definition.description },
518
430
  applied: result?.applied ?? false,
519
431
  ...result?.value === void 0 ? {} : { value: result.value },
520
- evidence: buildEvidenceRows(definition.checks, result?.checks, labels)
432
+ ...result?.raw === void 0 ? {} : { raw: result.raw },
433
+ ...result?.actual === void 0 ? {} : { actual: result.actual },
434
+ fallback: result?.fallback ?? false,
435
+ checks: result?.checks ?? []
521
436
  };
522
437
  }
523
438
  /**
@@ -525,7 +440,6 @@ function buildWorksheetFactor(definition, results, labels) {
525
440
  *
526
441
  * @param definition - The authored group
527
442
  * @param results - The definition's group results
528
- * @param labels - Optional field-to-label overrides, keyed by dot-joined field
529
443
  * @returns A fresh worksheet group
530
444
  *
531
445
  * @example
@@ -537,15 +451,15 @@ function buildWorksheetFactor(definition, results, labels) {
537
451
  * buildWorksheetGroup(group, [{ id: 'charge', applied: true, value: 100, factors: [] }])
538
452
  * ```
539
453
  */
540
- function buildWorksheetGroup(definition, results, labels) {
454
+ function buildWorksheetGroup(definition, results) {
541
455
  const result = results.find((entry) => entry.id === definition.id);
542
456
  return {
543
457
  id: definition.id,
544
458
  name: definition.name,
545
459
  ...definition.description === void 0 ? {} : { description: definition.description },
546
460
  applied: result?.applied ?? false,
547
- value: result?.value ?? 0,
548
- factors: definition.factors.map((factor) => buildWorksheetFactor(factor, result?.factors ?? [], labels))
461
+ ...result === void 0 ? {} : { value: result.value },
462
+ factors: definition.factors.map((factor) => buildWorksheetFactor(factor, result?.factors ?? []))
549
463
  };
550
464
  }
551
465
  /**
@@ -555,24 +469,22 @@ function buildWorksheetGroup(definition, results, labels) {
555
469
  * @param id - The stage's authored id, when it has one
556
470
  * @param name - The stage's authored name, when it has one
557
471
  * @param value - The stage's resolved value
558
- * @param expression - A display-neutral expression string
559
472
  * @returns A fresh step
560
473
  *
561
474
  * @example
562
475
  * ```ts
563
476
  * import { buildWorksheetStep } from '@orkestrel/rater'
564
477
  *
565
- * buildWorksheetStep('total', 'quote', 'Quote', 110, 'sum = 110')
566
- * // { stage: 'total', id: 'quote', name: 'Quote', value: 110, expression: 'sum = 110' }
478
+ * buildWorksheetStep('total', 'quote', 'Quote', 110)
479
+ * // { stage: 'total', id: 'quote', name: 'Quote', value: 110 }
567
480
  * ```
568
481
  */
569
- function buildWorksheetStep(stage, id, name, value, expression) {
482
+ function buildWorksheetStep(stage, id, name, value) {
570
483
  return {
571
484
  stage,
572
485
  ...id === void 0 ? {} : { id },
573
486
  ...name === void 0 ? {} : { name },
574
- value,
575
- expression
487
+ value
576
488
  };
577
489
  }
578
490
  /**
@@ -598,10 +510,10 @@ function buildWorksheetStep(stage, id, name, value, expression) {
598
510
  function buildWorksheetSteps(definition, result, groups) {
599
511
  const output = [];
600
512
  for (const group of groups) {
601
- for (const factor of group.factors) if (factor.applied && factor.value !== void 0) output.push(buildWorksheetStep("factor", factor.id, factor.name, factor.value, `${factor.id} = ${factor.value}`));
602
- output.push(buildWorksheetStep("group", group.id, group.name, group.value, `${group.id} = ${group.value}`));
513
+ for (const factor of group.factors) if (factor.applied && factor.value !== void 0) output.push(buildWorksheetStep("factor", factor.id, factor.name, factor.value));
514
+ if (group.value !== void 0) output.push(buildWorksheetStep("group", group.id, group.name, group.value));
603
515
  }
604
- output.push(buildWorksheetStep("total", definition.id, definition.name, result.value, `${definition.aggregation} = ${result.value}`));
516
+ output.push(buildWorksheetStep("total", definition.id, definition.name, result.value));
605
517
  return output;
606
518
  }
607
519
  /**
@@ -610,7 +522,6 @@ function buildWorksheetSteps(definition, result, groups) {
610
522
  *
611
523
  * @param definition - The authored quantitative definition
612
524
  * @param result - The evaluated quantitative result
613
- * @param labels - Optional field-to-label overrides, keyed by dot-joined field
614
525
  * @returns A fresh worksheet
615
526
  *
616
527
  * @example
@@ -623,8 +534,8 @@ function buildWorksheetSteps(definition, result, groups) {
623
534
  * if (result.reasoning === 'quantitative') buildWorksheet(definition, result) // the full audit trail
624
535
  * ```
625
536
  */
626
- function buildWorksheet(definition, result, labels) {
627
- const groups = definition.groups.map((group) => buildWorksheetGroup(group, result.groups, labels));
537
+ function buildWorksheet(definition, result) {
538
+ const groups = definition.groups.map((group) => buildWorksheetGroup(group, result.groups));
628
539
  return {
629
540
  id: definition.id,
630
541
  name: definition.name,
@@ -634,7 +545,7 @@ function buildWorksheet(definition, result, labels) {
634
545
  groups,
635
546
  steps: buildWorksheetSteps(definition, result, groups),
636
547
  trace: result.trace,
637
- errors: result.errors,
548
+ refusals: result.refusals,
638
549
  success: result.success,
639
550
  faults: result.faults,
640
551
  repairs: result.repairs,
@@ -647,7 +558,6 @@ function buildWorksheet(definition, result, labels) {
647
558
  *
648
559
  * @param definition - The authored line definition
649
560
  * @param result - The evaluated quantitative result
650
- * @param labels - Optional field-to-label overrides, keyed by dot-joined field
651
561
  * @returns A fresh line result
652
562
  *
653
563
  * @example
@@ -660,12 +570,272 @@ function buildWorksheet(definition, result, labels) {
660
570
  * if (result.reasoning === 'quantitative') buildLineResult(line, result) // amount present only on a successful worksheet
661
571
  * ```
662
572
  */
663
- function buildLineResult(definition, result, labels) {
573
+ function buildLineResult(definition, result) {
664
574
  return {
665
575
  id: definition.id,
666
576
  name: definition.name,
667
577
  ...result.success ? { amount: result.value } : {},
668
- worksheet: buildWorksheet(definition.rate, result, labels)
578
+ worksheet: buildWorksheet(definition.rate, result)
579
+ };
580
+ }
581
+ /**
582
+ * Copies a quantitative result into plain objects and arrays this package owns, reading each
583
+ * member of it once.
584
+ *
585
+ * @remarks
586
+ * The copy reaches the result's groups, their factors, and each factor's checks. A check's own
587
+ * `check` and `actual`, and the entries of `refusals`, `faults`, and `repairs`, are carried as
588
+ * they were read.
589
+ *
590
+ * @param result - The quantitative result to copy
591
+ * @returns A fresh result that holds each member as it read
592
+ *
593
+ * @example
594
+ * ```ts
595
+ * import { copyResult } from '@orkestrel/rater'
596
+ *
597
+ * const answer = {
598
+ * reasoning: 'quantitative',
599
+ * value: 5,
600
+ * groups: [],
601
+ * count: 0,
602
+ * success: true,
603
+ * trace: [],
604
+ * refusals: [],
605
+ * faults: [],
606
+ * repairs: [],
607
+ * defaulted: [],
608
+ * } as const
609
+ * copyResult(answer) === answer // false
610
+ * ```
611
+ */
612
+ function copyResult(result) {
613
+ const { reasoning, value, groups, count, success, trace, refusals, faults, repairs, defaulted } = result;
614
+ return {
615
+ reasoning,
616
+ value,
617
+ groups: groups.map(({ id, applied, value: held, factors }) => ({
618
+ id,
619
+ applied,
620
+ value: held,
621
+ factors: factors.map(({ id: key, applied: ran, value: scored, raw, actual, fallback, checks }) => ({
622
+ id: key,
623
+ applied: ran,
624
+ value: scored,
625
+ ...raw === void 0 ? {} : { raw },
626
+ ...actual === void 0 ? {} : { actual },
627
+ fallback,
628
+ ...checks === void 0 ? {} : { checks: checks.map((read) => ({
629
+ check: read.check,
630
+ state: read.state,
631
+ actual: read.actual
632
+ })) }
633
+ }))
634
+ })),
635
+ count,
636
+ success,
637
+ trace: [...trace],
638
+ refusals: [...refusals],
639
+ faults: [...faults],
640
+ repairs: [...repairs],
641
+ defaulted: [...defaulted]
642
+ };
643
+ }
644
+ /**
645
+ * Finds each enabled group of a definition that a result omits, and each enabled factor an
646
+ * answered group omits.
647
+ *
648
+ * @remarks
649
+ * An omitted group is named alone, because its factors have no group to answer in.
650
+ *
651
+ * @param definition - The authored quantitative definition
652
+ * @param result - The result the engine answered with
653
+ * @returns The `group`, and the `factor` where one is omitted, of each omission, in definition order
654
+ *
655
+ * @example
656
+ * ```ts
657
+ * import { createFactorGroup, createQuantitativeDefinition, createStaticFactor } from '@orkestrel/reason'
658
+ * import { findUnansweredParts } from '@orkestrel/rater'
659
+ *
660
+ * const definition = createQuantitativeDefinition('quote', 'Quote', [
661
+ * createFactorGroup('charge', 'sum', [createStaticFactor('base', 100)]),
662
+ * ])
663
+ * findUnansweredParts(definition, {
664
+ * reasoning: 'quantitative',
665
+ * value: 0,
666
+ * groups: [],
667
+ * count: 0,
668
+ * success: true,
669
+ * trace: [],
670
+ * refusals: [],
671
+ * faults: [],
672
+ * repairs: [],
673
+ * defaulted: [],
674
+ * }) // [{ group: 'charge' }]
675
+ * ```
676
+ */
677
+ function findUnansweredParts(definition, result) {
678
+ const answered = new Map(result.groups.map((group) => [group.id, new Set(group.factors.map((factor) => factor.id))]));
679
+ return definition.groups.filter((group) => group.enabled !== false).flatMap((group) => {
680
+ const held = answered.get(group.id);
681
+ if (held === void 0) return [{ group: group.id }];
682
+ return group.factors.filter((factor) => factor.enabled !== false && !held.has(factor.id)).map((factor) => ({
683
+ group: group.id,
684
+ factor: factor.id
685
+ }));
686
+ });
687
+ }
688
+ /**
689
+ * Finds each group id a result lists more than once, and each factor id one of its groups lists
690
+ * more than once.
691
+ *
692
+ * @remarks
693
+ * An entry that repeats an id is refused whatever it holds, because a worksheet reads the first
694
+ * entry and a completeness check reads the last. Each repeated id is named once, however many
695
+ * entries repeat it.
696
+ *
697
+ * @param result - The result the engine answered with
698
+ * @returns The `group`, and the `factor` where a factor repeats, of each repeated id
699
+ *
700
+ * @example
701
+ * ```ts
702
+ * import { findRepeatedParts } from '@orkestrel/rater'
703
+ *
704
+ * const group = { id: 'charge', applied: true, value: 100, factors: [] }
705
+ * findRepeatedParts({
706
+ * reasoning: 'quantitative',
707
+ * value: 100,
708
+ * groups: [group, group],
709
+ * count: 1,
710
+ * success: true,
711
+ * trace: [],
712
+ * refusals: [],
713
+ * faults: [],
714
+ * repairs: [],
715
+ * defaulted: [],
716
+ * }) // [{ group: 'charge' }]
717
+ * ```
718
+ */
719
+ function findRepeatedParts(result) {
720
+ const groups = (0, _orkestrel_reason.findDuplicates)(result.groups).map((group) => ({ group }));
721
+ const factors = result.groups.flatMap((group) => (0, _orkestrel_reason.findDuplicates)(group.factors).map((factor) => ({
722
+ group: group.id,
723
+ factor
724
+ })));
725
+ return [...groups, ...factors].filter((part, index, all) => all.findIndex((held) => held.group === part.group && held.factor === part.factor) === index);
726
+ }
727
+ /**
728
+ * Finds each line whose id an earlier line of the list holds.
729
+ *
730
+ * @param lines - The lines of one rating, in order
731
+ * @returns One `definition` refusal for each such line, its `path` the id and its `index` the line's place
732
+ *
733
+ * @example
734
+ * ```ts
735
+ * import { createQuantitativeDefinition } from '@orkestrel/reason'
736
+ * import { buildLineDefinition, findRepeatedLines } from '@orkestrel/rater'
737
+ *
738
+ * const rate = createQuantitativeDefinition('base', 'Base', [])
739
+ * const line = buildLineDefinition('base', 'Base', rate)
740
+ * findRepeatedLines([line, line]) // [{ cause: 'definition', path: ['base'], index: 1 }]
741
+ * ```
742
+ */
743
+ function findRepeatedLines(lines) {
744
+ const earliest = new Map(lines.map((line, index) => [line.id, index]).toReversed());
745
+ return lines.flatMap((line, index) => earliest.get(line.id) === index ? [] : [{
746
+ cause: "definition",
747
+ path: [line.id],
748
+ index
749
+ }]);
750
+ }
751
+ /**
752
+ * Holds an engine's answer to what its own members and the definition support.
753
+ *
754
+ * @remarks
755
+ * The answer is read once, through {@link copyResult}, and every verdict follows from that copy.
756
+ * An answer that is no quantitative result is `malformed` alone. A success beside a refusal or a
757
+ * fault, beside each enabled group or factor the answer omits, beside each group or factor id it
758
+ * lists more than once, and beside a value that is not a finite number, fails closed with one
759
+ * `malformed` refusal for each, the part in `group` and `factor` and the value in `actual`. A failure that names no refusal and no fault is
760
+ * `silent`. Any other answer returns as its copy.
761
+ *
762
+ * @param answer - What the engine answered
763
+ * @param definition - The authored quantitative definition the engine ran
764
+ * @returns A fresh result the package owns
765
+ *
766
+ * @example
767
+ * ```ts
768
+ * import { createQuantitativeDefinition } from '@orkestrel/reason'
769
+ * import { settleResult } from '@orkestrel/rater'
770
+ *
771
+ * settleResult(
772
+ * {
773
+ * reasoning: 'quantitative',
774
+ * value: 5,
775
+ * groups: [],
776
+ * count: 0,
777
+ * success: false,
778
+ * trace: [],
779
+ * refusals: [],
780
+ * faults: [],
781
+ * repairs: [],
782
+ * defaulted: [],
783
+ * },
784
+ * createQuantitativeDefinition('base', 'Base', []),
785
+ * ).refusals // [{ cause: 'silent' }]
786
+ * ```
787
+ */
788
+ function settleResult(answer, definition) {
789
+ const copied = (0, _orkestrel_reason.isQuantitativeResult)(answer) ? (0, _orkestrel_contract.attempt)(() => copyResult(answer)) : void 0;
790
+ if (copied === void 0 || !(0, _orkestrel_contract.isSuccess)(copied) || !(0, _orkestrel_reason.isQuantitativeResult)(copied.value)) return buildMalformedResult();
791
+ const result = copied.value;
792
+ const { success, value, refusals, faults } = result;
793
+ const named = refusals.length > 0 || faults.length > 0;
794
+ if (!success) return named ? result : {
795
+ ...result,
796
+ refusals: [{ cause: "silent" }]
797
+ };
798
+ const held = [
799
+ ...named ? [{}] : [],
800
+ ...findUnansweredParts(definition, result),
801
+ ...findRepeatedParts(result),
802
+ ...(0, _orkestrel_contract.isFiniteNumber)(value) ? [] : [{ actual: value }]
803
+ ];
804
+ if (held.length === 0) return result;
805
+ const contradictions = held.map((part) => ({
806
+ cause: "malformed",
807
+ ...part
808
+ }));
809
+ return {
810
+ ...result,
811
+ success: false,
812
+ refusals: [...refusals, ...contradictions]
813
+ };
814
+ }
815
+ /**
816
+ * Builds the failed {@link QuantitativeResult} for an engine answer that is no quantitative result.
817
+ *
818
+ * @returns A fresh failed result carrying one `malformed` refusal
819
+ *
820
+ * @example
821
+ * ```ts
822
+ * import { buildMalformedResult } from '@orkestrel/rater'
823
+ *
824
+ * buildMalformedResult().refusals // [{ cause: 'malformed' }]
825
+ * ```
826
+ */
827
+ function buildMalformedResult() {
828
+ return {
829
+ reasoning: "quantitative",
830
+ value: 0,
831
+ groups: [],
832
+ count: 0,
833
+ success: false,
834
+ trace: [],
835
+ refusals: [{ cause: "malformed" }],
836
+ faults: [],
837
+ repairs: [],
838
+ defaulted: []
669
839
  };
670
840
  }
671
841
  /**
@@ -693,8 +863,9 @@ function sumAmounts(lines) {
693
863
  * Projects a result to the JSON its contract reads.
694
864
  *
695
865
  * @remarks
696
- * An evidence row's `actual` holds whatever the subject held and a worksheet's numbers may be
697
- * `NaN`, so a result crosses a boundary as this projection, each `actual` on its own budget.
866
+ * A factor's `actual`, a check's `actual`, and a refusal's `actual` hold whatever the subject held
867
+ * and a worksheet's numbers may be `NaN`, so a result crosses a boundary as this projection, each
868
+ * `actual` on its own budget.
698
869
  *
699
870
  * @param result - The rating result
700
871
  * @returns Its JSON projection, which `ratingResultContract` admits
@@ -713,20 +884,21 @@ function projectRatingResult(result) {
713
884
  ...line,
714
885
  worksheet: {
715
886
  ...line.worksheet,
887
+ refusals: line.worksheet.refusals.map((refusal) => (0, _orkestrel_reason.projectRefusal)(refusal)),
716
888
  groups: line.worksheet.groups.map((group) => ({
717
889
  ...group,
718
890
  factors: group.factors.map((factor) => ({
719
891
  ...factor,
720
- evidence: factor.evidence.map((row) => ({
721
- ...row,
722
- actual: (0, _orkestrel_reason.projectValue)(row.actual)
723
- }))
892
+ actual: (0, _orkestrel_reason.projectValue)(factor.actual),
893
+ checks: factor.checks.map((check) => (0, _orkestrel_reason.projectCheck)(check))
724
894
  }))
725
895
  }))
726
896
  }
727
897
  }));
898
+ const refusals = result.refusals.map((refusal) => (0, _orkestrel_reason.projectRefusal)(refusal));
728
899
  return (0, _orkestrel_reason.projectValue)({
729
900
  ...result,
901
+ refusals,
730
902
  lines
731
903
  }, /* @__PURE__ */ new Set(), { left: Number.POSITIVE_INFINITY });
732
904
  }
@@ -750,15 +922,6 @@ var ratingDefinitionShape = (0, _orkestrel_contract.objectShape)({
750
922
  metadata: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.jsonShape)()),
751
923
  shape: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.shapeShape)())
752
924
  });
753
- /** Describes an `Evidence` row in its JSON projection. */
754
- var evidenceShape = (0, _orkestrel_contract.objectShape)({
755
- field: (0, _orkestrel_contract.optionalShape)(_orkestrel_reason.fieldPathShape),
756
- label: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
757
- comparison: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.literalShape)(_orkestrel_reason.COMPARISONS)),
758
- expected: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.jsonShape)()),
759
- actual: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.jsonShape)()),
760
- state: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.literalShape)(_orkestrel_reason.CHECK_STATES))
761
- });
762
925
  /** Describes a `WorksheetFactor` in its JSON projection. */
763
926
  var worksheetFactorShape = (0, _orkestrel_contract.objectShape)({
764
927
  id: (0, _orkestrel_contract.stringShape)(),
@@ -766,7 +929,10 @@ var worksheetFactorShape = (0, _orkestrel_contract.objectShape)({
766
929
  description: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
767
930
  applied: (0, _orkestrel_contract.booleanShape)(),
768
931
  value: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.nullableShape)((0, _orkestrel_contract.numberShape)())),
769
- evidence: (0, _orkestrel_contract.arrayShape)(evidenceShape)
932
+ raw: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.nullableShape)((0, _orkestrel_contract.numberShape)())),
933
+ actual: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.jsonShape)()),
934
+ fallback: (0, _orkestrel_contract.booleanShape)(),
935
+ checks: (0, _orkestrel_contract.arrayShape)(_orkestrel_reason.checkResultShape)
770
936
  });
771
937
  /** Describes a `WorksheetGroup` in its JSON projection. */
772
938
  var worksheetGroupShape = (0, _orkestrel_contract.objectShape)({
@@ -774,7 +940,7 @@ var worksheetGroupShape = (0, _orkestrel_contract.objectShape)({
774
940
  name: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
775
941
  description: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
776
942
  applied: (0, _orkestrel_contract.booleanShape)(),
777
- value: (0, _orkestrel_contract.nullableShape)((0, _orkestrel_contract.numberShape)()),
943
+ value: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.nullableShape)((0, _orkestrel_contract.numberShape)())),
778
944
  factors: (0, _orkestrel_contract.arrayShape)(worksheetFactorShape)
779
945
  });
780
946
  /** Describes a `Step` in its JSON projection. */
@@ -782,8 +948,7 @@ var worksheetStepShape = (0, _orkestrel_contract.objectShape)({
782
948
  stage: (0, _orkestrel_contract.literalShape)(WORKSHEET_STAGES),
783
949
  id: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
784
950
  name: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
785
- value: (0, _orkestrel_contract.nullableShape)((0, _orkestrel_contract.numberShape)()),
786
- expression: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)())
951
+ value: (0, _orkestrel_contract.nullableShape)((0, _orkestrel_contract.numberShape)())
787
952
  });
788
953
  /** Describes a `Worksheet` in its JSON projection. */
789
954
  var worksheetShape = (0, _orkestrel_contract.objectShape)({
@@ -795,7 +960,7 @@ var worksheetShape = (0, _orkestrel_contract.objectShape)({
795
960
  groups: (0, _orkestrel_contract.arrayShape)(worksheetGroupShape),
796
961
  steps: (0, _orkestrel_contract.arrayShape)(worksheetStepShape),
797
962
  trace: (0, _orkestrel_contract.arrayShape)((0, _orkestrel_contract.stringShape)()),
798
- errors: (0, _orkestrel_contract.arrayShape)((0, _orkestrel_contract.stringShape)()),
963
+ refusals: (0, _orkestrel_contract.arrayShape)(_orkestrel_reason.reasonRefusalShape),
799
964
  success: (0, _orkestrel_contract.booleanShape)(),
800
965
  faults: (0, _orkestrel_contract.arrayShape)((0, _orkestrel_contract.auditFaultShape)()),
801
966
  repairs: (0, _orkestrel_contract.arrayShape)((0, _orkestrel_contract.auditFaultShape)()),
@@ -813,7 +978,7 @@ var ratingResultShape = (0, _orkestrel_contract.objectShape)({
813
978
  lines: (0, _orkestrel_contract.arrayShape)(lineResultShape),
814
979
  total: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.nullableShape)((0, _orkestrel_contract.numberShape)())),
815
980
  success: (0, _orkestrel_contract.booleanShape)(),
816
- errors: (0, _orkestrel_contract.arrayShape)((0, _orkestrel_contract.stringShape)()),
981
+ refusals: (0, _orkestrel_contract.arrayShape)(_orkestrel_reason.reasonRefusalShape),
817
982
  faults: (0, _orkestrel_contract.arrayShape)((0, _orkestrel_contract.auditFaultShape)()),
818
983
  repairs: (0, _orkestrel_contract.arrayShape)((0, _orkestrel_contract.auditFaultShape)()),
819
984
  defaulted: (0, _orkestrel_contract.arrayShape)(_orkestrel_reason.fieldPathShape)
@@ -853,7 +1018,6 @@ var Rater = class {
853
1018
  #engine;
854
1019
  #owned;
855
1020
  #total;
856
- #labels;
857
1021
  #door = (0, _orkestrel_reason.createSubjectDoor)();
858
1022
  #valid = /* @__PURE__ */ new WeakSet();
859
1023
  #destroyed = false;
@@ -873,7 +1037,6 @@ var Rater = class {
873
1037
  this.#owned = false;
874
1038
  }
875
1039
  this.#total = options?.total;
876
- this.#labels = options?.labels;
877
1040
  }
878
1041
  get emitter() {
879
1042
  return this.#emitter;
@@ -888,7 +1051,7 @@ var Rater = class {
888
1051
  const refused = {
889
1052
  lines: [],
890
1053
  success: false,
891
- errors: admission.errors,
1054
+ refusals: admission.refusals,
892
1055
  faults: admission.faults,
893
1056
  repairs: [],
894
1057
  defaulted: []
@@ -897,29 +1060,29 @@ var Rater = class {
897
1060
  return refused;
898
1061
  }
899
1062
  const results = lines.map((line) => this.#rateLine(line, admitted));
900
- const rated = results.every((entry) => entry.worksheet.success);
1063
+ const repeated = findRepeatedLines(lines);
1064
+ const rated = results.every((entry) => entry.worksheet.success) && repeated.length === 0;
901
1065
  const summed = rated ? (this.#total ?? sumAmounts)(results) : void 0;
902
1066
  const overflowed = summed !== void 0 && !(0, _orkestrel_contract.isFiniteNumber)(summed);
903
1067
  const total = overflowed ? void 0 : summed;
904
1068
  const success = rated && !overflowed;
905
1069
  const faults = (0, _orkestrel_reason.filterUniqueFaults)(results.flatMap((entry) => entry.worksheet.faults));
906
- const said = new Set(faults.map((fault) => (0, _orkestrel_contract.describeFaults)([fault])));
907
- const other = results.flatMap((entry) => {
908
- const { errors, success: settled } = entry.worksheet;
909
- if (!settled && errors.length === 0) return [`${entry.id}: The line failed and said nothing`];
910
- return errors.filter((error) => !said.has(error)).map((error) => `${entry.id}: ${error}`);
911
- });
1070
+ const unfinite = overflowed ? [{
1071
+ cause: "value",
1072
+ actual: summed
1073
+ }] : [];
1074
+ const refusals = [
1075
+ ...results.flatMap((entry) => (0, _orkestrel_reason.nestRefusals)(entry.worksheet.refusals, entry.id)),
1076
+ ...repeated,
1077
+ ...unfinite
1078
+ ];
912
1079
  const repairs = (0, _orkestrel_reason.filterUniqueFaults)([...admission.repairs, ...results.flatMap((entry) => entry.worksheet.repairs)]);
913
1080
  const defaulted = (0, _orkestrel_reason.filterUniqueFields)([...admission.defaulted, ...results.flatMap((entry) => entry.worksheet.defaulted)]);
914
1081
  const result = {
915
1082
  lines: results,
916
1083
  ...total === void 0 ? {} : { total },
917
1084
  success,
918
- errors: [
919
- ...other,
920
- ...said,
921
- ...overflowed ? ["The total is not a finite number"] : []
922
- ],
1085
+ refusals,
923
1086
  faults,
924
1087
  repairs,
925
1088
  defaulted
@@ -950,35 +1113,10 @@ var Rater = class {
950
1113
  return shape;
951
1114
  }
952
1115
  #rateLine(line, subject) {
953
- return buildLineResult(line, this.#reasonQuantitative(subject, line.rate), this.#labels);
1116
+ return buildLineResult(line, this.#reasonQuantitative(subject, line.rate));
954
1117
  }
955
1118
  #reasonQuantitative(subject, definition) {
956
- const result = this.#reason(subject, definition);
957
- if ((0, _orkestrel_reason.isQuantitativeResult)(result)) return this.#settle(result);
958
- const answer = (0, _orkestrel_contract.isRecord)(result) ? result : {};
959
- const named = (0, _orkestrel_contract.isString)(answer.reasoning) ? answer.reasoning : "something else";
960
- return {
961
- reasoning: "quantitative",
962
- value: 0,
963
- groups: [],
964
- count: 0,
965
- success: false,
966
- trace: [],
967
- errors: [...(0, _orkestrel_contract.isArray)(answer.errors) ? answer.errors.filter(_orkestrel_contract.isString) : [], `Expected quantitative result, got ${named}`],
968
- faults: [],
969
- repairs: [],
970
- defaulted: []
971
- };
972
- }
973
- #settle(result) {
974
- if (!result.success) return result;
975
- if (result.errors.length === 0 && result.faults.length === 0 && (0, _orkestrel_contract.isFiniteNumber)(result.value)) return result;
976
- const said = result.errors.length > 0 ? [] : ["The line succeeded beside a fault or no value"];
977
- return {
978
- ...result,
979
- success: false,
980
- errors: [...result.errors, ...said]
981
- };
1119
+ return settleResult(this.#reason(subject, definition), definition);
982
1120
  }
983
1121
  #reason(subject, definition) {
984
1122
  try {
@@ -997,7 +1135,7 @@ var Rater = class {
997
1135
  * Creates a rating orchestrator over the shared quantitative engine, seeded
998
1136
  * from {@link RaterOptions} and returning a {@link RaterInterface}.
999
1137
  *
1000
- * @param options - Optional total handler, labels, injected engine, and emitter hooks
1138
+ * @param options - Optional total handler, injected engine, and emitter hooks
1001
1139
  * @returns A {@link RaterInterface}
1002
1140
  *
1003
1141
  * @example Create a rater
@@ -1014,19 +1152,20 @@ function createRater(options) {
1014
1152
  exports.Rater = Rater;
1015
1153
  exports.RaterError = RaterError;
1016
1154
  exports.WORKSHEET_STAGES = WORKSHEET_STAGES;
1017
- exports.buildEvidence = buildEvidence;
1018
- exports.buildEvidenceRows = buildEvidenceRows;
1019
1155
  exports.buildLineDefinition = buildLineDefinition;
1020
1156
  exports.buildLineResult = buildLineResult;
1157
+ exports.buildMalformedResult = buildMalformedResult;
1021
1158
  exports.buildRatingDefinition = buildRatingDefinition;
1022
1159
  exports.buildWorksheet = buildWorksheet;
1023
1160
  exports.buildWorksheetFactor = buildWorksheetFactor;
1024
1161
  exports.buildWorksheetGroup = buildWorksheetGroup;
1025
1162
  exports.buildWorksheetStep = buildWorksheetStep;
1026
1163
  exports.buildWorksheetSteps = buildWorksheetSteps;
1164
+ exports.copyResult = copyResult;
1027
1165
  exports.createRater = createRater;
1028
- exports.evidenceShape = evidenceShape;
1029
- exports.isEvidence = isEvidence;
1166
+ exports.findRepeatedLines = findRepeatedLines;
1167
+ exports.findRepeatedParts = findRepeatedParts;
1168
+ exports.findUnansweredParts = findUnansweredParts;
1030
1169
  exports.isLineDefinition = isLineDefinition;
1031
1170
  exports.isLineResult = isLineResult;
1032
1171
  exports.isRaterError = isRaterError;
@@ -1044,6 +1183,7 @@ exports.ratingDefinitionContract = ratingDefinitionContract;
1044
1183
  exports.ratingDefinitionShape = ratingDefinitionShape;
1045
1184
  exports.ratingResultContract = ratingResultContract;
1046
1185
  exports.ratingResultShape = ratingResultShape;
1186
+ exports.settleResult = settleResult;
1047
1187
  exports.sumAmounts = sumAmounts;
1048
1188
  exports.worksheetFactorShape = worksheetFactorShape;
1049
1189
  exports.worksheetGroupShape = worksheetGroupShape;