@orkestrel/qualifier 0.0.19 → 0.0.21

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,5 +1,5 @@
1
- import { INTRINSICS, arrayOf, holds, isArray, isBoolean, isError, isFiniteNumber, isFunction, isNumber, isObject, isRecord, isString, literalOf, objectOf, recordOf, resolveField, whereOf } from "@orkestrel/contract";
2
- import { createEvaluator, createLogicalReasoner, createQuantitativeReasoner, createReason, extractAtoms, extractConclusions, findDuplicates, formatField, isBounds, isComparison, isFieldPath, isLogicalDefinition, isQuantitativeDefinition, isReasonError } from "@orkestrel/reason";
1
+ import { INTRINSICS, arrayOf, arrayShape, auditFaultShape, booleanShape, createContract, describeFaults, holds, isArray, isAuditFault, isBoolean, isError, isFiniteNumber, isFunction, isJSONValue, isNumber, isObject, isRecord, isString, jsonShape, literalOf, literalShape, nullableShape, numberShape, objectOf, objectShape, optionalShape, recordOf, recordShape, resolveField, shapeShape, stringShape, unionShape, whereOf } from "@orkestrel/contract";
2
+ import { CHECK_STATES, COMPARISONS, collectConcluders, createLogicalDefinitionShape, createLogicalReasoner, createQuantitativeReasoner, createReason, createSubjectDoor, extractAtoms, extractConclusions, fieldPathShape, filterUniqueFaults, findDuplicates, findFieldShape, formatField, isBounds, isCheckState, isComparison, isContractShape, isFieldPath, isLogicalDefinition, isQuantitativeDefinition, isReasonError, isReasonResult, projectValue, quantitativeDefinitionShape, scanShape, scanShapeReads } from "@orkestrel/reason";
3
3
  import { Emitter } from "@orkestrel/emitter";
4
4
  // src/core/constants.ts
5
5
  /**
@@ -12,6 +12,20 @@ var DEFAULT_QUALIFIER_VALIDATE = true;
12
12
  * projection is written under.
13
13
  */
14
14
  var QUALIFICATION_KEY = "qualification";
15
+ /** Matches each `{{dotted.path}}` token of a message template, with the path as its one group. */
16
+ var MESSAGE_TOKEN = /\{\{\s*([^}]+?)\s*\}\}/g;
17
+ /** Lists the eligibility outcomes. */
18
+ var ELIGIBILITIES = [
19
+ "eligible",
20
+ "ineligible",
21
+ "referral"
22
+ ];
23
+ /** Lists the effects a ruling can carry. */
24
+ var QUALIFICATION_EFFECTS = [
25
+ "restriction",
26
+ "referral",
27
+ "condition"
28
+ ];
15
29
  /** Lists the eligibility severities most to least severe: `ineligible`, `referral`, `eligible`. */
16
30
  var ELIGIBILITY_PRECEDENCE = Object.freeze([
17
31
  "ineligible",
@@ -86,7 +100,7 @@ function isQualifierError(value) {
86
100
  * @param value - The value to test
87
101
  * @returns True if `value` is one of the eligibility literals; false otherwise
88
102
  */
89
- var isEligibility = literalOf("eligible", "ineligible", "referral");
103
+ var isEligibility = literalOf(...ELIGIBILITIES);
90
104
  /**
91
105
  * Determines whether a value is a {@link QualificationEffect} literal.
92
106
  *
@@ -97,7 +111,7 @@ var isEligibility = literalOf("eligible", "ineligible", "referral");
97
111
  * @param value - The value to test
98
112
  * @returns True if `value` is one of the effect literals; false otherwise
99
113
  */
100
- var isQualificationEffect = literalOf("restriction", "referral", "condition");
114
+ var isQualificationEffect = literalOf(...QUALIFICATION_EFFECTS);
101
115
  /**
102
116
  * Determines whether a value is an open string-keyed record of {@link Eligibility} values.
103
117
  *
@@ -132,13 +146,13 @@ function isPremise(value) {
132
146
  label: isString,
133
147
  description: isString,
134
148
  comparison: isComparison,
135
- met: isBoolean
149
+ state: isCheckState
136
150
  }, [
137
151
  "field",
138
152
  "label",
139
153
  "description",
140
154
  "comparison",
141
- "met"
155
+ "state"
142
156
  ])(value);
143
157
  }
144
158
  /**
@@ -160,7 +174,7 @@ function isFinding(value) {
160
174
  rule: isString,
161
175
  effect: isQualificationEffect,
162
176
  scope: isString,
163
- applied: isBoolean,
177
+ state: isCheckState,
164
178
  message: isString,
165
179
  premises: arrayOf(isPremise)
166
180
  }, ["scope", "message"])(value);
@@ -209,7 +223,10 @@ function isQualificationResult(value) {
209
223
  derivations: arrayOf(isDerivation),
210
224
  success: isBoolean,
211
225
  trace: arrayOf(isString),
212
- errors: arrayOf(isString)
226
+ errors: arrayOf(isString),
227
+ faults: arrayOf(isAuditFault),
228
+ repairs: arrayOf(isAuditFault),
229
+ defaulted: arrayOf(isFieldPath)
213
230
  })(value);
214
231
  }
215
232
  /**
@@ -247,6 +264,21 @@ function isRuling(value) {
247
264
  }, ["scope", "message"])(value);
248
265
  }
249
266
  /**
267
+ * Determines whether a value is a definition's `metadata`: a record of JSON values.
268
+ *
269
+ * @param value - The value to test
270
+ * @returns True for a record whose every value is JSON; false otherwise
271
+ *
272
+ * @example
273
+ * ```ts
274
+ * import { isDefinitionMetadata } from '@orkestrel/qualifier'
275
+ *
276
+ * isDefinitionMetadata({ a: 1 }) // true
277
+ * isDefinitionMetadata({ a: Number.NaN }) // false
278
+ * ```
279
+ */
280
+ var isDefinitionMetadata = whereOf(isRecord, (record) => Object.values(record).every(isJSONValue));
281
+ /**
250
282
  * Determines whether a value is an exact {@link QualificationDefinition} record.
251
283
  *
252
284
  * @remarks
@@ -264,11 +296,13 @@ function isQualificationDefinition(value) {
264
296
  description: isString,
265
297
  passes: arrayOf(isQualificationPass),
266
298
  rulings: arrayOf(isRuling),
267
- metadata: isRecord
299
+ metadata: isDefinitionMetadata,
300
+ shape: isContractShape
268
301
  }, [
269
302
  "description",
270
303
  "rulings",
271
- "metadata"
304
+ "metadata",
305
+ "shape"
272
306
  ])(value);
273
307
  }
274
308
  // src/core/helpers.ts
@@ -295,7 +329,7 @@ function isQualificationDefinition(value) {
295
329
  * ```
296
330
  */
297
331
  function interpolateMessage(template, subject) {
298
- return template.replace(/\{\{\s*([^}]+?)\s*\}\}/g, (_match, path) => {
332
+ return template.replace(MESSAGE_TOKEN, (_match, path) => {
299
333
  const value = resolveField(subject, path.split("."));
300
334
  if (value === void 0) return "";
301
335
  if (isFiniteNumber(value)) return value.toLocaleString("en-US");
@@ -303,6 +337,22 @@ function interpolateMessage(template, subject) {
303
337
  });
304
338
  }
305
339
  /**
340
+ * Finds the `{{dotted.path}}` tokens a message template reads.
341
+ *
342
+ * @param template - The message template
343
+ * @returns Each token's dotted path, trimmed, in order, repeats included
344
+ *
345
+ * @example
346
+ * ```ts
347
+ * import { findMessageTokens } from '@orkestrel/qualifier'
348
+ *
349
+ * findMessageTokens('Age {{ age }} in {{home.city}}') // ['age', 'home.city']
350
+ * ```
351
+ */
352
+ function findMessageTokens(template) {
353
+ return [...template.matchAll(MESSAGE_TOKEN)].map((match) => match[1] ?? "");
354
+ }
355
+ /**
306
356
  * Renders a {@link Premise} comparison as a display-neutral verb phrase.
307
357
  *
308
358
  * @param comparison - The comparison to describe
@@ -378,15 +428,15 @@ function renderValue(value) {
378
428
  * ```ts
379
429
  * import { renderPremise } from '@orkestrel/qualifier'
380
430
  *
381
- * renderPremise({ field: 'age', comparison: 'above', expected: 18, actual: 25, met: true })
431
+ * renderPremise({ field: 'age', comparison: 'above', expected: 18, actual: 25, state: 'met' })
382
432
  * // 'age is more than 18 → met'
383
433
  *
384
- * renderPremise({ description: 'Applicant is enrolled', met: true })
434
+ * renderPremise({ description: 'Applicant is enrolled', state: 'met' })
385
435
  * // 'Applicant is enrolled → met'
386
436
  * ```
387
437
  */
388
438
  function renderPremise(entry, labels) {
389
- const status = entry.met === void 0 ? "unknown" : entry.met ? "met" : "not met";
439
+ const status = entry.state === "met" ? "met" : entry.state === "unmet" ? "not met" : "unknown";
390
440
  if (entry.field === void 0 || entry.comparison === void 0) return `${entry.description ?? "Premise"} → ${status}`;
391
441
  const field = formatField(entry.field);
392
442
  const label = labels?.[field] ?? entry.label ?? field;
@@ -398,7 +448,7 @@ function renderPremise(entry, labels) {
398
448
  * `CheckResult`.
399
449
  *
400
450
  * @param check - The authored check
401
- * @param result - The evaluated check result carrying the resolved `actual` and `met`
451
+ * @param result - The evaluated check result carrying the resolved `actual` and `state`
402
452
  * @param labels - Optional field-to-label overrides, keyed by dot-joined field
403
453
  * @returns A fresh premise
404
454
  *
@@ -408,8 +458,8 @@ function renderPremise(entry, labels) {
408
458
  * import { createCheck } from '@orkestrel/reason'
409
459
  *
410
460
  * const authored = createCheck('age', 'above', 18)
411
- * checkToPremise(authored, { field: 'age', actual: 25, met: true })
412
- * // { field: 'age', comparison: 'above', expected: 18, actual: 25, met: true }
461
+ * checkToPremise(authored, { field: 'age', actual: 25, state: 'met' })
462
+ * // { field: 'age', comparison: 'above', expected: 18, actual: 25, state: 'met' }
413
463
  * ```
414
464
  */
415
465
  function checkToPremise(check, result, labels) {
@@ -420,48 +470,49 @@ function checkToPremise(check, result, labels) {
420
470
  comparison: check.operator,
421
471
  expected: check.value,
422
472
  actual: result.actual,
423
- met: result.met
473
+ state: result.state
424
474
  };
425
475
  }
426
476
  /**
427
477
  * Builds rich premises for one fired {@link Rule} by walking its premise atoms
428
- * and re-evaluating each against the working subject.
478
+ * and reading each from what the rule read.
429
479
  *
430
480
  * @remarks
431
- * A reason rule result carries only booleans, so this is the qualifier's own
432
- * premise-audit projection: each authored premise expression is flattened to its
433
- * atom leaves through `extractAtoms`, and each leaf's `Check` is re-evaluated through
434
- * the injected `evaluator`. A membership check (`any` / `none`) over an empty
435
- * array value is content-free and is skipped.
481
+ * Each authored premise expression is flattened to its atom leaves through `extractAtoms`,
482
+ * which lines up with the `checks` the rule result carries, so a premise cannot disagree with
483
+ * the pass. A rule with no result never ran, so its premises carry no `state` or `actual`.
436
484
  *
437
485
  * @param rule - The authored rule
438
- * @param working - The working subject to evaluate against
439
- * @param evaluator - The shared reason check evaluator
486
+ * @param resolved - The rule's result, absent when it never ran
440
487
  * @param labels - Optional field-to-label overrides, keyed by dot-joined field
441
488
  * @returns A fresh, ordered list of rich premises
442
489
  *
443
490
  * @example
444
491
  * ```ts
445
492
  * import { ruleToPremises } from '@orkestrel/qualifier'
446
- * import { createAtom, createEvaluator, createLogicalDefinition, createRule } from '@orkestrel/reason'
447
- *
448
- * const gates = createLogicalDefinition('gates', 'Gates', [
449
- * createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true)),
450
- * ])
451
- * const evaluator = createEvaluator()
452
- * const premises = ruleToPremises(gates.rules[0], { licensed: false }, evaluator)
453
- *
454
- * premises[0]?.met // true
493
+ * import { createAtom, createRule } from '@orkestrel/reason'
494
+ *
495
+ * const rule = createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true))
496
+ * const resolved = {
497
+ * id: 'licensed',
498
+ * state: 'met' as const,
499
+ * premises: ['met' as const],
500
+ * checks: [{ field: 'licensed', state: 'met' as const, actual: false }],
501
+ * }
502
+ * ruleToPremises(rule, resolved)[0]?.state // 'met'
455
503
  * ```
456
504
  */
457
- function ruleToPremises(rule, working, evaluator, labels) {
458
- const output = [];
459
- for (const premise of rule.premises) for (const atom of extractAtoms(premise)) {
460
- const { check } = atom;
461
- if ((check.operator === "any" || check.operator === "none") && isArray(check.value) && check.value.length === 0) continue;
462
- output.push(checkToPremise(check, evaluator.evaluate(check, working), labels));
463
- }
464
- return output;
505
+ function ruleToPremises(rule, resolved, labels) {
506
+ return rule.premises.flatMap((premise) => extractAtoms(premise)).map((atom, index) => {
507
+ const read = resolved?.checks[index];
508
+ if (read !== void 0) return checkToPremise(atom.check, read, labels);
509
+ const { state: _state, actual: _actual, ...unrun } = checkToPremise(atom.check, {
510
+ field: atom.check.field,
511
+ state: "unread",
512
+ actual: void 0
513
+ }, labels);
514
+ return unrun;
515
+ });
465
516
  }
466
517
  /**
467
518
  * Locates an authored {@link Rule} by id.
@@ -521,15 +572,218 @@ function findRule(definition, id) {
521
572
  function reasonResultToProjection(definition, result) {
522
573
  if (definition.reasoning === "quantitative" && result.reasoning === "quantitative") return result.value;
523
574
  if (definition.reasoning !== "logical" || result.reasoning !== "logical") return false;
524
- const projection = { conclusion: result.conclusion };
525
- for (const resolved of result.rules) {
526
- if (!resolved.applied) continue;
575
+ const fields = ["unmet", "met"].flatMap((state) => result.rules.filter((resolved) => resolved.state === state).flatMap((resolved) => {
527
576
  const authored = definition.rules.find((rule) => rule.id === resolved.id);
528
- if (authored === void 0) continue;
529
- const conclusions = extractConclusions(authored.conclusion);
530
- for (const [key, value] of Object.entries(conclusions)) projection[key] = value;
531
- }
532
- return projection;
577
+ if (authored === void 0) return [];
578
+ return Object.entries(extractConclusions(authored.conclusion)).map(([key, value]) => [key, state === "met" ? value : false]);
579
+ }));
580
+ return Object.fromEntries([...fields, ["conclusion", result.conclusion === "met"]]);
581
+ }
582
+ /**
583
+ * Replaces a read of an unread pass's projection with what that pass could not read.
584
+ *
585
+ * @remarks
586
+ * A pass reading `qualification.gates.blocked` is unread because `gates` projected nothing, so
587
+ * the question to ask is the one `gates` could not answer. A read of a pass that settled stays,
588
+ * because that pass holds no such key. Passes run in order and each stores its expanded faults,
589
+ * so a chain of unread passes reaches the input that started it.
590
+ *
591
+ * @param faults - The faults every pass reported, in order
592
+ * @param unread - The faults of each unread pass, by pass id
593
+ * @returns The input faults, once per field
594
+ *
595
+ * @example
596
+ * ```ts
597
+ * import { expandPassFaults } from '@orkestrel/qualifier'
598
+ *
599
+ * const leaf = { reason: 'missing', path: 'age', expected: 'number' } as const
600
+ * const read = { reason: 'missing', path: ['qualification', 'gates', 'ok'], expected: 'boolean' } as const
601
+ * expandPassFaults([read], new Map([['gates', [leaf]]])) // [leaf]
602
+ * ```
603
+ */
604
+ function expandPassFaults(faults, unread) {
605
+ return filterUniqueFaults(faults.flatMap((fault) => {
606
+ const { path } = fault;
607
+ if (!isArray(path) || path[0] !== "qualification") return [fault];
608
+ return unread.get(path[1] ?? "") ?? [fault];
609
+ }));
610
+ }
611
+ /**
612
+ * Describes what the definition's shape cannot stand for: a read of a field it does not declare,
613
+ * and the reserved `qualification` key, which a default could otherwise fill.
614
+ *
615
+ * @remarks
616
+ * A read under `qualification` reads a pass's projection, and a pass's own conclusion keys are
617
+ * its own, so neither needs a declaration. A host that projects a key of its own names it in
618
+ * `projections`. A `raw` or `json` read is a warning.
619
+ *
620
+ * @param definition - The definition
621
+ * @param projections - Further keys the host projects onto the subject. Default: none
622
+ * @returns The errors and warnings, empty with no shape
623
+ *
624
+ * @example
625
+ * ```ts
626
+ * import { numberShape, objectShape } from '@orkestrel/contract'
627
+ * import { createQualificationDefinition, scanDefinitionShape } from '@orkestrel/qualifier'
628
+ * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'
629
+ *
630
+ * const pass = createLogicalDefinition('gates', 'Gates', [
631
+ * createRule('r', [createAtom('agee', 'above', 1)], createAtom('ok', 'equals', true)),
632
+ * ])
633
+ * const shape = objectShape({ age: numberShape() })
634
+ * scanDefinitionShape(createQualificationDefinition('d', 'd', [pass], { shape })).errors.length // 1
635
+ * ```
636
+ */
637
+ function scanDefinitionShape(definition, projections = []) {
638
+ const { shape } = definition;
639
+ if (shape === void 0) return {
640
+ errors: [],
641
+ warnings: []
642
+ };
643
+ const scans = definition.passes.map((pass) => {
644
+ if (pass.reasoning === "logical") {
645
+ const enabled = pass.rules.filter((rule) => rule.enabled !== false);
646
+ const checks = enabled.flatMap((rule) => rule.premises.flatMap((premise) => extractAtoms(premise))).map((atom) => atom.check).filter((check) => !readsProjection(check.field, projections));
647
+ return scanShapeReads(shape, checks, [], new Set(collectConcluders(enabled).keys()));
648
+ }
649
+ const factors = pass.groups.flatMap((group) => group.factors);
650
+ return scanShapeReads(shape, factors.flatMap((factor) => factor.checks ?? []).filter((check) => !readsProjection(check.field, projections)), factors.flatMap((factor) => factor.source.origin === "static" ? [] : [factor.source.field]).filter((field) => !readsProjection(field, projections)), /* @__PURE__ */ new Set());
651
+ });
652
+ return {
653
+ errors: [...findFieldShape(shape, "qualification").shape === void 0 ? [] : [`Shape declares the reserved key '${QUALIFICATION_KEY}'`], ...new Set(scans.flatMap((scan) => scan.errors))],
654
+ warnings: [...new Set(scans.flatMap((scan) => scan.warnings))]
655
+ };
656
+ }
657
+ /**
658
+ * Determines whether a field reads a pass's projection under `qualification`, or a key the host projects.
659
+ *
660
+ * @param field - The field
661
+ * @param projections - Further keys the host projects onto the subject. Default: none
662
+ * @returns True for an array path starting at the reserved key or a projected key; false otherwise
663
+ *
664
+ * @example
665
+ * ```ts
666
+ * import { readsProjection } from '@orkestrel/qualifier'
667
+ *
668
+ * readsProjection(['qualification', 'gates', 'ok']) // true
669
+ * readsProjection(['aggregate', 'count'], ['aggregate']) // true
670
+ * readsProjection('age') // false
671
+ * ```
672
+ */
673
+ function readsProjection(field, projections = []) {
674
+ if (!isArray(field)) return false;
675
+ const key = field[0];
676
+ return key === "qualification" || key !== void 0 && projections.includes(key);
677
+ }
678
+ /**
679
+ * Describes each rule concluding `conclusion`, which a pass's projection reserves for itself.
680
+ *
681
+ * @param definition - The definition
682
+ * @returns One message per such rule
683
+ *
684
+ * @example
685
+ * ```ts
686
+ * import { createQualificationDefinition, describeReservedConclusions } from '@orkestrel/qualifier'
687
+ * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'
688
+ *
689
+ * const pass = createLogicalDefinition('gates', 'Gates', [
690
+ * createRule('r', [createAtom('a', 'equals', 1)], createAtom('conclusion', 'equals', true)),
691
+ * ])
692
+ * describeReservedConclusions(createQualificationDefinition('d', 'd', [pass])).length // 1
693
+ * ```
694
+ */
695
+ function describeReservedConclusions(definition) {
696
+ return definition.passes.flatMap((pass) => pass.reasoning !== "logical" ? [] : pass.rules.filter((rule) => Object.hasOwn(extractConclusions(rule.conclusion), "conclusion")).map((rule) => `Rule '${rule.id}' in pass '${pass.id}' concludes the reserved key 'conclusion'`));
697
+ }
698
+ /**
699
+ * Determines whether a logical result holds a rule left unread.
700
+ *
701
+ * @param result - The result of a pass
702
+ * @returns True when a logical result holds such a rule; false otherwise
703
+ *
704
+ * @example
705
+ * ```ts
706
+ * import { hasUnreadRule } from '@orkestrel/qualifier'
707
+ *
708
+ * const rule = { id: 'r', state: 'unread' as const, premises: [], checks: [] }
709
+ * hasUnreadRule({
710
+ * reasoning: 'logical',
711
+ * conclusion: 'unread',
712
+ * rules: [rule],
713
+ * count: 0,
714
+ * success: false,
715
+ * trace: [],
716
+ * errors: [],
717
+ * faults: [],
718
+ * repairs: [],
719
+ * defaulted: [],
720
+ * }) // true
721
+ * ```
722
+ */
723
+ function hasUnreadRule(result) {
724
+ return result.reasoning === "logical" && result.rules.some((rule) => rule.state === "unread");
725
+ }
726
+ /**
727
+ * Describes each message token no field of the definition's shape answers.
728
+ *
729
+ * @remarks
730
+ * A token under `qualification` reads a pass's projection, which no shape declares.
731
+ *
732
+ * @param definition - The definition
733
+ * @returns One message per unknown token, empty with no shape
734
+ *
735
+ * @example
736
+ * ```ts
737
+ * import { numberShape, objectShape } from '@orkestrel/contract'
738
+ * import { createQualificationDefinition, createRuling, describeUnknownTokens } from '@orkestrel/qualifier'
739
+ *
740
+ * const ruling = createRuling('r', 'gates', 'licensed', 'referral', { message: 'Age {{agee}}' })
741
+ * const shape = objectShape({ age: numberShape() })
742
+ * describeUnknownTokens(createQualificationDefinition('d', 'd', [], { rulings: [ruling], shape }))
743
+ * // ['Ruling \'r\' message reads "agee", and the shape does not declare it']
744
+ * ```
745
+ */
746
+ function describeUnknownTokens(definition) {
747
+ const { shape } = definition;
748
+ if (shape === void 0) return [];
749
+ return (definition.rulings ?? []).flatMap((ruling) => findMessageTokens(ruling.message ?? "").flatMap((token) => {
750
+ const path = token.split(".");
751
+ if (path[0] === "qualification" || findFieldShape(shape, path).declared) return [];
752
+ return [`Ruling '${ruling.id}' message reads "${token}", and the shape does not declare it`];
753
+ }));
754
+ }
755
+ /**
756
+ * Projects a result to the JSON its contract reads.
757
+ *
758
+ * @remarks
759
+ * A premise's `actual` holds whatever the subject held and a derivation's `value` may be `NaN`,
760
+ * so a result crosses a boundary as this projection, each `actual` on its own budget.
761
+ *
762
+ * @param result - The qualification result
763
+ * @returns Its JSON projection, which `qualificationResultContract` admits
764
+ *
765
+ * @example
766
+ * ```ts
767
+ * import { createQualificationDefinition, createQualifier, projectQualificationResult, qualificationResultContract } from '@orkestrel/qualifier'
768
+ *
769
+ * const qualifier = createQualifier()
770
+ * const result = qualifier.qualify({}, createQualificationDefinition('d', 'd', []))
771
+ * qualificationResultContract.is(projectQualificationResult(result)) // true
772
+ * qualifier.destroy()
773
+ * ```
774
+ */
775
+ function projectQualificationResult(result) {
776
+ const findings = result.findings.map((finding) => ({
777
+ ...finding,
778
+ premises: finding.premises.map((premise) => ({
779
+ ...premise,
780
+ actual: projectValue(premise.actual)
781
+ }))
782
+ }));
783
+ return projectValue({
784
+ ...result,
785
+ findings
786
+ }, /* @__PURE__ */ new Set(), { left: Number.POSITIVE_INFINITY });
533
787
  }
534
788
  /**
535
789
  * Projects a quantitative result into a {@link Derivation} audit record.
@@ -595,58 +849,65 @@ function mergeQualificationContext(context, id, projection) {
595
849
  };
596
850
  }
597
851
  /**
598
- * Joins a ruling, its logical rule result, the pass, the pre-projection subject,
599
- * and an evaluator into a {@link Finding}.
852
+ * Joins a ruling, its logical rule result, the pass, and the pre-projection subject into a
853
+ * {@link Finding}.
600
854
  *
601
855
  * @remarks
602
- * `applied` reflects whether the ruling's rule fired. Premises are re-evaluated
603
- * against the same subject snapshot the pass evaluated, so a conclusion the pass
604
- * derived can never satisfy its own reported premise. The message interpolates
605
- * against that snapshot.
856
+ * `state` is the state of the ruling's rule. A rule the result omits reads `unmet` when it is
857
+ * disabled, which is authored, and `unread` otherwise, because a refused pass evaluated no rule.
858
+ * Premises come from what the rule read. The message interpolates against the subject.
606
859
  *
607
860
  * @param ruling - The authored ruling
608
861
  * @param pass - The pass the ruling's rule lives in
609
862
  * @param result - The pass's evaluated logical result
610
863
  * @param subject - The pre-projection subject snapshot the pass evaluated
611
- * @param evaluator - The shared reason check evaluator
612
864
  * @param labels - Optional field-to-label overrides, keyed by dot-joined field
613
865
  * @returns A fresh finding
614
866
  *
615
867
  * @example
616
868
  * ```ts
617
869
  * import { rulingToFinding } from '@orkestrel/qualifier'
618
- * import { createAtom, createEvaluator, createLogicalDefinition, createRule } from '@orkestrel/reason'
870
+ * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'
619
871
  *
620
872
  * const gates = createLogicalDefinition('gates', 'Gates', [
621
873
  * createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true)),
622
874
  * ])
623
875
  * const ruling = { id: 'license', pass: 'gates', rule: 'licensed', effect: 'restriction' as const }
624
- * const result = { reasoning: 'logical' as const, conclusion: true, rules: [{ id: 'licensed', applied: true, premises: [true] }], count: 1, success: true, trace: [], errors: [] }
625
- * const finding = rulingToFinding(ruling, gates, result, { licensed: false }, createEvaluator())
626
- *
627
- * finding.applied // true
876
+ * const result = {
877
+ * reasoning: 'logical' as const,
878
+ * conclusion: 'met' as const,
879
+ * rules: [{ id: 'licensed', state: 'met' as const, premises: ['met' as const], checks: [] }],
880
+ * count: 1,
881
+ * success: true,
882
+ * trace: [],
883
+ * errors: [],
884
+ * faults: [],
885
+ * repairs: [],
886
+ * defaulted: [],
887
+ * }
888
+ * rulingToFinding(ruling, gates, result, { licensed: false }).state // 'met'
628
889
  * ```
629
890
  */
630
- function rulingToFinding(ruling, pass, result, subject, evaluator, labels) {
631
- const applied = result.rules.find((resolved) => resolved.id === ruling.rule)?.applied ?? false;
891
+ function rulingToFinding(ruling, pass, result, subject, labels) {
892
+ const entry = result.rules.find((resolved) => resolved.id === ruling.rule);
632
893
  const rule = pass.reasoning === "logical" ? findRule(pass, ruling.rule) : void 0;
633
- const premises = rule === void 0 ? [] : ruleToPremises(rule, subject, evaluator, labels);
894
+ const premises = rule === void 0 ? [] : ruleToPremises(rule, entry, labels);
634
895
  return {
635
896
  id: ruling.id,
636
897
  pass: ruling.pass,
637
898
  rule: ruling.rule,
638
899
  effect: ruling.effect,
639
900
  ...ruling.scope === void 0 ? {} : { scope: ruling.scope },
640
- applied,
901
+ state: entry?.state ?? (rule?.enabled === false ? "unmet" : "unread"),
641
902
  ...ruling.message === void 0 ? {} : { message: interpolateMessage(ruling.message, subject) },
642
903
  premises
643
904
  };
644
905
  }
645
906
  /**
646
- * Derives global eligibility from applied, unscoped findings.
907
+ * Derives global eligibility from unscoped findings whose rule is met.
647
908
  *
648
909
  * @remarks
649
- * Only findings that both applied and carry no `scope` shape global eligibility.
910
+ * Only findings that are `met` and carry no `scope` shape global eligibility.
650
911
  * A failed pass contributes a synthetic `referral` (fail-closed), passed through
651
912
  * `failed`.
652
913
  *
@@ -659,12 +920,12 @@ function rulingToFinding(ruling, pass, result, subject, evaluator, labels) {
659
920
  * ```ts
660
921
  * import { deriveFindingEligibility } from '@orkestrel/qualifier'
661
922
  *
662
- * const finding = { id: 'license', pass: 'gates', rule: 'licensed', effect: 'restriction' as const, applied: true, premises: [] }
923
+ * const finding = { id: 'license', pass: 'gates', rule: 'licensed', effect: 'restriction' as const, state: 'met' as const, premises: [] }
663
924
  * deriveFindingEligibility([finding]) // 'ineligible'
664
925
  * ```
665
926
  */
666
927
  function deriveFindingEligibility(findings, failed = false) {
667
- const eligibilities = findings.filter((finding) => finding.applied && finding.scope === void 0).map((finding) => EFFECT_ELIGIBILITIES[finding.effect]);
928
+ const eligibilities = findings.filter((finding) => finding.state === "met" && finding.scope === void 0).map((finding) => EFFECT_ELIGIBILITIES[finding.effect]);
668
929
  if (failed) eligibilities.push("referral");
669
930
  return combineEligibilities(eligibilities);
670
931
  }
@@ -689,7 +950,7 @@ function combineEligibilities(eligibilities) {
689
950
  * Derives one eligibility per finding scope.
690
951
  *
691
952
  * @remarks
692
- * Only applied, scoped findings contribute. Each named scope combines its own
953
+ * Only scoped findings that are `met` contribute. Each named scope combines its own
693
954
  * findings' impacts by severity. An unmentioned scope is absent (eligible by
694
955
  * default at the program layer).
695
956
  *
@@ -700,20 +961,18 @@ function combineEligibilities(eligibilities) {
700
961
  * ```ts
701
962
  * import { deriveScopeEligibilities } from '@orkestrel/qualifier'
702
963
  *
703
- * const finding = { id: 'coastal', pass: 'wind', rule: 'coastal', effect: 'restriction' as const, scope: 'wind', applied: true, premises: [] }
964
+ * const finding = { id: 'coastal', pass: 'wind', rule: 'coastal', effect: 'restriction' as const, scope: 'wind', state: 'met' as const, premises: [] }
704
965
  * deriveScopeEligibilities([finding]) // { wind: 'ineligible' }
705
966
  * ```
706
967
  */
707
968
  function deriveScopeEligibilities(findings) {
708
- const grouped = {};
969
+ const grouped = /* @__PURE__ */ new Map();
709
970
  for (const finding of findings) {
710
- if (!finding.applied || finding.scope === void 0) continue;
711
- const current = grouped[finding.scope] ?? [];
712
- grouped[finding.scope] = [...current, EFFECT_ELIGIBILITIES[finding.effect]];
971
+ if (finding.state !== "met" || finding.scope === void 0) continue;
972
+ const current = grouped.get(finding.scope) ?? [];
973
+ grouped.set(finding.scope, [...current, EFFECT_ELIGIBILITIES[finding.effect]]);
713
974
  }
714
- const scopes = {};
715
- for (const [scope, eligibilities] of Object.entries(grouped)) scopes[scope] = combineEligibilities(eligibilities);
716
- return scopes;
975
+ return Object.fromEntries([...grouped].map(([scope, eligibilities]) => [scope, combineEligibilities(eligibilities)]));
717
976
  }
718
977
  /**
719
978
  * Describes each ruling whose pass or rule does not exist or whose pass is not
@@ -907,6 +1166,90 @@ function describeUnreadDerivations(definition) {
907
1166
  });
908
1167
  return warnings;
909
1168
  }
1169
+ // src/core/shapers.ts
1170
+ /** Describes a `Ruling`. */
1171
+ var rulingShape = objectShape({
1172
+ id: stringShape(),
1173
+ pass: stringShape(),
1174
+ rule: stringShape(),
1175
+ effect: literalShape(QUALIFICATION_EFFECTS),
1176
+ scope: optionalShape(stringShape()),
1177
+ message: optionalShape(stringShape())
1178
+ });
1179
+ /**
1180
+ * Creates the shape of a `QualificationDefinition`.
1181
+ *
1182
+ * @remarks
1183
+ * `shape` is checked as a recursive contract shape.
1184
+ *
1185
+ * @returns A shape holding quantitative and logical passes and rulings
1186
+ *
1187
+ * @example
1188
+ * ```ts
1189
+ * import { createContract } from '@orkestrel/contract'
1190
+ * import { createQualificationDefinition, createQualificationDefinitionShape } from '@orkestrel/qualifier'
1191
+ *
1192
+ * createContract(createQualificationDefinitionShape()).is(createQualificationDefinition('d', 'd', [])) // true
1193
+ * ```
1194
+ */
1195
+ function createQualificationDefinitionShape() {
1196
+ return objectShape({
1197
+ id: stringShape(),
1198
+ name: stringShape(),
1199
+ description: optionalShape(stringShape()),
1200
+ passes: arrayShape(unionShape(quantitativeDefinitionShape, createLogicalDefinitionShape())),
1201
+ rulings: optionalShape(arrayShape(rulingShape)),
1202
+ metadata: optionalShape(recordShape(jsonShape())),
1203
+ shape: optionalShape(shapeShape())
1204
+ });
1205
+ }
1206
+ /** Describes a `Premise` in its JSON projection. */
1207
+ var premiseShape = objectShape({
1208
+ field: optionalShape(fieldPathShape),
1209
+ label: optionalShape(stringShape()),
1210
+ description: optionalShape(stringShape()),
1211
+ comparison: optionalShape(literalShape(COMPARISONS)),
1212
+ expected: optionalShape(jsonShape()),
1213
+ actual: optionalShape(jsonShape()),
1214
+ state: optionalShape(literalShape(CHECK_STATES))
1215
+ });
1216
+ /** Describes a `Finding` in its JSON projection. */
1217
+ var findingShape = objectShape({
1218
+ id: stringShape(),
1219
+ pass: stringShape(),
1220
+ rule: stringShape(),
1221
+ effect: literalShape(QUALIFICATION_EFFECTS),
1222
+ scope: optionalShape(stringShape()),
1223
+ state: literalShape(CHECK_STATES),
1224
+ message: optionalShape(stringShape()),
1225
+ premises: arrayShape(premiseShape)
1226
+ });
1227
+ /** Describes a `Derivation` in its JSON projection, where a non-finite number is `null`. */
1228
+ var derivationShape = objectShape({
1229
+ id: stringShape(),
1230
+ value: nullableShape(numberShape()),
1231
+ success: booleanShape(),
1232
+ trace: arrayShape(stringShape()),
1233
+ errors: arrayShape(stringShape())
1234
+ });
1235
+ /** Describes a `QualificationResult` in its JSON projection. */
1236
+ var qualificationResultShape = objectShape({
1237
+ id: stringShape(),
1238
+ name: stringShape(),
1239
+ eligibility: literalShape(ELIGIBILITIES),
1240
+ scopes: recordShape(literalShape(ELIGIBILITIES)),
1241
+ findings: arrayShape(findingShape),
1242
+ derivations: arrayShape(derivationShape),
1243
+ success: booleanShape(),
1244
+ trace: arrayShape(stringShape()),
1245
+ errors: arrayShape(stringShape()),
1246
+ faults: arrayShape(auditFaultShape()),
1247
+ repairs: arrayShape(auditFaultShape()),
1248
+ defaulted: arrayShape(fieldPathShape)
1249
+ });
1250
+ // src/core/contracts.ts
1251
+ /** Publishes a `QualificationResult`'s JSON projection as a contract, read through `projectQualificationResult`. */
1252
+ var qualificationResultContract = createContract(qualificationResultShape);
910
1253
  // src/core/Qualifier.ts
911
1254
  /**
912
1255
  * Runs ordered passes over one reason engine and returns eligibility.
@@ -921,20 +1264,21 @@ function describeUnreadDerivations(definition) {
921
1264
  var Qualifier = class {
922
1265
  #emitter;
923
1266
  #engine;
924
- #evaluator;
925
1267
  #owned;
926
1268
  #validate;
927
1269
  #labels;
1270
+ #door = createSubjectDoor();
1271
+ #valid = /* @__PURE__ */ new WeakSet();
1272
+ #shaped = /* @__PURE__ */ new WeakSet();
928
1273
  #destroyed = false;
929
1274
  constructor(options) {
930
1275
  this.#emitter = new Emitter({
931
1276
  ...options?.on === void 0 ? {} : { on: options.on },
932
1277
  ...options?.error === void 0 ? {} : { error: options.error }
933
1278
  });
934
- this.#evaluator = createEvaluator();
935
1279
  this.#owned = options?.engine === void 0;
936
1280
  this.#engine = options?.engine ?? createReason({
937
- reasoners: [createQuantitativeReasoner({ evaluator: this.#evaluator }), createLogicalReasoner({ evaluator: this.#evaluator })],
1281
+ reasoners: [createQuantitativeReasoner(), createLogicalReasoner()],
938
1282
  bail: false
939
1283
  });
940
1284
  this.#validate = options?.validate ?? true;
@@ -964,9 +1308,11 @@ var Qualifier = class {
964
1308
  * @remarks
965
1309
  * Semantic validation runs first when the `validate` option is on, so an invalid
966
1310
  * definition throws before any pass runs. Passes run in authored order over a
967
- * copy-on-write working subject, and the caller's `subject` is never mutated. An
968
- * unscoped restriction stops the remaining passes because no later finding can be
969
- * more severe.
1311
+ * copy-on-write working subject, and the caller's `subject` is never mutated. A
1312
+ * `shape` on the definition admits the subject through a door first. An unscoped
1313
+ * restriction stops the remaining passes because no later finding can be more severe.
1314
+ * A pass left unread projects nothing and reads `referral`, and the run goes on, so a later
1315
+ * restriction can still outrank it. An error no fault can say stops the run.
970
1316
  *
971
1317
  * @param subject - The record to qualify
972
1318
  * @param definition - The authored qualification definition
@@ -996,9 +1342,10 @@ var Qualifier = class {
996
1342
  */
997
1343
  qualify(subject, definition) {
998
1344
  this.#alive();
999
- if (this.#validate) {
1345
+ if (this.#validate && !this.#valid.has(definition)) {
1000
1346
  const validation = this.validate(definition);
1001
- if (!validation.valid) throw new QualifierError("DEFINITION", `Qualification definition is invalid: ${validation.errors.join(", ")}`, { definition: definition.id });
1347
+ if (!validation.valid) throw new QualifierError("DEFINITION", `Qualification definition is invalid: ${validation.errors.join(", ")}`, isRecord(definition) && isString(definition.id) ? { definition: definition.id } : {});
1348
+ this.#valid.add(definition);
1002
1349
  }
1003
1350
  return this.#qualify(subject, definition);
1004
1351
  }
@@ -1009,8 +1356,10 @@ var Qualifier = class {
1009
1356
  * Structural shape is `isQualificationDefinition`'s job. This checks the meaning:
1010
1357
  * non-empty id and name, valid and uniquely identified passes and rulings, every
1011
1358
  * ruling reference resolving to a logical pass and one of its rules, and no pass id
1012
- * shadowing `QUALIFICATION_KEY`. An empty definition, a logical pass carrying no
1013
- * ruling, and a derivation no later pass reads are warnings rather than errors.
1359
+ * shadowing `QUALIFICATION_KEY`. The engine validates each pass, whose errors carry the
1360
+ * pass id. A pass may carry no shape, and a `shape` on the definition must stand and
1361
+ * declare every message token. An empty definition, a logical pass carrying no ruling,
1362
+ * and a derivation no later pass reads are warnings rather than errors.
1014
1363
  *
1015
1364
  * @param definition - The authored qualification definition
1016
1365
  * @returns A fresh validation result carrying `valid`, `errors`, and `warnings`
@@ -1028,22 +1377,56 @@ var Qualifier = class {
1028
1377
  */
1029
1378
  validate(definition) {
1030
1379
  this.#alive();
1380
+ if (!isRecord(definition)) return {
1381
+ valid: false,
1382
+ errors: ["Definition must be a record"],
1383
+ warnings: []
1384
+ };
1031
1385
  const errors = [];
1032
1386
  const warnings = [];
1033
- if (definition.id.length === 0) errors.push("Definition id must not be empty");
1034
- if (definition.name.length === 0) errors.push("Definition name must not be empty");
1035
- definition.passes.forEach((pass, index) => {
1036
- if (!isQualificationPass(pass)) errors.push(`Pass at index ${index} is not a valid qualification pass`);
1387
+ if (!isString(definition.id) || definition.id.length === 0) errors.push("Definition id must not be empty");
1388
+ if (!isString(definition.name) || definition.name.length === 0) errors.push("Definition name must not be empty");
1389
+ const authoredPasses = isArray(definition.passes) ? definition.passes : [];
1390
+ const authoredRulings = definition.rulings === void 0 ? [] : definition.rulings;
1391
+ if (!isArray(definition.passes)) errors.push("Definition must have a passes array");
1392
+ if (!isArray(authoredRulings)) errors.push("Definition rulings must be an array");
1393
+ authoredPasses.forEach((pass, index) => {
1394
+ if (!isQualificationPass(pass)) {
1395
+ errors.push(`Pass at index ${index} is not a valid qualification pass`);
1396
+ return;
1397
+ }
1398
+ if (pass.shape !== void 0) errors.push(`Pass '${pass.id}' may not carry a shape`);
1399
+ const validation = this.#validatePass(pass);
1400
+ for (const error of validation.errors) errors.push(`${pass.id}: ${error}`);
1401
+ for (const warning of validation.warnings) warnings.push(`${pass.id}: ${warning}`);
1037
1402
  });
1038
- (definition.rulings ?? []).forEach((ruling, index) => {
1403
+ const rulingEntries = isArray(authoredRulings) ? authoredRulings : [];
1404
+ rulingEntries.forEach((ruling, index) => {
1039
1405
  if (!isRuling(ruling)) errors.push(`Ruling at index ${index} is not a valid ruling`);
1040
1406
  });
1041
- for (const id of findDuplicates(definition.passes)) errors.push(`Duplicate pass id '${id}'`);
1042
- for (const id of findDuplicates(definition.rulings ?? [])) errors.push(`Duplicate ruling id '${id}'`);
1043
- for (const reference of describeMissingReferences(definition)) errors.push(reference);
1044
- if (definition.passes.length === 0) warnings.push("Definition has no passes");
1045
- for (const warning of describeEmptyLogicalPasses(definition)) warnings.push(warning);
1046
- for (const warning of describeUnreadDerivations(definition)) warnings.push(warning);
1407
+ const passes = authoredPasses.filter((pass) => isQualificationPass(pass));
1408
+ const rulings = rulingEntries.filter((ruling) => isRuling(ruling));
1409
+ const shape = isContractShape(definition.shape) ? definition.shape : void 0;
1410
+ if (definition.shape !== void 0 && shape === void 0) errors.push("Definition shape is not a valid contract shape");
1411
+ if (definition.metadata !== void 0 && !isDefinitionMetadata(definition.metadata)) errors.push("Definition metadata must be a record of JSON values");
1412
+ const readable = {
1413
+ id: definition.id,
1414
+ name: definition.name,
1415
+ passes,
1416
+ rulings,
1417
+ ...shape === void 0 ? {} : { shape }
1418
+ };
1419
+ for (const id of findDuplicates(passes)) errors.push(`Duplicate pass id '${id}'`);
1420
+ for (const id of findDuplicates(rulings)) errors.push(`Duplicate ruling id '${id}'`);
1421
+ for (const reference of describeMissingReferences(readable)) errors.push(reference);
1422
+ for (const conclusion of describeReservedConclusions(readable)) errors.push(conclusion);
1423
+ const scan = scanDefinitionShape(readable);
1424
+ errors.push(...shape === void 0 ? [] : scanShape(shape), ...scan.errors);
1425
+ errors.push(...describeUnknownTokens(readable));
1426
+ warnings.push(...scan.warnings);
1427
+ if (passes.length === 0) warnings.push("Definition has no passes");
1428
+ for (const warning of describeEmptyLogicalPasses(readable)) warnings.push(warning);
1429
+ for (const warning of describeUnreadDerivations(readable)) warnings.push(warning);
1047
1430
  return {
1048
1431
  valid: errors.length === 0,
1049
1432
  errors,
@@ -1076,23 +1459,50 @@ var Qualifier = class {
1076
1459
  }
1077
1460
  #qualify(subject, definition) {
1078
1461
  assertSubject(subject);
1462
+ if (!this.#shaped.has(definition)) {
1463
+ if (!isQualificationDefinition(definition)) throw new QualifierError("DEFINITION", "Qualification definition is malformed");
1464
+ this.#shaped.add(definition);
1465
+ }
1466
+ const admission = this.#door.admit(subject, definition.shape);
1467
+ const admitted = admission.subject;
1468
+ if (admitted !== void 0) assertSubject(admitted);
1469
+ if (admitted === void 0) return this.#finish(definition, [], [], [], [...admission.errors], admission.faults, admission);
1079
1470
  const steps = [{
1080
1471
  context: {},
1081
- subject: { ...subject },
1472
+ subject: { ...admitted },
1082
1473
  success: true
1083
1474
  }];
1084
1475
  const findings = [];
1085
1476
  const derivations = [];
1086
1477
  const trace = [];
1087
1478
  const errors = [];
1479
+ const faults = [];
1480
+ const unread = /* @__PURE__ */ new Map();
1088
1481
  for (const pass of definition.passes) {
1089
1482
  this.#alive();
1090
1483
  const previous = steps.at(-1);
1091
1484
  if (previous === void 0) throw new Error("Qualification has no initial step");
1092
1485
  const evaluated = previous.subject;
1093
1486
  const result = this.#reason(evaluated, pass);
1487
+ if (!isReasonResult(result)) {
1488
+ errors.push(`${pass.id}: The engine returned a malformed result`);
1489
+ steps.push({
1490
+ ...previous,
1491
+ success: false
1492
+ });
1493
+ break;
1494
+ }
1094
1495
  trace.push(...result.trace.map((entry) => `${pass.id}: ${entry}`));
1095
- errors.push(...result.errors.map((entry) => `${pass.id}: ${entry}`));
1496
+ const said = new Set(result.faults.map((fault) => describeFaults([fault])));
1497
+ const fatal = [
1498
+ ...result.errors.filter((entry) => !said.has(entry)),
1499
+ ...!result.success && result.errors.length === 0 ? ["The pass failed and said nothing"] : [],
1500
+ ...result.success && hasUnreadRule(result) ? ["The pass succeeded beside an unread rule"] : []
1501
+ ];
1502
+ errors.push(...fatal.map((entry) => `${pass.id}: ${entry}`));
1503
+ const leaves = expandPassFaults(result.faults, unread);
1504
+ faults.push(...leaves);
1505
+ if (leaves.length > 0) unread.set(pass.id, leaves);
1096
1506
  if (result.reasoning === "quantitative") {
1097
1507
  const derivation = quantitativeResultToDerivation(pass.id, result);
1098
1508
  derivations.push(derivation);
@@ -1101,40 +1511,52 @@ var Qualifier = class {
1101
1511
  if (result.reasoning === "logical") {
1102
1512
  const rulings = (definition.rulings ?? []).filter((ruling) => ruling.pass === pass.id);
1103
1513
  for (const ruling of rulings) {
1104
- const finding = rulingToFinding(ruling, pass, result, evaluated, this.#evaluator, this.#labels);
1514
+ const finding = rulingToFinding(ruling, pass, result, evaluated, this.#labels);
1105
1515
  findings.push(finding);
1106
1516
  this.#emitter.emit("finding", finding);
1107
1517
  }
1108
1518
  }
1109
- const projection = reasonResultToProjection(pass, result);
1110
- const context = mergeQualificationContext(previous.context, pass.id, projection);
1519
+ const context = result.success && fatal.length === 0 ? mergeQualificationContext(previous.context, pass.id, reasonResultToProjection(pass, result)) : previous.context;
1111
1520
  steps.push({
1112
1521
  context,
1113
1522
  subject: {
1114
- ...subject,
1523
+ ...admitted,
1115
1524
  ...qualificationToRecord(context)
1116
1525
  },
1117
- success: result.success
1526
+ success: result.success && fatal.length === 0
1118
1527
  });
1119
- if (!result.success) break;
1528
+ if (fatal.length > 0) break;
1120
1529
  if (deriveFindingEligibility(findings) === "ineligible") break;
1121
1530
  }
1122
- const success = steps.every((step) => step.success) && errors.length === 0;
1123
- const scopes = deriveScopeEligibilities(findings);
1531
+ const leaves = filterUniqueFaults(faults);
1532
+ return this.#finish(definition, findings, derivations, trace, [...errors, ...leaves.map((fault) => describeFaults([fault]))], leaves, admission);
1533
+ }
1534
+ #finish(definition, findings, derivations, trace, errors, faults, admission) {
1535
+ const success = errors.length === 0;
1124
1536
  const qualification = Object.freeze({
1125
1537
  id: definition.id,
1126
1538
  name: definition.name,
1127
1539
  eligibility: deriveFindingEligibility(findings, !success),
1128
- scopes: Object.freeze(scopes),
1540
+ scopes: Object.freeze(deriveScopeEligibilities(findings)),
1129
1541
  findings: Object.freeze(findings),
1130
1542
  derivations: Object.freeze(derivations),
1131
1543
  success,
1132
1544
  trace: Object.freeze(trace),
1133
- errors: Object.freeze(errors)
1545
+ errors: Object.freeze(errors),
1546
+ faults: Object.freeze(faults),
1547
+ repairs: Object.freeze([...admission.repairs]),
1548
+ defaulted: Object.freeze([...admission.defaulted])
1134
1549
  });
1135
1550
  this.#emitter.emit("qualify", qualification);
1136
1551
  return qualification;
1137
1552
  }
1553
+ #validatePass(pass) {
1554
+ try {
1555
+ return this.#engine.validate(pass);
1556
+ } catch (error) {
1557
+ throw mapEngineError(error, pass.id);
1558
+ }
1559
+ }
1138
1560
  #reason(subject, pass) {
1139
1561
  try {
1140
1562
  return this.#engine.reason(subject, pass);
@@ -1148,6 +1570,26 @@ var Qualifier = class {
1148
1570
  };
1149
1571
  // src/core/factories.ts
1150
1572
  /**
1573
+ * Creates the contract of a `QualificationDefinition`, its `schema` for an LLM, a tool, or MCP.
1574
+ *
1575
+ * @remarks
1576
+ * Cross a definition on `is`, never `parse`, and hold the result, because building it walks the
1577
+ * recursive expressions of its logical passes. `is` checks nested contract shapes;
1578
+ * semantic validation remains the qualifier's responsibility.
1579
+ *
1580
+ * @returns A contract over a qualification definition
1581
+ *
1582
+ * @example
1583
+ * ```ts
1584
+ * import { createQualificationDefinition, createQualificationDefinitionContract } from '@orkestrel/qualifier'
1585
+ *
1586
+ * createQualificationDefinitionContract().is(createQualificationDefinition('d', 'd', [])) // true
1587
+ * ```
1588
+ */
1589
+ function createQualificationDefinitionContract() {
1590
+ return createContract(createQualificationDefinitionShape());
1591
+ }
1592
+ /**
1151
1593
  * Creates one {@link QualifierInterface} over a reason engine.
1152
1594
  *
1153
1595
  * @remarks
@@ -1208,7 +1650,7 @@ function createQualifier(options) {
1208
1650
  * @param id - The definition id
1209
1651
  * @param name - The display name
1210
1652
  * @param passes - The ordered qualification passes
1211
- * @param input - Optional description, rulings, and metadata
1653
+ * @param input - Optional description, rulings, metadata, and subject shape
1212
1654
  * @returns A fresh qualification definition
1213
1655
  *
1214
1656
  * @example
@@ -1225,7 +1667,8 @@ function createQualificationDefinition(id, name, passes, input) {
1225
1667
  passes: [...passes],
1226
1668
  ...input?.description === void 0 ? {} : { description: input.description },
1227
1669
  ...input?.rulings === void 0 ? {} : { rulings: [...input.rulings] },
1228
- ...input?.metadata === void 0 ? {} : { metadata: { ...input.metadata } }
1670
+ ...input?.metadata === void 0 ? {} : { metadata: { ...input.metadata } },
1671
+ ...input?.shape === void 0 ? {} : { shape: input.shape }
1229
1672
  };
1230
1673
  }
1231
1674
  /**
@@ -1255,6 +1698,6 @@ function createRuling(id, pass, rule, effect, input) {
1255
1698
  ...input?.message === void 0 ? {} : { message: input.message }
1256
1699
  };
1257
1700
  }
1258
- export { DEFAULT_QUALIFIER_VALIDATE, EFFECT_ELIGIBILITIES, ELIGIBILITY_PRECEDENCE, QUALIFICATION_KEY, Qualifier, QualifierError, assertSubject, checkToPremise, combineEligibilities, createQualificationDefinition, createQualifier, createRuling, deriveFindingEligibility, deriveScopeEligibilities, describeEmptyLogicalPasses, describeMissingReferences, describeUnreadDerivations, findRule, hasReservedKey, interpolateMessage, isDerivation, isEligibility, isEligibilityRecord, isFinding, isPremise, isQualificationDefinition, isQualificationEffect, isQualificationPass, isQualificationResult, isQualifierError, isRuling, mapEngineError, mergeQualificationContext, qualificationToRecord, quantitativeResultToDerivation, reasonResultToProjection, renderComparison, renderPremise, renderValue, ruleToPremises, rulingToFinding };
1701
+ export { DEFAULT_QUALIFIER_VALIDATE, EFFECT_ELIGIBILITIES, ELIGIBILITIES, ELIGIBILITY_PRECEDENCE, MESSAGE_TOKEN, QUALIFICATION_EFFECTS, QUALIFICATION_KEY, Qualifier, QualifierError, assertSubject, checkToPremise, combineEligibilities, createQualificationDefinition, createQualificationDefinitionContract, createQualificationDefinitionShape, createQualifier, createRuling, derivationShape, deriveFindingEligibility, deriveScopeEligibilities, describeEmptyLogicalPasses, describeMissingReferences, describeReservedConclusions, describeUnknownTokens, describeUnreadDerivations, expandPassFaults, findMessageTokens, findRule, findingShape, hasReservedKey, hasUnreadRule, interpolateMessage, isDefinitionMetadata, isDerivation, isEligibility, isEligibilityRecord, isFinding, isPremise, isQualificationDefinition, isQualificationEffect, isQualificationPass, isQualificationResult, isQualifierError, isRuling, mapEngineError, mergeQualificationContext, premiseShape, projectQualificationResult, qualificationResultContract, qualificationResultShape, qualificationToRecord, quantitativeResultToDerivation, readsProjection, reasonResultToProjection, renderComparison, renderPremise, renderValue, ruleToPremises, rulingShape, rulingToFinding, scanDefinitionShape };
1259
1702
 
1260
1703
  //# sourceMappingURL=index.js.map