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