@orkestrel/qualifier 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,713 @@
1
+ import { arrayOf, isFiniteNumber, isRecord, isString, literalOf, recordOf, resolveField } from "@orkestrel/contract";
2
+ import { createEvaluator, createLogicalReasoner, createQuantitativeReasoner, createReason, extractAtoms, extractConclusions, formatField, isBounds, isLogicalDefinition, isQuantitativeDefinition } from "@orkestrel/reason";
3
+ import { Emitter } from "@orkestrel/emitter";
4
+ //#region src/core/constants.ts
5
+ /** Default definition validation policy for `createQualifier` / `Qualifier.qualify`. */
6
+ var DEFAULT_QUALIFIER_VALIDATE = true;
7
+ /** The reserved internal projection namespace a pass's working projection is written under. */
8
+ var QUALIFICATION_KEY = "qualification";
9
+ /** Eligibility severity order — most to least severe. */
10
+ var ELIGIBILITY_PRECEDENCE = Object.freeze([
11
+ "ineligible",
12
+ "referral",
13
+ "eligible"
14
+ ]);
15
+ /** The eligibility impact of each {@link QualificationEffect}; `condition` remains eligible. */
16
+ var EFFECT_ELIGIBILITIES = Object.freeze({
17
+ restriction: "ineligible",
18
+ referral: "referral",
19
+ condition: "eligible"
20
+ });
21
+ //#endregion
22
+ //#region src/core/errors.ts
23
+ /**
24
+ * A coded programmer error thrown by the qualifier layer.
25
+ *
26
+ * @remarks
27
+ * `DEFINITION` — a qualification definition failed semantic validation.
28
+ * `MISMATCH` — a subject is not a record or already carries the reserved
29
+ * `qualification` key. `DESTROYED` — use of a destroyed qualifier.
30
+ */
31
+ var QualifierError = class extends Error {
32
+ code;
33
+ context;
34
+ constructor(code, message, context) {
35
+ super(message);
36
+ this.name = "QualifierError";
37
+ this.code = code;
38
+ this.context = context;
39
+ }
40
+ };
41
+ /** Narrow a caught value to a {@link QualifierError}. */
42
+ function isQualifierError(value) {
43
+ return value instanceof QualifierError;
44
+ }
45
+ //#endregion
46
+ //#region src/core/validators.ts
47
+ /** Determine whether a value is an {@link Eligibility} literal. */
48
+ var isEligibility = literalOf("eligible", "ineligible", "referral");
49
+ /** Determine whether a value is a {@link QualificationEffect} literal. */
50
+ var isQualificationEffect = literalOf("restriction", "referral", "condition");
51
+ /** Determine whether a value is a {@link QualificationPass} (a quantitative or logical definition). */
52
+ function isQualificationPass(value) {
53
+ return isQuantitativeDefinition(value) || isLogicalDefinition(value);
54
+ }
55
+ /** Determine whether a value is an exact {@link Ruling} record. */
56
+ function isRuling(value) {
57
+ return recordOf({
58
+ id: isString,
59
+ pass: isString,
60
+ rule: isString,
61
+ effect: isQualificationEffect,
62
+ scope: isString,
63
+ message: isString
64
+ }, ["scope", "message"])(value);
65
+ }
66
+ /** Determine whether a value is an exact {@link QualificationDefinition} record. */
67
+ function isQualificationDefinition(value) {
68
+ if (!isRecord(value)) return false;
69
+ return recordOf({
70
+ id: isString,
71
+ name: isString,
72
+ description: isString,
73
+ passes: arrayOf(isQualificationPass),
74
+ rulings: arrayOf(isRuling),
75
+ metadata: isRecord
76
+ }, [
77
+ "description",
78
+ "rulings",
79
+ "metadata"
80
+ ])(value);
81
+ }
82
+ //#endregion
83
+ //#region src/core/helpers.ts
84
+ /**
85
+ * Interpolate `{{dotted.path}}` tokens in a message template against a subject.
86
+ *
87
+ * @remarks
88
+ * Each token is split on `.` into a `FieldPath` array and resolved with
89
+ * `resolveField` (a plain string field is ONE key, never dot-split — the split
90
+ * here is the token-to-path bridge). A finite number renders with `en-US`
91
+ * thousand grouping (`5010` → `5,010`); any other resolved value String-coerces.
92
+ * An UNRESOLVED path renders as the empty string.
93
+ *
94
+ * @param template - The message template carrying `{{dotted.path}}` tokens
95
+ * @param subject - The record tokens resolve against
96
+ * @returns The template with every token replaced
97
+ *
98
+ * @example
99
+ * ```ts
100
+ * import { interpolateMessage } from '@orkestrel/qualifier'
101
+ *
102
+ * interpolateMessage('Limit is {{limit}}', { limit: 5010 }) // 'Limit is 5,010'
103
+ * interpolateMessage('Missing {{gone}}', {}) // 'Missing '
104
+ * ```
105
+ */
106
+ function interpolateMessage(template, subject) {
107
+ return template.replace(/\{\{\s*([^}]+?)\s*\}\}/g, (_match, path) => {
108
+ const value = resolveField(subject, path.split("."));
109
+ if (value === void 0) return "";
110
+ if (isFiniteNumber(value)) return value.toLocaleString("en-US");
111
+ return String(value);
112
+ });
113
+ }
114
+ /**
115
+ * Describe a {@link Premise} comparison as a display-neutral verb phrase.
116
+ *
117
+ * @param comparison - The comparison to describe
118
+ * @returns A display-neutral phrase
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * import { describeComparison } from '@orkestrel/qualifier'
123
+ *
124
+ * describeComparison('above') // 'is more than'
125
+ * ```
126
+ */
127
+ function describeComparison(comparison) {
128
+ switch (comparison) {
129
+ case "equals": return "is";
130
+ case "not": return "is not";
131
+ case "above": return "is more than";
132
+ case "below": return "is less than";
133
+ case "from": return "is at least";
134
+ case "to": return "is at most";
135
+ case "any": return "is any of";
136
+ case "none": return "is none of";
137
+ case "between": return "is between";
138
+ case "outside": return "is outside";
139
+ }
140
+ }
141
+ /**
142
+ * Render a structured or scalar expected value display-neutrally.
143
+ *
144
+ * @remarks
145
+ * An array renders as its elements, each `String`-coerced, joined with `', '`.
146
+ * A reason `Bounds`-shaped record (the `between` / `outside` expected value)
147
+ * renders its present sides joined with the word `and`; an absent side is
148
+ * omitted. A finite number and everything else fall back to plain `String()` —
149
+ * a finite number is NOT grouped here (grouping is {@link interpolateMessage}'s
150
+ * message-token-only behavior).
151
+ *
152
+ * @param value - The value to render
153
+ * @returns A display-neutral rendering
154
+ *
155
+ * @example
156
+ * ```ts
157
+ * import { describeValue } from '@orkestrel/qualifier'
158
+ *
159
+ * describeValue([18, 25, 40]) // '18, 25, 40'
160
+ * describeValue({ minimum: 18, maximum: 65 }) // '18 and 65'
161
+ * describeValue(42) // '42'
162
+ * ```
163
+ */
164
+ function describeValue(value) {
165
+ if (Array.isArray(value)) return value.map((entry) => String(entry)).join(", ");
166
+ if (isBounds(value)) {
167
+ const sides = [];
168
+ if (value.minimum !== void 0) sides.push(String(value.minimum));
169
+ if (value.maximum !== void 0) sides.push(String(value.maximum));
170
+ return sides.join(" and ");
171
+ }
172
+ return String(value);
173
+ }
174
+ /**
175
+ * Render one {@link Premise} into a display-neutral sentence.
176
+ *
177
+ * @param entry - The premise to render
178
+ * @param labels - Optional field-to-label overrides, keyed by dot-joined field
179
+ * @returns A display-neutral sentence
180
+ *
181
+ * @example
182
+ * ```ts
183
+ * import { describePremise } from '@orkestrel/qualifier'
184
+ *
185
+ * describePremise({ field: 'age', comparison: 'above', expected: 18, actual: 25, met: true })
186
+ * // 'age is more than 18 → met'
187
+ * ```
188
+ */
189
+ function describePremise(entry, labels) {
190
+ const status = entry.met === void 0 ? "unknown" : entry.met ? "met" : "not met";
191
+ if (entry.field === void 0 || entry.comparison === void 0) return `${entry.description ?? "Premise"} → ${status}`;
192
+ const field = formatField(entry.field);
193
+ const label = labels?.[field] ?? entry.label ?? field;
194
+ const expected = entry.expected === void 0 ? "" : ` ${describeValue(entry.expected)}`;
195
+ return `${label} ${describeComparison(entry.comparison)}${expected} → ${status}`;
196
+ }
197
+ /**
198
+ * Build a {@link Premise} from an authored {@link Check} and its evaluated
199
+ * `CheckResult`.
200
+ *
201
+ * @param check - The authored check
202
+ * @param result - The evaluated check result carrying the resolved `actual` and `met`
203
+ * @param labels - Optional field-to-label overrides, keyed by dot-joined field
204
+ * @returns A fresh premise
205
+ *
206
+ * @example
207
+ * ```ts
208
+ * import { premiseCheck } from '@orkestrel/qualifier'
209
+ * import { check } from '@orkestrel/reason'
210
+ *
211
+ * const authored = check('age', 'above', 18)
212
+ * premiseCheck(authored, { field: 'age', actual: 25, met: true })
213
+ * // { field: 'age', comparison: 'above', expected: 18, actual: 25, met: true }
214
+ * ```
215
+ */
216
+ function premiseCheck(check, result, labels) {
217
+ const field = formatField(check.field);
218
+ return {
219
+ field: check.field,
220
+ ...labels?.[field] === void 0 ? {} : { label: labels[field] },
221
+ comparison: check.operator,
222
+ expected: check.value,
223
+ actual: result.actual,
224
+ ...result.met === void 0 ? {} : { met: result.met }
225
+ };
226
+ }
227
+ /**
228
+ * Build rich premises for one fired {@link Rule} by walking its premise atoms
229
+ * and re-evaluating each against the working subject.
230
+ *
231
+ * @remarks
232
+ * A reason rule result carries only booleans, so this is the qualifier's own
233
+ * premise-audit projection: each authored premise expression is flattened to its
234
+ * atom leaves via `extractAtoms`, and each leaf's `Check` is re-evaluated through
235
+ * the injected `evaluator`. A membership check (`any` / `none`) over an EMPTY
236
+ * array value is content-free and is skipped.
237
+ *
238
+ * @param rule - The authored rule
239
+ * @param working - The working subject to evaluate against
240
+ * @param evaluator - The shared reason check evaluator
241
+ * @param labels - Optional field-to-label overrides, keyed by dot-joined field
242
+ * @returns A fresh, ordered list of rich premises
243
+ *
244
+ * @example
245
+ * ```ts
246
+ * import { logicalPremises } from '@orkestrel/qualifier'
247
+ * import { atom, createEvaluator, logicalDefinition, rule } from '@orkestrel/reason'
248
+ *
249
+ * const gates = logicalDefinition('gates', 'Gates', [
250
+ * rule('licensed', [atom('licensed', 'equals', false)], atom('blocked', 'equals', true)),
251
+ * ])
252
+ * const evaluator = createEvaluator()
253
+ * const premises = logicalPremises(gates.rules[0], { licensed: false }, evaluator)
254
+ *
255
+ * premises[0]?.met // true
256
+ * ```
257
+ */
258
+ function logicalPremises(rule, working, evaluator, labels) {
259
+ const output = [];
260
+ for (const premise of rule.premises) for (const atom of extractAtoms(premise)) {
261
+ const { check } = atom;
262
+ if ((check.operator === "any" || check.operator === "none") && Array.isArray(check.value) && check.value.length === 0) continue;
263
+ output.push(premiseCheck(check, evaluator.evaluate(check, working), labels));
264
+ }
265
+ return output;
266
+ }
267
+ /**
268
+ * Locate an authored {@link Rule} by id.
269
+ *
270
+ * @param definition - The logical definition to search
271
+ * @param id - The rule id
272
+ * @returns The matching rule, or `undefined`
273
+ *
274
+ * @example
275
+ * ```ts
276
+ * import { findRule } from '@orkestrel/qualifier'
277
+ * import { atom, logicalDefinition, rule } from '@orkestrel/reason'
278
+ *
279
+ * const gates = logicalDefinition('gates', 'Gates', [
280
+ * rule('licensed', [atom('licensed', 'equals', false)], atom('blocked', 'equals', true)),
281
+ * ])
282
+ *
283
+ * findRule(gates, 'licensed')?.id // 'licensed'
284
+ * ```
285
+ */
286
+ function findRule(definition, id) {
287
+ return definition.rules.find((rule) => rule.id === id);
288
+ }
289
+ /**
290
+ * Project one reason result into the internal qualification namespace.
291
+ *
292
+ * @remarks
293
+ * A quantitative result contributes its numeric `value`. A logical result
294
+ * contributes a record of its `conclusion` plus every applied rule's asserted
295
+ * conclusion fields (`extractConclusions`). A mismatched pairing contributes
296
+ * `false`. The projection is pure — it never mutates the subject or the result.
297
+ *
298
+ * @param definition - The pass definition that produced the result
299
+ * @param result - The evaluated reason result
300
+ * @returns The pass's working projection
301
+ */
302
+ function reasonResultToProjection(definition, result) {
303
+ if (definition.reasoning === "quantitative" && result.reasoning === "quantitative") return result.value;
304
+ if (definition.reasoning !== "logical" || result.reasoning !== "logical") return false;
305
+ const projection = { conclusion: result.conclusion };
306
+ for (const resolved of result.rules) {
307
+ if (!resolved.applied) continue;
308
+ const authored = definition.rules.find((rule) => rule.id === resolved.id);
309
+ if (authored === void 0) continue;
310
+ const conclusions = extractConclusions(authored.conclusion);
311
+ for (const [key, value] of Object.entries(conclusions)) projection[key] = value;
312
+ }
313
+ return projection;
314
+ }
315
+ /**
316
+ * Project a quantitative result into a {@link Derivation} audit record.
317
+ *
318
+ * @param id - The pass id
319
+ * @param result - The evaluated quantitative result
320
+ * @returns A fresh derivation
321
+ */
322
+ function quantitativeResultToDerivation(id, result) {
323
+ return {
324
+ id,
325
+ value: result.value,
326
+ success: result.success,
327
+ trace: [...result.trace],
328
+ errors: [...result.errors]
329
+ };
330
+ }
331
+ /**
332
+ * Wrap a {@link QualificationContext} under {@link QUALIFICATION_KEY}.
333
+ *
334
+ * @param context - The accumulated projection context
335
+ * @returns A record carrying the context under the reserved key
336
+ */
337
+ function qualificationToRecord(context) {
338
+ return { [QUALIFICATION_KEY]: context };
339
+ }
340
+ /**
341
+ * Copy-on-write merge one pass projection into the context.
342
+ *
343
+ * @param context - The current projection context
344
+ * @param id - The pass id to project under
345
+ * @param projection - The pass's working projection
346
+ * @returns A fresh context with the projection added
347
+ */
348
+ function mergeQualificationContext(context, id, projection) {
349
+ return {
350
+ ...context,
351
+ [id]: projection
352
+ };
353
+ }
354
+ /**
355
+ * Join a ruling, its logical rule result, the pass, the pre-projection subject,
356
+ * and an evaluator into a {@link Finding}.
357
+ *
358
+ * @remarks
359
+ * `applied` reflects whether the ruling's rule fired. Premises are re-evaluated
360
+ * against the SAME subject snapshot the pass evaluated, so a conclusion the pass
361
+ * derived can never satisfy its own reported premise. The message interpolates
362
+ * against that snapshot.
363
+ *
364
+ * @param ruling - The authored ruling
365
+ * @param pass - The pass the ruling's rule lives in
366
+ * @param result - The pass's evaluated logical result
367
+ * @param subject - The pre-projection subject snapshot the pass evaluated
368
+ * @param evaluator - The shared reason check evaluator
369
+ * @param labels - Optional field-to-label overrides, keyed by dot-joined field
370
+ * @returns A fresh finding
371
+ */
372
+ function rulingToFinding(ruling, pass, result, subject, evaluator, labels) {
373
+ const applied = result.rules.find((item) => item.id === ruling.rule)?.applied ?? false;
374
+ const rule = pass.reasoning === "logical" ? findRule(pass, ruling.rule) : void 0;
375
+ const premises = rule === void 0 ? [] : logicalPremises(rule, subject, evaluator, labels);
376
+ return {
377
+ id: ruling.id,
378
+ pass: ruling.pass,
379
+ rule: ruling.rule,
380
+ effect: ruling.effect,
381
+ ...ruling.scope === void 0 ? {} : { scope: ruling.scope },
382
+ applied,
383
+ ...ruling.message === void 0 ? {} : { message: interpolateMessage(ruling.message, subject) },
384
+ premises
385
+ };
386
+ }
387
+ /**
388
+ * Derive global eligibility from applied, unscoped findings.
389
+ *
390
+ * @remarks
391
+ * Only findings that both applied and carry no `scope` shape global eligibility.
392
+ * A failed pass contributes a synthetic `referral` (fail-closed), passed through
393
+ * `failed`.
394
+ *
395
+ * @param findings - The resolved findings
396
+ * @param failed - Whether an operational pass failure occurred
397
+ * @returns The most severe global eligibility
398
+ */
399
+ function deriveFindingEligibility(findings, failed = false) {
400
+ const eligibilities = findings.filter((finding) => finding.applied && finding.scope === void 0).map((finding) => EFFECT_ELIGIBILITIES[finding.effect]);
401
+ if (failed) eligibilities.push("referral");
402
+ return combineEligibilities(eligibilities);
403
+ }
404
+ /**
405
+ * Return the most severe {@link Eligibility} in a list.
406
+ *
407
+ * @param eligibilities - The eligibilities to combine
408
+ * @returns The most severe eligibility, or `'eligible'` for an empty list
409
+ *
410
+ * @example
411
+ * ```ts
412
+ * import { combineEligibilities } from '@orkestrel/qualifier'
413
+ *
414
+ * combineEligibilities(['eligible', 'referral']) // 'referral'
415
+ * ```
416
+ */
417
+ function combineEligibilities(eligibilities) {
418
+ for (const eligibility of ELIGIBILITY_PRECEDENCE) if (eligibilities.includes(eligibility)) return eligibility;
419
+ return "eligible";
420
+ }
421
+ /**
422
+ * Derive one eligibility per finding scope.
423
+ *
424
+ * @remarks
425
+ * Only applied, scoped findings contribute. Each named scope combines its own
426
+ * findings' impacts by severity. An unmentioned scope is absent (eligible by
427
+ * default at the program layer).
428
+ *
429
+ * @param findings - The resolved findings
430
+ * @returns A fresh record of scope to its combined eligibility
431
+ */
432
+ function deriveScopeEligibilities(findings) {
433
+ const grouped = {};
434
+ for (const finding of findings) {
435
+ if (!finding.applied || finding.scope === void 0) continue;
436
+ const current = grouped[finding.scope] ?? [];
437
+ grouped[finding.scope] = [...current, EFFECT_ELIGIBILITIES[finding.effect]];
438
+ }
439
+ const scopes = {};
440
+ for (const [scope, eligibilities] of Object.entries(grouped)) scopes[scope] = combineEligibilities(eligibilities);
441
+ return scopes;
442
+ }
443
+ /**
444
+ * Find rulings whose pass or rule does not exist, whose pass is not logical, or
445
+ * a pass id shadowing the reserved {@link QUALIFICATION_KEY}.
446
+ *
447
+ * @param definition - The qualification definition to check
448
+ * @returns A fresh list of reference-error messages
449
+ */
450
+ function findMissingReferences(definition) {
451
+ const errors = [];
452
+ const passes = new Map(definition.passes.map((pass) => [pass.id, pass]));
453
+ for (const pass of definition.passes) if (pass.id === "qualification") errors.push(`Pass id must not equal reserved key '${QUALIFICATION_KEY}'`);
454
+ for (const ruling of definition.rulings ?? []) {
455
+ const pass = passes.get(ruling.pass);
456
+ if (pass === void 0) {
457
+ errors.push(`Ruling '${ruling.id}' references missing pass '${ruling.pass}'`);
458
+ continue;
459
+ }
460
+ if (pass.reasoning !== "logical") {
461
+ errors.push(`Ruling '${ruling.id}' references non-logical pass '${ruling.pass}'`);
462
+ continue;
463
+ }
464
+ if (findRule(pass, ruling.rule) === void 0) errors.push(`Ruling '${ruling.id}' references missing rule '${ruling.rule}' in pass '${ruling.pass}'`);
465
+ }
466
+ return errors;
467
+ }
468
+ /**
469
+ * Find duplicate ids in a list, once each.
470
+ *
471
+ * @param ids - The ids to scan
472
+ * @returns A fresh list of ids that appear more than once
473
+ */
474
+ function findDuplicateIds(ids) {
475
+ const seen = /* @__PURE__ */ new Set();
476
+ const duplicates = /* @__PURE__ */ new Set();
477
+ for (const id of ids) if (seen.has(id)) duplicates.add(id);
478
+ else seen.add(id);
479
+ return [...duplicates];
480
+ }
481
+ /**
482
+ * Determine whether a subject already owns the reserved {@link QUALIFICATION_KEY}.
483
+ *
484
+ * @param subject - The subject to check
485
+ * @returns `true` when the subject owns the reserved key
486
+ */
487
+ function hasReservedKey(subject) {
488
+ return Object.hasOwn(subject, QUALIFICATION_KEY);
489
+ }
490
+ /**
491
+ * Assert a value is a valid qualification {@link Subject}, narrowing it in place.
492
+ *
493
+ * @param value - The candidate subject to validate
494
+ * @throws {@link QualifierError} `'MISMATCH'` when the value is not a record, or
495
+ * when it already carries the reserved `qualification` key
496
+ */
497
+ function assertSubject(value) {
498
+ if (!isRecord(value)) throw new QualifierError("MISMATCH", "Qualification subject must be a record");
499
+ if (hasReservedKey(value)) throw new QualifierError("MISMATCH", `Qualification subject must not contain reserved key '${QUALIFICATION_KEY}'`);
500
+ }
501
+ //#endregion
502
+ //#region src/core/Qualifier.ts
503
+ /**
504
+ * A qualifier — runs ordered passes over one reason engine and returns
505
+ * pre-rating eligibility.
506
+ *
507
+ * @remarks
508
+ * The engine is OWNED when self-created (destroyed on `destroy()`) and borrowed
509
+ * when injected (never destroyed). `qualify` builds its working subject through
510
+ * copy-on-write overlays only — the caller's `subject` is never mutated, and the
511
+ * qualifier's internal projection is discarded after each call.
512
+ */
513
+ var Qualifier = class {
514
+ #emitter;
515
+ #engine;
516
+ #evaluator;
517
+ #owned;
518
+ #validate;
519
+ #labels;
520
+ #destroyed = false;
521
+ constructor(options) {
522
+ this.#emitter = new Emitter({
523
+ on: options?.on,
524
+ error: options?.error
525
+ });
526
+ this.#evaluator = createEvaluator();
527
+ this.#owned = options?.engine === void 0;
528
+ this.#engine = options?.engine ?? createReason({
529
+ reasoners: [createQuantitativeReasoner({ evaluator: this.#evaluator }), createLogicalReasoner({ evaluator: this.#evaluator })],
530
+ bail: false
531
+ });
532
+ this.#validate = options?.validate ?? true;
533
+ this.#labels = options?.labels;
534
+ }
535
+ get emitter() {
536
+ return this.#emitter;
537
+ }
538
+ qualify(subject, definition) {
539
+ this.#alive();
540
+ if (this.#validate) {
541
+ const validation = this.validate(definition);
542
+ if (!validation.valid) throw new QualifierError("DEFINITION", `Qualification definition is invalid: ${validation.errors.join(", ")}`, definition.id);
543
+ }
544
+ return this.#qualify(subject, definition);
545
+ }
546
+ validate(definition) {
547
+ this.#alive();
548
+ const errors = [];
549
+ const warnings = [];
550
+ if (definition.id.length === 0) errors.push("Definition id must not be empty");
551
+ if (definition.name.length === 0) errors.push("Definition name must not be empty");
552
+ if (definition.passes.length === 0) warnings.push("Definition has no passes");
553
+ for (const id of findDuplicateIds(definition.passes.map((pass) => pass.id))) errors.push(`Duplicate pass id '${id}'`);
554
+ for (const id of findDuplicateIds((definition.rulings ?? []).map((ruling) => ruling.id))) errors.push(`Duplicate ruling id '${id}'`);
555
+ for (const reference of findMissingReferences(definition)) errors.push(reference);
556
+ return {
557
+ valid: errors.length === 0,
558
+ errors,
559
+ warnings
560
+ };
561
+ }
562
+ destroy() {
563
+ if (this.#destroyed) return;
564
+ if (this.#owned) this.#engine.destroy();
565
+ this.#destroyed = true;
566
+ this.#emitter.emit("destroy");
567
+ this.#emitter.destroy();
568
+ }
569
+ #qualify(subject, definition) {
570
+ assertSubject(subject);
571
+ let context = {};
572
+ let working = { ...subject };
573
+ const findings = [];
574
+ const derivations = [];
575
+ const trace = [];
576
+ const errors = [];
577
+ let failed = false;
578
+ for (const pass of definition.passes) {
579
+ const evaluated = working;
580
+ const result = this.#engine.reason(evaluated, pass);
581
+ trace.push(...result.trace.map((entry) => `${pass.id}: ${entry}`));
582
+ errors.push(...result.errors.map((entry) => `${pass.id}: ${entry}`));
583
+ if (result.reasoning === "quantitative") {
584
+ const derivation = quantitativeResultToDerivation(pass.id, result);
585
+ derivations.push(derivation);
586
+ this.#emitter.emit("derive", derivation);
587
+ }
588
+ if (result.reasoning === "logical") {
589
+ const rulings = (definition.rulings ?? []).filter((ruling) => ruling.pass === pass.id);
590
+ for (const ruling of rulings) {
591
+ const finding = rulingToFinding(ruling, pass, result, evaluated, this.#evaluator, this.#labels);
592
+ findings.push(finding);
593
+ this.#emitter.emit("finding", finding);
594
+ }
595
+ }
596
+ const projection = reasonResultToProjection(pass, result);
597
+ context = mergeQualificationContext(context, pass.id, projection);
598
+ working = {
599
+ ...subject,
600
+ ...qualificationToRecord(context)
601
+ };
602
+ if (!result.success) {
603
+ failed = true;
604
+ break;
605
+ }
606
+ if (deriveFindingEligibility(findings) === "ineligible") break;
607
+ }
608
+ const success = !failed && errors.length === 0;
609
+ const qualification = {
610
+ id: definition.id,
611
+ name: definition.name,
612
+ eligibility: deriveFindingEligibility(findings, !success),
613
+ scopes: deriveScopeEligibilities(findings),
614
+ findings,
615
+ derivations,
616
+ success,
617
+ trace,
618
+ errors
619
+ };
620
+ this.#emitter.emit("qualify", qualification);
621
+ return qualification;
622
+ }
623
+ #alive() {
624
+ if (this.#destroyed) throw new QualifierError("DESTROYED", "Qualifier has been destroyed");
625
+ }
626
+ };
627
+ //#endregion
628
+ //#region src/core/factories.ts
629
+ /**
630
+ * Create one qualifier over a reason engine.
631
+ *
632
+ * @remarks
633
+ * A standalone qualifier creates and OWNS one shared quantitative-plus-logical
634
+ * reason engine, destroying it on `destroy()`. An injected `options.engine`
635
+ * remains caller-owned and is never destroyed. Validation is on by default.
636
+ *
637
+ * @param options - Optional injected engine, validation, labels, and emitter hooks
638
+ * @returns A {@link QualifierInterface}
639
+ *
640
+ * @example
641
+ * ```ts
642
+ * import { createQualifier } from '@orkestrel/qualifier'
643
+ *
644
+ * const qualifier = createQualifier()
645
+ * qualifier.qualify({ id: 'risk-1' }, definition)
646
+ * qualifier.destroy()
647
+ * ```
648
+ */
649
+ function createQualifier(options) {
650
+ return new Qualifier(options);
651
+ }
652
+ /**
653
+ * Build a {@link QualificationDefinition}.
654
+ *
655
+ * @remarks
656
+ * Returns a fresh top-level definition, omitting absent optional keys;
657
+ * `passes` and `rulings` arrays are copied, and record `metadata` is
658
+ * shallow-copied so nested values are not deep-cloned.
659
+ *
660
+ * @param id - The definition id
661
+ * @param name - The display name
662
+ * @param passes - The ordered qualification passes
663
+ * @param input - Optional description, rulings, and metadata
664
+ * @returns A fresh qualification definition
665
+ *
666
+ * @example
667
+ * ```ts
668
+ * import { qualificationDefinition } from '@orkestrel/qualifier'
669
+ *
670
+ * qualificationDefinition('standard', 'Standard', [gates], { rulings: [ruling] })
671
+ * ```
672
+ */
673
+ function qualificationDefinition(id, name, passes, input) {
674
+ return {
675
+ id,
676
+ name,
677
+ passes: [...passes],
678
+ ...input?.description === void 0 ? {} : { description: input.description },
679
+ ...input?.rulings === void 0 ? {} : { rulings: [...input.rulings] },
680
+ ...input?.metadata === void 0 ? {} : { metadata: { ...input.metadata } }
681
+ };
682
+ }
683
+ /**
684
+ * Build a {@link Ruling} — one authored consequence for one rule in one pass.
685
+ *
686
+ * @param id - The ruling id
687
+ * @param pass - The logical pass id the rule lives in
688
+ * @param rule - The rule id whose firing this ruling reacts to
689
+ * @param effect - The eligibility impact when the rule fires
690
+ * @param input - Optional rating scope and message template
691
+ * @returns A fresh ruling
692
+ *
693
+ * @example
694
+ * ```ts
695
+ * import { rulingDefinition } from '@orkestrel/qualifier'
696
+ *
697
+ * rulingDefinition('license', 'gates', 'licensed', 'restriction', { message: 'A license is required' })
698
+ * ```
699
+ */
700
+ function rulingDefinition(id, pass, rule, effect, input) {
701
+ return {
702
+ id,
703
+ pass,
704
+ rule,
705
+ effect,
706
+ ...input?.scope === void 0 ? {} : { scope: input.scope },
707
+ ...input?.message === void 0 ? {} : { message: input.message }
708
+ };
709
+ }
710
+ //#endregion
711
+ export { DEFAULT_QUALIFIER_VALIDATE, EFFECT_ELIGIBILITIES, ELIGIBILITY_PRECEDENCE, QUALIFICATION_KEY, Qualifier, QualifierError, assertSubject, combineEligibilities, createQualifier, deriveFindingEligibility, deriveScopeEligibilities, describeComparison, describePremise, describeValue, findDuplicateIds, findMissingReferences, findRule, hasReservedKey, interpolateMessage, isEligibility, isQualificationDefinition, isQualificationEffect, isQualificationPass, isQualifierError, isRuling, logicalPremises, mergeQualificationContext, premiseCheck, qualificationDefinition, qualificationToRecord, quantitativeResultToDerivation, reasonResultToProjection, rulingDefinition, rulingToFinding };
712
+
713
+ //# sourceMappingURL=index.js.map