@orkestrel/qualifier 0.0.25 → 0.0.27
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/README.md +1 -1
- package/dist/src/core/index.cjs +398 -300
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +261 -224
- package/dist/src/core/index.d.ts +261 -224
- package/dist/src/core/index.js +391 -294
- package/dist/src/core/index.js.map +1 -1
- package/package.json +17 -16
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["holds","INTRINSICS","isObject","isFunction","literalOf","whereOf","objectOf","isFieldPath","isString","isComparison","isCheckState","arrayOf","isNumber","isBoolean","isAuditFault","isQuantitativeDefinition","isLogicalDefinition","recordOf","isRecord","isJSONValue","isContractShape","resolveField","isFiniteNumber","isArray","isBounds","formatField","extractAtoms","extractConclusions","filterUniqueFaults","scanShapeReads","collectConcluders","findFieldShape","projectValue","isRecord","isReasonError","isError","objectShape","stringShape","literalShape","optionalShape","arrayShape","unionShape","quantitativeDefinitionShape","createLogicalDefinitionShape","recordShape","jsonShape","shapeShape","fieldPathShape","COMPARISONS","CHECK_STATES","nullableShape","numberShape","booleanShape","auditFaultShape","createContract","createSubjectDoor","Emitter","createReason","createQuantitativeReasoner","createLogicalReasoner","isRecord","isString","isArray","isContractShape","findDuplicates","scanShape","isReasonResult","describeFaults","filterUniqueFaults","createContract"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/shapers.ts","../../../src/core/contracts.ts","../../../src/core/Qualifier.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { Eligibility, QualificationEffect } from './types.js'\n\n/**\n * Holds the default definition validation policy for `createQualifier` and\n * `Qualifier.qualify`, `true`.\n */\nexport const DEFAULT_QUALIFIER_VALIDATE = true\n\n/**\n * Names `'qualification'`, the reserved internal projection namespace a pass's working\n * projection is written under.\n */\nexport const QUALIFICATION_KEY = 'qualification'\n\n/** Matches each `{{dotted.path}}` token of a message template, with the path as its one group. */\nexport const MESSAGE_TOKEN = /\\{\\{\\s*([^}]+?)\\s*\\}\\}/g\n\n/** Lists the eligibility outcomes. */\nexport const ELIGIBILITIES = ['eligible', 'ineligible', 'referral'] as const\n\n/** Lists the effects a ruling can carry. */\nexport const QUALIFICATION_EFFECTS = ['restriction', 'referral', 'condition'] as const\n\n/** Lists the eligibility severities most to least severe: `ineligible`, `referral`, `eligible`. */\nexport const ELIGIBILITY_PRECEDENCE: readonly Eligibility[] = Object.freeze([\n\t'ineligible',\n\t'referral',\n\t'eligible',\n])\n\n/**\n * Maps each {@link QualificationEffect} to its eligibility impact — `restriction` to\n * `ineligible`, `referral` to `referral`, and `condition` to `eligible`.\n */\nexport const EFFECT_ELIGIBILITIES: Readonly<Record<QualificationEffect, Eligibility>> =\n\tObject.freeze({\n\t\trestriction: 'ineligible',\n\t\treferral: 'referral',\n\t\tcondition: 'eligible',\n\t})\n","import type { QualifierErrorCode, QualifierErrorContext } from './types.js'\nimport { holds, INTRINSICS, isFunction, isObject } from '@orkestrel/contract'\n\n/**\n * Represents a coded programmer error thrown by the qualifier layer, carrying a\n * `QualifierErrorCode` and an optional context record.\n *\n * @remarks\n * `DEFINITION` — a qualification definition failed semantic validation; when\n * `qualify`'s own validation raises it, `context.definition` names the\n * definition, and when an engine throw maps to it, `context.pass` names the pass\n * and `context.cause` preserves the original throw. `MISMATCH` — a subject is\n * not a record or already carries the reserved `qualification` key.\n * `DESTROYED` — use of a destroyed qualifier; an engine-mapped one carries\n * `context.pass` and `context.cause`. `ENGINE` — the underlying reason engine\n * threw while running a pass; `context.pass` names the pass and `context.cause`\n * preserves the original throw. `context` is absent for a throw that carries no\n * payload.\n */\nexport class QualifierError extends Error {\n\treadonly code: QualifierErrorCode\n\treadonly context: QualifierErrorContext | undefined\n\n\tconstructor(code: QualifierErrorCode, message: string, context?: QualifierErrorContext) {\n\t\tsuper(message)\n\t\tINTRINSICS.define(this, Symbol.for('@orkestrel/qualifier.QualifierError'), { value: this })\n\t\tthis.name = 'QualifierError'\n\t\tthis.code = code\n\t\tthis.context = context\n\t}\n}\n\n/**\n * Narrows a caught value to a {@link QualifierError}.\n *\n * @param value - The caught value to test\n * @returns True if the error carries its own identity brand and declared members; false otherwise\n */\nexport function isQualifierError(value: unknown): value is QualifierError {\n\treturn holds(() => {\n\t\tif (!(value instanceof Error) || INTRINSICS.prototype(value) === Error.prototype) return false\n\t\tconst brand = INTRINSICS.describe(value, Symbol.for('@orkestrel/qualifier.QualifierError'))\n\t\tif (brand?.value !== value) return false\n\t\tconst code: unknown = INTRINSICS.reflect.read(value, 'code')\n\t\tif (code !== 'DEFINITION' && code !== 'MISMATCH' && code !== 'DESTROYED' && code !== 'ENGINE')\n\t\t\treturn false\n\t\tconst context: unknown = INTRINSICS.reflect.read(value, 'context')\n\t\tif (context === undefined) return true\n\t\tif (!isObject(context) && !isFunction(context)) return false\n\t\tconst pass: unknown = INTRINSICS.reflect.read(context, 'pass')\n\t\tconst definition: unknown = INTRINSICS.reflect.read(context, 'definition')\n\t\treturn (\n\t\t\t(pass === undefined || typeof pass === 'string') &&\n\t\t\t(definition === undefined || typeof definition === 'string')\n\t\t)\n\t})\n}\n","import type {\n\tDerivation,\n\tEligibility,\n\tFinding,\n\tPremise,\n\tQualificationDefinition,\n\tQualificationPass,\n\tQualificationResult,\n\tRuling,\n} from './types.js'\nimport {\n\tisAuditFault,\n\tarrayOf,\n\tisBoolean,\n\tisJSONValue,\n\tisNumber,\n\tisRecord,\n\tisString,\n\tliteralOf,\n\tobjectOf,\n\trecordOf,\n\twhereOf,\n} from '@orkestrel/contract'\nimport { ELIGIBILITIES, QUALIFICATION_EFFECTS } from './constants.js'\nimport {\n\tisCheckState,\n\tisComparison,\n\tisContractShape,\n\tisFieldPath,\n\tisLogicalDefinition,\n\tisQuantitativeDefinition,\n} from '@orkestrel/reason'\n\n/**\n * Determines whether a value is an {@link Eligibility} literal.\n *\n * @remarks\n * The guard is total and leaves nothing unchecked: a scalar union has no open or exact\n * axis.\n *\n * @param value - The value to test\n * @returns True if `value` is one of the eligibility literals; false otherwise\n */\nexport const isEligibility = literalOf(...ELIGIBILITIES)\n\n/**\n * Determines whether a value is a {@link QualificationEffect} literal.\n *\n * @remarks\n * The guard is total and leaves nothing unchecked: a scalar union has no open or exact\n * axis.\n *\n * @param value - The value to test\n * @returns True if `value` is one of the effect literals; false otherwise\n */\nexport const isQualificationEffect = literalOf(...QUALIFICATION_EFFECTS)\n\n/**\n * Determines whether a value is an open string-keyed record of {@link Eligibility} values.\n *\n * @remarks\n * Every own string-named value is checked through {@link isEligibility}, including\n * non-enumerable values. Inherited and symbol-named members are left unchecked because they\n * are outside the own string-keyed record this guard certifies.\n *\n * @param value - The value to test\n * @returns True if `value` is a non-array object whose own string-named values are\n * eligibilities; false otherwise\n */\nexport function isEligibilityRecord(\n\tvalue: unknown,\n): value is Readonly<Record<string, Eligibility>> {\n\treturn whereOf(objectOf({}), (record): record is Readonly<Record<string, Eligibility>> =>\n\t\tObject.getOwnPropertyNames(record).every((key) => isEligibility(Reflect.get(record, key))),\n\t)(value)\n}\n\n/**\n * Determines whether a value is an open result-side {@link Premise}.\n *\n * @remarks\n * The optional `field`, `label`, `description`, `comparison`, and `met` members are checked\n * when they are defined. `expected` is unchecked and may be absent or contain any value\n * because its published type is `unknown`. `actual` is unchecked and may be absent or contain\n * any value for the same reason. Unknown members are admitted, because an open result admits\n * what the published contract does not name.\n *\n * @param value - The value to test\n * @returns True if every checked premise member follows its published type; false otherwise\n */\nexport function isPremise(value: unknown): value is Premise {\n\treturn objectOf(\n\t\t{\n\t\t\tfield: isFieldPath,\n\t\t\tlabel: isString,\n\t\t\tdescription: isString,\n\t\t\tcomparison: isComparison,\n\t\t\tstate: isCheckState,\n\t\t},\n\t\t['field', 'label', 'description', 'comparison', 'state'],\n\t)(value)\n}\n\n/**\n * Determines whether a value is an open result-side {@link Finding}.\n *\n * @remarks\n * Every published member is checked, including each nested {@link Premise}. Optional `scope`\n * and `message` members may be absent or `undefined`; a present defined value must be a\n * string. Unknown members are admitted, because a foreign result implementation may add them\n * without changing the published contract.\n *\n * @param value - The value to test\n * @returns True if every published finding member is valid; false otherwise\n */\nexport function isFinding(value: unknown): value is Finding {\n\treturn objectOf(\n\t\t{\n\t\t\tid: isString,\n\t\t\tpass: isString,\n\t\t\trule: isString,\n\t\t\teffect: isQualificationEffect,\n\t\t\tscope: isString,\n\t\t\tstate: isCheckState,\n\t\t\tmessage: isString,\n\t\t\tpremises: arrayOf(isPremise),\n\t\t},\n\t\t['scope', 'message'],\n\t)(value)\n}\n\n/**\n * Determines whether a value is an open result-side {@link Derivation}.\n *\n * @remarks\n * Every published member is checked: `value` follows the published `number` type, including\n * `NaN` and the infinities, and `trace` and `errors` hold strings. Unknown members are\n * admitted, because a foreign result implementation may add them without changing the\n * published contract.\n *\n * @param value - The value to test\n * @returns True if every published derivation member is valid; false otherwise\n */\nexport function isDerivation(value: unknown): value is Derivation {\n\treturn objectOf({\n\t\tid: isString,\n\t\tvalue: isNumber,\n\t\tsuccess: isBoolean,\n\t\ttrace: arrayOf(isString),\n\t\terrors: arrayOf(isString),\n\t})(value)\n}\n\n/**\n * Determines whether a value is an open {@link QualificationResult} returned by a qualifier.\n *\n * @remarks\n * This guard is result-postured for values returned through a borrowed qualifier interface. It\n * checks the complete published result closure — eligibility, scope values, findings,\n * derivations, success, and the audit trail — and admits unknown members and class instances,\n * because a borrowed `QualifierInterface` implementation may add them beyond the\n * published contract.\n *\n * @param value - The value to test\n * @returns True if every published qualification-result member is valid; false otherwise\n */\nexport function isQualificationResult(value: unknown): value is QualificationResult {\n\treturn objectOf({\n\t\tid: isString,\n\t\tname: isString,\n\t\teligibility: isEligibility,\n\t\tscopes: isEligibilityRecord,\n\t\tfindings: arrayOf(isFinding),\n\t\tderivations: arrayOf(isDerivation),\n\t\tsuccess: isBoolean,\n\t\ttrace: arrayOf(isString),\n\t\terrors: arrayOf(isString),\n\t\tfaults: arrayOf(isAuditFault),\n\t\trepairs: arrayOf(isAuditFault),\n\t\tdefaulted: arrayOf(isFieldPath),\n\t})(value)\n}\n\n/**\n * Determines whether a value is a {@link QualificationPass} (a quantitative or logical definition).\n *\n * @remarks\n * The guard is exact and requires either complete reason shape, the quantitative definition or\n * the logical one. Nothing is left unchecked, because the reason package owns both authored\n * input shapes.\n *\n * @param value - The value to test\n * @returns True if `value` is a complete reason quantitative or logical definition; false otherwise\n */\nexport function isQualificationPass(value: unknown): value is QualificationPass {\n\treturn isQuantitativeDefinition(value) || isLogicalDefinition(value)\n}\n\n/**\n * Determines whether a value is an exact {@link Ruling} record.\n *\n * @remarks\n * Every authored ruling member and the complete key set are checked. Nothing is left\n * unchecked, because this package owns the authored input record.\n *\n * @param value - The value to test\n * @returns True if `value` carries every ruling member and no unknown key; false otherwise\n */\nexport function isRuling(value: unknown): value is Ruling {\n\treturn recordOf(\n\t\t{\n\t\t\tid: isString,\n\t\t\tpass: isString,\n\t\t\trule: isString,\n\t\t\teffect: isQualificationEffect,\n\t\t\tscope: isString,\n\t\t\tmessage: isString,\n\t\t},\n\t\t['scope', 'message'],\n\t)(value)\n}\n\n/**\n * Determines whether a value is a definition's `metadata`: a record of JSON values.\n *\n * @param value - The value to test\n * @returns True for a record whose every value is JSON; false otherwise\n *\n * @example\n * ```ts\n * import { isDefinitionMetadata } from '@orkestrel/qualifier'\n *\n * isDefinitionMetadata({ a: 1 }) // true\n * isDefinitionMetadata({ a: Number.NaN }) // false\n * ```\n */\nexport const isDefinitionMetadata = whereOf(isRecord, (record) =>\n\tObject.values(record).every(isJSONValue),\n)\n\n/**\n * Determines whether a value is an exact {@link QualificationDefinition} record.\n *\n * @remarks\n * Every authored definition member, the nested pass and ruling shapes, and the complete key\n * set are checked. Nothing is left unchecked, because this package owns the authored input\n * record.\n *\n * @param value - The value to test\n * @returns True if `value` carries every definition member and no unknown key; false otherwise\n */\nexport function isQualificationDefinition(value: unknown): value is QualificationDefinition {\n\treturn recordOf(\n\t\t{\n\t\t\tid: isString,\n\t\t\tname: isString,\n\t\t\tdescription: isString,\n\t\t\tpasses: arrayOf(isQualificationPass),\n\t\t\trulings: arrayOf(isRuling),\n\t\t\tmetadata: isDefinitionMetadata,\n\t\t\tshape: isContractShape,\n\t\t},\n\t\t['description', 'rulings', 'metadata', 'shape'],\n\t)(value)\n}\n","import type { AuditFault, FieldPath, JSONValue } from '@orkestrel/contract'\nimport type {\n\tDerivation,\n\tEligibility,\n\tFinding,\n\tPremise,\n\tQualificationContext,\n\tQualificationDefinition,\n\tQualificationPass,\n\tQualificationProjection,\n\tQualificationResult,\n\tRuling,\n} from './types.js'\nimport type {\n\tCheck,\n\tCheckResult,\n\tLogicalDefinition,\n\tLogicalResult,\n\tQuantitativeResult,\n\tReasonResult,\n\tRule,\n\tRuleResult,\n\tShapeScan,\n\tSubject,\n} from '@orkestrel/reason'\nimport {\n\tEFFECT_ELIGIBILITIES,\n\tELIGIBILITY_PRECEDENCE,\n\tMESSAGE_TOKEN,\n\tQUALIFICATION_KEY,\n} from './constants.js'\nimport { QualifierError } from './errors.js'\nimport { isArray, isError, isFiniteNumber, isRecord, resolveField } from '@orkestrel/contract'\nimport {\n\textractAtoms,\n\textractConclusions,\n\tfilterUniqueFaults,\n\tcollectConcluders,\n\tfindFieldShape,\n\tformatField,\n\tisBounds,\n\tisReasonError,\n\tprojectValue,\n\tscanShapeReads,\n} from '@orkestrel/reason'\n\n/**\n * Interpolates `{{dotted.path}}` tokens in a message template against a subject.\n *\n * @remarks\n * Each token is split on `.` into a `FieldPath` array and resolved with\n * `resolveField` (a plain string field is one key, never dot-split — the split\n * here is the token-to-path bridge). A finite number renders with `en-US`\n * thousand grouping (`5010` → `5,010`); any other resolved value String-coerces.\n * An unresolved path renders as the empty string.\n *\n * @param template - The message template carrying `{{dotted.path}}` tokens\n * @param subject - The record tokens resolve against\n * @returns The template with every token replaced\n *\n * @example\n * ```ts\n * import { interpolateMessage } from '@orkestrel/qualifier'\n *\n * interpolateMessage('Limit is {{limit}}', { limit: 5010 }) // 'Limit is 5,010'\n * interpolateMessage('Missing {{gone}}', {}) // 'Missing '\n * ```\n */\nexport function interpolateMessage(\n\ttemplate: string,\n\tsubject: Readonly<Record<string, unknown>>,\n): string {\n\treturn template.replace(MESSAGE_TOKEN, (_match, path: string) => {\n\t\tconst value = resolveField(subject, path.split('.'))\n\t\tif (value === undefined) return ''\n\t\tif (isFiniteNumber(value)) return value.toLocaleString('en-US')\n\t\treturn String(value)\n\t})\n}\n\n/**\n * Finds the `{{dotted.path}}` tokens a message template reads.\n *\n * @param template - The message template\n * @returns Each token's dotted path, trimmed, in order, repeats included\n *\n * @example\n * ```ts\n * import { findMessageTokens } from '@orkestrel/qualifier'\n *\n * findMessageTokens('Age {{ age }} in {{home.city}}') // ['age', 'home.city']\n * ```\n */\nexport function findMessageTokens(template: string): readonly string[] {\n\treturn [...template.matchAll(MESSAGE_TOKEN)].map((match) => match[1] ?? '')\n}\n\n/**\n * Renders a {@link Premise} comparison as a display-neutral verb phrase.\n *\n * @param comparison - The comparison to describe\n * @returns A display-neutral phrase\n *\n * @example\n * ```ts\n * import { renderComparison } from '@orkestrel/qualifier'\n *\n * renderComparison('above') // 'is more than'\n * ```\n */\nexport function renderComparison(comparison: NonNullable<Premise['comparison']>): string {\n\tswitch (comparison) {\n\t\tcase 'equals':\n\t\t\treturn 'is'\n\t\tcase 'not':\n\t\t\treturn 'is not'\n\t\tcase 'above':\n\t\t\treturn 'is more than'\n\t\tcase 'below':\n\t\t\treturn 'is less than'\n\t\tcase 'from':\n\t\t\treturn 'is at least'\n\t\tcase 'to':\n\t\t\treturn 'is at most'\n\t\tcase 'any':\n\t\t\treturn 'is any of'\n\t\tcase 'none':\n\t\t\treturn 'is none of'\n\t\tcase 'between':\n\t\t\treturn 'is between'\n\t\tcase 'outside':\n\t\t\treturn 'is outside'\n\t}\n}\n\n/**\n * Renders a structured or scalar expected value display-neutrally.\n *\n * @remarks\n * An array renders as its elements, each `String`-coerced, joined with `', '`.\n * A reason `Bounds`-shaped record (the `between` / `outside` expected value)\n * renders its present sides joined with the word `and`; an absent side is\n * omitted. A finite number and everything else fall back to plain `String()` —\n * a finite number is not grouped here (grouping is {@link interpolateMessage}'s\n * message-token-only behavior).\n *\n * @param value - The value to render\n * @returns A display-neutral rendering\n *\n * @example\n * ```ts\n * import { renderValue } from '@orkestrel/qualifier'\n *\n * renderValue([18, 25, 40]) // '18, 25, 40'\n * renderValue({ minimum: 18, maximum: 65 }) // '18 and 65'\n * renderValue(42) // '42'\n * ```\n */\nexport function renderValue(value: unknown): string {\n\tif (isArray(value)) return value.map((entry) => String(entry)).join(', ')\n\tif (isBounds(value)) {\n\t\tconst sides: string[] = []\n\t\tif (value.minimum !== undefined) sides.push(String(value.minimum))\n\t\tif (value.maximum !== undefined) sides.push(String(value.maximum))\n\t\treturn sides.join(' and ')\n\t}\n\treturn String(value)\n}\n\n/**\n * Renders one {@link Premise} into a display-neutral sentence.\n *\n * @remarks\n * The checked form renders only when `field` and `comparison` are both\n * present, and `description` then goes unused; a premise missing either half\n * of the checked pair renders as described instead.\n *\n * @param entry - The premise to render\n * @param labels - Optional field-to-label overrides, keyed by dot-joined field\n * @returns A display-neutral sentence\n *\n * @example\n * ```ts\n * import { renderPremise } from '@orkestrel/qualifier'\n *\n * renderPremise({ field: 'age', comparison: 'above', expected: 18, actual: 25, state: 'met' })\n * // 'age is more than 18 → met'\n *\n * renderPremise({ description: 'Applicant is enrolled', state: 'met' })\n * // 'Applicant is enrolled → met'\n * ```\n */\nexport function renderPremise(entry: Premise, labels?: Readonly<Record<string, string>>): string {\n\tconst status = entry.state === 'met' ? 'met' : entry.state === 'unmet' ? 'not met' : 'unknown'\n\tif (entry.field === undefined || entry.comparison === undefined) {\n\t\treturn `${entry.description ?? 'Premise'} → ${status}`\n\t}\n\tconst field = formatField(entry.field)\n\tconst label = labels?.[field] ?? entry.label ?? field\n\tconst expected = entry.expected === undefined ? '' : ` ${renderValue(entry.expected)}`\n\treturn `${label} ${renderComparison(entry.comparison)}${expected} → ${status}`\n}\n\n/**\n * Builds a {@link Premise} from an authored {@link Check} and its evaluated\n * `CheckResult`.\n *\n * @param check - The authored check\n * @param result - The evaluated check result carrying the resolved `actual` and `state`\n * @param labels - Optional field-to-label overrides, keyed by dot-joined field\n * @returns A fresh premise\n *\n * @example\n * ```ts\n * import { checkToPremise } from '@orkestrel/qualifier'\n * import { createCheck } from '@orkestrel/reason'\n *\n * const authored = createCheck('age', 'above', 18)\n * checkToPremise(authored, { field: 'age', actual: 25, state: 'met' })\n * // { field: 'age', comparison: 'above', expected: 18, actual: 25, state: 'met' }\n * ```\n */\nexport function checkToPremise(\n\tcheck: Check,\n\tresult: CheckResult,\n\tlabels?: Readonly<Record<string, string>>,\n): Premise {\n\tconst field = formatField(check.field)\n\treturn {\n\t\tfield: check.field,\n\t\t...(labels?.[field] === undefined ? {} : { label: labels[field] }),\n\t\tcomparison: check.operator,\n\t\texpected: check.value,\n\t\tactual: result.actual,\n\t\tstate: result.state,\n\t}\n}\n\n/**\n * Builds rich premises for one fired {@link Rule} by walking its premise atoms\n * and reading each from what the rule read.\n *\n * @remarks\n * Each authored premise expression is flattened to its atom leaves through `extractAtoms`,\n * which lines up with the `checks` the rule result carries, so a premise cannot disagree with\n * the pass. A rule with no result never ran, so its premises carry no `state` or `actual`.\n *\n * @param rule - The authored rule\n * @param resolved - The rule's result, absent when it never ran\n * @param labels - Optional field-to-label overrides, keyed by dot-joined field\n * @returns A fresh, ordered list of rich premises\n *\n * @example\n * ```ts\n * import { ruleToPremises } from '@orkestrel/qualifier'\n * import { createAtom, createRule } from '@orkestrel/reason'\n *\n * const rule = createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true))\n * const resolved = {\n * id: 'licensed',\n * state: 'met' as const,\n * premises: ['met' as const],\n * checks: [{ field: 'licensed', state: 'met' as const, actual: false }],\n * }\n * ruleToPremises(rule, resolved)[0]?.state // 'met'\n * ```\n */\nexport function ruleToPremises(\n\trule: Rule,\n\tresolved: RuleResult | undefined,\n\tlabels?: Readonly<Record<string, string>>,\n): readonly Premise[] {\n\treturn rule.premises\n\t\t.flatMap((premise) => extractAtoms(premise))\n\t\t.map((atom, index) => {\n\t\t\tconst read = resolved?.checks[index]\n\t\t\tif (read !== undefined) return checkToPremise(atom.check, read, labels)\n\t\t\tconst {\n\t\t\t\tstate: _state,\n\t\t\t\tactual: _actual,\n\t\t\t\t...unrun\n\t\t\t} = checkToPremise(\n\t\t\t\tatom.check,\n\t\t\t\t{ field: atom.check.field, state: 'unread', actual: undefined },\n\t\t\t\tlabels,\n\t\t\t)\n\t\t\treturn unrun\n\t\t})\n}\n\n/**\n * Locates an authored {@link Rule} by id.\n *\n * @param definition - The logical definition to search\n * @param id - The rule id\n * @returns The matching rule, or `undefined`\n *\n * @example\n * ```ts\n * import { findRule } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const gates = createLogicalDefinition('gates', 'Gates', [\n * createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true)),\n * ])\n *\n * findRule(gates, 'licensed')?.id // 'licensed'\n * ```\n */\nexport function findRule(definition: LogicalDefinition, id: string): Rule | undefined {\n\treturn definition.rules.find((rule) => rule.id === id)\n}\n\n/**\n * Projects one reason result into the internal qualification namespace.\n *\n * @remarks\n * A quantitative result contributes its numeric `value`. A logical result\n * contributes a record of its `conclusion` plus every applied rule's asserted\n * conclusion fields (`extractConclusions`). A mismatched pairing contributes\n * `false`. The projection is pure — it never mutates the subject or the result.\n *\n * @param definition - The pass definition that produced the result\n * @param result - The evaluated reason result\n * @returns The pass's working projection\n *\n * @example\n * ```ts\n * import { reasonResultToProjection } from '@orkestrel/qualifier'\n * import { createFactorGroup, createQuantitativeDefinition, createStaticFactor } from '@orkestrel/reason'\n *\n * const cap = createQuantitativeDefinition('cap', 'TIV cap', [\n * createFactorGroup('limit', 'sum', [createStaticFactor('base', 500_000)]),\n * ])\n * const result = {\n * reasoning: 'quantitative' as const,\n * value: 500_000,\n * groups: [],\n * count: 1,\n * success: true,\n * trace: [],\n * errors: [],\n * }\n * reasonResultToProjection(cap, result) // 500000\n * ```\n */\nexport function reasonResultToProjection(\n\tdefinition: QualificationPass,\n\tresult: ReasonResult,\n): QualificationProjection {\n\tif (definition.reasoning === 'quantitative' && result.reasoning === 'quantitative') {\n\t\treturn result.value\n\t}\n\tif (definition.reasoning !== 'logical' || result.reasoning !== 'logical') return false\n\t// An unfired rule's keys read false first, so a key another rule fired keeps that rule's value,\n\t// and the pass's own conclusion goes last, so no rule can stand in for it.\n\tconst fields = ['unmet', 'met'].flatMap((state) =>\n\t\tresult.rules\n\t\t\t.filter((resolved) => resolved.state === state)\n\t\t\t.flatMap((resolved) => {\n\t\t\t\tconst authored = definition.rules.find((rule) => rule.id === resolved.id)\n\t\t\t\tif (authored === undefined) return []\n\t\t\t\treturn Object.entries(extractConclusions(authored.conclusion)).map(\n\t\t\t\t\t([key, value]): readonly [string, unknown] => [key, state === 'met' ? value : false],\n\t\t\t\t)\n\t\t\t}),\n\t)\n\treturn Object.fromEntries([...fields, ['conclusion', result.conclusion === 'met']])\n}\n\n/**\n * Replaces a read of an unread pass's projection with what that pass could not read.\n *\n * @remarks\n * A pass reading `qualification.gates.blocked` is unread because `gates` projected nothing, so\n * the question to ask is the one `gates` could not answer. A read of a pass that settled stays,\n * because that pass holds no such key. Passes run in order and each stores its expanded faults,\n * so a chain of unread passes reaches the input that started it.\n *\n * @param faults - The faults every pass reported, in order\n * @param unread - The faults of each unread pass, by pass id\n * @returns The input faults, once per field\n *\n * @example\n * ```ts\n * import { expandPassFaults } from '@orkestrel/qualifier'\n *\n * const leaf = { reason: 'missing', path: 'age', expected: 'number' } as const\n * const read = { reason: 'missing', path: ['qualification', 'gates', 'ok'], expected: 'boolean' } as const\n * expandPassFaults([read], new Map([['gates', [leaf]]])) // [leaf]\n * ```\n */\nexport function expandPassFaults(\n\tfaults: readonly AuditFault[],\n\tunread: ReadonlyMap<string, readonly AuditFault[]>,\n): readonly AuditFault[] {\n\treturn filterUniqueFaults(\n\t\tfaults.flatMap((fault) => {\n\t\t\t// A projection is read through an array path, and its second key is the pass id whole.\n\t\t\tconst { path } = fault\n\t\t\tif (!isArray(path) || path[0] !== QUALIFICATION_KEY) return [fault]\n\t\t\treturn unread.get(path[1] ?? '') ?? [fault]\n\t\t}),\n\t)\n}\n\n/**\n * Describes what the definition's shape cannot stand for: a read of a field it does not declare,\n * and the reserved `qualification` key, which a default could otherwise fill.\n *\n * @remarks\n * A read under `qualification` reads a pass's projection, and a pass's own conclusion keys are\n * its own, so neither needs a declaration. A host that projects a key of its own names it in\n * `projections`. A `raw` or `json` read is a warning.\n *\n * @param definition - The definition\n * @param projections - Further keys the host projects onto the subject. Default: none\n * @returns The errors and warnings, empty with no shape\n *\n * @example\n * ```ts\n * import { numberShape, objectShape } from '@orkestrel/contract'\n * import { createQualificationDefinition, scanDefinitionShape } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const pass = createLogicalDefinition('gates', 'Gates', [\n * createRule('r', [createAtom('agee', 'above', 1)], createAtom('ok', 'equals', true)),\n * ])\n * const shape = objectShape({ age: numberShape() })\n * scanDefinitionShape(createQualificationDefinition('d', 'd', [pass], { shape })).errors.length // 1\n * ```\n */\nexport function scanDefinitionShape(\n\tdefinition: QualificationDefinition,\n\tprojections: readonly string[] = [],\n): ShapeScan {\n\tconst { shape } = definition\n\tif (shape === undefined) return { errors: [], warnings: [] }\n\tconst scans = definition.passes.map((pass) => {\n\t\tif (pass.reasoning === 'logical') {\n\t\t\tconst enabled = pass.rules.filter((rule) => rule.enabled !== false)\n\t\t\tconst checks = enabled\n\t\t\t\t.flatMap((rule) => rule.premises.flatMap((premise) => extractAtoms(premise)))\n\t\t\t\t.map((atom) => atom.check)\n\t\t\t\t.filter((check) => !readsProjection(check.field, projections))\n\t\t\treturn scanShapeReads(shape, checks, [], new Set(collectConcluders(enabled).keys()))\n\t\t}\n\t\tconst factors = pass.groups.flatMap((group) => group.factors)\n\t\treturn scanShapeReads(\n\t\t\tshape,\n\t\t\tfactors\n\t\t\t\t.flatMap((factor) => factor.checks ?? [])\n\t\t\t\t.filter((check) => !readsProjection(check.field, projections)),\n\t\t\tfactors\n\t\t\t\t.flatMap((factor) => (factor.source.origin === 'static' ? [] : [factor.source.field]))\n\t\t\t\t.filter((field) => !readsProjection(field, projections)),\n\t\t\tnew Set(),\n\t\t)\n\t})\n\treturn {\n\t\terrors: [\n\t\t\t...(findFieldShape(shape, QUALIFICATION_KEY).shape === undefined\n\t\t\t\t? []\n\t\t\t\t: [`Shape declares the reserved key '${QUALIFICATION_KEY}'`]),\n\t\t\t...new Set(scans.flatMap((scan) => scan.errors)),\n\t\t],\n\t\twarnings: [...new Set(scans.flatMap((scan) => scan.warnings))],\n\t}\n}\n\n/**\n * Determines whether a field reads a pass's projection under `qualification`, or a key the host projects.\n *\n * @param field - The field\n * @param projections - Further keys the host projects onto the subject. Default: none\n * @returns True for an array path starting at the reserved key or a projected key; false otherwise\n *\n * @example\n * ```ts\n * import { readsProjection } from '@orkestrel/qualifier'\n *\n * readsProjection(['qualification', 'gates', 'ok']) // true\n * readsProjection(['aggregate', 'count'], ['aggregate']) // true\n * readsProjection('age') // false\n * ```\n */\nexport function readsProjection(field: FieldPath, projections: readonly string[] = []): boolean {\n\tif (!isArray(field)) return false\n\tconst key = field[0]\n\treturn key === QUALIFICATION_KEY || (key !== undefined && projections.includes(key))\n}\n\n/**\n * Describes each rule concluding `conclusion`, which a pass's projection reserves for itself.\n *\n * @param definition - The definition\n * @returns One message per such rule\n *\n * @example\n * ```ts\n * import { createQualificationDefinition, describeReservedConclusions } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const pass = createLogicalDefinition('gates', 'Gates', [\n * createRule('r', [createAtom('a', 'equals', 1)], createAtom('conclusion', 'equals', true)),\n * ])\n * describeReservedConclusions(createQualificationDefinition('d', 'd', [pass])).length // 1\n * ```\n */\nexport function describeReservedConclusions(\n\tdefinition: QualificationDefinition,\n): readonly string[] {\n\treturn definition.passes.flatMap((pass) =>\n\t\tpass.reasoning !== 'logical'\n\t\t\t? []\n\t\t\t: pass.rules\n\t\t\t\t\t.filter((rule) => Object.hasOwn(extractConclusions(rule.conclusion), 'conclusion'))\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(rule) =>\n\t\t\t\t\t\t\t`Rule '${rule.id}' in pass '${pass.id}' concludes the reserved key 'conclusion'`,\n\t\t\t\t\t),\n\t)\n}\n\n/**\n * Determines whether a logical result holds a rule left unread.\n *\n * @param result - The result of a pass\n * @returns True when a logical result holds such a rule; false otherwise\n *\n * @example\n * ```ts\n * import { hasUnreadRule } from '@orkestrel/qualifier'\n *\n * const rule = { id: 'r', state: 'unread' as const, premises: [], checks: [] }\n * hasUnreadRule({\n * reasoning: 'logical',\n * conclusion: 'unread',\n * rules: [rule],\n * count: 0,\n * success: false,\n * trace: [],\n * errors: [],\n * faults: [],\n * repairs: [],\n * defaulted: [],\n * }) // true\n * ```\n */\nexport function hasUnreadRule(result: ReasonResult): boolean {\n\treturn result.reasoning === 'logical' && result.rules.some((rule) => rule.state === 'unread')\n}\n\n/**\n * Describes each message token no field of the definition's shape answers.\n *\n * @remarks\n * A token under `qualification` reads a pass's projection, which no shape declares.\n *\n * @param definition - The definition\n * @returns One message per unknown token, empty with no shape\n *\n * @example\n * ```ts\n * import { numberShape, objectShape } from '@orkestrel/contract'\n * import { createQualificationDefinition, createRuling, describeUnknownTokens } from '@orkestrel/qualifier'\n *\n * const ruling = createRuling('r', 'gates', 'licensed', 'referral', { message: 'Age {{agee}}' })\n * const shape = objectShape({ age: numberShape() })\n * describeUnknownTokens(createQualificationDefinition('d', 'd', [], { rulings: [ruling], shape }))\n * // ['Ruling \\'r\\' message reads \"agee\", and the shape does not declare it']\n * ```\n */\nexport function describeUnknownTokens(definition: QualificationDefinition): readonly string[] {\n\tconst { shape } = definition\n\tif (shape === undefined) return []\n\treturn (definition.rulings ?? []).flatMap((ruling) =>\n\t\tfindMessageTokens(ruling.message ?? '').flatMap((token) => {\n\t\t\tconst path = token.split('.')\n\t\t\tif (path[0] === QUALIFICATION_KEY || findFieldShape(shape, path).declared) return []\n\t\t\treturn [`Ruling '${ruling.id}' message reads \"${token}\", and the shape does not declare it`]\n\t\t}),\n\t)\n}\n\n/**\n * Projects a result to the JSON its contract reads.\n *\n * @remarks\n * A premise's `actual` holds whatever the subject held and a derivation's `value` may be `NaN`,\n * so a result crosses a boundary as this projection, each `actual` on its own budget.\n *\n * @param result - The qualification result\n * @returns Its JSON projection, which `qualificationResultContract` admits\n *\n * @example\n * ```ts\n * import { createQualificationDefinition, createQualifier, projectQualificationResult, qualificationResultContract } from '@orkestrel/qualifier'\n *\n * const qualifier = createQualifier()\n * const result = qualifier.qualify({}, createQualificationDefinition('d', 'd', []))\n * qualificationResultContract.is(projectQualificationResult(result)) // true\n * qualifier.destroy()\n * ```\n */\nexport function projectQualificationResult(result: QualificationResult): JSONValue | undefined {\n\tconst findings = result.findings.map((finding) => ({\n\t\t...finding,\n\t\tpremises: finding.premises.map((premise) => ({\n\t\t\t...premise,\n\t\t\tactual: projectValue(premise.actual),\n\t\t})),\n\t}))\n\treturn projectValue({ ...result, findings }, new Set(), { left: Number.POSITIVE_INFINITY })\n}\n\n/**\n * Projects a quantitative result into a {@link Derivation} audit record.\n *\n * @param id - The pass id\n * @param result - The evaluated quantitative result\n * @returns A fresh derivation\n *\n * @example\n * ```ts\n * import { quantitativeResultToDerivation } from '@orkestrel/qualifier'\n *\n * const result = { reasoning: 'quantitative' as const, value: 500_000, groups: [], count: 1, success: true, trace: ['cap: 500000'], errors: [] }\n * quantitativeResultToDerivation('cap', result)\n * // { id: 'cap', value: 500000, success: true, trace: ['cap: 500000'], errors: [] }\n * ```\n */\nexport function quantitativeResultToDerivation(id: string, result: QuantitativeResult): Derivation {\n\treturn {\n\t\tid,\n\t\tvalue: result.value,\n\t\tsuccess: result.success,\n\t\ttrace: [...result.trace],\n\t\terrors: [...result.errors],\n\t}\n}\n\n/**\n * Wraps a {@link QualificationContext} under {@link QUALIFICATION_KEY}.\n *\n * @param context - The accumulated projection context\n * @returns A record carrying the context under the reserved key\n *\n * @example\n * ```ts\n * import { qualificationToRecord } from '@orkestrel/qualifier'\n *\n * qualificationToRecord({ cap: 500_000 }) // { qualification: { cap: 500000 } }\n * ```\n */\nexport function qualificationToRecord(\n\tcontext: QualificationContext,\n): Readonly<Record<string, QualificationContext>> {\n\treturn { [QUALIFICATION_KEY]: context }\n}\n\n/**\n * Merges one pass projection into the context, copy-on-write.\n *\n * @param context - The current projection context\n * @param id - The pass id to project under\n * @param projection - The pass's working projection\n * @returns A fresh context with the projection added\n *\n * @example\n * ```ts\n * import { mergeQualificationContext } from '@orkestrel/qualifier'\n *\n * mergeQualificationContext({ cap: 500_000 }, 'excess', 250_000)\n * // { cap: 500000, excess: 250000 }\n * ```\n */\nexport function mergeQualificationContext(\n\tcontext: QualificationContext,\n\tid: string,\n\tprojection: QualificationProjection,\n): QualificationContext {\n\treturn { ...context, [id]: projection }\n}\n\n/**\n * Joins a ruling, its logical rule result, the pass, and the pre-projection subject into a\n * {@link Finding}.\n *\n * @remarks\n * `state` is the state of the ruling's rule. A rule the result omits reads `unmet` when it is\n * disabled, which is authored, and `unread` otherwise, because a refused pass evaluated no rule.\n * Premises come from what the rule read. The message interpolates against the subject.\n *\n * @param ruling - The authored ruling\n * @param pass - The pass the ruling's rule lives in\n * @param result - The pass's evaluated logical result\n * @param subject - The pre-projection subject snapshot the pass evaluated\n * @param labels - Optional field-to-label overrides, keyed by dot-joined field\n * @returns A fresh finding\n *\n * @example\n * ```ts\n * import { rulingToFinding } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const gates = createLogicalDefinition('gates', 'Gates', [\n * createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true)),\n * ])\n * const ruling = { id: 'license', pass: 'gates', rule: 'licensed', effect: 'restriction' as const }\n * const result = {\n * reasoning: 'logical' as const,\n * conclusion: 'met' as const,\n * rules: [{ id: 'licensed', state: 'met' as const, premises: ['met' as const], checks: [] }],\n * count: 1,\n * success: true,\n * trace: [],\n * errors: [],\n * faults: [],\n * repairs: [],\n * defaulted: [],\n * }\n * rulingToFinding(ruling, gates, result, { licensed: false }).state // 'met'\n * ```\n */\nexport function rulingToFinding(\n\truling: Ruling,\n\tpass: QualificationPass,\n\tresult: LogicalResult,\n\tsubject: Subject,\n\tlabels?: Readonly<Record<string, string>>,\n): Finding {\n\tconst entry = result.rules.find((resolved) => resolved.id === ruling.rule)\n\tconst rule = pass.reasoning === 'logical' ? findRule(pass, ruling.rule) : undefined\n\tconst premises = rule === undefined ? [] : ruleToPremises(rule, entry, labels)\n\treturn {\n\t\tid: ruling.id,\n\t\tpass: ruling.pass,\n\t\trule: ruling.rule,\n\t\teffect: ruling.effect,\n\t\t...(ruling.scope === undefined ? {} : { scope: ruling.scope }),\n\t\t// A disabled rule is authored not to fire. Any other rule missing here was never evaluated.\n\t\tstate: entry?.state ?? (rule?.enabled === false ? 'unmet' : 'unread'),\n\t\t...(ruling.message === undefined\n\t\t\t? {}\n\t\t\t: { message: interpolateMessage(ruling.message, subject) }),\n\t\tpremises,\n\t}\n}\n\n/**\n * Derives global eligibility from unscoped findings whose rule is met.\n *\n * @remarks\n * Only findings that are `met` and carry no `scope` shape global eligibility.\n * A failed pass contributes a synthetic `referral` (fail-closed), passed through\n * `failed`.\n *\n * @param findings - The resolved findings\n * @param failed - If `true`, adds a synthetic `referral` impact so an operational failure\n * fails closed; if `false`, derives eligibility from the findings alone. Default: `false`\n * @returns The most severe global eligibility\n *\n * @example\n * ```ts\n * import { deriveFindingEligibility } from '@orkestrel/qualifier'\n *\n * const finding = { id: 'license', pass: 'gates', rule: 'licensed', effect: 'restriction' as const, state: 'met' as const, premises: [] }\n * deriveFindingEligibility([finding]) // 'ineligible'\n * ```\n */\nexport function deriveFindingEligibility(\n\tfindings: readonly Finding[],\n\tfailed = false,\n): Eligibility {\n\tconst eligibilities = findings\n\t\t.filter((finding) => finding.state === 'met' && finding.scope === undefined)\n\t\t.map((finding) => EFFECT_ELIGIBILITIES[finding.effect])\n\tif (failed) eligibilities.push('referral')\n\treturn combineEligibilities(eligibilities)\n}\n\n/**\n * Returns the most severe {@link Eligibility} in a list.\n *\n * @param eligibilities - The eligibilities to combine\n * @returns The most severe eligibility, or `'eligible'` for an empty list\n *\n * @example\n * ```ts\n * import { combineEligibilities } from '@orkestrel/qualifier'\n *\n * combineEligibilities(['eligible', 'referral']) // 'referral'\n * ```\n */\nexport function combineEligibilities(eligibilities: readonly Eligibility[]): Eligibility {\n\tfor (const eligibility of ELIGIBILITY_PRECEDENCE) {\n\t\tif (eligibilities.includes(eligibility)) return eligibility\n\t}\n\treturn 'eligible'\n}\n\n/**\n * Derives one eligibility per finding scope.\n *\n * @remarks\n * Only scoped findings that are `met` contribute. Each named scope combines its own\n * findings' impacts by severity. An unmentioned scope is absent (eligible by\n * default at the program layer).\n *\n * @param findings - The resolved findings\n * @returns A fresh record of scope to its combined eligibility\n *\n * @example\n * ```ts\n * import { deriveScopeEligibilities } from '@orkestrel/qualifier'\n *\n * const finding = { id: 'coastal', pass: 'wind', rule: 'coastal', effect: 'restriction' as const, scope: 'wind', state: 'met' as const, premises: [] }\n * deriveScopeEligibilities([finding]) // { wind: 'ineligible' }\n * ```\n */\nexport function deriveScopeEligibilities(\n\tfindings: readonly Finding[],\n): Readonly<Record<string, Eligibility>> {\n\t// A Map, because a scope may be named `constructor` or `__proto__`.\n\tconst grouped = new Map<string, Eligibility[]>()\n\tfor (const finding of findings) {\n\t\tif (finding.state !== 'met' || finding.scope === undefined) continue\n\t\tconst current = grouped.get(finding.scope) ?? []\n\t\tgrouped.set(finding.scope, [...current, EFFECT_ELIGIBILITIES[finding.effect]])\n\t}\n\treturn Object.fromEntries(\n\t\t[...grouped].map(([scope, eligibilities]) => [scope, combineEligibilities(eligibilities)]),\n\t)\n}\n\n/**\n * Describes each ruling whose pass or rule does not exist or whose pass is not\n * logical, and each pass id shadowing the reserved {@link QUALIFICATION_KEY}.\n *\n * @param definition - The qualification definition to check\n * @returns A fresh list of reference-error messages\n *\n * @example\n * ```ts\n * import { createQualificationDefinition, createRuling, describeMissingReferences } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const gates = createLogicalDefinition('gates', 'Gates', [\n * createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true)),\n * ])\n * const definition = createQualificationDefinition('standard', 'Standard', [gates], {\n * rulings: [createRuling('license', 'gates', 'absent', 'restriction')],\n * })\n *\n * describeMissingReferences(definition)\n * // [\"Ruling 'license' references missing rule 'absent' in pass 'gates'\"]\n * ```\n */\nexport function describeMissingReferences(definition: QualificationDefinition): readonly string[] {\n\tconst errors: string[] = []\n\tconst passes = new Map(definition.passes.map((pass) => [pass.id, pass]))\n\tfor (const pass of definition.passes) {\n\t\tif (pass.id === QUALIFICATION_KEY) {\n\t\t\terrors.push(`Pass id must not equal reserved key '${QUALIFICATION_KEY}'`)\n\t\t}\n\t}\n\tfor (const ruling of definition.rulings ?? []) {\n\t\tconst pass = passes.get(ruling.pass)\n\t\tif (pass === undefined) {\n\t\t\terrors.push(`Ruling '${ruling.id}' references missing pass '${ruling.pass}'`)\n\t\t\tcontinue\n\t\t}\n\t\tif (pass.reasoning !== 'logical') {\n\t\t\terrors.push(`Ruling '${ruling.id}' references non-logical pass '${ruling.pass}'`)\n\t\t\tcontinue\n\t\t}\n\t\tif (findRule(pass, ruling.rule) === undefined) {\n\t\t\terrors.push(\n\t\t\t\t`Ruling '${ruling.id}' references missing rule '${ruling.rule}' in pass '${ruling.pass}'`,\n\t\t\t)\n\t\t}\n\t}\n\treturn errors\n}\n\n/**\n * Determines whether a subject already owns the reserved {@link QUALIFICATION_KEY}.\n *\n * @param subject - The subject to check\n * @returns True if the subject owns the reserved key; false otherwise\n *\n * @example\n * ```ts\n * import { hasReservedKey } from '@orkestrel/qualifier'\n *\n * hasReservedKey({ id: 's1', qualification: {} }) // true\n * ```\n */\nexport function hasReservedKey(subject: Subject): boolean {\n\treturn Object.hasOwn(subject, QUALIFICATION_KEY)\n}\n\n/**\n * Asserts a value is a valid qualification {@link Subject}, narrowing it in place.\n *\n * @param value - The candidate subject to validate\n * @throws {@link QualifierError} `'MISMATCH'` when the value is not a record, or\n * when it already carries the reserved `qualification` key\n *\n * @example\n * ```ts\n * import { assertSubject } from '@orkestrel/qualifier'\n *\n * assertSubject({ id: 's1' }) // narrows to Subject\n * ```\n */\nexport function assertSubject(value: unknown): asserts value is Subject {\n\tif (!isRecord(value)) {\n\t\tthrow new QualifierError('MISMATCH', 'Qualification subject must be a record')\n\t}\n\tif (hasReservedKey(value)) {\n\t\tthrow new QualifierError(\n\t\t\t'MISMATCH',\n\t\t\t`Qualification subject must not contain reserved key '${QUALIFICATION_KEY}'`,\n\t\t)\n\t}\n}\n\n/**\n * Maps an engine throw caught while running one pass to a typed {@link QualifierError}.\n *\n * @remarks\n * A reason `ReasonError('INVALID')` maps to `DEFINITION` (the engine rejected the\n * pass as an invalid definition); `ReasonError('DESTROYED')` maps to `DESTROYED`;\n * every other `ReasonError` code (for example `MISSING`) and every non-`ReasonError` throw\n * (including a `bail: true` reasoner rethrow) maps to `ENGINE`. The original throw\n * is preserved as `context.cause`.\n *\n * @param error - The value caught from the engine's `reason` call\n * @param pass - The id of the pass that was running\n * @returns A fresh, typed {@link QualifierError}\n *\n * @example\n * ```ts\n * import { mapEngineError } from '@orkestrel/qualifier'\n * import { ReasonError } from '@orkestrel/reason'\n *\n * mapEngineError(new ReasonError('MISSING', 'No reasoner registered'), 'cap').code // 'ENGINE'\n * ```\n */\nexport function mapEngineError(error: unknown, pass: string): QualifierError {\n\tif (isReasonError(error)) {\n\t\tif (error.code === 'INVALID') {\n\t\t\treturn new QualifierError(\n\t\t\t\t'DEFINITION',\n\t\t\t\t`Pass '${pass}' failed engine validation: ${error.message}`,\n\t\t\t\t{ pass, cause: error },\n\t\t\t)\n\t\t}\n\t\tif (error.code === 'DESTROYED') {\n\t\t\treturn new QualifierError(\n\t\t\t\t'DESTROYED',\n\t\t\t\t`Qualifier engine was destroyed during pass '${pass}'`,\n\t\t\t\t{ pass, cause: error },\n\t\t\t)\n\t\t}\n\t\treturn new QualifierError('ENGINE', `Pass '${pass}' engine failure: ${error.message}`, {\n\t\t\tpass,\n\t\t\tcause: error,\n\t\t})\n\t}\n\tconst message = isError(error) ? error.message : String(error)\n\treturn new QualifierError('ENGINE', `Pass '${pass}' engine failure: ${message}`, {\n\t\tpass,\n\t\tcause: error,\n\t})\n}\n\n/**\n * Describes each logical pass carrying no rulings.\n *\n * @remarks\n * A logical pass with no matching ruling can never contribute a finding, so its\n * rules only ever influence later passes' reads — this is very likely an authoring\n * oversight.\n *\n * @param definition - The qualification definition to check\n * @returns A fresh list of warning messages\n *\n * @example\n * ```ts\n * import { createQualificationDefinition, describeEmptyLogicalPasses } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const gates = createLogicalDefinition('gates', 'Gates', [\n * createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true)),\n * ])\n * const definition = createQualificationDefinition('standard', 'Standard', [gates])\n *\n * describeEmptyLogicalPasses(definition) // [\"Logical pass 'gates' has no rulings\"]\n * ```\n */\nexport function describeEmptyLogicalPasses(definition: QualificationDefinition): readonly string[] {\n\tconst warnings: string[] = []\n\tfor (const pass of definition.passes) {\n\t\tif (pass.reasoning !== 'logical') continue\n\t\tconst hasRuling = (definition.rulings ?? []).some((ruling) => ruling.pass === pass.id)\n\t\tif (!hasRuling) warnings.push(`Logical pass '${pass.id}' has no rulings`)\n\t}\n\treturn warnings\n}\n\n/**\n * Describes each quantitative pass never read by a later pass.\n *\n * @remarks\n * A quantitative pass's projected value lives under `qualification.<id>` — if no\n * later logical premise or quantitative factor field reads that key, the\n * derivation is dead weight. Reads are collected per later pass: a logical pass's\n * premise atoms (conclusion atoms are writes, not reads), and a quantitative\n * pass's field/lookup/range factor sources plus factor checks.\n *\n * @param definition - The qualification definition to check\n * @returns A fresh list of warning messages\n *\n * @example\n * ```ts\n * import { createQualificationDefinition, describeUnreadDerivations } from '@orkestrel/qualifier'\n * import { createFactorGroup, createQuantitativeDefinition, createStaticFactor } from '@orkestrel/reason'\n *\n * const cap = createQuantitativeDefinition('cap', 'TIV cap', [\n * createFactorGroup('limit', 'sum', [createStaticFactor('base', 500_000)]),\n * ])\n * const definition = createQualificationDefinition('standard', 'Standard', [cap])\n *\n * describeUnreadDerivations(definition) // [\"Quantitative pass 'cap' is never read by a later pass\"]\n * ```\n */\nexport function describeUnreadDerivations(definition: QualificationDefinition): readonly string[] {\n\tconst warnings: string[] = []\n\tdefinition.passes.forEach((pass, index) => {\n\t\tif (pass.reasoning !== 'quantitative') return\n\t\tconst key = formatField(['qualification', pass.id])\n\t\tconst reads = new Set<string>()\n\t\tfor (const later of definition.passes.slice(index + 1)) {\n\t\t\tif (later.reasoning === 'logical') {\n\t\t\t\tfor (const rule of later.rules) {\n\t\t\t\t\tfor (const premise of rule.premises) {\n\t\t\t\t\t\tfor (const atom of extractAtoms(premise)) reads.add(formatField(atom.check.field))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (later.reasoning === 'quantitative') {\n\t\t\t\tfor (const group of later.groups) {\n\t\t\t\t\tfor (const factor of group.factors) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tfactor.source.origin === 'field' ||\n\t\t\t\t\t\t\tfactor.source.origin === 'lookup' ||\n\t\t\t\t\t\t\tfactor.source.origin === 'range'\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\treads.add(formatField(factor.source.field))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (const check of factor.checks ?? []) reads.add(formatField(check.field))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!reads.has(key)) {\n\t\t\twarnings.push(`Quantitative pass '${pass.id}' is never read by a later pass`)\n\t\t}\n\t})\n\treturn warnings\n}\n","import type { ContractShape } from '@orkestrel/contract'\nimport {\n\tarrayShape,\n\tauditFaultShape,\n\tshapeShape,\n\tjsonShape,\n\tliteralShape,\n\tnullableShape,\n\tnumberShape,\n\tobjectShape,\n\toptionalShape,\n\trecordShape,\n\tstringShape,\n\tbooleanShape,\n\tunionShape,\n} from '@orkestrel/contract'\nimport {\n\tCHECK_STATES,\n\tCOMPARISONS,\n\tcreateLogicalDefinitionShape,\n\tfieldPathShape,\n\tquantitativeDefinitionShape,\n} from '@orkestrel/reason'\nimport { ELIGIBILITIES, QUALIFICATION_EFFECTS } from './constants.js'\n\n// A qualification definition and result as shapes, so they reach an LLM, a tool, and MCP as JSON\n// Schema. A definition holds logical passes, whose recursive expressions `reason` builds behind a\n// function, so the definition's shape is behind one too and an import pays nothing for it.\n\n/** Describes a `Ruling`. */\nexport const rulingShape: ContractShape = objectShape({\n\tid: stringShape(),\n\tpass: stringShape(),\n\trule: stringShape(),\n\teffect: literalShape(QUALIFICATION_EFFECTS),\n\tscope: optionalShape(stringShape()),\n\tmessage: optionalShape(stringShape()),\n})\n\n/**\n * Creates the shape of a `QualificationDefinition`.\n *\n * @remarks\n * `shape` is checked as a recursive contract shape.\n *\n * @returns A shape holding quantitative and logical passes and rulings\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { createQualificationDefinition, createQualificationDefinitionShape } from '@orkestrel/qualifier'\n *\n * createContract(createQualificationDefinitionShape()).is(createQualificationDefinition('d', 'd', [])) // true\n * ```\n */\nexport function createQualificationDefinitionShape(): ContractShape {\n\treturn objectShape({\n\t\tid: stringShape(),\n\t\tname: stringShape(),\n\t\tdescription: optionalShape(stringShape()),\n\t\tpasses: arrayShape(unionShape(quantitativeDefinitionShape, createLogicalDefinitionShape())),\n\t\trulings: optionalShape(arrayShape(rulingShape)),\n\t\tmetadata: optionalShape(recordShape(jsonShape())),\n\t\tshape: optionalShape(shapeShape()),\n\t})\n}\n\n/** Describes a `Premise` in its JSON projection. */\nexport const premiseShape: ContractShape = objectShape({\n\tfield: optionalShape(fieldPathShape),\n\tlabel: optionalShape(stringShape()),\n\tdescription: optionalShape(stringShape()),\n\tcomparison: optionalShape(literalShape(COMPARISONS)),\n\texpected: optionalShape(jsonShape()),\n\tactual: optionalShape(jsonShape()),\n\tstate: optionalShape(literalShape(CHECK_STATES)),\n})\n\n/** Describes a `Finding` in its JSON projection. */\nexport const findingShape: ContractShape = objectShape({\n\tid: stringShape(),\n\tpass: stringShape(),\n\trule: stringShape(),\n\teffect: literalShape(QUALIFICATION_EFFECTS),\n\tscope: optionalShape(stringShape()),\n\tstate: literalShape(CHECK_STATES),\n\tmessage: optionalShape(stringShape()),\n\tpremises: arrayShape(premiseShape),\n})\n\n/** Describes a `Derivation` in its JSON projection, where a non-finite number is `null`. */\nexport const derivationShape: ContractShape = objectShape({\n\tid: stringShape(),\n\tvalue: nullableShape(numberShape()),\n\tsuccess: booleanShape(),\n\ttrace: arrayShape(stringShape()),\n\terrors: arrayShape(stringShape()),\n})\n\n/** Describes a `QualificationResult` in its JSON projection. */\nexport const qualificationResultShape: ContractShape = objectShape({\n\tid: stringShape(),\n\tname: stringShape(),\n\teligibility: literalShape(ELIGIBILITIES),\n\tscopes: recordShape(literalShape(ELIGIBILITIES)),\n\tfindings: arrayShape(findingShape),\n\tderivations: arrayShape(derivationShape),\n\tsuccess: booleanShape(),\n\ttrace: arrayShape(stringShape()),\n\terrors: arrayShape(stringShape()),\n\tfaults: arrayShape(auditFaultShape()),\n\trepairs: arrayShape(auditFaultShape()),\n\tdefaulted: arrayShape(fieldPathShape),\n})\n","import type { ContractInterface } from '@orkestrel/contract'\nimport { createContract } from '@orkestrel/contract'\nimport { qualificationResultShape } from './shapers.js'\n\n/** Publishes a `QualificationResult`'s JSON projection as a contract, read through `projectQualificationResult`. */\nexport const qualificationResultContract: ContractInterface<unknown> =\n\tcreateContract(qualificationResultShape)\n","import type {\n\tDerivation,\n\tFinding,\n\tQualificationContext,\n\tQualificationDefinition,\n\tQualificationPass,\n\tQualificationResult,\n\tQualifierEventMap,\n\tQualifierInterface,\n\tQualifierOptions,\n} from './types.js'\nimport type { AuditFault } from '@orkestrel/contract'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tReasonInterface,\n\tReasonResult,\n\tReasonValidationResult,\n\tSubject,\n\tSubjectAdmission,\n} from '@orkestrel/reason'\nimport { DEFAULT_QUALIFIER_VALIDATE } from './constants.js'\nimport { QualifierError } from './errors.js'\nimport {\n\tassertSubject,\n\tdescribeEmptyLogicalPasses,\n\tdescribeMissingReferences,\n\tdescribeReservedConclusions,\n\tdescribeUnknownTokens,\n\tdescribeUnreadDerivations,\n\tderiveFindingEligibility,\n\tderiveScopeEligibilities,\n\texpandPassFaults,\n\thasUnreadRule,\n\tmapEngineError,\n\tmergeQualificationContext,\n\tqualificationToRecord,\n\tquantitativeResultToDerivation,\n\treasonResultToProjection,\n\trulingToFinding,\n\tscanDefinitionShape,\n} from './helpers.js'\nimport {\n\tisDefinitionMetadata,\n\tisQualificationDefinition,\n\tisQualificationPass,\n\tisRuling,\n} from './validators.js'\nimport { describeFaults, isArray, isRecord, isString } from '@orkestrel/contract'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tcreateLogicalReasoner,\n\tcreateQuantitativeReasoner,\n\tcreateReason,\n\tcreateSubjectDoor,\n\tfilterUniqueFaults,\n\tisContractShape,\n\tisReasonResult,\n\tscanShape,\n\tfindDuplicates,\n} from '@orkestrel/reason'\n\n/**\n * Runs ordered passes over one reason engine and returns eligibility.\n *\n * @remarks\n * The engine is owned when self-created (destroyed on `destroy()`) and borrowed\n * when injected (never destroyed). Semantic validation runs before the first pass\n * whenever the `validate` option is on. `qualify` builds its working subject through\n * copy-on-write overlays only — the caller's `subject` is never mutated, and the\n * qualifier's internal projection is discarded after each call.\n */\nexport class Qualifier implements QualifierInterface {\n\treadonly #emitter: Emitter<QualifierEventMap>\n\treadonly #engine: ReasonInterface\n\treadonly #owned: boolean\n\treadonly #validate: boolean\n\treadonly #labels: Readonly<Record<string, string>> | undefined\n\treadonly #door = createSubjectDoor()\n\treadonly #valid = new WeakSet<QualificationDefinition>()\n\treadonly #shaped = new WeakSet<QualificationDefinition>()\n\t#destroyed = false\n\n\tconstructor(options?: QualifierOptions) {\n\t\tthis.#emitter = new Emitter({\n\t\t\t...(options?.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options?.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t\tthis.#owned = options?.engine === undefined\n\t\tthis.#engine =\n\t\t\toptions?.engine ??\n\t\t\tcreateReason({\n\t\t\t\treasoners: [createQuantitativeReasoner(), createLogicalReasoner()],\n\t\t\t\tbail: false,\n\t\t\t})\n\t\tthis.#validate = options?.validate ?? DEFAULT_QUALIFIER_VALIDATE\n\t\tthis.#labels = options?.labels\n\t}\n\n\t/**\n\t * Holds the typed observation surface carrying `derive`, `finding`, `qualify`, and\n\t * `destroy`.\n\t *\n\t * @returns The emitter this qualifier owns\n\t *\n\t * @example\n\t * ```ts\n\t * import { Qualifier } from '@orkestrel/qualifier'\n\t *\n\t * const qualifier = new Qualifier()\n\t * qualifier.emitter.on('qualify', (result) => console.log(result.eligibility))\n\t * qualifier.destroy()\n\t * ```\n\t */\n\tget emitter(): EmitterInterface<QualifierEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\t/**\n\t * Qualifies one subject against one authored definition.\n\t *\n\t * @remarks\n\t * Semantic validation runs first when the `validate` option is on, so an invalid\n\t * definition throws before any pass runs. Passes run in authored order over a\n\t * copy-on-write working subject, and the caller's `subject` is never mutated. A\n\t * `shape` on the definition admits the subject through a door first. An unscoped\n\t * restriction stops the remaining passes because no later finding can be more severe.\n\t * A pass left unread projects nothing and reads `referral`, and the run goes on, so a later\n\t * restriction can still outrank it. An error no fault can say stops the run.\n\t *\n\t * @param subject - The record to qualify\n\t * @param definition - The authored qualification definition\n\t * @returns A fresh, frozen qualification result\n\t * @throws {@link QualifierError} `'DEFINITION'` when validation is enabled and the\n\t * definition fails semantic validation, or when the engine rejects a pass as an invalid\n\t * definition; `'MISMATCH'` when the subject is not a record or already carries the\n\t * reserved `qualification` key; `'DESTROYED'` after `destroy`, or when the engine\n\t * reports itself destroyed mid-pass; `'ENGINE'` for every other engine throw\n\t *\n\t * @example\n\t * ```ts\n\t * import { createQualificationDefinition, createRuling, Qualifier } from '@orkestrel/qualifier'\n\t * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n\t *\n\t * const gates = createLogicalDefinition('gates', 'Eligibility gates', [\n\t * createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true)),\n\t * ])\n\t * const definition = createQualificationDefinition('standard', 'Standard eligibility', [gates], {\n\t * rulings: [createRuling('license', 'gates', 'licensed', 'restriction')],\n\t * })\n\t *\n\t * const qualifier = new Qualifier()\n\t * qualifier.qualify({ id: 'risk-1', licensed: false }, definition).eligibility // 'ineligible'\n\t * qualifier.destroy()\n\t * ```\n\t */\n\tqualify(subject: Subject, definition: QualificationDefinition): QualificationResult {\n\t\tthis.#alive()\n\t\tif (this.#validate && !this.#valid.has(definition)) {\n\t\t\tconst validation = this.validate(definition)\n\t\t\tif (!validation.valid) {\n\t\t\t\tthrow new QualifierError(\n\t\t\t\t\t'DEFINITION',\n\t\t\t\t\t`Qualification definition is invalid: ${validation.errors.join(', ')}`,\n\t\t\t\t\tisRecord(definition) && isString(definition.id) ? { definition: definition.id } : {},\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.#valid.add(definition)\n\t\t}\n\t\treturn this.#qualify(subject, definition)\n\t}\n\n\t/**\n\t * Validates one authored definition semantically, without running it.\n\t *\n\t * @remarks\n\t * Structural shape is `isQualificationDefinition`'s job. This checks the meaning:\n\t * non-empty id and name, valid and uniquely identified passes and rulings, every\n\t * ruling reference resolving to a logical pass and one of its rules, and no pass id\n\t * shadowing `QUALIFICATION_KEY`. The engine validates each pass, whose errors carry the\n\t * pass id. A pass may carry no shape, and a `shape` on the definition must stand and\n\t * declare every message token. An empty definition, a logical pass carrying no ruling,\n\t * and a derivation no later pass reads are warnings rather than errors.\n\t *\n\t * @param definition - The authored qualification definition\n\t * @returns A fresh validation result carrying `valid`, `errors`, and `warnings`\n\t * @throws {@link QualifierError} `'DESTROYED'` after `destroy`\n\t *\n\t * @example\n\t * ```ts\n\t * import { createQualificationDefinition, Qualifier } from '@orkestrel/qualifier'\n\t *\n\t * const qualifier = new Qualifier()\n\t * qualifier.validate(createQualificationDefinition('empty', 'Empty', []))\n\t * // { valid: true, errors: [], warnings: ['Definition has no passes'] }\n\t * qualifier.destroy()\n\t * ```\n\t */\n\tvalidate(definition: QualificationDefinition): ReasonValidationResult {\n\t\tthis.#alive()\n\t\tif (!isRecord(definition)) {\n\t\t\treturn { valid: false, errors: ['Definition must be a record'], warnings: [] }\n\t\t}\n\t\tconst errors: string[] = []\n\t\tconst warnings: string[] = []\n\t\tif (!isString(definition.id) || definition.id.length === 0) {\n\t\t\terrors.push('Definition id must not be empty')\n\t\t}\n\t\tif (!isString(definition.name) || definition.name.length === 0) {\n\t\t\terrors.push('Definition name must not be empty')\n\t\t}\n\t\tconst authoredPasses: readonly unknown[] = isArray(definition.passes) ? definition.passes : []\n\t\tconst authoredRulings: unknown = definition.rulings === undefined ? [] : definition.rulings\n\t\tif (!isArray(definition.passes)) errors.push('Definition must have a passes array')\n\t\tif (!isArray(authoredRulings)) errors.push('Definition rulings must be an array')\n\t\tauthoredPasses.forEach((pass, index) => {\n\t\t\tif (!isQualificationPass(pass)) {\n\t\t\t\terrors.push(`Pass at index ${index} is not a valid qualification pass`)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (pass.shape !== undefined) errors.push(`Pass '${pass.id}' may not carry a shape`)\n\t\t\tconst validation = this.#validatePass(pass)\n\t\t\tfor (const error of validation.errors) errors.push(`${pass.id}: ${error}`)\n\t\t\tfor (const warning of validation.warnings) warnings.push(`${pass.id}: ${warning}`)\n\t\t})\n\t\tconst rulingEntries: readonly unknown[] = isArray(authoredRulings) ? authoredRulings : []\n\t\trulingEntries.forEach((ruling, index) => {\n\t\t\tif (!isRuling(ruling)) errors.push(`Ruling at index ${index} is not a valid ruling`)\n\t\t})\n\t\t// The checks below read only what stood up, so one bad entry cannot throw past its own error.\n\t\tconst passes = authoredPasses.filter((pass) => isQualificationPass(pass))\n\t\tconst rulings = rulingEntries.filter((ruling) => isRuling(ruling))\n\t\tconst shape = isContractShape(definition.shape) ? definition.shape : undefined\n\t\tif (definition.shape !== undefined && shape === undefined) {\n\t\t\terrors.push('Definition shape is not a valid contract shape')\n\t\t}\n\t\tif (definition.metadata !== undefined && !isDefinitionMetadata(definition.metadata)) {\n\t\t\terrors.push('Definition metadata must be a record of JSON values')\n\t\t}\n\t\tconst readable: QualificationDefinition = {\n\t\t\tid: definition.id,\n\t\t\tname: definition.name,\n\t\t\tpasses,\n\t\t\trulings,\n\t\t\t...(shape === undefined ? {} : { shape }),\n\t\t}\n\t\tfor (const id of findDuplicates(passes)) errors.push(`Duplicate pass id '${id}'`)\n\t\tfor (const id of findDuplicates(rulings)) errors.push(`Duplicate ruling id '${id}'`)\n\t\tfor (const reference of describeMissingReferences(readable)) errors.push(reference)\n\t\tfor (const conclusion of describeReservedConclusions(readable)) errors.push(conclusion)\n\t\tconst scan = scanDefinitionShape(readable)\n\t\terrors.push(...(shape === undefined ? [] : scanShape(shape)), ...scan.errors)\n\t\terrors.push(...describeUnknownTokens(readable))\n\t\twarnings.push(...scan.warnings)\n\t\tif (passes.length === 0) warnings.push('Definition has no passes')\n\t\tfor (const warning of describeEmptyLogicalPasses(readable)) warnings.push(warning)\n\t\tfor (const warning of describeUnreadDerivations(readable)) warnings.push(warning)\n\t\treturn { valid: errors.length === 0, errors, warnings }\n\t}\n\n\t/**\n\t * Destroys this qualifier, idempotently.\n\t *\n\t * @remarks\n\t * An engine this qualifier created is destroyed; an injected engine stays\n\t * caller-owned and is left alone. The `destroy` event fires before the emitter\n\t * itself is destroyed, and a later call returns without re-emitting.\n\t *\n\t * @example\n\t * ```ts\n\t * import { Qualifier } from '@orkestrel/qualifier'\n\t *\n\t * const qualifier = new Qualifier()\n\t * qualifier.destroy()\n\t * qualifier.destroy() // idempotent\n\t * ```\n\t */\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tif (this.#owned) this.#engine.destroy()\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#qualify(subject: Subject, definition: QualificationDefinition): QualificationResult {\n\t\tassertSubject(subject)\n\t\t// Structure is checked even with `validate` off, once per definition, because the walk below\n\t\t// reads it, and a malformed definition is the caller's error, never a raw TypeError.\n\t\tif (!this.#shaped.has(definition)) {\n\t\t\tif (!isQualificationDefinition(definition)) {\n\t\t\t\tthrow new QualifierError('DEFINITION', 'Qualification definition is malformed')\n\t\t\t}\n\t\t\tthis.#shaped.add(definition)\n\t\t}\n\t\tconst admission = this.#door.admit(subject, definition.shape)\n\t\tconst admitted = admission.subject\n\t\t// A default could fill the reserved key, so the same rule holds for what the door admitted.\n\t\tif (admitted !== undefined) assertSubject(admitted)\n\t\tif (admitted === undefined) {\n\t\t\treturn this.#finish(\n\t\t\t\tdefinition,\n\t\t\t\t[],\n\t\t\t\t[],\n\t\t\t\t[],\n\t\t\t\t[...admission.errors],\n\t\t\t\tadmission.faults,\n\t\t\t\tadmission,\n\t\t\t)\n\t\t}\n\t\tconst steps: Array<{\n\t\t\treadonly context: QualificationContext\n\t\t\treadonly subject: Subject\n\t\t\treadonly success: boolean\n\t\t}> = [{ context: {}, subject: { ...admitted }, success: true }]\n\t\tconst findings: Finding[] = []\n\t\tconst derivations: Derivation[] = []\n\t\tconst trace: string[] = []\n\t\tconst errors: string[] = []\n\t\tconst faults: AuditFault[] = []\n\t\tconst unread = new Map<string, readonly AuditFault[]>()\n\n\t\tfor (const pass of definition.passes) {\n\t\t\tthis.#alive()\n\t\t\tconst previous = steps.at(-1)\n\t\t\tif (previous === undefined) throw new Error('Qualification has no initial step')\n\t\t\tconst evaluated = previous.subject\n\t\t\tconst result = this.#reason(evaluated, pass)\n\n\t\t\t// An injected engine answers through an interface, so its result is read, not trusted.\n\t\t\tif (!isReasonResult(result)) {\n\t\t\t\terrors.push(`${pass.id}: The engine returned a malformed result`)\n\t\t\t\tsteps.push({ ...previous, success: false })\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttrace.push(...result.trace.map((entry) => `${pass.id}: ${entry}`))\n\t\t\t// A fault's own string is written once at the end, after a read of an unread pass has\n\t\t\t// become what that pass could not read. What no fault can say stays here. `success` is\n\t\t\t// the verdict, so one that says nothing, or a success beside an unread rule, is an error.\n\t\t\tconst said = new Set(result.faults.map((fault) => describeFaults([fault])))\n\t\t\tconst fatal = [\n\t\t\t\t...result.errors.filter((entry) => !said.has(entry)),\n\t\t\t\t...(!result.success && result.errors.length === 0\n\t\t\t\t\t? ['The pass failed and said nothing']\n\t\t\t\t\t: []),\n\t\t\t\t...(result.success && hasUnreadRule(result)\n\t\t\t\t\t? ['The pass succeeded beside an unread rule']\n\t\t\t\t\t: []),\n\t\t\t]\n\t\t\terrors.push(...fatal.map((entry) => `${pass.id}: ${entry}`))\n\t\t\tconst leaves = expandPassFaults(result.faults, unread)\n\t\t\tfaults.push(...leaves)\n\t\t\tif (leaves.length > 0) unread.set(pass.id, leaves)\n\n\t\t\tif (result.reasoning === 'quantitative') {\n\t\t\t\tconst derivation = quantitativeResultToDerivation(pass.id, result)\n\t\t\t\tderivations.push(derivation)\n\t\t\t\tthis.#emitter.emit('derive', derivation)\n\t\t\t}\n\n\t\t\tif (result.reasoning === 'logical') {\n\t\t\t\tconst rulings = (definition.rulings ?? []).filter((ruling) => ruling.pass === pass.id)\n\t\t\t\tfor (const ruling of rulings) {\n\t\t\t\t\tconst finding = rulingToFinding(ruling, pass, result, evaluated, this.#labels)\n\t\t\t\t\tfindings.push(finding)\n\t\t\t\t\tthis.#emitter.emit('finding', finding)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// An unread pass projects nothing and the run goes on, so a later restriction can still\n\t\t\t// outrank the referral it reads as. An error no fault can say stops the run.\n\t\t\tconst context =\n\t\t\t\tresult.success && fatal.length === 0\n\t\t\t\t\t? mergeQualificationContext(\n\t\t\t\t\t\t\tprevious.context,\n\t\t\t\t\t\t\tpass.id,\n\t\t\t\t\t\t\treasonResultToProjection(pass, result),\n\t\t\t\t\t\t)\n\t\t\t\t\t: previous.context\n\t\t\tsteps.push({\n\t\t\t\tcontext,\n\t\t\t\tsubject: { ...admitted, ...qualificationToRecord(context) },\n\t\t\t\tsuccess: result.success && fatal.length === 0,\n\t\t\t})\n\n\t\t\tif (fatal.length > 0) break\n\t\t\tif (deriveFindingEligibility(findings) === 'ineligible') break\n\t\t}\n\n\t\tconst leaves = filterUniqueFaults(faults)\n\t\treturn this.#finish(\n\t\t\tdefinition,\n\t\t\tfindings,\n\t\t\tderivations,\n\t\t\ttrace,\n\t\t\t[...errors, ...leaves.map((fault) => describeFaults([fault]))],\n\t\t\tleaves,\n\t\t\tadmission,\n\t\t)\n\t}\n\n\t#finish(\n\t\tdefinition: QualificationDefinition,\n\t\tfindings: readonly Finding[],\n\t\tderivations: readonly Derivation[],\n\t\ttrace: readonly string[],\n\t\terrors: readonly string[],\n\t\tfaults: readonly AuditFault[],\n\t\tadmission: SubjectAdmission,\n\t): QualificationResult {\n\t\tconst success = errors.length === 0\n\t\tconst qualification: QualificationResult = Object.freeze({\n\t\t\tid: definition.id,\n\t\t\tname: definition.name,\n\t\t\teligibility: deriveFindingEligibility(findings, !success),\n\t\t\tscopes: Object.freeze(deriveScopeEligibilities(findings)),\n\t\t\tfindings: Object.freeze(findings),\n\t\t\tderivations: Object.freeze(derivations),\n\t\t\tsuccess,\n\t\t\ttrace: Object.freeze(trace),\n\t\t\terrors: Object.freeze(errors),\n\t\t\tfaults: Object.freeze(faults),\n\t\t\trepairs: Object.freeze([...admission.repairs]),\n\t\t\tdefaulted: Object.freeze([...admission.defaulted]),\n\t\t})\n\t\tthis.#emitter.emit('qualify', qualification)\n\t\treturn qualification\n\t}\n\n\t#validatePass(pass: QualificationPass): ReasonValidationResult {\n\t\ttry {\n\t\t\treturn this.#engine.validate(pass)\n\t\t} catch (error) {\n\t\t\tthrow mapEngineError(error, pass.id)\n\t\t}\n\t}\n\n\t#reason(subject: Subject, pass: QualificationPass): ReasonResult {\n\t\ttry {\n\t\t\treturn this.#engine.reason(subject, pass)\n\t\t} catch (error) {\n\t\t\tthrow mapEngineError(error, pass.id)\n\t\t}\n\t}\n\n\t#alive(): void {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new QualifierError('DESTROYED', 'Qualifier has been destroyed')\n\t\t}\n\t}\n}\n","import type { ContractInterface } from '@orkestrel/contract'\nimport type {\n\tQualificationDefinition,\n\tQualificationEffect,\n\tQualificationInput,\n\tQualificationPass,\n\tQualifierInterface,\n\tQualifierOptions,\n\tRuling,\n\tRulingInput,\n} from './types.js'\nimport { createContract } from '@orkestrel/contract'\nimport { Qualifier } from './Qualifier.js'\nimport { createQualificationDefinitionShape } from './shapers.js'\n\n/**\n * Creates the contract of a `QualificationDefinition`, its `schema` for an LLM, a tool, or MCP.\n *\n * @remarks\n * Cross a definition on `is`, never `parse`, and hold the result, because building it walks the\n * recursive expressions of its logical passes. `is` checks nested contract shapes;\n * semantic validation remains the qualifier's responsibility.\n *\n * @returns A contract over a qualification definition\n *\n * @example\n * ```ts\n * import { createQualificationDefinition, createQualificationDefinitionContract } from '@orkestrel/qualifier'\n *\n * createQualificationDefinitionContract().is(createQualificationDefinition('d', 'd', [])) // true\n * ```\n */\nexport function createQualificationDefinitionContract(): ContractInterface<unknown> {\n\treturn createContract(createQualificationDefinitionShape())\n}\n\n/**\n * Creates one {@link QualifierInterface} over a reason engine.\n *\n * @remarks\n * A standalone qualifier creates and owns one shared quantitative-plus-logical\n * reason engine, destroying it on `destroy()`. An injected `options.engine`\n * remains caller-owned and is never destroyed. `validate` runs semantic\n * validation before every qualification. Default: `true`. `labels` overrides the\n * display name of a premise field, keyed by the dot-joined field path\n * `formatField` produces, and takes precedence over a premise's own `label`.\n *\n * @param options - Optional injected engine, validation, labels, and emitter hooks\n * @returns A {@link QualifierInterface}\n *\n * @example Create a qualifier\n * ```ts\n * import { createQualificationDefinition, createQualifier, createRuling } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const gates = createLogicalDefinition('gates', 'Eligibility gates', [\n * \tcreateRule(\n * \t\t'licensed',\n * \t\t[createAtom('licensed', 'equals', false)],\n * \t\tcreateAtom('blocked', 'equals', true),\n * \t),\n * ])\n *\n * const bare = createRuling('license', 'gates', 'licensed', 'restriction')\n * const messaged = createRuling('license', 'gates', 'licensed', 'restriction', {\n * \tmessage: 'A license is required',\n * })\n *\n * 'message' in bare // false — an absent optional key is omitted, never written as undefined\n * messaged.message // 'A license is required'\n *\n * const passes = [gates]\n * const definition = createQualificationDefinition('standard', 'Standard eligibility', passes, {\n * \trulings: [messaged],\n * })\n *\n * 'description' in definition // false\n * definition.passes === passes // false — the factory copies what it is handed\n *\n * const qualifier = createQualifier()\n * qualifier.qualify({ id: 'risk-1', licensed: false }, definition)\n * qualifier.destroy()\n * ```\n */\nexport function createQualifier(options?: QualifierOptions): QualifierInterface {\n\treturn new Qualifier(options)\n}\n\n/**\n * Creates a fresh {@link QualificationDefinition}, omitting every absent optional key.\n *\n * @remarks\n * `passes` and `rulings` arrays are copied, and record `metadata` is\n * shallow-copied so nested values are not deep-cloned.\n *\n * @param id - The definition id\n * @param name - The display name\n * @param passes - The ordered qualification passes\n * @param input - Optional description, rulings, metadata, and subject shape\n * @returns A fresh qualification definition\n *\n * @example\n * ```ts\n * import { createQualificationDefinition } from '@orkestrel/qualifier'\n *\n * createQualificationDefinition('standard', 'Standard', [gates], { rulings: [ruling] })\n * ```\n */\nexport function createQualificationDefinition(\n\tid: string,\n\tname: string,\n\tpasses: readonly QualificationPass[],\n\tinput?: QualificationInput,\n): QualificationDefinition {\n\treturn {\n\t\tid,\n\t\tname,\n\t\tpasses: [...passes],\n\t\t...(input?.description === undefined ? {} : { description: input.description }),\n\t\t...(input?.rulings === undefined ? {} : { rulings: [...input.rulings] }),\n\t\t...(input?.metadata === undefined ? {} : { metadata: { ...input.metadata } }),\n\t\t...(input?.shape === undefined ? {} : { shape: input.shape }),\n\t}\n}\n\n/**\n * Creates a fresh {@link Ruling} from the rule it reacts to and the effect it applies.\n *\n * @param id - The ruling id\n * @param pass - The logical pass id the rule lives in\n * @param rule - The rule id whose firing this ruling reacts to\n * @param effect - The eligibility impact when the rule fires\n * @param input - Optional selection scope and message template\n * @returns A fresh ruling\n *\n * @example\n * ```ts\n * import { createRuling } from '@orkestrel/qualifier'\n *\n * createRuling('license', 'gates', 'licensed', 'restriction', { message: 'A license is required' })\n * ```\n */\nexport function createRuling(\n\tid: string,\n\tpass: string,\n\trule: string,\n\teffect: QualificationEffect,\n\tinput?: RulingInput,\n): Ruling {\n\treturn {\n\t\tid,\n\t\tpass,\n\t\trule,\n\t\teffect,\n\t\t...(input?.scope === undefined ? {} : { scope: input.scope }),\n\t\t...(input?.message === undefined ? {} : { message: input.message }),\n\t}\n}\n"],"mappings":";;;;;;;;;AAMA,IAAa,6BAA6B;;;;;AAM1C,IAAa,oBAAoB;;AAGjC,IAAa,gBAAgB;;AAG7B,IAAa,gBAAgB;CAAC;CAAY;CAAc;AAAU;;AAGlE,IAAa,wBAAwB;CAAC;CAAe;CAAY;AAAW;;AAG5E,IAAa,yBAAiD,OAAO,OAAO;CAC3E;CACA;CACA;AACD,CAAC;;;;;AAMD,IAAa,uBACZ,O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D"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["INTRINSICS","holds","isObject","isFunction","literalOf","whereOf","objectOf","isFieldPath","isString","isCheckState","arrayOf","unionOf","isCheckResult","isNumber","isBoolean","isReasonRefusal","isAuditFault","isQuantitativeDefinition","isLogicalDefinition","recordOf","isRecord","isJSONValue","isContractShape","resolveField","projectValue","extractConclusions","filterUniqueFaults","isArray","extractAtoms","scanShapeReads","collectConcluders","findFieldShape","findDuplicates","isFiniteNumber","nestRefusals","isString","projectCheck","projectRefusal","isRecord","isReasonError","isError","formatField","isArray","isObject","isString","attempt","isRecord","isSuccess","isReasonResult","objectShape","stringShape","literalShape","optionalShape","arrayShape","unionShape","quantitativeDefinitionShape","createLogicalDefinitionShape","recordShape","jsonShape","shapeShape","fieldPathShape","CHECK_STATES","checkResultShape","nullableShape","numberShape","booleanShape","reasonRefusalShape","auditFaultShape","createContract","createSubjectDoor","Emitter","createReason","createQuantitativeReasoner","createLogicalReasoner","isRecord","isString","isArray","isContractShape","findDuplicates","scanShape","filterUniqueFaults","createContract"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/cloners.ts","../../../src/core/shapers.ts","../../../src/core/contracts.ts","../../../src/core/Qualifier.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { Eligibility, QualificationEffect } from './types.js'\n\n/**\n * Holds the default definition validation policy for `createQualifier` and\n * `Qualifier.qualify`, `true`.\n */\nexport const DEFAULT_QUALIFIER_VALIDATE = true\n\n/**\n * Names `'qualification'`, the reserved internal projection namespace a pass's working\n * projection is written under.\n */\nexport const QUALIFICATION_KEY = 'qualification'\n\n/** Matches each `{{dotted.path}}` token of a message template, with the path as its one group. */\nexport const MESSAGE_TOKEN = /\\{\\{\\s*([^}]+?)\\s*\\}\\}/g\n\n/** Lists the eligibility outcomes. */\nexport const ELIGIBILITIES = ['eligible', 'ineligible', 'referral'] as const\n\n/** Lists the effects a ruling can carry. */\nexport const QUALIFICATION_EFFECTS = ['restriction', 'referral', 'condition'] as const\n\n/** Lists the eligibility severities most to least severe: `ineligible`, `referral`, `eligible`. */\nexport const ELIGIBILITY_PRECEDENCE: readonly Eligibility[] = Object.freeze([\n\t'ineligible',\n\t'referral',\n\t'eligible',\n])\n\n/**\n * Maps each {@link QualificationEffect} to its eligibility impact — `restriction` to\n * `ineligible`, `referral` to `referral`, and `condition` to `eligible`.\n */\nexport const EFFECT_ELIGIBILITIES: Readonly<Record<QualificationEffect, Eligibility>> =\n\tObject.freeze({\n\t\trestriction: 'ineligible',\n\t\treferral: 'referral',\n\t\tcondition: 'eligible',\n\t})\n","import type { QualifierErrorCode, QualifierErrorContext } from './types.js'\nimport { holds, INTRINSICS, isFunction, isObject } from '@orkestrel/contract'\n\n/**\n * Represents a coded programmer error thrown by the qualifier layer, carrying a\n * `QualifierErrorCode` and an optional context record.\n *\n * @remarks\n * `DEFINITION` — a qualification definition failed semantic validation; when\n * `qualify`'s own validation raises it, `context.definition` names the\n * definition, and when an engine throw maps to it, `context.pass` names the pass\n * and `context.cause` preserves the original throw. `MISMATCH` — a subject is\n * not a record or already carries the reserved `qualification` key.\n * `DESTROYED` — use of a destroyed qualifier; an engine-mapped one carries\n * `context.pass` and `context.cause`. `ENGINE` — the underlying reason engine\n * threw while running a pass; `context.pass` names the pass and `context.cause`\n * preserves the original throw. `context` is absent for a throw that carries no\n * payload.\n */\nexport class QualifierError extends Error {\n\treadonly code: QualifierErrorCode\n\treadonly context: QualifierErrorContext | undefined\n\n\tconstructor(code: QualifierErrorCode, message: string, context?: QualifierErrorContext) {\n\t\tsuper(message)\n\t\tINTRINSICS.define(this, Symbol.for('@orkestrel/qualifier.QualifierError'), { value: this })\n\t\tthis.name = 'QualifierError'\n\t\tthis.code = code\n\t\tthis.context = context\n\t}\n}\n\n/**\n * Narrows a caught value to a {@link QualifierError}.\n *\n * @param value - The caught value to test\n * @returns True if the error carries its own identity brand and declared members; false otherwise\n */\nexport function isQualifierError(value: unknown): value is QualifierError {\n\treturn holds(() => {\n\t\tif (!(value instanceof Error) || INTRINSICS.prototype(value) === Error.prototype) return false\n\t\tconst brand = INTRINSICS.describe(value, Symbol.for('@orkestrel/qualifier.QualifierError'))\n\t\tif (brand?.value !== value) return false\n\t\tconst code: unknown = INTRINSICS.reflect.read(value, 'code')\n\t\tif (code !== 'DEFINITION' && code !== 'MISMATCH' && code !== 'DESTROYED' && code !== 'ENGINE')\n\t\t\treturn false\n\t\tconst context: unknown = INTRINSICS.reflect.read(value, 'context')\n\t\tif (context === undefined) return true\n\t\tif (!isObject(context) && !isFunction(context)) return false\n\t\tconst pass: unknown = INTRINSICS.reflect.read(context, 'pass')\n\t\tconst definition: unknown = INTRINSICS.reflect.read(context, 'definition')\n\t\treturn (\n\t\t\t(pass === undefined || typeof pass === 'string') &&\n\t\t\t(definition === undefined || typeof definition === 'string')\n\t\t)\n\t})\n}\n","import type {\n\tDerivation,\n\tEligibility,\n\tFinding,\n\tMessageSlot,\n\tQualificationDefinition,\n\tQualificationPass,\n\tQualificationResult,\n\tRuling,\n} from './types.js'\nimport {\n\tisAuditFault,\n\tarrayOf,\n\tisBoolean,\n\tisJSONValue,\n\tisNumber,\n\tisRecord,\n\tisString,\n\tliteralOf,\n\tobjectOf,\n\trecordOf,\n\tunionOf,\n\twhereOf,\n} from '@orkestrel/contract'\nimport { ELIGIBILITIES, QUALIFICATION_EFFECTS } from './constants.js'\nimport {\n\tisCheckResult,\n\tisCheckState,\n\tisContractShape,\n\tisFieldPath,\n\tisLogicalDefinition,\n\tisQuantitativeDefinition,\n\tisReasonRefusal,\n} from '@orkestrel/reason'\n\n/**\n * Determines whether a value is an {@link Eligibility} literal.\n *\n * @remarks\n * The guard is total and leaves nothing unchecked: a scalar union has no open or exact\n * axis.\n *\n * @param value - The value to test\n * @returns True if `value` is one of the eligibility literals; false otherwise\n */\nexport const isEligibility = literalOf(...ELIGIBILITIES)\n\n/**\n * Determines whether a value is a {@link QualificationEffect} literal.\n *\n * @remarks\n * The guard is total and leaves nothing unchecked: a scalar union has no open or exact\n * axis.\n *\n * @param value - The value to test\n * @returns True if `value` is one of the effect literals; false otherwise\n */\nexport const isQualificationEffect = literalOf(...QUALIFICATION_EFFECTS)\n\n/**\n * Determines whether a value is an open string-keyed record of {@link Eligibility} values.\n *\n * @remarks\n * Every own string-named value is checked through {@link isEligibility}, including\n * non-enumerable values. Inherited and symbol-named members are left unchecked because they\n * are outside the own string-keyed record this guard certifies.\n *\n * @param value - The value to test\n * @returns True if `value` is a non-array object whose own string-named values are\n * eligibilities; false otherwise\n */\nexport function isEligibilityRecord(\n\tvalue: unknown,\n): value is Readonly<Record<string, Eligibility>> {\n\treturn whereOf(objectOf({}), (record): record is Readonly<Record<string, Eligibility>> =>\n\t\tObject.getOwnPropertyNames(record).every((key) => isEligibility(Reflect.get(record, key))),\n\t)(value)\n}\n\n/**\n * Determines whether a value is an open result-side {@link MessageSlot}.\n *\n * @remarks\n * `field` is checked. `actual` must be present and may hold anything, and is never read, because\n * its published type is `unknown`. Unknown members are admitted, because an open result admits\n * what the published contract does not name.\n *\n * @param value - The value to test\n * @returns True if the slot names a field and carries a value; false otherwise\n *\n * @example\n * ```ts\n * import { isMessageSlot } from '@orkestrel/qualifier'\n *\n * isMessageSlot({ field: ['age'], actual: undefined }) // true\n * isMessageSlot({ field: ['age'] }) // false\n * ```\n */\nexport function isMessageSlot(value: unknown): value is MessageSlot {\n\treturn whereOf(objectOf({ field: isFieldPath }), (slot): slot is MessageSlot =>\n\t\tReflect.has(slot, 'actual'),\n\t)(value)\n}\n\n/**\n * Determines whether a value is an open result-side {@link Finding}.\n *\n * @remarks\n * Every published member is checked, including each nested {@link MessageSlot} and check result.\n * Optional `scope` and `message` members may be absent or `undefined`; a present defined value is\n * checked in full. Unknown members are admitted, because a foreign result implementation may add\n * them without changing the published contract.\n *\n * @param value - The value to test\n * @returns True if every published finding member is valid; false otherwise\n */\nexport function isFinding(value: unknown): value is Finding {\n\treturn objectOf(\n\t\t{\n\t\t\tid: isString,\n\t\t\tpass: isString,\n\t\t\trule: isString,\n\t\t\teffect: isQualificationEffect,\n\t\t\tscope: isString,\n\t\t\tstate: isCheckState,\n\t\t\tmessage: arrayOf(unionOf(isString, isMessageSlot)),\n\t\t\tchecks: arrayOf(isCheckResult),\n\t\t},\n\t\t['scope', 'message'],\n\t)(value)\n}\n\n/**\n * Determines whether a value is an open result-side {@link Derivation}.\n *\n * @remarks\n * Every published member is checked: `value` follows the published `number` type, including\n * `NaN` and the infinities. Unknown members are admitted, because a foreign result\n * implementation may add them without changing the published contract.\n *\n * @param value - The value to test\n * @returns True if every published derivation member is valid; false otherwise\n */\nexport function isDerivation(value: unknown): value is Derivation {\n\treturn objectOf({\n\t\tid: isString,\n\t\tvalue: isNumber,\n\t\tsuccess: isBoolean,\n\t\ttrace: arrayOf(isString),\n\t\trefusals: arrayOf(isReasonRefusal),\n\t\tfaults: arrayOf(isAuditFault),\n\t})(value)\n}\n\n/**\n * Determines whether a value is an open {@link QualificationResult} returned by a qualifier.\n *\n * @remarks\n * This guard is result-postured for values returned through a borrowed qualifier interface. It\n * checks the complete published result closure — eligibility, scope values, findings,\n * derivations, success, and the audit trail — and admits unknown members and class instances,\n * because a borrowed `QualifierInterface` implementation may add them beyond the\n * published contract.\n *\n * @param value - The value to test\n * @returns True if every published qualification-result member is valid; false otherwise\n */\nexport function isQualificationResult(value: unknown): value is QualificationResult {\n\treturn objectOf({\n\t\tid: isString,\n\t\tname: isString,\n\t\teligibility: isEligibility,\n\t\tscopes: isEligibilityRecord,\n\t\tfindings: arrayOf(isFinding),\n\t\tderivations: arrayOf(isDerivation),\n\t\tsuccess: isBoolean,\n\t\ttrace: arrayOf(isString),\n\t\trefusals: arrayOf(isReasonRefusal),\n\t\tfaults: arrayOf(isAuditFault),\n\t\trepairs: arrayOf(isAuditFault),\n\t\tdefaulted: arrayOf(isFieldPath),\n\t})(value)\n}\n\n/**\n * Determines whether a value is a {@link QualificationPass} (a quantitative or logical definition).\n *\n * @remarks\n * The guard is exact and requires either complete reason shape, the quantitative definition or\n * the logical one. Nothing is left unchecked, because the reason package owns both authored\n * input shapes.\n *\n * @param value - The value to test\n * @returns True if `value` is a complete reason quantitative or logical definition; false otherwise\n */\nexport function isQualificationPass(value: unknown): value is QualificationPass {\n\treturn isQuantitativeDefinition(value) || isLogicalDefinition(value)\n}\n\n/**\n * Determines whether a value is an exact {@link Ruling} record.\n *\n * @remarks\n * Every authored ruling member and the complete key set are checked. Nothing is left\n * unchecked, because this package owns the authored input record.\n *\n * @param value - The value to test\n * @returns True if `value` carries every ruling member and no unknown key; false otherwise\n */\nexport function isRuling(value: unknown): value is Ruling {\n\treturn recordOf(\n\t\t{\n\t\t\tid: isString,\n\t\t\tpass: isString,\n\t\t\trule: isString,\n\t\t\teffect: isQualificationEffect,\n\t\t\tscope: isString,\n\t\t\tmessage: isString,\n\t\t},\n\t\t['scope', 'message'],\n\t)(value)\n}\n\n/**\n * Determines whether a value is a definition's `metadata`: a record of JSON values.\n *\n * @param value - The value to test\n * @returns True for a record whose every value is JSON; false otherwise\n *\n * @example\n * ```ts\n * import { isDefinitionMetadata } from '@orkestrel/qualifier'\n *\n * isDefinitionMetadata({ a: 1 }) // true\n * isDefinitionMetadata({ a: Number.NaN }) // false\n * ```\n */\nexport const isDefinitionMetadata = whereOf(isRecord, (record) =>\n\tObject.values(record).every(isJSONValue),\n)\n\n/**\n * Determines whether a value is an exact {@link QualificationDefinition} record.\n *\n * @remarks\n * Every authored definition member, the nested pass and ruling shapes, and the complete key\n * set are checked. Nothing is left unchecked, because this package owns the authored input\n * record.\n *\n * @param value - The value to test\n * @returns True if `value` carries every definition member and no unknown key; false otherwise\n */\nexport function isQualificationDefinition(value: unknown): value is QualificationDefinition {\n\treturn recordOf(\n\t\t{\n\t\t\tid: isString,\n\t\t\tname: isString,\n\t\t\tdescription: isString,\n\t\t\tpasses: arrayOf(isQualificationPass),\n\t\t\trulings: arrayOf(isRuling),\n\t\t\tmetadata: isDefinitionMetadata,\n\t\t\tshape: isContractShape,\n\t\t},\n\t\t['description', 'rulings', 'metadata', 'shape'],\n\t)(value)\n}\n","import type { AuditFault, FieldPath, JSONValue } from '@orkestrel/contract'\nimport type {\n\tDerivation,\n\tEligibility,\n\tFinding,\n\tMessageSlot,\n\tQualificationContext,\n\tQualificationDefinition,\n\tQualificationPass,\n\tQualificationProjection,\n\tQualificationResult,\n\tRuling,\n} from './types.js'\nimport type {\n\tLogicalDefinition,\n\tLogicalResult,\n\tQuantitativeResult,\n\tReasonRefusal,\n\tReasonResult,\n\tRule,\n\tShapeScan,\n\tSubject,\n} from '@orkestrel/reason'\nimport {\n\tEFFECT_ELIGIBILITIES,\n\tELIGIBILITY_PRECEDENCE,\n\tMESSAGE_TOKEN,\n\tQUALIFICATION_KEY,\n} from './constants.js'\nimport { QualifierError } from './errors.js'\nimport {\n\tisArray,\n\tisError,\n\tisFiniteNumber,\n\tisRecord,\n\tisString,\n\tresolveField,\n} from '@orkestrel/contract'\nimport {\n\textractAtoms,\n\textractConclusions,\n\tfilterUniqueFaults,\n\tcollectConcluders,\n\tfindDuplicates,\n\tfindFieldShape,\n\tformatField,\n\tisReasonError,\n\tnestRefusals,\n\tprojectCheck,\n\tprojectRefusal,\n\tprojectValue,\n\tscanShapeReads,\n} from '@orkestrel/reason'\n\n/**\n * Splits a message template at its `{{dotted.path}}` tokens, reading each from a subject.\n *\n * @remarks\n * The text between tokens stays as authored, and an empty text is left out. Each token becomes a\n * {@link MessageSlot} whose `field` is the token's path as an array of keys and whose `actual` is\n * the raw value there, `undefined` for an absent one. Nothing is formatted. The tokens are those\n * {@link findMessageTokens} finds.\n *\n * @param template - The message template carrying `{{dotted.path}}` tokens\n * @param subject - The record tokens resolve against\n * @returns The authored texts and the slots, in order\n *\n * @example\n * ```ts\n * import { splitMessage } from '@orkestrel/qualifier'\n *\n * splitMessage('Limit is {{limit}}', { limit: 5010 })\n * // ['Limit is ', { field: ['limit'], actual: 5010 }]\n * ```\n */\nexport function splitMessage(\n\ttemplate: string,\n\tsubject: Readonly<Record<string, unknown>>,\n): ReadonlyArray<string | MessageSlot> {\n\t// The pattern's one group puts each token's path at an odd index.\n\treturn template\n\t\t.split(MESSAGE_TOKEN)\n\t\t.flatMap((part, index): ReadonlyArray<string | MessageSlot> => {\n\t\t\tif (index % 2 === 0) return part === '' ? [] : [part]\n\t\t\tconst field = part.split('.')\n\t\t\treturn [{ field, actual: resolveField(subject, field) }]\n\t\t})\n}\n\n/**\n * Projects a slot's `actual` to JSON on its own budget, as `undefined` when it has no JSON form.\n *\n * @param slot - The slot\n * @returns The slot, its `actual` JSON or `undefined`\n *\n * @example\n * ```ts\n * import { projectMessageSlot } from '@orkestrel/qualifier'\n *\n * projectMessageSlot({ field: ['limit'], actual: Number.NaN }) // { field: ['limit'], actual: null }\n * ```\n */\nexport function projectMessageSlot(slot: MessageSlot): MessageSlot {\n\treturn { field: slot.field, actual: projectValue(slot.actual) }\n}\n\n/**\n * Finds the `{{dotted.path}}` tokens a message template reads.\n *\n * @remarks\n * White space around a path is trimmed, and the white space inside it stays. A token of white\n * space alone names one key, its last character, and `{{}}` is text.\n *\n * @param template - The message template\n * @returns Each token's dotted path, in order, repeats included\n *\n * @example\n * ```ts\n * import { findMessageTokens } from '@orkestrel/qualifier'\n *\n * findMessageTokens('Age {{ age }} in {{home.city}}') // ['age', 'home.city']\n * ```\n */\nexport function findMessageTokens(template: string): readonly string[] {\n\treturn [...template.matchAll(MESSAGE_TOKEN)].map((match) => match[1] ?? '')\n}\n\n/**\n * Locates an authored {@link Rule} by id.\n *\n * @param definition - The logical definition to search\n * @param id - The rule id\n * @returns The matching rule, or `undefined`\n *\n * @example\n * ```ts\n * import { findRule } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const gates = createLogicalDefinition('gates', 'Gates', [\n * createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true)),\n * ])\n *\n * findRule(gates, 'licensed')?.id // 'licensed'\n * ```\n */\nexport function findRule(definition: LogicalDefinition, id: string): Rule | undefined {\n\treturn definition.rules.find((rule) => rule.id === id)\n}\n\n/**\n * Projects one reason result into the internal qualification namespace.\n *\n * @remarks\n * A quantitative result contributes its numeric `value`. A logical result\n * contributes a record of its `conclusion` plus every applied rule's asserted\n * conclusion fields (`extractConclusions`). A mismatched pairing contributes\n * `false`. The projection is pure — it never mutates the subject or the result.\n *\n * @param definition - The pass definition that produced the result\n * @param result - The evaluated reason result\n * @returns The pass's working projection\n *\n * @example\n * ```ts\n * import { reasonResultToProjection } from '@orkestrel/qualifier'\n * import { createFactorGroup, createQuantitativeDefinition, createStaticFactor } from '@orkestrel/reason'\n *\n * const cap = createQuantitativeDefinition('cap', 'TIV cap', [\n * createFactorGroup('limit', 'sum', [createStaticFactor('base', 500_000)]),\n * ])\n * const result = {\n * reasoning: 'quantitative' as const,\n * value: 500_000,\n * groups: [],\n * count: 1,\n * success: true,\n * trace: [],\n * refusals: [],\n * faults: [],\n * repairs: [],\n * defaulted: [],\n * }\n * reasonResultToProjection(cap, result) // 500000\n * ```\n */\nexport function reasonResultToProjection(\n\tdefinition: QualificationPass,\n\tresult: ReasonResult,\n): QualificationProjection {\n\tif (definition.reasoning === 'quantitative' && result.reasoning === 'quantitative') {\n\t\treturn result.value\n\t}\n\tif (definition.reasoning !== 'logical' || result.reasoning !== 'logical') return false\n\t// An unfired rule's keys read false first, so a key another rule fired keeps that rule's value,\n\t// and the pass's own conclusion goes last, so no rule can stand in for it.\n\tconst fields = ['unmet', 'met'].flatMap((state) =>\n\t\tresult.rules\n\t\t\t.filter((resolved) => resolved.state === state)\n\t\t\t.flatMap((resolved) => {\n\t\t\t\tconst authored = definition.rules.find((rule) => rule.id === resolved.id)\n\t\t\t\tif (authored === undefined) return []\n\t\t\t\treturn Object.entries(extractConclusions(authored.conclusion)).map(\n\t\t\t\t\t([key, value]): readonly [string, unknown] => [key, state === 'met' ? value : false],\n\t\t\t\t)\n\t\t\t}),\n\t)\n\treturn Object.fromEntries([...fields, ['conclusion', result.conclusion === 'met']])\n}\n\n/**\n * Replaces a read of an unread pass's projection with what that pass could not read.\n *\n * @remarks\n * A pass reading `qualification.gates.blocked` is unread because `gates` projected nothing, so\n * the question to ask is the one `gates` could not answer. A read of a pass that settled stays,\n * because that pass holds no such key. Passes run in order and each stores its expanded faults,\n * so a chain of unread passes reaches the input that started it.\n *\n * @param faults - The faults every pass reported, in order\n * @param unread - The faults of each unread pass, by pass id\n * @returns The input faults, once per field\n *\n * @example\n * ```ts\n * import { expandPassFaults } from '@orkestrel/qualifier'\n *\n * const leaf = { reason: 'missing', path: 'age', expected: 'number' } as const\n * const read = { reason: 'missing', path: ['qualification', 'gates', 'ok'], expected: 'boolean' } as const\n * expandPassFaults([read], new Map([['gates', [leaf]]])) // [leaf]\n * ```\n */\nexport function expandPassFaults(\n\tfaults: readonly AuditFault[],\n\tunread: ReadonlyMap<string, readonly AuditFault[]>,\n): readonly AuditFault[] {\n\treturn filterUniqueFaults(\n\t\tfaults.flatMap((fault) => {\n\t\t\t// A projection is read through an array path, and its second key is the pass id whole.\n\t\t\tconst { path } = fault\n\t\t\tif (!isArray(path) || path[0] !== QUALIFICATION_KEY) return [fault]\n\t\t\treturn unread.get(path[1] ?? '') ?? [fault]\n\t\t}),\n\t)\n}\n\n/**\n * Describes what the definition's shape cannot stand for: a read of a field it does not declare,\n * and the reserved `qualification` key, which a default could otherwise fill.\n *\n * @remarks\n * A read under `qualification` reads a pass's projection, and a pass's own conclusion keys are\n * its own, so neither needs a declaration. A host that projects a key of its own names it in\n * `projections`. A `raw` or `json` read is a warning.\n *\n * @param definition - The definition\n * @param projections - Further keys the host projects onto the subject. Default: none\n * @returns The errors and warnings, empty with no shape\n *\n * @example\n * ```ts\n * import { numberShape, objectShape } from '@orkestrel/contract'\n * import { createQualificationDefinition, scanDefinitionShape } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const pass = createLogicalDefinition('gates', 'Gates', [\n * createRule('r', [createAtom('agee', 'above', 1)], createAtom('ok', 'equals', true)),\n * ])\n * const shape = objectShape({ age: numberShape() })\n * scanDefinitionShape(createQualificationDefinition('d', 'd', [pass], { shape })).errors.length // 1\n * ```\n */\nexport function scanDefinitionShape(\n\tdefinition: QualificationDefinition,\n\tprojections: readonly string[] = [],\n): ShapeScan {\n\tconst { shape } = definition\n\tif (shape === undefined) return { errors: [], warnings: [] }\n\tconst scans = definition.passes.map((pass) => {\n\t\tif (pass.reasoning === 'logical') {\n\t\t\tconst enabled = pass.rules.filter((rule) => rule.enabled !== false)\n\t\t\tconst checks = enabled\n\t\t\t\t.flatMap((rule) => rule.premises.flatMap((premise) => extractAtoms(premise)))\n\t\t\t\t.map((atom) => atom.check)\n\t\t\t\t.filter((check) => !readsProjection(check.field, projections))\n\t\t\treturn scanShapeReads(shape, checks, [], new Set(collectConcluders(enabled).keys()))\n\t\t}\n\t\tconst factors = pass.groups.flatMap((group) => group.factors)\n\t\treturn scanShapeReads(\n\t\t\tshape,\n\t\t\tfactors\n\t\t\t\t.flatMap((factor) => factor.checks ?? [])\n\t\t\t\t.filter((check) => !readsProjection(check.field, projections)),\n\t\t\tfactors\n\t\t\t\t.flatMap((factor) => (factor.source.origin === 'static' ? [] : [factor.source.field]))\n\t\t\t\t.filter((field) => !readsProjection(field, projections)),\n\t\t\tnew Set(),\n\t\t)\n\t})\n\treturn {\n\t\terrors: [\n\t\t\t...(findFieldShape(shape, QUALIFICATION_KEY).shape === undefined\n\t\t\t\t? []\n\t\t\t\t: [`Shape declares the reserved key '${QUALIFICATION_KEY}'`]),\n\t\t\t...new Set(scans.flatMap((scan) => scan.errors)),\n\t\t],\n\t\twarnings: [...new Set(scans.flatMap((scan) => scan.warnings))],\n\t}\n}\n\n/**\n * Determines whether a field reads a pass's projection under `qualification`, or a key the host projects.\n *\n * @param field - The field\n * @param projections - Further keys the host projects onto the subject. Default: none\n * @returns True for an array path starting at the reserved key or a projected key; false otherwise\n *\n * @example\n * ```ts\n * import { readsProjection } from '@orkestrel/qualifier'\n *\n * readsProjection(['qualification', 'gates', 'ok']) // true\n * readsProjection(['aggregate', 'count'], ['aggregate']) // true\n * readsProjection('age') // false\n * ```\n */\nexport function readsProjection(field: FieldPath, projections: readonly string[] = []): boolean {\n\tif (!isArray(field)) return false\n\tconst key = field[0]\n\treturn key === QUALIFICATION_KEY || (key !== undefined && projections.includes(key))\n}\n\n/**\n * Describes each rule concluding `conclusion`, which a pass's projection reserves for itself.\n *\n * @param definition - The definition\n * @returns One message per such rule\n *\n * @example\n * ```ts\n * import { createQualificationDefinition, describeReservedConclusions } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const pass = createLogicalDefinition('gates', 'Gates', [\n * createRule('r', [createAtom('a', 'equals', 1)], createAtom('conclusion', 'equals', true)),\n * ])\n * describeReservedConclusions(createQualificationDefinition('d', 'd', [pass])).length // 1\n * ```\n */\nexport function describeReservedConclusions(\n\tdefinition: QualificationDefinition,\n): readonly string[] {\n\treturn definition.passes.flatMap((pass) =>\n\t\tpass.reasoning !== 'logical'\n\t\t\t? []\n\t\t\t: pass.rules\n\t\t\t\t\t.filter((rule) => Object.hasOwn(extractConclusions(rule.conclusion), 'conclusion'))\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(rule) =>\n\t\t\t\t\t\t\t`Rule '${rule.id}' in pass '${pass.id}' concludes the reserved key 'conclusion'`,\n\t\t\t\t\t),\n\t)\n}\n\n/**\n * Finds each rule a logical result does not answer: one it left unread, and an enabled one it\n * omits.\n *\n * @param definition - The logical pass\n * @param result - The result of the pass\n * @returns The rule ids, each once, the unread ones first\n *\n * @example\n * ```ts\n * import { findUnansweredRules } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const gates = createLogicalDefinition('gates', 'Gates', [\n * createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true)),\n * ])\n * findUnansweredRules(gates, {\n * reasoning: 'logical',\n * conclusion: 'unmet',\n * rules: [],\n * count: 0,\n * success: true,\n * trace: [],\n * refusals: [],\n * faults: [],\n * repairs: [],\n * defaulted: [],\n * }) // ['licensed']\n * ```\n */\nexport function findUnansweredRules(\n\tdefinition: LogicalDefinition,\n\tresult: LogicalResult,\n): readonly string[] {\n\tconst answered = new Set(result.rules.map((rule) => rule.id))\n\treturn [\n\t\t...new Set([\n\t\t\t...result.rules.filter((rule) => rule.state === 'unread').map((rule) => rule.id),\n\t\t\t...definition.rules\n\t\t\t\t.filter((rule) => rule.enabled !== false && !answered.has(rule.id))\n\t\t\t\t.map((rule) => rule.id),\n\t\t]),\n\t]\n}\n\n/**\n * Collects why an answer refused: the engine's own refusals, and what the answer leaves out or\n * contradicts by itself.\n *\n * @remarks\n * A failure naming no refusal and no fault is `silent`. A success is `malformed` beside a refusal\n * or a fault, and at a value that is not finite, held in `actual`. Whatever verdict it claims, an\n * answer is `malformed` for each rule it lists more than once, named in `rule`.\n *\n * @param result - The engine's answer\n * @returns The refusals, with no path of this package's\n *\n * @example\n * ```ts\n * import { collectAnswerRefusals } from '@orkestrel/qualifier'\n *\n * collectAnswerRefusals({\n * reasoning: 'quantitative',\n * value: Number.NaN,\n * groups: [],\n * count: 0,\n * success: true,\n * trace: [],\n * refusals: [],\n * faults: [],\n * repairs: [],\n * defaulted: [],\n * }) // [{ cause: 'malformed', actual: NaN }]\n * ```\n */\nexport function collectAnswerRefusals(result: ReasonResult): readonly ReasonRefusal[] {\n\tconst { refusals, faults, success } = result\n\tconst named = refusals.length > 0 || faults.length > 0\n\tconst repeated =\n\t\tresult.reasoning === 'logical'\n\t\t\t? findDuplicates(result.rules).map((rule): ReasonRefusal => ({ cause: 'malformed', rule }))\n\t\t\t: []\n\tconst silent: readonly ReasonRefusal[] = named ? [] : [{ cause: 'silent' }]\n\tif (!success) return [...refusals, ...silent, ...repeated]\n\tconst beside: readonly ReasonRefusal[] = named ? [{ cause: 'malformed' }] : []\n\tconst valued: readonly ReasonRefusal[] =\n\t\tresult.reasoning === 'quantitative' && !isFiniteNumber(result.value)\n\t\t\t? [{ cause: 'malformed', actual: result.value }]\n\t\t\t: []\n\treturn [...refusals, ...beside, ...valued, ...repeated]\n}\n\n/**\n * Collects why a pass refused: the engine's own refusals under the pass id, and what its answer\n * leaves out or contradicts.\n *\n * @remarks\n * An injected engine answers through an interface, so its verdict is checked against the rest of\n * its answer, as `collectAnswerRefusals` does, and against its pass. An answer of another\n * reasoning is `malformed`, and so is a success for each rule it does not answer, named in `rule`.\n *\n * @param pass - The pass the engine ran\n * @param result - The engine's answer\n * @returns The refusals, each with the pass id at the head of its `path`\n *\n * @example\n * ```ts\n * import { collectPassRefusals } from '@orkestrel/qualifier'\n * import { createQuantitativeDefinition } from '@orkestrel/reason'\n *\n * collectPassRefusals(createQuantitativeDefinition('cap', 'Cap', []), {\n * reasoning: 'quantitative',\n * value: 0,\n * groups: [],\n * count: 0,\n * success: false,\n * trace: [],\n * refusals: [],\n * faults: [],\n * repairs: [],\n * defaulted: [],\n * }) // [{ cause: 'silent', path: ['cap'] }]\n * ```\n */\nexport function collectPassRefusals(\n\tpass: QualificationPass,\n\tresult: ReasonResult,\n): readonly ReasonRefusal[] {\n\tif (result.reasoning !== pass.reasoning) {\n\t\treturn nestRefusals([...result.refusals, { cause: 'malformed' }], pass.id)\n\t}\n\tconst refusals = collectAnswerRefusals(result)\n\t// A rule the answer repeats is refused already.\n\tconst refused = new Set(\n\t\trefusals.filter(({ cause }) => cause === 'malformed').map(({ rule }) => rule),\n\t)\n\tconst unanswered =\n\t\tresult.success && pass.reasoning === 'logical' && result.reasoning === 'logical'\n\t\t\t? findUnansweredRules(pass, result).filter((rule) => !refused.has(rule))\n\t\t\t: []\n\treturn nestRefusals(\n\t\t[...refusals, ...unanswered.map((rule): ReasonRefusal => ({ cause: 'malformed', rule }))],\n\t\tpass.id,\n\t)\n}\n\n/**\n * Describes each message token no field of the definition's shape answers.\n *\n * @remarks\n * A token under `qualification` reads a pass's projection, which no shape declares.\n *\n * @param definition - The definition\n * @returns One message per unknown token, empty with no shape\n *\n * @example\n * ```ts\n * import { numberShape, objectShape } from '@orkestrel/contract'\n * import { createQualificationDefinition, createRuling, describeUnknownTokens } from '@orkestrel/qualifier'\n *\n * const ruling = createRuling('r', 'gates', 'licensed', 'referral', { message: 'Age {{agee}}' })\n * const shape = objectShape({ age: numberShape() })\n * describeUnknownTokens(createQualificationDefinition('d', 'd', [], { rulings: [ruling], shape }))\n * // ['Ruling \\'r\\' message reads \"agee\", and the shape does not declare it']\n * ```\n */\nexport function describeUnknownTokens(definition: QualificationDefinition): readonly string[] {\n\tconst { shape } = definition\n\tif (shape === undefined) return []\n\treturn (definition.rulings ?? []).flatMap((ruling) =>\n\t\tfindMessageTokens(ruling.message ?? '').flatMap((token) => {\n\t\t\tconst path = token.split('.')\n\t\t\tif (path[0] === QUALIFICATION_KEY || findFieldShape(shape, path).declared) return []\n\t\t\treturn [`Ruling '${ruling.id}' message reads \"${token}\", and the shape does not declare it`]\n\t\t}),\n\t)\n}\n\n/**\n * Projects a result to the JSON its contract reads.\n *\n * @remarks\n * A check's, a slot's, and a refusal's `actual` holds whatever the run read, and a derivation's\n * `value` may be `NaN`, so a result crosses a boundary as this projection, each `actual` on its\n * own budget.\n *\n * @param result - The qualification result\n * @returns Its JSON projection, which `qualificationResultContract` admits\n *\n * @example\n * ```ts\n * import { createQualificationDefinition, createQualifier, projectQualificationResult, qualificationResultContract } from '@orkestrel/qualifier'\n *\n * const qualifier = createQualifier()\n * const result = qualifier.qualify({}, createQualificationDefinition('d', 'd', []))\n * qualificationResultContract.is(projectQualificationResult(result)) // true\n * qualifier.destroy()\n * ```\n */\nexport function projectQualificationResult(result: QualificationResult): JSONValue | undefined {\n\tconst findings = result.findings.map((finding) => ({\n\t\t...finding,\n\t\t...(finding.message === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tmessage: finding.message.map((part) =>\n\t\t\t\t\t\tisString(part) ? part : projectMessageSlot(part),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\tchecks: finding.checks.map((check) => projectCheck(check)),\n\t}))\n\tconst derivations = result.derivations.map((derivation) => ({\n\t\t...derivation,\n\t\trefusals: derivation.refusals.map((refusal) => projectRefusal(refusal)),\n\t}))\n\tconst refusals = result.refusals.map((refusal) => projectRefusal(refusal))\n\treturn projectValue({ ...result, findings, derivations, refusals }, new Set(), {\n\t\tleft: Number.POSITIVE_INFINITY,\n\t})\n}\n\n/**\n * Projects a quantitative result into a {@link Derivation} audit record.\n *\n * @remarks\n * `refusals` are what `collectAnswerRefusals` collects, and `success` is false exactly when they or\n * the faults hold an entry, whatever verdict the result claims.\n *\n * @param id - The pass id\n * @param result - The evaluated quantitative result\n * @returns A fresh derivation\n *\n * @example\n * ```ts\n * import { quantitativeResultToDerivation } from '@orkestrel/qualifier'\n *\n * const result = { reasoning: 'quantitative' as const, value: 500_000, groups: [], count: 1, success: true, trace: ['cap: 500000'], refusals: [], faults: [], repairs: [], defaulted: [] }\n * quantitativeResultToDerivation('cap', result)\n * // { id: 'cap', value: 500000, success: true, trace: ['cap: 500000'], refusals: [], faults: [] }\n * ```\n */\nexport function quantitativeResultToDerivation(id: string, result: QuantitativeResult): Derivation {\n\tconst refusals = [...collectAnswerRefusals(result)]\n\tconst faults = [...result.faults]\n\treturn {\n\t\tid,\n\t\tvalue: result.value,\n\t\tsuccess: refusals.length === 0 && faults.length === 0,\n\t\ttrace: [...result.trace],\n\t\trefusals,\n\t\tfaults,\n\t}\n}\n\n/**\n * Wraps a {@link QualificationContext} under {@link QUALIFICATION_KEY}.\n *\n * @param context - The accumulated projection context\n * @returns A record carrying the context under the reserved key\n *\n * @example\n * ```ts\n * import { qualificationToRecord } from '@orkestrel/qualifier'\n *\n * qualificationToRecord({ cap: 500_000 }) // { qualification: { cap: 500000 } }\n * ```\n */\nexport function qualificationToRecord(\n\tcontext: QualificationContext,\n): Readonly<Record<string, QualificationContext>> {\n\treturn { [QUALIFICATION_KEY]: context }\n}\n\n/**\n * Merges one pass projection into the context, copy-on-write.\n *\n * @param context - The current projection context\n * @param id - The pass id to project under\n * @param projection - The pass's working projection\n * @returns A fresh context with the projection added\n *\n * @example\n * ```ts\n * import { mergeQualificationContext } from '@orkestrel/qualifier'\n *\n * mergeQualificationContext({ cap: 500_000 }, 'excess', 250_000)\n * // { cap: 500000, excess: 250000 }\n * ```\n */\nexport function mergeQualificationContext(\n\tcontext: QualificationContext,\n\tid: string,\n\tprojection: QualificationProjection,\n): QualificationContext {\n\treturn { ...context, [id]: projection }\n}\n\n/**\n * Joins a ruling, its logical rule result, the pass, and the pre-projection subject into a\n * {@link Finding}.\n *\n * @remarks\n * `state` is the state of the ruling's rule. A rule the result omits reads `unmet` when it is\n * disabled, which is authored, and `unread` otherwise, because a refused pass evaluated no rule.\n * `checks` are the rule result's own, empty for a rule the result omits. A rule the result lists\n * more than once reads `unread` with no checks, because no entry answers for it. The message is\n * split against the subject.\n *\n * @param ruling - The authored ruling\n * @param pass - The pass the ruling's rule lives in\n * @param result - The pass's evaluated logical result\n * @param subject - The pre-projection subject snapshot the pass evaluated\n * @returns A fresh finding\n *\n * @example\n * ```ts\n * import { rulingToFinding } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const gates = createLogicalDefinition('gates', 'Gates', [\n * createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true)),\n * ])\n * const ruling = { id: 'license', pass: 'gates', rule: 'licensed', effect: 'restriction' as const }\n * const result = {\n * reasoning: 'logical' as const,\n * conclusion: 'met' as const,\n * rules: [{ id: 'licensed', state: 'met' as const, premises: ['met' as const], checks: [] }],\n * count: 1,\n * success: true,\n * trace: [],\n * refusals: [],\n * faults: [],\n * repairs: [],\n * defaulted: [],\n * }\n * rulingToFinding(ruling, gates, result, { licensed: false }).state // 'met'\n * ```\n */\nexport function rulingToFinding(\n\truling: Ruling,\n\tpass: QualificationPass,\n\tresult: LogicalResult,\n\tsubject: Subject,\n): Finding {\n\tconst entries = result.rules.filter((resolved) => resolved.id === ruling.rule)\n\tconst repeated = entries.length > 1\n\tconst entry = repeated ? undefined : entries[0]\n\tconst rule = pass.reasoning === 'logical' ? findRule(pass, ruling.rule) : undefined\n\treturn {\n\t\tid: ruling.id,\n\t\tpass: ruling.pass,\n\t\trule: ruling.rule,\n\t\teffect: ruling.effect,\n\t\t...(ruling.scope === undefined ? {} : { scope: ruling.scope }),\n\t\t// A disabled rule is authored not to fire. Any other rule missing here was never evaluated.\n\t\tstate: entry?.state ?? (rule?.enabled === false && !repeated ? 'unmet' : 'unread'),\n\t\t...(ruling.message === undefined ? {} : { message: splitMessage(ruling.message, subject) }),\n\t\tchecks: [...(entry?.checks ?? [])],\n\t}\n}\n\n/**\n * Derives global eligibility from unscoped findings whose rule is met.\n *\n * @remarks\n * Only findings that are `met` and carry no `scope` shape global eligibility.\n * A failed pass contributes a synthetic `referral` (fail-closed), passed through\n * `failed`.\n *\n * @param findings - The resolved findings\n * @param failed - If `true`, adds a synthetic `referral` impact so an operational failure\n * fails closed; if `false`, derives eligibility from the findings alone. Default: `false`\n * @returns The most severe global eligibility\n *\n * @example\n * ```ts\n * import { deriveFindingEligibility } from '@orkestrel/qualifier'\n *\n * const finding = { id: 'license', pass: 'gates', rule: 'licensed', effect: 'restriction' as const, state: 'met' as const, checks: [] }\n * deriveFindingEligibility([finding]) // 'ineligible'\n * ```\n */\nexport function deriveFindingEligibility(\n\tfindings: readonly Finding[],\n\tfailed = false,\n): Eligibility {\n\tconst eligibilities = findings\n\t\t.filter((finding) => finding.state === 'met' && finding.scope === undefined)\n\t\t.map((finding) => EFFECT_ELIGIBILITIES[finding.effect])\n\tif (failed) eligibilities.push('referral')\n\treturn combineEligibilities(eligibilities)\n}\n\n/**\n * Returns the most severe {@link Eligibility} in a list.\n *\n * @param eligibilities - The eligibilities to combine\n * @returns The most severe eligibility, or `'eligible'` for an empty list\n *\n * @example\n * ```ts\n * import { combineEligibilities } from '@orkestrel/qualifier'\n *\n * combineEligibilities(['eligible', 'referral']) // 'referral'\n * ```\n */\nexport function combineEligibilities(eligibilities: readonly Eligibility[]): Eligibility {\n\tfor (const eligibility of ELIGIBILITY_PRECEDENCE) {\n\t\tif (eligibilities.includes(eligibility)) return eligibility\n\t}\n\treturn 'eligible'\n}\n\n/**\n * Derives one eligibility per finding scope.\n *\n * @remarks\n * Only scoped findings that are `met` contribute. Each named scope combines its own\n * findings' impacts by severity. A scope no finding is met for is absent, which is eligible only\n * where the run succeeded, because a finding left unread leaves its scope absent too.\n *\n * @param findings - The resolved findings\n * @returns A fresh record of scope to its combined eligibility\n *\n * @example\n * ```ts\n * import { deriveScopeEligibilities } from '@orkestrel/qualifier'\n *\n * const finding = { id: 'coastal', pass: 'wind', rule: 'coastal', effect: 'restriction' as const, scope: 'wind', state: 'met' as const, checks: [] }\n * deriveScopeEligibilities([finding]) // { wind: 'ineligible' }\n * ```\n */\nexport function deriveScopeEligibilities(\n\tfindings: readonly Finding[],\n): Readonly<Record<string, Eligibility>> {\n\t// A Map, because a scope may be named `constructor` or `__proto__`.\n\tconst grouped = new Map<string, Eligibility[]>()\n\tfor (const finding of findings) {\n\t\tif (finding.state !== 'met' || finding.scope === undefined) continue\n\t\tconst current = grouped.get(finding.scope) ?? []\n\t\tgrouped.set(finding.scope, [...current, EFFECT_ELIGIBILITIES[finding.effect]])\n\t}\n\treturn Object.fromEntries(\n\t\t[...grouped].map(([scope, eligibilities]) => [scope, combineEligibilities(eligibilities)]),\n\t)\n}\n\n/**\n * Describes each ruling whose pass or rule does not exist or whose pass is not\n * logical, and each pass id shadowing the reserved {@link QUALIFICATION_KEY}.\n *\n * @param definition - The qualification definition to check\n * @returns A fresh list of reference-error messages\n *\n * @example\n * ```ts\n * import { createQualificationDefinition, createRuling, describeMissingReferences } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const gates = createLogicalDefinition('gates', 'Gates', [\n * createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true)),\n * ])\n * const definition = createQualificationDefinition('standard', 'Standard', [gates], {\n * rulings: [createRuling('license', 'gates', 'absent', 'restriction')],\n * })\n *\n * describeMissingReferences(definition)\n * // [\"Ruling 'license' references missing rule 'absent' in pass 'gates'\"]\n * ```\n */\nexport function describeMissingReferences(definition: QualificationDefinition): readonly string[] {\n\tconst errors: string[] = []\n\tconst passes = new Map(definition.passes.map((pass) => [pass.id, pass]))\n\tfor (const pass of definition.passes) {\n\t\tif (pass.id === QUALIFICATION_KEY) {\n\t\t\terrors.push(`Pass id must not equal reserved key '${QUALIFICATION_KEY}'`)\n\t\t}\n\t}\n\tfor (const ruling of definition.rulings ?? []) {\n\t\tconst pass = passes.get(ruling.pass)\n\t\tif (pass === undefined) {\n\t\t\terrors.push(`Ruling '${ruling.id}' references missing pass '${ruling.pass}'`)\n\t\t\tcontinue\n\t\t}\n\t\tif (pass.reasoning !== 'logical') {\n\t\t\terrors.push(`Ruling '${ruling.id}' references non-logical pass '${ruling.pass}'`)\n\t\t\tcontinue\n\t\t}\n\t\tif (findRule(pass, ruling.rule) === undefined) {\n\t\t\terrors.push(\n\t\t\t\t`Ruling '${ruling.id}' references missing rule '${ruling.rule}' in pass '${ruling.pass}'`,\n\t\t\t)\n\t\t}\n\t}\n\treturn errors\n}\n\n/**\n * Determines whether a subject already owns the reserved {@link QUALIFICATION_KEY}.\n *\n * @param subject - The subject to check\n * @returns True if the subject owns the reserved key; false otherwise\n *\n * @example\n * ```ts\n * import { hasReservedKey } from '@orkestrel/qualifier'\n *\n * hasReservedKey({ id: 's1', qualification: {} }) // true\n * ```\n */\nexport function hasReservedKey(subject: Subject): boolean {\n\treturn Object.hasOwn(subject, QUALIFICATION_KEY)\n}\n\n/**\n * Asserts a value is a valid qualification {@link Subject}, narrowing it in place.\n *\n * @param value - The candidate subject to validate\n * @throws {@link QualifierError} `'MISMATCH'` when the value is not a record, or\n * when it already carries the reserved `qualification` key\n *\n * @example\n * ```ts\n * import { assertSubject } from '@orkestrel/qualifier'\n *\n * assertSubject({ id: 's1' }) // narrows to Subject\n * ```\n */\nexport function assertSubject(value: unknown): asserts value is Subject {\n\tif (!isRecord(value)) {\n\t\tthrow new QualifierError('MISMATCH', 'Qualification subject must be a record')\n\t}\n\tif (hasReservedKey(value)) {\n\t\tthrow new QualifierError(\n\t\t\t'MISMATCH',\n\t\t\t`Qualification subject must not contain reserved key '${QUALIFICATION_KEY}'`,\n\t\t)\n\t}\n}\n\n/**\n * Maps an engine throw caught while running one pass to a typed {@link QualifierError}.\n *\n * @remarks\n * A reason `ReasonError('INVALID')` maps to `DEFINITION` (the engine rejected the\n * pass as an invalid definition); `ReasonError('DESTROYED')` maps to `DESTROYED`;\n * every other `ReasonError` code (for example `MISSING`) and every non-`ReasonError` throw\n * (including a `bail: true` reasoner rethrow) maps to `ENGINE`. The original throw\n * is preserved as `context.cause`.\n *\n * @param error - The value caught from the engine's `reason` call\n * @param pass - The id of the pass that was running\n * @returns A fresh, typed {@link QualifierError}\n *\n * @example\n * ```ts\n * import { mapEngineError } from '@orkestrel/qualifier'\n * import { ReasonError } from '@orkestrel/reason'\n *\n * mapEngineError(new ReasonError('MISSING', 'No reasoner registered'), 'cap').code // 'ENGINE'\n * ```\n */\nexport function mapEngineError(error: unknown, pass: string): QualifierError {\n\tif (isReasonError(error)) {\n\t\tif (error.code === 'INVALID') {\n\t\t\treturn new QualifierError(\n\t\t\t\t'DEFINITION',\n\t\t\t\t`Pass '${pass}' failed engine validation: ${error.message}`,\n\t\t\t\t{ pass, cause: error },\n\t\t\t)\n\t\t}\n\t\tif (error.code === 'DESTROYED') {\n\t\t\treturn new QualifierError(\n\t\t\t\t'DESTROYED',\n\t\t\t\t`Qualifier engine was destroyed during pass '${pass}'`,\n\t\t\t\t{ pass, cause: error },\n\t\t\t)\n\t\t}\n\t\treturn new QualifierError('ENGINE', `Pass '${pass}' engine failure: ${error.message}`, {\n\t\t\tpass,\n\t\t\tcause: error,\n\t\t})\n\t}\n\tconst message = isError(error) ? error.message : String(error)\n\treturn new QualifierError('ENGINE', `Pass '${pass}' engine failure: ${message}`, {\n\t\tpass,\n\t\tcause: error,\n\t})\n}\n\n/**\n * Describes each logical pass carrying no rulings.\n *\n * @remarks\n * A logical pass with no matching ruling can never contribute a finding, so its\n * rules only ever influence later passes' reads — this is very likely an authoring\n * oversight.\n *\n * @param definition - The qualification definition to check\n * @returns A fresh list of warning messages\n *\n * @example\n * ```ts\n * import { createQualificationDefinition, describeEmptyLogicalPasses } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const gates = createLogicalDefinition('gates', 'Gates', [\n * createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true)),\n * ])\n * const definition = createQualificationDefinition('standard', 'Standard', [gates])\n *\n * describeEmptyLogicalPasses(definition) // [\"Logical pass 'gates' has no rulings\"]\n * ```\n */\nexport function describeEmptyLogicalPasses(definition: QualificationDefinition): readonly string[] {\n\tconst warnings: string[] = []\n\tfor (const pass of definition.passes) {\n\t\tif (pass.reasoning !== 'logical') continue\n\t\tconst hasRuling = (definition.rulings ?? []).some((ruling) => ruling.pass === pass.id)\n\t\tif (!hasRuling) warnings.push(`Logical pass '${pass.id}' has no rulings`)\n\t}\n\treturn warnings\n}\n\n/**\n * Describes each quantitative pass never read by a later pass.\n *\n * @remarks\n * A quantitative pass's projected value lives under `qualification.<id>` — if no\n * later logical premise or quantitative factor field reads that key, the\n * derivation is dead weight. Reads are collected per later pass: a logical pass's\n * premise atoms (conclusion atoms are writes, not reads), and a quantitative\n * pass's field/lookup/range factor sources plus factor checks.\n *\n * @param definition - The qualification definition to check\n * @returns A fresh list of warning messages\n *\n * @example\n * ```ts\n * import { createQualificationDefinition, describeUnreadDerivations } from '@orkestrel/qualifier'\n * import { createFactorGroup, createQuantitativeDefinition, createStaticFactor } from '@orkestrel/reason'\n *\n * const cap = createQuantitativeDefinition('cap', 'TIV cap', [\n * createFactorGroup('limit', 'sum', [createStaticFactor('base', 500_000)]),\n * ])\n * const definition = createQualificationDefinition('standard', 'Standard', [cap])\n *\n * describeUnreadDerivations(definition) // [\"Quantitative pass 'cap' is never read by a later pass\"]\n * ```\n */\nexport function describeUnreadDerivations(definition: QualificationDefinition): readonly string[] {\n\tconst warnings: string[] = []\n\tdefinition.passes.forEach((pass, index) => {\n\t\tif (pass.reasoning !== 'quantitative') return\n\t\tconst key = formatField(['qualification', pass.id])\n\t\tconst reads = new Set<string>()\n\t\tfor (const later of definition.passes.slice(index + 1)) {\n\t\t\tif (later.reasoning === 'logical') {\n\t\t\t\tfor (const rule of later.rules) {\n\t\t\t\t\tfor (const premise of rule.premises) {\n\t\t\t\t\t\tfor (const atom of extractAtoms(premise)) reads.add(formatField(atom.check.field))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (later.reasoning === 'quantitative') {\n\t\t\t\tfor (const group of later.groups) {\n\t\t\t\t\tfor (const factor of group.factors) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tfactor.source.origin === 'field' ||\n\t\t\t\t\t\t\tfactor.source.origin === 'lookup' ||\n\t\t\t\t\t\t\tfactor.source.origin === 'range'\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\treads.add(formatField(factor.source.field))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (const check of factor.checks ?? []) reads.add(formatField(check.field))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!reads.has(key)) {\n\t\t\twarnings.push(`Quantitative pass '${pass.id}' is never read by a later pass`)\n\t\t}\n\t})\n\treturn warnings\n}\n","import type { ReasonResult } from '@orkestrel/reason'\nimport { attempt, isArray, isObject, isRecord, isString, isSuccess } from '@orkestrel/contract'\nimport { isReasonResult } from '@orkestrel/reason'\n\n/**\n * Copies a list, reading its length and each entry once.\n *\n * @param value - The value to copy\n * @param clone - Copies one entry. Default: carries it as it is\n * @returns A fresh list, or the value itself when it is no list\n *\n * @example\n * ```ts\n * import { cloneList } from '@orkestrel/qualifier'\n *\n * cloneList(['a', 'b']) // ['a', 'b']\n * cloneList('a') // 'a'\n * ```\n */\nexport function cloneList(value: unknown, clone?: (entry: unknown) => unknown): unknown {\n\tif (!isArray<unknown>(value)) return value\n\treturn Array.from({ length: value.length }, (_, index) => {\n\t\tconst entry = value[index]\n\t\treturn clone === undefined ? entry : clone(entry)\n\t})\n}\n\n/**\n * Copies the named members a value has into a plain record, reading each once.\n *\n * @remarks\n * An inherited member and an accessor count, so a class instance keeps what it gives. A member the\n * names leave out is dropped, and one the value lacks stays absent.\n *\n * @param value - The value to copy\n * @param names - The members to read\n * @param clones - Copies a member of that name; any other is carried as it is. Default: none\n * @returns A fresh record, or the value itself when it is a list or no object\n *\n * @example\n * ```ts\n * import { cloneMembers } from '@orkestrel/qualifier'\n *\n * cloneMembers({ a: 1, b: 2 }, ['a']) // { a: 1 }\n * ```\n */\nexport function cloneMembers(\n\tvalue: unknown,\n\tnames: readonly PropertyKey[],\n\tclones: Readonly<Record<string, (member: unknown) => unknown>> = {},\n): unknown {\n\tif (!isObject(value) || isArray(value)) return value\n\treturn Object.fromEntries(\n\t\tnames\n\t\t\t.filter((name) => Reflect.has(value, name))\n\t\t\t.map((name): readonly [PropertyKey, unknown] => {\n\t\t\t\tconst member: unknown = Reflect.get(value, name)\n\t\t\t\tconst clone = isString(name) && Object.hasOwn(clones, name) ? clones[name] : undefined\n\t\t\t\treturn [name, clone === undefined ? member : clone(member)]\n\t\t\t}),\n\t)\n}\n\n/**\n * Copies an untrusted engine's answer, reading each member a verdict rests on once, and admits the\n * copy alone.\n *\n * @remarks\n * Reading the answer again could give another verdict, so everything is derived from the copy. A\n * check's and a refusal's `actual` and a check's expected value are carried by identity, and so are\n * the members that hold no verdict, such as a quantitative result's `groups`. A member its contract\n * does not name is dropped. It never throws.\n *\n * @param value - The answer\n * @returns The copy, or `undefined` when it is no reason result or throws on being read\n *\n * @example\n * ```ts\n * import { cloneReasonResult } from '@orkestrel/qualifier'\n * import { createLogicalDefinition, createLogicalReasoner } from '@orkestrel/reason'\n *\n * const result = createLogicalReasoner().reason({}, createLogicalDefinition('d', 'd', []))\n * cloneReasonResult(result)?.success // true\n * cloneReasonResult({ success: true }) // undefined\n * ```\n */\nexport function cloneReasonResult(value: unknown): ReasonResult | undefined {\n\tconst outcome = attempt(() =>\n\t\tcloneMembers(\n\t\t\tvalue,\n\t\t\t[\n\t\t\t\t'reasoning',\n\t\t\t\t'value',\n\t\t\t\t'groups',\n\t\t\t\t'conclusion',\n\t\t\t\t'rules',\n\t\t\t\t'count',\n\t\t\t\t'solutions',\n\t\t\t\t'bindings',\n\t\t\t\t'derived',\n\t\t\t\t'proof',\n\t\t\t\t'success',\n\t\t\t\t'trace',\n\t\t\t\t'refusals',\n\t\t\t\t'faults',\n\t\t\t\t'repairs',\n\t\t\t\t'defaulted',\n\t\t\t],\n\t\t\t{\n\t\t\t\ttrace: (trace) => cloneList(trace),\n\t\t\t\trefusals: (refusals) =>\n\t\t\t\t\tcloneList(refusals, (refusal) =>\n\t\t\t\t\t\tcloneMembers(\n\t\t\t\t\t\t\trefusal,\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t'cause',\n\t\t\t\t\t\t\t\t'path',\n\t\t\t\t\t\t\t\t'rule',\n\t\t\t\t\t\t\t\t'group',\n\t\t\t\t\t\t\t\t'factor',\n\t\t\t\t\t\t\t\t'equation',\n\t\t\t\t\t\t\t\t'deduction',\n\t\t\t\t\t\t\t\t'index',\n\t\t\t\t\t\t\t\t'key',\n\t\t\t\t\t\t\t\t'operator',\n\t\t\t\t\t\t\t\t'field',\n\t\t\t\t\t\t\t\t'actual',\n\t\t\t\t\t\t\t\t'depth',\n\t\t\t\t\t\t\t\t'message',\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t{ path: (path) => cloneList(path), field: (field) => cloneList(field) },\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t// A fault is a plain record of its declared members alone, so each one it has is copied.\n\t\t\t\tfaults: (faults) =>\n\t\t\t\t\tcloneList(faults, (fault) =>\n\t\t\t\t\t\tisRecord(fault)\n\t\t\t\t\t\t\t? cloneMembers(fault, Reflect.ownKeys(fault), {\n\t\t\t\t\t\t\t\t\tpath: (path) => cloneList(path),\n\t\t\t\t\t\t\t\t\texpected: (expected) => cloneList(expected),\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t: fault,\n\t\t\t\t\t),\n\t\t\t\trules: (rules) =>\n\t\t\t\t\tcloneList(rules, (rule) =>\n\t\t\t\t\t\tcloneMembers(rule, ['id', 'state', 'premises', 'checks'], {\n\t\t\t\t\t\t\tpremises: (premises) => cloneList(premises),\n\t\t\t\t\t\t\tchecks: (checks) =>\n\t\t\t\t\t\t\t\tcloneList(checks, (read) =>\n\t\t\t\t\t\t\t\t\tcloneMembers(read, ['check', 'state', 'actual'], {\n\t\t\t\t\t\t\t\t\t\tcheck: (check) =>\n\t\t\t\t\t\t\t\t\t\t\tcloneMembers(check, ['field', 'operator', 'value'], {\n\t\t\t\t\t\t\t\t\t\t\t\tfield: (field) => cloneList(field),\n\t\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t},\n\t\t),\n\t)\n\treturn isSuccess(outcome) && isReasonResult(outcome.value) ? outcome.value : undefined\n}\n","import type { ContractShape } from '@orkestrel/contract'\nimport {\n\tarrayShape,\n\tauditFaultShape,\n\tshapeShape,\n\tjsonShape,\n\tliteralShape,\n\tnullableShape,\n\tnumberShape,\n\tobjectShape,\n\toptionalShape,\n\trecordShape,\n\tstringShape,\n\tbooleanShape,\n\tunionShape,\n} from '@orkestrel/contract'\nimport {\n\tCHECK_STATES,\n\tcheckResultShape,\n\tcreateLogicalDefinitionShape,\n\tfieldPathShape,\n\tquantitativeDefinitionShape,\n\treasonRefusalShape,\n} from '@orkestrel/reason'\nimport { ELIGIBILITIES, QUALIFICATION_EFFECTS } from './constants.js'\n\n// A qualification definition and result as shapes, so they reach an LLM, a tool, and MCP as JSON\n// Schema. A definition holds logical passes, whose recursive expressions `reason` builds behind a\n// function, so the definition's shape is behind one too and an import pays nothing for it.\n\n/** Describes a `Ruling`. */\nexport const rulingShape: ContractShape = objectShape({\n\tid: stringShape(),\n\tpass: stringShape(),\n\trule: stringShape(),\n\teffect: literalShape(QUALIFICATION_EFFECTS),\n\tscope: optionalShape(stringShape()),\n\tmessage: optionalShape(stringShape()),\n})\n\n/**\n * Creates the shape of a `QualificationDefinition`.\n *\n * @remarks\n * `shape` is checked as a recursive contract shape.\n *\n * @returns A shape holding quantitative and logical passes and rulings\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { createQualificationDefinition, createQualificationDefinitionShape } from '@orkestrel/qualifier'\n *\n * createContract(createQualificationDefinitionShape()).is(createQualificationDefinition('d', 'd', [])) // true\n * ```\n */\nexport function createQualificationDefinitionShape(): ContractShape {\n\treturn objectShape({\n\t\tid: stringShape(),\n\t\tname: stringShape(),\n\t\tdescription: optionalShape(stringShape()),\n\t\tpasses: arrayShape(unionShape(quantitativeDefinitionShape, createLogicalDefinitionShape())),\n\t\trulings: optionalShape(arrayShape(rulingShape)),\n\t\tmetadata: optionalShape(recordShape(jsonShape())),\n\t\tshape: optionalShape(shapeShape()),\n\t})\n}\n\n/** Describes a `MessageSlot` in its JSON projection. */\nexport const messageSlotShape: ContractShape = objectShape({\n\tfield: fieldPathShape,\n\tactual: optionalShape(jsonShape()),\n})\n\n/** Describes a `Finding` in its JSON projection. */\nexport const findingShape: ContractShape = objectShape({\n\tid: stringShape(),\n\tpass: stringShape(),\n\trule: stringShape(),\n\teffect: literalShape(QUALIFICATION_EFFECTS),\n\tscope: optionalShape(stringShape()),\n\tstate: literalShape(CHECK_STATES),\n\tmessage: optionalShape(arrayShape(unionShape(stringShape(), messageSlotShape))),\n\tchecks: arrayShape(checkResultShape),\n})\n\n/** Describes a `Derivation` in its JSON projection, where a non-finite number is `null`. */\nexport const derivationShape: ContractShape = objectShape({\n\tid: stringShape(),\n\tvalue: nullableShape(numberShape()),\n\tsuccess: booleanShape(),\n\ttrace: arrayShape(stringShape()),\n\trefusals: arrayShape(reasonRefusalShape),\n\tfaults: arrayShape(auditFaultShape()),\n})\n\n/** Describes a `QualificationResult` in its JSON projection. */\nexport const qualificationResultShape: ContractShape = objectShape({\n\tid: stringShape(),\n\tname: stringShape(),\n\teligibility: literalShape(ELIGIBILITIES),\n\tscopes: recordShape(literalShape(ELIGIBILITIES)),\n\tfindings: arrayShape(findingShape),\n\tderivations: arrayShape(derivationShape),\n\tsuccess: booleanShape(),\n\ttrace: arrayShape(stringShape()),\n\trefusals: arrayShape(reasonRefusalShape),\n\tfaults: arrayShape(auditFaultShape()),\n\trepairs: arrayShape(auditFaultShape()),\n\tdefaulted: arrayShape(fieldPathShape),\n})\n","import type { ContractInterface } from '@orkestrel/contract'\nimport { createContract } from '@orkestrel/contract'\nimport { qualificationResultShape } from './shapers.js'\n\n/** Publishes a `QualificationResult`'s JSON projection as a contract, read through `projectQualificationResult`. */\nexport const qualificationResultContract: ContractInterface<unknown> =\n\tcreateContract(qualificationResultShape)\n","import type {\n\tDerivation,\n\tFinding,\n\tQualificationContext,\n\tQualificationDefinition,\n\tQualificationPass,\n\tQualificationResult,\n\tQualifierEventMap,\n\tQualifierInterface,\n\tQualifierOptions,\n} from './types.js'\nimport type { AuditFault } from '@orkestrel/contract'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tReasonInterface,\n\tReasonRefusal,\n\tReasonResult,\n\tReasonValidationResult,\n\tSubject,\n\tSubjectAdmission,\n} from '@orkestrel/reason'\nimport { cloneReasonResult } from './cloners.js'\nimport { DEFAULT_QUALIFIER_VALIDATE } from './constants.js'\nimport { QualifierError } from './errors.js'\nimport {\n\tassertSubject,\n\tcollectPassRefusals,\n\tdescribeEmptyLogicalPasses,\n\tdescribeMissingReferences,\n\tdescribeReservedConclusions,\n\tdescribeUnknownTokens,\n\tdescribeUnreadDerivations,\n\tderiveFindingEligibility,\n\tderiveScopeEligibilities,\n\texpandPassFaults,\n\tmapEngineError,\n\tmergeQualificationContext,\n\tqualificationToRecord,\n\tquantitativeResultToDerivation,\n\treasonResultToProjection,\n\trulingToFinding,\n\tscanDefinitionShape,\n} from './helpers.js'\nimport {\n\tisDefinitionMetadata,\n\tisQualificationDefinition,\n\tisQualificationPass,\n\tisRuling,\n} from './validators.js'\nimport { isArray, isRecord, isString } from '@orkestrel/contract'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tcreateLogicalReasoner,\n\tcreateQuantitativeReasoner,\n\tcreateReason,\n\tcreateSubjectDoor,\n\tfilterUniqueFaults,\n\tisContractShape,\n\tscanShape,\n\tfindDuplicates,\n} from '@orkestrel/reason'\n\n/**\n * Runs ordered passes over one reason engine and returns eligibility.\n *\n * @remarks\n * The engine is owned when self-created (destroyed on `destroy()`) and borrowed\n * when injected (never destroyed). Semantic validation runs before the first pass\n * whenever the `validate` option is on. `qualify` builds its working subject through\n * copy-on-write overlays only — the caller's `subject` is never mutated, and the\n * qualifier's internal projection is discarded after each call.\n */\nexport class Qualifier implements QualifierInterface {\n\treadonly #emitter: Emitter<QualifierEventMap>\n\treadonly #engine: ReasonInterface\n\treadonly #owned: boolean\n\treadonly #validate: boolean\n\treadonly #door = createSubjectDoor()\n\treadonly #valid = new WeakSet<QualificationDefinition>()\n\treadonly #shaped = new WeakSet<QualificationDefinition>()\n\t#destroyed = false\n\n\tconstructor(options?: QualifierOptions) {\n\t\tthis.#emitter = new Emitter({\n\t\t\t...(options?.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options?.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t\tthis.#owned = options?.engine === undefined\n\t\tthis.#engine =\n\t\t\toptions?.engine ??\n\t\t\tcreateReason({\n\t\t\t\treasoners: [createQuantitativeReasoner(), createLogicalReasoner()],\n\t\t\t\tbail: false,\n\t\t\t})\n\t\tthis.#validate = options?.validate ?? DEFAULT_QUALIFIER_VALIDATE\n\t}\n\n\t/**\n\t * Holds the typed observation surface carrying `derive`, `finding`, `qualify`, and\n\t * `destroy`.\n\t *\n\t * @returns The emitter this qualifier owns\n\t *\n\t * @example\n\t * ```ts\n\t * import { Qualifier } from '@orkestrel/qualifier'\n\t *\n\t * const qualifier = new Qualifier()\n\t * qualifier.emitter.on('qualify', (result) => console.log(result.eligibility))\n\t * qualifier.destroy()\n\t * ```\n\t */\n\tget emitter(): EmitterInterface<QualifierEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\t/**\n\t * Qualifies one subject against one authored definition.\n\t *\n\t * @remarks\n\t * Semantic validation runs first when the `validate` option is on, so an invalid\n\t * definition throws before any pass runs. Passes run in authored order over a\n\t * copy-on-write working subject, and the caller's `subject` is never mutated. A\n\t * `shape` on the definition admits the subject through a door first. An unscoped\n\t * restriction stops the remaining passes because no later finding can be more severe.\n\t * A pass left unread projects nothing and reads `referral`, and the run goes on, so a later\n\t * restriction can still outrank it. A refusal stops the run, and so does an answer that\n\t * contradicts itself or its pass, which is refused as `malformed`.\n\t *\n\t * @param subject - The record to qualify\n\t * @param definition - The authored qualification definition\n\t * @returns A fresh, frozen qualification result\n\t * @throws {@link QualifierError} `'DEFINITION'` when validation is enabled and the\n\t * definition fails semantic validation, or when the engine rejects a pass as an invalid\n\t * definition; `'MISMATCH'` when the subject is not a record or already carries the\n\t * reserved `qualification` key; `'DESTROYED'` after `destroy`, or when the engine\n\t * reports itself destroyed mid-pass; `'ENGINE'` for every other engine throw\n\t *\n\t * @example\n\t * ```ts\n\t * import { createQualificationDefinition, createRuling, Qualifier } from '@orkestrel/qualifier'\n\t * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n\t *\n\t * const gates = createLogicalDefinition('gates', 'Eligibility gates', [\n\t * createRule('licensed', [createAtom('licensed', 'equals', false)], createAtom('blocked', 'equals', true)),\n\t * ])\n\t * const definition = createQualificationDefinition('standard', 'Standard eligibility', [gates], {\n\t * rulings: [createRuling('license', 'gates', 'licensed', 'restriction')],\n\t * })\n\t *\n\t * const qualifier = new Qualifier()\n\t * qualifier.qualify({ id: 'risk-1', licensed: false }, definition).eligibility // 'ineligible'\n\t * qualifier.destroy()\n\t * ```\n\t */\n\tqualify(subject: Subject, definition: QualificationDefinition): QualificationResult {\n\t\tthis.#alive()\n\t\tif (this.#validate && !this.#valid.has(definition)) {\n\t\t\tconst validation = this.validate(definition)\n\t\t\tif (!validation.valid) {\n\t\t\t\tthrow new QualifierError(\n\t\t\t\t\t'DEFINITION',\n\t\t\t\t\t`Qualification definition is invalid: ${validation.errors.join(', ')}`,\n\t\t\t\t\tisRecord(definition) && isString(definition.id) ? { definition: definition.id } : {},\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.#valid.add(definition)\n\t\t}\n\t\treturn this.#qualify(subject, definition)\n\t}\n\n\t/**\n\t * Validates one authored definition semantically, without running it.\n\t *\n\t * @remarks\n\t * Structural shape is `isQualificationDefinition`'s job. This checks the meaning:\n\t * non-empty id and name, valid and uniquely identified passes and rulings, every\n\t * ruling reference resolving to a logical pass and one of its rules, and no pass id\n\t * shadowing `QUALIFICATION_KEY`. The engine validates each pass, whose errors carry the\n\t * pass id. A pass may carry no shape, and a `shape` on the definition must stand and\n\t * declare every message token. An empty definition, a logical pass carrying no ruling,\n\t * and a derivation no later pass reads are warnings rather than errors.\n\t *\n\t * @param definition - The authored qualification definition\n\t * @returns A fresh validation result carrying `valid`, `errors`, and `warnings`\n\t * @throws {@link QualifierError} `'DESTROYED'` after `destroy`\n\t *\n\t * @example\n\t * ```ts\n\t * import { createQualificationDefinition, Qualifier } from '@orkestrel/qualifier'\n\t *\n\t * const qualifier = new Qualifier()\n\t * qualifier.validate(createQualificationDefinition('empty', 'Empty', []))\n\t * // { valid: true, errors: [], warnings: ['Definition has no passes'] }\n\t * qualifier.destroy()\n\t * ```\n\t */\n\tvalidate(definition: QualificationDefinition): ReasonValidationResult {\n\t\tthis.#alive()\n\t\tif (!isRecord(definition)) {\n\t\t\treturn { valid: false, errors: ['Definition must be a record'], warnings: [] }\n\t\t}\n\t\tconst errors: string[] = []\n\t\tconst warnings: string[] = []\n\t\tif (!isString(definition.id) || definition.id.length === 0) {\n\t\t\terrors.push('Definition id must not be empty')\n\t\t}\n\t\tif (!isString(definition.name) || definition.name.length === 0) {\n\t\t\terrors.push('Definition name must not be empty')\n\t\t}\n\t\tconst authoredPasses: readonly unknown[] = isArray(definition.passes) ? definition.passes : []\n\t\tconst authoredRulings: unknown = definition.rulings === undefined ? [] : definition.rulings\n\t\tif (!isArray(definition.passes)) errors.push('Definition must have a passes array')\n\t\tif (!isArray(authoredRulings)) errors.push('Definition rulings must be an array')\n\t\tauthoredPasses.forEach((pass, index) => {\n\t\t\tif (!isQualificationPass(pass)) {\n\t\t\t\terrors.push(`Pass at index ${index} is not a valid qualification pass`)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (pass.shape !== undefined) errors.push(`Pass '${pass.id}' may not carry a shape`)\n\t\t\tconst validation = this.#validatePass(pass)\n\t\t\tfor (const error of validation.errors) errors.push(`${pass.id}: ${error}`)\n\t\t\tfor (const warning of validation.warnings) warnings.push(`${pass.id}: ${warning}`)\n\t\t})\n\t\tconst rulingEntries: readonly unknown[] = isArray(authoredRulings) ? authoredRulings : []\n\t\trulingEntries.forEach((ruling, index) => {\n\t\t\tif (!isRuling(ruling)) errors.push(`Ruling at index ${index} is not a valid ruling`)\n\t\t})\n\t\t// The checks below read only what stood up, so one bad entry cannot throw past its own error.\n\t\tconst passes = authoredPasses.filter((pass) => isQualificationPass(pass))\n\t\tconst rulings = rulingEntries.filter((ruling) => isRuling(ruling))\n\t\tconst shape = isContractShape(definition.shape) ? definition.shape : undefined\n\t\tif (definition.shape !== undefined && shape === undefined) {\n\t\t\terrors.push('Definition shape is not a valid contract shape')\n\t\t}\n\t\tif (definition.metadata !== undefined && !isDefinitionMetadata(definition.metadata)) {\n\t\t\terrors.push('Definition metadata must be a record of JSON values')\n\t\t}\n\t\tconst readable: QualificationDefinition = {\n\t\t\tid: definition.id,\n\t\t\tname: definition.name,\n\t\t\tpasses,\n\t\t\trulings,\n\t\t\t...(shape === undefined ? {} : { shape }),\n\t\t}\n\t\tfor (const id of findDuplicates(passes)) errors.push(`Duplicate pass id '${id}'`)\n\t\tfor (const id of findDuplicates(rulings)) errors.push(`Duplicate ruling id '${id}'`)\n\t\tfor (const reference of describeMissingReferences(readable)) errors.push(reference)\n\t\tfor (const conclusion of describeReservedConclusions(readable)) errors.push(conclusion)\n\t\tconst scan = scanDefinitionShape(readable)\n\t\terrors.push(...(shape === undefined ? [] : scanShape(shape)), ...scan.errors)\n\t\terrors.push(...describeUnknownTokens(readable))\n\t\twarnings.push(...scan.warnings)\n\t\tif (passes.length === 0) warnings.push('Definition has no passes')\n\t\tfor (const warning of describeEmptyLogicalPasses(readable)) warnings.push(warning)\n\t\tfor (const warning of describeUnreadDerivations(readable)) warnings.push(warning)\n\t\treturn { valid: errors.length === 0, errors, warnings }\n\t}\n\n\t/**\n\t * Destroys this qualifier, idempotently.\n\t *\n\t * @remarks\n\t * An engine this qualifier created is destroyed; an injected engine stays\n\t * caller-owned and is left alone. The `destroy` event fires before the emitter\n\t * itself is destroyed, and a later call returns without re-emitting.\n\t *\n\t * @example\n\t * ```ts\n\t * import { Qualifier } from '@orkestrel/qualifier'\n\t *\n\t * const qualifier = new Qualifier()\n\t * qualifier.destroy()\n\t * qualifier.destroy() // idempotent\n\t * ```\n\t */\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tif (this.#owned) this.#engine.destroy()\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#qualify(subject: Subject, definition: QualificationDefinition): QualificationResult {\n\t\tassertSubject(subject)\n\t\t// Structure is checked even with `validate` off, once per definition, because the walk below\n\t\t// reads it, and a malformed definition is the caller's error, never a raw TypeError.\n\t\tif (!this.#shaped.has(definition)) {\n\t\t\tif (!isQualificationDefinition(definition)) {\n\t\t\t\tthrow new QualifierError('DEFINITION', 'Qualification definition is malformed')\n\t\t\t}\n\t\t\tthis.#shaped.add(definition)\n\t\t}\n\t\tconst admission = this.#door.admit(subject, definition.shape)\n\t\tconst admitted = admission.subject\n\t\t// A default could fill the reserved key, so the same rule holds for what the door admitted.\n\t\tif (admitted !== undefined) assertSubject(admitted)\n\t\tif (admitted === undefined) {\n\t\t\treturn this.#finish(\n\t\t\t\tdefinition,\n\t\t\t\t[],\n\t\t\t\t[],\n\t\t\t\t[],\n\t\t\t\t[...admission.refusals],\n\t\t\t\t[...admission.faults],\n\t\t\t\tadmission,\n\t\t\t)\n\t\t}\n\t\tconst steps: Array<{\n\t\t\treadonly context: QualificationContext\n\t\t\treadonly subject: Subject\n\t\t}> = [{ context: {}, subject: { ...admitted } }]\n\t\tconst findings: Finding[] = []\n\t\tconst derivations: Derivation[] = []\n\t\tconst trace: string[] = []\n\t\tconst refusals: ReasonRefusal[] = []\n\t\tconst faults: AuditFault[] = []\n\t\tconst unread = new Map<string, readonly AuditFault[]>()\n\n\t\tfor (const pass of definition.passes) {\n\t\t\tthis.#alive()\n\t\t\tconst previous = steps.at(-1)\n\t\t\tif (previous === undefined) throw new Error('Qualification has no initial step')\n\t\t\tconst evaluated = previous.subject\n\t\t\t// An injected engine answers through an interface, so its result is read once into a copy\n\t\t\t// this package owns, and everything after reads the copy.\n\t\t\tconst result = cloneReasonResult(this.#reason(evaluated, pass))\n\n\t\t\tif (result === undefined) {\n\t\t\t\trefusals.push({ cause: 'malformed', path: [pass.id] })\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttrace.push(...result.trace.map((entry) => `${pass.id}: ${entry}`))\n\t\t\tconst refused = collectPassRefusals(pass, result)\n\t\t\trefusals.push(...refused)\n\t\t\tconst leaves = expandPassFaults(result.faults, unread)\n\t\t\tfaults.push(...leaves)\n\t\t\tif (leaves.length > 0) unread.set(pass.id, leaves)\n\n\t\t\tif (pass.reasoning === 'quantitative' && result.reasoning === 'quantitative') {\n\t\t\t\tconst derivation = quantitativeResultToDerivation(pass.id, result)\n\t\t\t\tderivations.push(derivation)\n\t\t\t\tthis.#emitter.emit('derive', derivation)\n\t\t\t}\n\n\t\t\tif (pass.reasoning === 'logical' && result.reasoning === 'logical') {\n\t\t\t\tconst rulings = (definition.rulings ?? []).filter((ruling) => ruling.pass === pass.id)\n\t\t\t\tfor (const ruling of rulings) {\n\t\t\t\t\tconst finding = rulingToFinding(ruling, pass, result, evaluated)\n\t\t\t\t\tfindings.push(finding)\n\t\t\t\t\tthis.#emitter.emit('finding', finding)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// An unread pass projects nothing and the run goes on, so a later restriction can still\n\t\t\t// outrank the referral it reads as. A refusal stops the run.\n\t\t\tif (refused.length > 0) break\n\t\t\tif (deriveFindingEligibility(findings) === 'ineligible') break\n\t\t\tconst context = result.success\n\t\t\t\t? mergeQualificationContext(\n\t\t\t\t\t\tprevious.context,\n\t\t\t\t\t\tpass.id,\n\t\t\t\t\t\treasonResultToProjection(pass, result),\n\t\t\t\t\t)\n\t\t\t\t: previous.context\n\t\t\tsteps.push({ context, subject: { ...admitted, ...qualificationToRecord(context) } })\n\t\t}\n\n\t\treturn this.#finish(\n\t\t\tdefinition,\n\t\t\tfindings,\n\t\t\tderivations,\n\t\t\ttrace,\n\t\t\trefusals,\n\t\t\tfilterUniqueFaults(faults),\n\t\t\tadmission,\n\t\t)\n\t}\n\n\t#finish(\n\t\tdefinition: QualificationDefinition,\n\t\tfindings: readonly Finding[],\n\t\tderivations: readonly Derivation[],\n\t\ttrace: readonly string[],\n\t\trefusals: readonly ReasonRefusal[],\n\t\tfaults: readonly AuditFault[],\n\t\tadmission: SubjectAdmission,\n\t): QualificationResult {\n\t\tconst success = refusals.length === 0 && faults.length === 0\n\t\tconst qualification: QualificationResult = Object.freeze({\n\t\t\tid: definition.id,\n\t\t\tname: definition.name,\n\t\t\teligibility: deriveFindingEligibility(findings, !success),\n\t\t\tscopes: Object.freeze(deriveScopeEligibilities(findings)),\n\t\t\tfindings: Object.freeze(findings),\n\t\t\tderivations: Object.freeze(derivations),\n\t\t\tsuccess,\n\t\t\ttrace: Object.freeze(trace),\n\t\t\trefusals: Object.freeze(refusals),\n\t\t\tfaults: Object.freeze(faults),\n\t\t\trepairs: Object.freeze([...admission.repairs]),\n\t\t\tdefaulted: Object.freeze([...admission.defaulted]),\n\t\t})\n\t\tthis.#emitter.emit('qualify', qualification)\n\t\treturn qualification\n\t}\n\n\t#validatePass(pass: QualificationPass): ReasonValidationResult {\n\t\ttry {\n\t\t\treturn this.#engine.validate(pass)\n\t\t} catch (error) {\n\t\t\tthrow mapEngineError(error, pass.id)\n\t\t}\n\t}\n\n\t#reason(subject: Subject, pass: QualificationPass): ReasonResult {\n\t\ttry {\n\t\t\treturn this.#engine.reason(subject, pass)\n\t\t} catch (error) {\n\t\t\tthrow mapEngineError(error, pass.id)\n\t\t}\n\t}\n\n\t#alive(): void {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new QualifierError('DESTROYED', 'Qualifier has been destroyed')\n\t\t}\n\t}\n}\n","import type { ContractInterface } from '@orkestrel/contract'\nimport type {\n\tQualificationDefinition,\n\tQualificationEffect,\n\tQualificationInput,\n\tQualificationPass,\n\tQualifierInterface,\n\tQualifierOptions,\n\tRuling,\n\tRulingInput,\n} from './types.js'\nimport { createContract } from '@orkestrel/contract'\nimport { Qualifier } from './Qualifier.js'\nimport { createQualificationDefinitionShape } from './shapers.js'\n\n/**\n * Creates the contract of a `QualificationDefinition`, its `schema` for an LLM, a tool, or MCP.\n *\n * @remarks\n * Cross a definition on `is`, never `parse`, and hold the result, because building it walks the\n * recursive expressions of its logical passes. `is` checks nested contract shapes;\n * semantic validation remains the qualifier's responsibility.\n *\n * @returns A contract over a qualification definition\n *\n * @example\n * ```ts\n * import { createQualificationDefinition, createQualificationDefinitionContract } from '@orkestrel/qualifier'\n *\n * createQualificationDefinitionContract().is(createQualificationDefinition('d', 'd', [])) // true\n * ```\n */\nexport function createQualificationDefinitionContract(): ContractInterface<unknown> {\n\treturn createContract(createQualificationDefinitionShape())\n}\n\n/**\n * Creates one {@link QualifierInterface} over a reason engine.\n *\n * @remarks\n * A standalone qualifier creates and owns one shared quantitative-plus-logical\n * reason engine, destroying it on `destroy()`. An injected `options.engine`\n * remains caller-owned and is never destroyed. `validate` runs semantic\n * validation before every qualification. Default: `true`.\n *\n * @param options - Optional injected engine, validation, and emitter hooks\n * @returns A {@link QualifierInterface}\n *\n * @example Create a qualifier\n * ```ts\n * import { createQualificationDefinition, createQualifier, createRuling } from '@orkestrel/qualifier'\n * import { createAtom, createLogicalDefinition, createRule } from '@orkestrel/reason'\n *\n * const gates = createLogicalDefinition('gates', 'Eligibility gates', [\n * \tcreateRule(\n * \t\t'licensed',\n * \t\t[createAtom('licensed', 'equals', false)],\n * \t\tcreateAtom('blocked', 'equals', true),\n * \t),\n * ])\n *\n * const bare = createRuling('license', 'gates', 'licensed', 'restriction')\n * const messaged = createRuling('license', 'gates', 'licensed', 'restriction', {\n * \tmessage: 'A license is required',\n * })\n *\n * 'message' in bare // false — an absent optional key is omitted, never written as undefined\n * messaged.message // 'A license is required'\n *\n * const passes = [gates]\n * const definition = createQualificationDefinition('standard', 'Standard eligibility', passes, {\n * \trulings: [messaged],\n * })\n *\n * 'description' in definition // false\n * definition.passes === passes // false — the factory copies what it is handed\n *\n * const qualifier = createQualifier()\n * qualifier.qualify({ id: 'risk-1', licensed: false }, definition)\n * qualifier.destroy()\n * ```\n */\nexport function createQualifier(options?: QualifierOptions): QualifierInterface {\n\treturn new Qualifier(options)\n}\n\n/**\n * Creates a fresh {@link QualificationDefinition}, omitting every absent optional key.\n *\n * @remarks\n * `passes` and `rulings` arrays are copied, and record `metadata` is\n * shallow-copied so nested values are not deep-cloned.\n *\n * @param id - The definition id\n * @param name - The display name\n * @param passes - The ordered qualification passes\n * @param input - Optional description, rulings, metadata, and subject shape\n * @returns A fresh qualification definition\n *\n * @example\n * ```ts\n * import { createQualificationDefinition } from '@orkestrel/qualifier'\n *\n * createQualificationDefinition('standard', 'Standard', [gates], { rulings: [ruling] })\n * ```\n */\nexport function createQualificationDefinition(\n\tid: string,\n\tname: string,\n\tpasses: readonly QualificationPass[],\n\tinput?: QualificationInput,\n): QualificationDefinition {\n\treturn {\n\t\tid,\n\t\tname,\n\t\tpasses: [...passes],\n\t\t...(input?.description === undefined ? {} : { description: input.description }),\n\t\t...(input?.rulings === undefined ? {} : { rulings: [...input.rulings] }),\n\t\t...(input?.metadata === undefined ? {} : { metadata: { ...input.metadata } }),\n\t\t...(input?.shape === undefined ? {} : { shape: input.shape }),\n\t}\n}\n\n/**\n * Creates a fresh {@link Ruling} from the rule it reacts to and the effect it applies.\n *\n * @param id - The ruling id\n * @param pass - The logical pass id the rule lives in\n * @param rule - The rule id whose firing this ruling reacts to\n * @param effect - The eligibility impact when the rule fires\n * @param input - Optional selection scope and message template\n * @returns A fresh ruling\n *\n * @example\n * ```ts\n * import { createRuling } from '@orkestrel/qualifier'\n *\n * createRuling('license', 'gates', 'licensed', 'restriction', { message: 'A license is required' })\n * ```\n */\nexport function createRuling(\n\tid: string,\n\tpass: string,\n\trule: string,\n\teffect: QualificationEffect,\n\tinput?: RulingInput,\n): Ruling {\n\treturn {\n\t\tid,\n\t\tpass,\n\t\trule,\n\t\teffect,\n\t\t...(input?.scope === undefined ? {} : { scope: input.scope }),\n\t\t...(input?.message === undefined ? {} : { message: input.message }),\n\t}\n}\n"],"mappings":";;;;;;;;;AAMA,IAAa,6BAA6B;;;;;AAM1C,IAAa,oBAAoB;;AAGjC,IAAa,gBAAgB;;AAG7B,IAAa,gBAAgB;CAAC;CAAY;CAA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