@orkestrel/qualifier 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["#emitter","#engine","#evaluator","#owned","#validate","#labels","#alive","#qualify","#destroyed"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/Qualifier.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { Eligibility, QualificationEffect } from './types.js'\n\n/** Default definition validation policy for `createQualifier` / `Qualifier.qualify`. */\nexport const DEFAULT_QUALIFIER_VALIDATE = true\n\n/** The reserved internal projection namespace a pass's working projection is written under. */\nexport const QUALIFICATION_KEY = 'qualification'\n\n/** Eligibility severity order — most to least severe. */\nexport const ELIGIBILITY_PRECEDENCE: readonly Eligibility[] = Object.freeze([\n\t'ineligible',\n\t'referral',\n\t'eligible',\n])\n\n/** The eligibility impact of each {@link QualificationEffect}; `condition` remains eligible. */\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 } from './types.js'\n\n/**\n * A coded programmer error thrown by the qualifier layer.\n *\n * @remarks\n * `DEFINITION` — a qualification definition failed semantic validation.\n * `MISMATCH` — a subject is not a record or already carries the reserved\n * `qualification` key. `DESTROYED` — use of a destroyed qualifier.\n */\nexport class QualifierError extends Error {\n\treadonly code: QualifierErrorCode\n\treadonly context: unknown\n\n\tconstructor(code: QualifierErrorCode, message: string, context?: unknown) {\n\t\tsuper(message)\n\t\tthis.name = 'QualifierError'\n\t\tthis.code = code\n\t\tthis.context = context\n\t}\n}\n\n/** Narrow a caught value to a {@link QualifierError}. */\nexport function isQualifierError(value: unknown): value is QualifierError {\n\treturn value instanceof QualifierError\n}\n","import type { QualificationDefinition, QualificationPass, Ruling } from './types.js'\nimport { arrayOf, isRecord, isString, literalOf, recordOf } from '@orkestrel/contract'\nimport { isLogicalDefinition, isQuantitativeDefinition } from '@orkestrel/reason'\n\n/** Determine whether a value is an {@link Eligibility} literal. */\nexport const isEligibility = literalOf('eligible', 'ineligible', 'referral')\n\n/** Determine whether a value is a {@link QualificationEffect} literal. */\nexport const isQualificationEffect = literalOf('restriction', 'referral', 'condition')\n\n/** Determine whether a value is a {@link QualificationPass} (a quantitative or logical definition). */\nexport function isQualificationPass(value: unknown): value is QualificationPass {\n\treturn isQuantitativeDefinition(value) || isLogicalDefinition(value)\n}\n\n/** Determine whether a value is an exact {@link Ruling} record. */\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/** Determine whether a value is an exact {@link QualificationDefinition} record. */\nexport function isQualificationDefinition(value: unknown): value is QualificationDefinition {\n\tif (!isRecord(value)) return false\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: isRecord,\n\t\t},\n\t\t['description', 'rulings', 'metadata'],\n\t)(value)\n}\n","import type {\n\tDerivation,\n\tEligibility,\n\tFinding,\n\tPremise,\n\tQualificationContext,\n\tQualificationDefinition,\n\tQualificationPass,\n\tQualificationProjection,\n\tRuling,\n} from './types.js'\nimport type {\n\tCheck,\n\tCheckResult,\n\tEvaluatorInterface,\n\tLogicalDefinition,\n\tLogicalResult,\n\tQuantitativeResult,\n\tReasonResult,\n\tRule,\n\tSubject,\n} from '@orkestrel/reason'\nimport { EFFECT_ELIGIBILITIES, ELIGIBILITY_PRECEDENCE, QUALIFICATION_KEY } from './constants.js'\nimport { QualifierError } from './errors.js'\nimport { isFiniteNumber, isRecord, resolveField } from '@orkestrel/contract'\nimport { extractAtoms, extractConclusions, formatField, isBounds } from '@orkestrel/reason'\n\n/**\n * Interpolate `{{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(/\\{\\{\\s*([^}]+?)\\s*\\}\\}/g, (_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 * Describe 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 { describeComparison } from '@orkestrel/qualifier'\n *\n * describeComparison('above') // 'is more than'\n * ```\n */\nexport function describeComparison(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 * Render 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 { describeValue } from '@orkestrel/qualifier'\n *\n * describeValue([18, 25, 40]) // '18, 25, 40'\n * describeValue({ minimum: 18, maximum: 65 }) // '18 and 65'\n * describeValue(42) // '42'\n * ```\n */\nexport function describeValue(value: unknown): string {\n\tif (Array.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 * Render one {@link Premise} into a display-neutral sentence.\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 { describePremise } from '@orkestrel/qualifier'\n *\n * describePremise({ field: 'age', comparison: 'above', expected: 18, actual: 25, met: true })\n * // 'age is more than 18 → met'\n * ```\n */\nexport function describePremise(entry: Premise, labels?: Readonly<Record<string, string>>): string {\n\tconst status = entry.met === undefined ? 'unknown' : entry.met ? 'met' : 'not met'\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 ? '' : ` ${describeValue(entry.expected)}`\n\treturn `${label} ${describeComparison(entry.comparison)}${expected} → ${status}`\n}\n\n/**\n * Build 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 `met`\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 { premiseCheck } from '@orkestrel/qualifier'\n * import { check } from '@orkestrel/reason'\n *\n * const authored = check('age', 'above', 18)\n * premiseCheck(authored, { field: 'age', actual: 25, met: true })\n * // { field: 'age', comparison: 'above', expected: 18, actual: 25, met: true }\n * ```\n */\nexport function premiseCheck(\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\t...(result.met === undefined ? {} : { met: result.met }),\n\t}\n}\n\n/**\n * Build rich premises for one fired {@link Rule} by walking its premise atoms\n * and re-evaluating each against the working subject.\n *\n * @remarks\n * A reason rule result carries only booleans, so this is the qualifier's own\n * premise-audit projection: each authored premise expression is flattened to its\n * atom leaves via `extractAtoms`, and each leaf's `Check` is re-evaluated through\n * the injected `evaluator`. A membership check (`any` / `none`) over an EMPTY\n * array value is content-free and is skipped.\n *\n * @param rule - The authored rule\n * @param working - The working subject to evaluate against\n * @param evaluator - The shared reason check evaluator\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 { logicalPremises } from '@orkestrel/qualifier'\n * import { atom, createEvaluator, logicalDefinition, rule } from '@orkestrel/reason'\n *\n * const gates = logicalDefinition('gates', 'Gates', [\n * rule('licensed', [atom('licensed', 'equals', false)], atom('blocked', 'equals', true)),\n * ])\n * const evaluator = createEvaluator()\n * const premises = logicalPremises(gates.rules[0], { licensed: false }, evaluator)\n *\n * premises[0]?.met // true\n * ```\n */\nexport function logicalPremises(\n\trule: Rule,\n\tworking: Subject,\n\tevaluator: EvaluatorInterface,\n\tlabels?: Readonly<Record<string, string>>,\n): readonly Premise[] {\n\tconst output: Premise[] = []\n\tfor (const premise of rule.premises) {\n\t\tfor (const atom of extractAtoms(premise)) {\n\t\t\tconst { check } = atom\n\t\t\tif (\n\t\t\t\t(check.operator === 'any' || check.operator === 'none') &&\n\t\t\t\tArray.isArray(check.value) &&\n\t\t\t\tcheck.value.length === 0\n\t\t\t) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\toutput.push(premiseCheck(check, evaluator.evaluate(check, working), labels))\n\t\t}\n\t}\n\treturn output\n}\n\n/**\n * Locate 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 { atom, logicalDefinition, rule } from '@orkestrel/reason'\n *\n * const gates = logicalDefinition('gates', 'Gates', [\n * rule('licensed', [atom('licensed', 'equals', false)], atom('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 * Project 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 */\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\tconst projection: Record<string, unknown> = { conclusion: result.conclusion }\n\tfor (const resolved of result.rules) {\n\t\tif (!resolved.applied) continue\n\t\tconst authored = definition.rules.find((rule) => rule.id === resolved.id)\n\t\tif (authored === undefined) continue\n\t\tconst conclusions = extractConclusions(authored.conclusion)\n\t\tfor (const [key, value] of Object.entries(conclusions)) projection[key] = value\n\t}\n\treturn projection\n}\n\n/**\n * Project 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 */\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 * Wrap 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 */\nexport function qualificationToRecord(\n\tcontext: QualificationContext,\n): Readonly<Record<string, QualificationContext>> {\n\treturn { [QUALIFICATION_KEY]: context }\n}\n\n/**\n * Copy-on-write merge one pass projection into the context.\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 */\nexport function mergeQualificationContext(\n\tcontext: QualificationContext,\n\tid: string,\n\tprojection: QualificationProjection,\n): QualificationContext {\n\treturn { ...context, [id]: projection }\n}\n\n/**\n * Join a ruling, its logical rule result, the pass, the pre-projection subject,\n * and an evaluator into a {@link Finding}.\n *\n * @remarks\n * `applied` reflects whether the ruling's rule fired. Premises are re-evaluated\n * against the SAME subject snapshot the pass evaluated, so a conclusion the pass\n * derived can never satisfy its own reported premise. The message interpolates\n * against that snapshot.\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 evaluator - The shared reason check evaluator\n * @param labels - Optional field-to-label overrides, keyed by dot-joined field\n * @returns A fresh finding\n */\nexport function rulingToFinding(\n\truling: Ruling,\n\tpass: QualificationPass,\n\tresult: LogicalResult,\n\tsubject: Subject,\n\tevaluator: EvaluatorInterface,\n\tlabels?: Readonly<Record<string, string>>,\n): Finding {\n\tconst entry = result.rules.find((item) => item.id === ruling.rule)\n\tconst applied = entry?.applied ?? false\n\tconst rule = pass.reasoning === 'logical' ? findRule(pass, ruling.rule) : undefined\n\tconst premises = rule === undefined ? [] : logicalPremises(rule, subject, evaluator, 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\tapplied,\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 * Derive global eligibility from applied, unscoped findings.\n *\n * @remarks\n * Only findings that both applied 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 - Whether an operational pass failure occurred\n * @returns The most severe global eligibility\n */\nexport function deriveFindingEligibility(findings: Finding[], failed = false): Eligibility {\n\tconst eligibilities = findings\n\t\t.filter((finding) => finding.applied && 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 * Return 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: 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 * Derive one eligibility per finding scope.\n *\n * @remarks\n * Only applied, scoped findings 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 */\nexport function deriveScopeEligibilities(\n\tfindings: Finding[],\n): Readonly<Record<string, Eligibility>> {\n\tconst grouped: Record<string, Eligibility[]> = {}\n\tfor (const finding of findings) {\n\t\tif (!finding.applied || finding.scope === undefined) continue\n\t\tconst current = grouped[finding.scope] ?? []\n\t\tgrouped[finding.scope] = [...current, EFFECT_ELIGIBILITIES[finding.effect]]\n\t}\n\tconst scopes: Record<string, Eligibility> = {}\n\tfor (const [scope, eligibilities] of Object.entries(grouped)) {\n\t\tscopes[scope] = combineEligibilities(eligibilities)\n\t}\n\treturn scopes\n}\n\n/**\n * Find rulings whose pass or rule does not exist, whose pass is not logical, or\n * a 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 */\nexport function findMissingReferences(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 * Find duplicate ids in a list, once each.\n *\n * @param ids - The ids to scan\n * @returns A fresh list of ids that appear more than once\n */\nexport function findDuplicateIds(ids: readonly string[]): readonly string[] {\n\tconst seen = new Set<string>()\n\tconst duplicates = new Set<string>()\n\tfor (const id of ids) {\n\t\tif (seen.has(id)) duplicates.add(id)\n\t\telse seen.add(id)\n\t}\n\treturn [...duplicates]\n}\n\n/**\n * Determine whether a subject already owns the reserved {@link QUALIFICATION_KEY}.\n *\n * @param subject - The subject to check\n * @returns `true` when the subject owns the reserved key\n */\nexport function hasReservedKey(subject: Subject): boolean {\n\treturn Object.hasOwn(subject, QUALIFICATION_KEY)\n}\n\n/**\n * Assert 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 */\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","import type {\n\tDerivation,\n\tFinding,\n\tQualificationContext,\n\tQualificationDefinition,\n\tQualificationResult,\n\tQualificationValidationResult,\n\tQualifierEventMap,\n\tQualifierInterface,\n\tQualifierOptions,\n} from './types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type { EvaluatorInterface, ReasonInterface, Subject } from '@orkestrel/reason'\nimport { DEFAULT_QUALIFIER_VALIDATE } from './constants.js'\nimport { QualifierError } from './errors.js'\nimport {\n\tassertSubject,\n\tderiveFindingEligibility,\n\tderiveScopeEligibilities,\n\tfindDuplicateIds,\n\tfindMissingReferences,\n\tmergeQualificationContext,\n\tqualificationToRecord,\n\tquantitativeResultToDerivation,\n\treasonResultToProjection,\n\trulingToFinding,\n} from './helpers.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tcreateEvaluator,\n\tcreateLogicalReasoner,\n\tcreateQuantitativeReasoner,\n\tcreateReason,\n} from '@orkestrel/reason'\n\n/**\n * A qualifier — runs ordered passes over one reason engine and returns\n * pre-rating eligibility.\n *\n * @remarks\n * The engine is OWNED when self-created (destroyed on `destroy()`) and borrowed\n * when injected (never destroyed). `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 #evaluator: EvaluatorInterface\n\treadonly #owned: boolean\n\treadonly #validate: boolean\n\treadonly #labels: Readonly<Record<string, string>> | undefined\n\t#destroyed = false\n\n\tconstructor(options?: QualifierOptions) {\n\t\tthis.#emitter = new Emitter({ on: options?.on, error: options?.error })\n\t\tthis.#evaluator = createEvaluator()\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: [\n\t\t\t\t\tcreateQuantitativeReasoner({ evaluator: this.#evaluator }),\n\t\t\t\t\tcreateLogicalReasoner({ evaluator: this.#evaluator }),\n\t\t\t\t],\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\tget emitter(): EmitterInterface<QualifierEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tqualify(subject: Subject, definition: QualificationDefinition): QualificationResult {\n\t\tthis.#alive()\n\t\tif (this.#validate) {\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\tdefinition.id,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\treturn this.#qualify(subject, definition)\n\t}\n\n\tvalidate(definition: QualificationDefinition): QualificationValidationResult {\n\t\tthis.#alive()\n\t\tconst errors: string[] = []\n\t\tconst warnings: string[] = []\n\t\tif (definition.id.length === 0) errors.push('Definition id must not be empty')\n\t\tif (definition.name.length === 0) errors.push('Definition name must not be empty')\n\t\tif (definition.passes.length === 0) warnings.push('Definition has no passes')\n\t\tfor (const id of findDuplicateIds(definition.passes.map((pass) => pass.id))) {\n\t\t\terrors.push(`Duplicate pass id '${id}'`)\n\t\t}\n\t\tfor (const id of findDuplicateIds((definition.rulings ?? []).map((ruling) => ruling.id))) {\n\t\t\terrors.push(`Duplicate ruling id '${id}'`)\n\t\t}\n\t\tfor (const reference of findMissingReferences(definition)) errors.push(reference)\n\t\treturn { valid: errors.length === 0, errors, warnings }\n\t}\n\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\tlet context: QualificationContext = {}\n\t\tlet working: Subject = { ...subject }\n\t\tconst findings: Finding[] = []\n\t\tconst derivations: Derivation[] = []\n\t\tconst trace: string[] = []\n\t\tconst errors: string[] = []\n\t\tlet failed = false\n\n\t\tfor (const pass of definition.passes) {\n\t\t\tconst evaluated = working\n\t\t\tconst result = this.#engine.reason(evaluated, pass)\n\n\t\t\ttrace.push(...result.trace.map((entry) => `${pass.id}: ${entry}`))\n\t\t\terrors.push(...result.errors.map((entry) => `${pass.id}: ${entry}`))\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(\n\t\t\t\t\t\truling,\n\t\t\t\t\t\tpass,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\tevaluated,\n\t\t\t\t\t\tthis.#evaluator,\n\t\t\t\t\t\tthis.#labels,\n\t\t\t\t\t)\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\tconst projection = reasonResultToProjection(pass, result)\n\t\t\tcontext = mergeQualificationContext(context, pass.id, projection)\n\t\t\tworking = { ...subject, ...qualificationToRecord(context) }\n\n\t\t\tif (!result.success) {\n\t\t\t\tfailed = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif (deriveFindingEligibility(findings) === 'ineligible') break\n\t\t}\n\n\t\tconst success = !failed && errors.length === 0\n\t\tconst qualification: QualificationResult = {\n\t\t\tid: definition.id,\n\t\t\tname: definition.name,\n\t\t\teligibility: deriveFindingEligibility(findings, !success),\n\t\t\tscopes: deriveScopeEligibilities(findings),\n\t\t\tfindings,\n\t\t\tderivations,\n\t\t\tsuccess,\n\t\t\ttrace,\n\t\t\terrors,\n\t\t}\n\t\tthis.#emitter.emit('qualify', qualification)\n\t\treturn qualification\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 {\n\tQualificationDefinition,\n\tQualificationEffect,\n\tQualificationInput,\n\tQualificationPass,\n\tQualifierInterface,\n\tQualifierOptions,\n\tRuling,\n\tRulingInput,\n} from './types.js'\nimport { Qualifier } from './Qualifier.js'\n\n/**\n * Create one qualifier 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. Validation is on by default.\n *\n * @param options - Optional injected engine, validation, labels, and emitter hooks\n * @returns A {@link QualifierInterface}\n *\n * @example\n * ```ts\n * import { createQualifier } from '@orkestrel/qualifier'\n *\n * const qualifier = createQualifier()\n * qualifier.qualify({ id: 'risk-1' }, definition)\n * qualifier.destroy()\n * ```\n */\nexport function createQualifier(options?: QualifierOptions): QualifierInterface {\n\treturn new Qualifier(options)\n}\n\n/**\n * Build a {@link QualificationDefinition}.\n *\n * @remarks\n * Returns a fresh top-level definition, omitting absent optional keys;\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, and metadata\n * @returns A fresh qualification definition\n *\n * @example\n * ```ts\n * import { qualificationDefinition } from '@orkestrel/qualifier'\n *\n * qualificationDefinition('standard', 'Standard', [gates], { rulings: [ruling] })\n * ```\n */\nexport function qualificationDefinition(\n\tid: string,\n\tname: string,\n\tpasses: 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}\n}\n\n/**\n * Build a {@link Ruling} — one authored consequence for one rule in one pass.\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 rating scope and message template\n * @returns A fresh ruling\n *\n * @example\n * ```ts\n * import { rulingDefinition } from '@orkestrel/qualifier'\n *\n * rulingDefinition('license', 'gates', 'licensed', 'restriction', { message: 'A license is required' })\n * ```\n */\nexport function rulingDefinition(\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":";;;;;;AAGA,IAAa,6BAA6B;;AAG1C,IAAa,oBAAoB;;AAGjC,IAAa,yBAAiD,OAAO,OAAO;CAC3E;CACA;CACA;AACD,CAAC;;AAGD,IAAa,uBACZ,OAAO,OAAO;CACb,aAAa;CACb,UAAU;CACV,WAAW;AACZ,CAAC;;;;;;;;;;;ACXF,IAAa,iBAAb,cAAoC,MAAM;CACzC;CACA;CAEA,YAAY,MAA0B,SAAiB,SAAmB;EACzE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAAU;CAChB;AACD;;AAGA,SAAgB,iBAAiB,OAAyC;CACzE,OAAO,iBAAiB;AACzB;;;;ACpBA,IAAa,iBAAA,GAAA,oBAAA,UAAA,CAA0B,YAAY,cAAc,UAAU;;AAG3E,IAAa,yBAAA,GAAA,oBAAA,UAAA,CAAkC,eAAe,YAAY,WAAW;;AAGrF,SAAgB,oBAAoB,OAA4C;CAC/E,QAAA,GAAA,kBAAA,yBAAA,CAAgC,KAAK,MAAA,GAAA,kBAAA,oBAAA,CAAyB,KAAK;AACpE;;AAGA,SAAgB,SAAS,OAAiC;CACzD,QAAA,GAAA,oBAAA,SAAA,CACC;EACC,IAAI,oBAAA;EACJ,MAAM,oBAAA;EACN,MAAM,oBAAA;EACN,QAAQ;EACR,OAAO,oBAAA;EACP,SAAS,oBAAA;CACV,GACA,CAAC,SAAS,SAAS,CACpB,CAAC,CAAC,KAAK;AACR;;A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,IAAI,EAAE,UAAU,EAAE,GAAG,MAAM,SAAS,EAAE;CAC5E;AACD;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,iBACf,IACA,MACA,MACA,QACA,OACS;CACT,OAAO;EACN;EACA;EACA;EACA;EACA,GAAI,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;EAC3D,GAAI,OAAO,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,MAAM,QAAQ;CAClE;AACD"}
1
+ {"version":3,"file":"index.cjs","names":["#emitter","#engine","#evaluator","#owned","#validate","#labels","#alive","#qualify","#destroyed"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/Qualifier.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { Eligibility, QualificationEffect } from './types.js'\n\n/** Default definition validation policy for `createQualifier` / `Qualifier.qualify`. */\nexport const DEFAULT_QUALIFIER_VALIDATE = true\n\n/** The reserved internal projection namespace a pass's working projection is written under. */\nexport const QUALIFICATION_KEY = 'qualification'\n\n/** Eligibility severity order — most to least severe. */\nexport const ELIGIBILITY_PRECEDENCE: readonly Eligibility[] = Object.freeze([\n\t'ineligible',\n\t'referral',\n\t'eligible',\n])\n\n/** The eligibility impact of each {@link QualificationEffect}; `condition` remains eligible. */\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 } from './types.js'\n\n/**\n * A coded programmer error thrown by the qualifier layer.\n *\n * @remarks\n * `DEFINITION` — a qualification definition failed semantic validation.\n * `MISMATCH` — a subject is not a record or already carries the reserved\n * `qualification` key. `DESTROYED` — use of a destroyed qualifier.\n * `ENGINE` — the underlying reason engine threw while running a pass (the\n * original throw is preserved as `context.cause`).\n */\nexport class QualifierError extends Error {\n\treadonly code: QualifierErrorCode\n\treadonly context: unknown\n\n\tconstructor(code: QualifierErrorCode, message: string, context?: unknown) {\n\t\tsuper(message)\n\t\tthis.name = 'QualifierError'\n\t\tthis.code = code\n\t\tthis.context = context\n\t}\n}\n\n/** Narrow a caught value to a {@link QualifierError}. */\nexport function isQualifierError(value: unknown): value is QualifierError {\n\treturn value instanceof QualifierError\n}\n","import type { QualificationDefinition, QualificationPass, Ruling } from './types.js'\nimport { arrayOf, isRecord, isString, literalOf, recordOf } from '@orkestrel/contract'\nimport { isLogicalDefinition, isQuantitativeDefinition } from '@orkestrel/reason'\n\n/** Determine whether a value is an {@link Eligibility} literal. */\nexport const isEligibility = literalOf('eligible', 'ineligible', 'referral')\n\n/** Determine whether a value is a {@link QualificationEffect} literal. */\nexport const isQualificationEffect = literalOf('restriction', 'referral', 'condition')\n\n/** Determine whether a value is a {@link QualificationPass} (a quantitative or logical definition). */\nexport function isQualificationPass(value: unknown): value is QualificationPass {\n\treturn isQuantitativeDefinition(value) || isLogicalDefinition(value)\n}\n\n/** Determine whether a value is an exact {@link Ruling} record. */\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/** Determine whether a value is an exact {@link QualificationDefinition} record. */\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: isRecord,\n\t\t},\n\t\t['description', 'rulings', 'metadata'],\n\t)(value)\n}\n","import type {\n\tDerivation,\n\tEligibility,\n\tFinding,\n\tPremise,\n\tQualificationContext,\n\tQualificationDefinition,\n\tQualificationEffect,\n\tQualificationInput,\n\tQualificationPass,\n\tQualificationProjection,\n\tRuling,\n\tRulingInput,\n} from './types.js'\nimport type {\n\tCheck,\n\tCheckResult,\n\tEvaluatorInterface,\n\tLogicalDefinition,\n\tLogicalResult,\n\tQuantitativeResult,\n\tReasonResult,\n\tRule,\n\tSubject,\n} from '@orkestrel/reason'\nimport { EFFECT_ELIGIBILITIES, ELIGIBILITY_PRECEDENCE, QUALIFICATION_KEY } from './constants.js'\nimport { QualifierError } from './errors.js'\nimport { isFiniteNumber, isRecord, resolveField } from '@orkestrel/contract'\nimport {\n\textractAtoms,\n\textractConclusions,\n\tformatField,\n\tisBounds,\n\tisReasonError,\n} from '@orkestrel/reason'\n\n/**\n * Interpolate `{{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(/\\{\\{\\s*([^}]+?)\\s*\\}\\}/g, (_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 * Describe 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 { describeComparison } from '@orkestrel/qualifier'\n *\n * describeComparison('above') // 'is more than'\n * ```\n */\nexport function describeComparison(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 * Render 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 { describeValue } from '@orkestrel/qualifier'\n *\n * describeValue([18, 25, 40]) // '18, 25, 40'\n * describeValue({ minimum: 18, maximum: 65 }) // '18 and 65'\n * describeValue(42) // '42'\n * ```\n */\nexport function describeValue(value: unknown): string {\n\tif (Array.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 * Render one {@link Premise} into a display-neutral sentence.\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 { describePremise } from '@orkestrel/qualifier'\n *\n * describePremise({ field: 'age', comparison: 'above', expected: 18, actual: 25, met: true })\n * // 'age is more than 18 → met'\n * ```\n */\nexport function describePremise(entry: Premise, labels?: Readonly<Record<string, string>>): string {\n\tconst status = entry.met === undefined ? 'unknown' : entry.met ? 'met' : 'not met'\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 ? '' : ` ${describeValue(entry.expected)}`\n\treturn `${label} ${describeComparison(entry.comparison)}${expected} → ${status}`\n}\n\n/**\n * Build 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 `met`\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 { premiseCheck } from '@orkestrel/qualifier'\n * import { check } from '@orkestrel/reason'\n *\n * const authored = check('age', 'above', 18)\n * premiseCheck(authored, { field: 'age', actual: 25, met: true })\n * // { field: 'age', comparison: 'above', expected: 18, actual: 25, met: true }\n * ```\n */\nexport function premiseCheck(\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\t...(result.met === undefined ? {} : { met: result.met }),\n\t}\n}\n\n/**\n * Build rich premises for one fired {@link Rule} by walking its premise atoms\n * and re-evaluating each against the working subject.\n *\n * @remarks\n * A reason rule result carries only booleans, so this is the qualifier's own\n * premise-audit projection: each authored premise expression is flattened to its\n * atom leaves via `extractAtoms`, and each leaf's `Check` is re-evaluated through\n * the injected `evaluator`. A membership check (`any` / `none`) over an EMPTY\n * array value is content-free and is skipped.\n *\n * @param rule - The authored rule\n * @param working - The working subject to evaluate against\n * @param evaluator - The shared reason check evaluator\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 { logicalPremises } from '@orkestrel/qualifier'\n * import { atom, createEvaluator, logicalDefinition, rule } from '@orkestrel/reason'\n *\n * const gates = logicalDefinition('gates', 'Gates', [\n * rule('licensed', [atom('licensed', 'equals', false)], atom('blocked', 'equals', true)),\n * ])\n * const evaluator = createEvaluator()\n * const premises = logicalPremises(gates.rules[0], { licensed: false }, evaluator)\n *\n * premises[0]?.met // true\n * ```\n */\nexport function logicalPremises(\n\trule: Rule,\n\tworking: Subject,\n\tevaluator: EvaluatorInterface,\n\tlabels?: Readonly<Record<string, string>>,\n): readonly Premise[] {\n\tconst output: Premise[] = []\n\tfor (const premise of rule.premises) {\n\t\tfor (const atom of extractAtoms(premise)) {\n\t\t\tconst { check } = atom\n\t\t\tif (\n\t\t\t\t(check.operator === 'any' || check.operator === 'none') &&\n\t\t\t\tArray.isArray(check.value) &&\n\t\t\t\tcheck.value.length === 0\n\t\t\t) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\toutput.push(premiseCheck(check, evaluator.evaluate(check, working), labels))\n\t\t}\n\t}\n\treturn output\n}\n\n/**\n * Locate 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 { atom, logicalDefinition, rule } from '@orkestrel/reason'\n *\n * const gates = logicalDefinition('gates', 'Gates', [\n * rule('licensed', [atom('licensed', 'equals', false)], atom('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 * Project 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 { factorGroup, quantitativeDefinition, staticFactor } from '@orkestrel/reason'\n *\n * const cap = quantitativeDefinition('cap', 'TIV cap', [\n * factorGroup('limit', 'sum', [staticFactor('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\tconst projection: Record<string, unknown> = { conclusion: result.conclusion }\n\tfor (const resolved of result.rules) {\n\t\tif (!resolved.applied) continue\n\t\tconst authored = definition.rules.find((rule) => rule.id === resolved.id)\n\t\tif (authored === undefined) continue\n\t\tconst conclusions = extractConclusions(authored.conclusion)\n\t\tfor (const [key, value] of Object.entries(conclusions)) projection[key] = value\n\t}\n\treturn projection\n}\n\n/**\n * Project 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 * Wrap 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 * Copy-on-write merge one pass projection into the context.\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 * Join a ruling, its logical rule result, the pass, the pre-projection subject,\n * and an evaluator into a {@link Finding}.\n *\n * @remarks\n * `applied` reflects whether the ruling's rule fired. Premises are re-evaluated\n * against the SAME subject snapshot the pass evaluated, so a conclusion the pass\n * derived can never satisfy its own reported premise. The message interpolates\n * against that snapshot.\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 evaluator - The shared reason check evaluator\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 { atom, createEvaluator, logicalDefinition, rule } from '@orkestrel/reason'\n *\n * const gates = logicalDefinition('gates', 'Gates', [\n * rule('licensed', [atom('licensed', 'equals', false)], atom('blocked', 'equals', true)),\n * ])\n * const ruling = { id: 'license', pass: 'gates', rule: 'licensed', effect: 'restriction' as const }\n * const result = { reasoning: 'logical' as const, conclusion: true, rules: [{ id: 'licensed', applied: true, premises: [true], conclusion: true }], count: 1, success: true, trace: [], errors: [] }\n * const finding = rulingToFinding(ruling, gates, result, { licensed: false }, createEvaluator())\n *\n * finding.applied // true\n * ```\n */\nexport function rulingToFinding(\n\truling: Ruling,\n\tpass: QualificationPass,\n\tresult: LogicalResult,\n\tsubject: Subject,\n\tevaluator: EvaluatorInterface,\n\tlabels?: Readonly<Record<string, string>>,\n): Finding {\n\tconst entry = result.rules.find((item) => item.id === ruling.rule)\n\tconst applied = entry?.applied ?? false\n\tconst rule = pass.reasoning === 'logical' ? findRule(pass, ruling.rule) : undefined\n\tconst premises = rule === undefined ? [] : logicalPremises(rule, subject, evaluator, 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\tapplied,\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 * Derive global eligibility from applied, unscoped findings.\n *\n * @remarks\n * Only findings that both applied 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 - Whether an operational pass failure occurred\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, applied: true, premises: [] }\n * deriveFindingEligibility([finding]) // 'ineligible'\n * ```\n */\nexport function deriveFindingEligibility(findings: Finding[], failed = false): Eligibility {\n\tconst eligibilities = findings\n\t\t.filter((finding) => finding.applied && 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 * Return 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: 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 * Derive one eligibility per finding scope.\n *\n * @remarks\n * Only applied, scoped findings 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', applied: true, premises: [] }\n * deriveScopeEligibilities([finding]) // { wind: 'ineligible' }\n * ```\n */\nexport function deriveScopeEligibilities(\n\tfindings: Finding[],\n): Readonly<Record<string, Eligibility>> {\n\tconst grouped: Record<string, Eligibility[]> = {}\n\tfor (const finding of findings) {\n\t\tif (!finding.applied || finding.scope === undefined) continue\n\t\tconst current = grouped[finding.scope] ?? []\n\t\tgrouped[finding.scope] = [...current, EFFECT_ELIGIBILITIES[finding.effect]]\n\t}\n\tconst scopes: Record<string, Eligibility> = {}\n\tfor (const [scope, eligibilities] of Object.entries(grouped)) {\n\t\tscopes[scope] = combineEligibilities(eligibilities)\n\t}\n\treturn scopes\n}\n\n/**\n * Find rulings whose pass or rule does not exist, whose pass is not logical, or\n * a 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 { findMissingReferences, qualificationDefinition, rulingDefinition } from '@orkestrel/qualifier'\n * import { atom, logicalDefinition, rule } from '@orkestrel/reason'\n *\n * const gates = logicalDefinition('gates', 'Gates', [\n * rule('licensed', [atom('licensed', 'equals', false)], atom('blocked', 'equals', true)),\n * ])\n * const definition = qualificationDefinition('standard', 'Standard', [gates], {\n * rulings: [rulingDefinition('license', 'gates', 'absent', 'restriction')],\n * })\n *\n * findMissingReferences(definition)\n * // [\"Ruling 'license' references missing rule 'absent' in pass 'gates'\"]\n * ```\n */\nexport function findMissingReferences(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 * Determine whether a subject already owns the reserved {@link QUALIFICATION_KEY}.\n *\n * @param subject - The subject to check\n * @returns `true` when the subject owns the reserved key\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 * Assert 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 * Map 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 (e.g. `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 = error instanceof 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 * Find logical passes 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 { findEmptyLogicalPasses, qualificationDefinition } from '@orkestrel/qualifier'\n * import { atom, logicalDefinition, rule } from '@orkestrel/reason'\n *\n * const gates = logicalDefinition('gates', 'Gates', [\n * rule('licensed', [atom('licensed', 'equals', false)], atom('blocked', 'equals', true)),\n * ])\n * const definition = qualificationDefinition('standard', 'Standard', [gates])\n *\n * findEmptyLogicalPasses(definition) // [\"Logical pass 'gates' has no rulings\"]\n * ```\n */\nexport function findEmptyLogicalPasses(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 * Find quantitative passes 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 { findUnreadDerivations, qualificationDefinition } from '@orkestrel/qualifier'\n * import { factorGroup, quantitativeDefinition, staticFactor } from '@orkestrel/reason'\n *\n * const cap = quantitativeDefinition('cap', 'TIV cap', [\n * factorGroup('limit', 'sum', [staticFactor('base', 500_000)]),\n * ])\n * const definition = qualificationDefinition('standard', 'Standard', [cap])\n *\n * findUnreadDerivations(definition) // [\"Quantitative pass 'cap' is never read by a later pass\"]\n * ```\n */\nexport function findUnreadDerivations(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\n/**\n * Build a {@link QualificationDefinition}.\n *\n * @remarks\n * Returns a fresh top-level definition, omitting absent optional keys;\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, and metadata\n * @returns A fresh qualification definition\n *\n * @example\n * ```ts\n * import { qualificationDefinition } from '@orkestrel/qualifier'\n *\n * qualificationDefinition('standard', 'Standard', [gates], { rulings: [ruling] })\n * ```\n */\nexport function qualificationDefinition(\n\tid: string,\n\tname: string,\n\tpasses: 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}\n}\n\n/**\n * Build a {@link Ruling} — one authored consequence for one rule in one pass.\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 { rulingDefinition } from '@orkestrel/qualifier'\n *\n * rulingDefinition('license', 'gates', 'licensed', 'restriction', { message: 'A license is required' })\n * ```\n */\nexport function rulingDefinition(\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","import type {\n\tDerivation,\n\tFinding,\n\tQualificationContext,\n\tQualificationDefinition,\n\tQualificationResult,\n\tQualificationValidationResult,\n\tQualifierEventMap,\n\tQualifierInterface,\n\tQualifierOptions,\n} from './types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type { EvaluatorInterface, ReasonInterface, ReasonResult, Subject } from '@orkestrel/reason'\nimport { DEFAULT_QUALIFIER_VALIDATE } from './constants.js'\nimport { QualifierError } from './errors.js'\nimport {\n\tassertSubject,\n\tderiveFindingEligibility,\n\tderiveScopeEligibilities,\n\tfindEmptyLogicalPasses,\n\tfindMissingReferences,\n\tfindUnreadDerivations,\n\tmapEngineError,\n\tmergeQualificationContext,\n\tqualificationToRecord,\n\tquantitativeResultToDerivation,\n\treasonResultToProjection,\n\trulingToFinding,\n} from './helpers.js'\nimport { isQualificationPass, isRuling } from './validators.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tcreateEvaluator,\n\tcreateLogicalReasoner,\n\tcreateQuantitativeReasoner,\n\tcreateReason,\n\tfindDuplicates,\n} from '@orkestrel/reason'\n\n/**\n * A qualifier — runs ordered passes over one reason engine and returns\n * eligibility.\n *\n * @remarks\n * The engine is OWNED when self-created (destroyed on `destroy()`) and borrowed\n * when injected (never destroyed). `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 #evaluator: EvaluatorInterface\n\treadonly #owned: boolean\n\treadonly #validate: boolean\n\treadonly #labels: Readonly<Record<string, string>> | undefined\n\t#destroyed = false\n\n\tconstructor(options?: QualifierOptions) {\n\t\tthis.#emitter = new Emitter({ on: options?.on, error: options?.error })\n\t\tthis.#evaluator = createEvaluator()\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: [\n\t\t\t\t\tcreateQuantitativeReasoner({ evaluator: this.#evaluator }),\n\t\t\t\t\tcreateLogicalReasoner({ evaluator: this.#evaluator }),\n\t\t\t\t],\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\tget emitter(): EmitterInterface<QualifierEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tqualify(subject: Subject, definition: QualificationDefinition): QualificationResult {\n\t\tthis.#alive()\n\t\tif (this.#validate) {\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\tdefinition.id,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\treturn this.#qualify(subject, definition)\n\t}\n\n\tvalidate(definition: QualificationDefinition): QualificationValidationResult {\n\t\tthis.#alive()\n\t\tconst errors: string[] = []\n\t\tconst warnings: string[] = []\n\t\tif (definition.id.length === 0) errors.push('Definition id must not be empty')\n\t\tif (definition.name.length === 0) errors.push('Definition name must not be empty')\n\t\tdefinition.passes.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}\n\t\t})\n\t\t;(definition.rulings ?? []).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\tfor (const id of findDuplicates(definition.passes)) errors.push(`Duplicate pass id '${id}'`)\n\t\tfor (const id of findDuplicates(definition.rulings ?? [])) {\n\t\t\terrors.push(`Duplicate ruling id '${id}'`)\n\t\t}\n\t\tfor (const reference of findMissingReferences(definition)) errors.push(reference)\n\t\tif (definition.passes.length === 0) warnings.push('Definition has no passes')\n\t\tfor (const warning of findEmptyLogicalPasses(definition)) warnings.push(warning)\n\t\tfor (const warning of findUnreadDerivations(definition)) warnings.push(warning)\n\t\treturn { valid: errors.length === 0, errors, warnings }\n\t}\n\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\tlet context: QualificationContext = {}\n\t\tlet working: Subject = { ...subject }\n\t\tconst findings: Finding[] = []\n\t\tconst derivations: Derivation[] = []\n\t\tconst trace: string[] = []\n\t\tconst errors: string[] = []\n\t\tlet failed = false\n\n\t\tfor (const pass of definition.passes) {\n\t\t\tthis.#alive()\n\t\t\tconst evaluated = working\n\t\t\tlet result: ReasonResult\n\t\t\ttry {\n\t\t\t\tresult = this.#engine.reason(evaluated, pass)\n\t\t\t} catch (error) {\n\t\t\t\tthrow mapEngineError(error, pass.id)\n\t\t\t}\n\n\t\t\ttrace.push(...result.trace.map((entry) => `${pass.id}: ${entry}`))\n\t\t\terrors.push(...result.errors.map((entry) => `${pass.id}: ${entry}`))\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(\n\t\t\t\t\t\truling,\n\t\t\t\t\t\tpass,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\tevaluated,\n\t\t\t\t\t\tthis.#evaluator,\n\t\t\t\t\t\tthis.#labels,\n\t\t\t\t\t)\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\tconst projection = reasonResultToProjection(pass, result)\n\t\t\tcontext = mergeQualificationContext(context, pass.id, projection)\n\t\t\tworking = { ...subject, ...qualificationToRecord(context) }\n\n\t\t\tif (!result.success) {\n\t\t\t\tfailed = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif (deriveFindingEligibility(findings) === 'ineligible') break\n\t\t}\n\n\t\tconst success = !failed && errors.length === 0\n\t\tconst scopes = deriveScopeEligibilities(findings)\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(scopes),\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})\n\t\tthis.#emitter.emit('qualify', qualification)\n\t\treturn qualification\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 { QualifierInterface, QualifierOptions } from './types.js'\nimport { Qualifier } from './Qualifier.js'\n\n/**\n * Create one qualifier 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. Validation is on by default.\n *\n * @param options - Optional injected engine, validation, labels, and emitter hooks\n * @returns A {@link QualifierInterface}\n *\n * @example\n * ```ts\n * import { createQualifier } from '@orkestrel/qualifier'\n *\n * const qualifier = createQualifier()\n * qualifier.qualify({ id: 'risk-1' }, definition)\n * qualifier.destroy()\n * ```\n */\nexport function createQualifier(options?: QualifierOptions): QualifierInterface {\n\treturn new Qualifier(options)\n}\n"],"mappings":";;;;;;AAGA,IAAa,6BAA6B;;AAG1C,IAAa,oBAAoB;;AAGjC,IAAa,yBAAiD,OAAO,OAAO;CAC3E;CACA;CACA;AACD,CAAC;;AAGD,IAAa,uBACZ,OAAO,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A,MACA,QACA,WACA,KAAKE,YACL,KAAKG,OACN;KACA,SAAS,KAAK,OAAO;KACrB,KAAKL,SAAS,KAAK,WAAW,OAAO;IACtC;GACD;GAEA,MAAM,aAAa,yBAAyB,MAAM,MAAM;GACxD,UAAU,0BAA0B,SAAS,KAAK,IAAI,UAAU;GAChE,UAAU;IAAE,GAAG;IAAS,GAAG,sBAAsB,OAAO;GAAE;GAE1D,IAAI,CAAC,OAAO,SAAS;IACpB,SAAS;IACT;GACD;GACA,IAAI,yBAAyB,QAAQ,MAAM,cAAc;EAC1D;EAEA,MAAM,UAAU,CAAC,UAAU,OAAO,WAAW;EAC7C,MAAM,SAAS,yBAAyB,QAAQ;EAChD,MAAM,gBAAqC,OAAO,OAAO;GACxD,IAAI,WAAW;GACf,MAAM,WAAW;GACjB,aAAa,yBAAyB,UAAU,CAAC,OAAO;GACxD,QAAQ,OAAO,OAAO,MAAM;GAC5B,UAAU,OAAO,OAAO,QAAQ;GAChC,aAAa,OAAO,OAAO,WAAW;GACtC;GACA,OAAO,OAAO,OAAO,KAAK;GAC1B,QAAQ,OAAO,OAAO,MAAM;EAC7B,CAAC;EACD,KAAKA,SAAS,KAAK,WAAW,aAAa;EAC3C,OAAO;CACR;CAEA,SAAe;EACd,IAAI,KAAKQ,YACR,MAAM,IAAI,eAAe,aAAa,8BAA8B;CAEtE;AACD;;;;;;;;;;;;;;;;;;;;;;;ACtLA,SAAgB,gBAAgB,SAAgD;CAC/E,OAAO,IAAI,UAAU,OAAO;AAC7B"}
@@ -14,6 +14,7 @@ import { QuantitativeDefinition } from '@orkestrel/reason';
14
14
  import { QuantitativeResult } from '@orkestrel/reason';
15
15
  import { ReasonInterface } from '@orkestrel/reason';
16
16
  import { ReasonResult } from '@orkestrel/reason';
17
+ import { ReasonValidationResult } from '@orkestrel/reason';
17
18
  import { Rule } from '@orkestrel/reason';
18
19
  import { Subject } from '@orkestrel/reason';
19
20
 
@@ -23,6 +24,13 @@ import { Subject } from '@orkestrel/reason';
23
24
  * @param value - The candidate subject to validate
24
25
  * @throws {@link QualifierError} `'MISMATCH'` when the value is not a record, or
25
26
  * when it already carries the reserved `qualification` key
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import { assertSubject } from '@orkestrel/qualifier'
31
+ *
32
+ * assertSubject({ id: 's1' }) // narrows to Subject
33
+ * ```
26
34
  */
27
35
  export declare function assertSubject(value: unknown): asserts value is Subject;
28
36
 
@@ -86,6 +94,14 @@ import { Subject } from '@orkestrel/reason';
86
94
  * @param findings - The resolved findings
87
95
  * @param failed - Whether an operational pass failure occurred
88
96
  * @returns The most severe global eligibility
97
+ *
98
+ * @example
99
+ * ```ts
100
+ * import { deriveFindingEligibility } from '@orkestrel/qualifier'
101
+ *
102
+ * const finding = { id: 'license', pass: 'gates', rule: 'licensed', effect: 'restriction' as const, applied: true, premises: [] }
103
+ * deriveFindingEligibility([finding]) // 'ineligible'
104
+ * ```
89
105
  */
90
106
  export declare function deriveFindingEligibility(findings: Finding[], failed?: boolean): Eligibility;
91
107
 
@@ -99,6 +115,14 @@ import { Subject } from '@orkestrel/reason';
99
115
  *
100
116
  * @param findings - The resolved findings
101
117
  * @returns A fresh record of scope to its combined eligibility
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * import { deriveScopeEligibilities } from '@orkestrel/qualifier'
122
+ *
123
+ * const finding = { id: 'coastal', pass: 'wind', rule: 'coastal', effect: 'restriction' as const, scope: 'wind', applied: true, premises: [] }
124
+ * deriveScopeEligibilities([finding]) // { wind: 'ineligible' }
125
+ * ```
102
126
  */
103
127
  export declare function deriveScopeEligibilities(findings: Finding[]): Readonly<Record<string, Eligibility>>;
104
128
 
@@ -162,19 +186,37 @@ import { Subject } from '@orkestrel/reason';
162
186
  /** The eligibility impact of each {@link QualificationEffect}; `condition` remains eligible. */
163
187
  export declare const EFFECT_ELIGIBILITIES: Readonly<Record<QualificationEffect, Eligibility>>;
164
188
 
165
- /** The pre-rating outcome axis. */
189
+ /** The eligibility outcome axis. */
166
190
  export declare type Eligibility = 'eligible' | 'ineligible' | 'referral';
167
191
 
168
192
  /** Eligibility severity order — most to least severe. */
169
193
  export declare const ELIGIBILITY_PRECEDENCE: readonly Eligibility[];
170
194
 
171
195
  /**
172
- * Find duplicate ids in a list, once each.
196
+ * Find logical passes carrying no rulings.
197
+ *
198
+ * @remarks
199
+ * A logical pass with no matching ruling can never contribute a finding, so its
200
+ * rules only ever influence later passes' reads — this is very likely an authoring
201
+ * oversight.
173
202
  *
174
- * @param ids - The ids to scan
175
- * @returns A fresh list of ids that appear more than once
203
+ * @param definition - The qualification definition to check
204
+ * @returns A fresh list of warning messages
205
+ *
206
+ * @example
207
+ * ```ts
208
+ * import { findEmptyLogicalPasses, qualificationDefinition } from '@orkestrel/qualifier'
209
+ * import { atom, logicalDefinition, rule } from '@orkestrel/reason'
210
+ *
211
+ * const gates = logicalDefinition('gates', 'Gates', [
212
+ * rule('licensed', [atom('licensed', 'equals', false)], atom('blocked', 'equals', true)),
213
+ * ])
214
+ * const definition = qualificationDefinition('standard', 'Standard', [gates])
215
+ *
216
+ * findEmptyLogicalPasses(definition) // ["Logical pass 'gates' has no rulings"]
217
+ * ```
176
218
  */
177
- export declare function findDuplicateIds(ids: readonly string[]): readonly string[];
219
+ export declare function findEmptyLogicalPasses(definition: QualificationDefinition): readonly string[];
178
220
 
179
221
  /** One resolved ruling. */
180
222
  export declare interface Finding {
@@ -194,6 +236,22 @@ import { Subject } from '@orkestrel/reason';
194
236
  *
195
237
  * @param definition - The qualification definition to check
196
238
  * @returns A fresh list of reference-error messages
239
+ *
240
+ * @example
241
+ * ```ts
242
+ * import { findMissingReferences, qualificationDefinition, rulingDefinition } from '@orkestrel/qualifier'
243
+ * import { atom, logicalDefinition, rule } from '@orkestrel/reason'
244
+ *
245
+ * const gates = logicalDefinition('gates', 'Gates', [
246
+ * rule('licensed', [atom('licensed', 'equals', false)], atom('blocked', 'equals', true)),
247
+ * ])
248
+ * const definition = qualificationDefinition('standard', 'Standard', [gates], {
249
+ * rulings: [rulingDefinition('license', 'gates', 'absent', 'restriction')],
250
+ * })
251
+ *
252
+ * findMissingReferences(definition)
253
+ * // ["Ruling 'license' references missing rule 'absent' in pass 'gates'"]
254
+ * ```
197
255
  */
198
256
  export declare function findMissingReferences(definition: QualificationDefinition): readonly string[];
199
257
 
@@ -218,11 +276,46 @@ import { Subject } from '@orkestrel/reason';
218
276
  */
219
277
  export declare function findRule(definition: LogicalDefinition, id: string): Rule | undefined;
220
278
 
279
+ /**
280
+ * Find quantitative passes never read by a later pass.
281
+ *
282
+ * @remarks
283
+ * A quantitative pass's projected value lives under `qualification.<id>` — if no
284
+ * later logical premise or quantitative factor field reads that key, the
285
+ * derivation is dead weight. Reads are collected per later pass: a logical pass's
286
+ * premise atoms (conclusion atoms are writes, not reads), and a quantitative
287
+ * pass's field/lookup/range factor sources plus factor checks.
288
+ *
289
+ * @param definition - The qualification definition to check
290
+ * @returns A fresh list of warning messages
291
+ *
292
+ * @example
293
+ * ```ts
294
+ * import { findUnreadDerivations, qualificationDefinition } from '@orkestrel/qualifier'
295
+ * import { factorGroup, quantitativeDefinition, staticFactor } from '@orkestrel/reason'
296
+ *
297
+ * const cap = quantitativeDefinition('cap', 'TIV cap', [
298
+ * factorGroup('limit', 'sum', [staticFactor('base', 500_000)]),
299
+ * ])
300
+ * const definition = qualificationDefinition('standard', 'Standard', [cap])
301
+ *
302
+ * findUnreadDerivations(definition) // ["Quantitative pass 'cap' is never read by a later pass"]
303
+ * ```
304
+ */
305
+ export declare function findUnreadDerivations(definition: QualificationDefinition): readonly string[];
306
+
221
307
  /**
222
308
  * Determine whether a subject already owns the reserved {@link QUALIFICATION_KEY}.
223
309
  *
224
310
  * @param subject - The subject to check
225
311
  * @returns `true` when the subject owns the reserved key
312
+ *
313
+ * @example
314
+ * ```ts
315
+ * import { hasReservedKey } from '@orkestrel/qualifier'
316
+ *
317
+ * hasReservedKey({ id: 's1', qualification: {} }) // true
318
+ * ```
226
319
  */
227
320
  export declare function hasReservedKey(subject: Subject): boolean;
228
321
 
@@ -301,6 +394,30 @@ import { Subject } from '@orkestrel/reason';
301
394
  */
302
395
  export declare function logicalPremises(rule: Rule, working: Subject, evaluator: EvaluatorInterface, labels?: Readonly<Record<string, string>>): readonly Premise[];
303
396
 
397
+ /**
398
+ * Map an engine throw caught while running one pass to a typed {@link QualifierError}.
399
+ *
400
+ * @remarks
401
+ * A reason `ReasonError('INVALID')` maps to `DEFINITION` (the engine rejected the
402
+ * pass as an invalid definition); `ReasonError('DESTROYED')` maps to `DESTROYED`;
403
+ * every other `ReasonError` code (e.g. `MISSING`) and every non-`ReasonError` throw
404
+ * (including a `bail: true` reasoner rethrow) maps to `ENGINE`. The original throw
405
+ * is preserved as `context.cause`.
406
+ *
407
+ * @param error - The value caught from the engine's `reason` call
408
+ * @param pass - The id of the pass that was running
409
+ * @returns A fresh, typed {@link QualifierError}
410
+ *
411
+ * @example
412
+ * ```ts
413
+ * import { mapEngineError } from '@orkestrel/qualifier'
414
+ * import { ReasonError } from '@orkestrel/reason'
415
+ *
416
+ * mapEngineError(new ReasonError('MISSING', 'No reasoner registered'), 'cap').code // 'ENGINE'
417
+ * ```
418
+ */
419
+ export declare function mapEngineError(error: unknown, pass: string): QualifierError;
420
+
304
421
  /**
305
422
  * Copy-on-write merge one pass projection into the context.
306
423
  *
@@ -308,6 +425,14 @@ import { Subject } from '@orkestrel/reason';
308
425
  * @param id - The pass id to project under
309
426
  * @param projection - The pass's working projection
310
427
  * @returns A fresh context with the projection added
428
+ *
429
+ * @example
430
+ * ```ts
431
+ * import { mergeQualificationContext } from '@orkestrel/qualifier'
432
+ *
433
+ * mergeQualificationContext({ cap: 500_000 }, 'excess', 250_000)
434
+ * // { cap: 500000, excess: 250000 }
435
+ * ```
311
436
  */
312
437
  export declare function mergeQualificationContext(context: QualificationContext, id: string, projection: QualificationProjection): QualificationContext;
313
438
 
@@ -416,19 +541,22 @@ import { Subject } from '@orkestrel/reason';
416
541
  *
417
542
  * @param context - The accumulated projection context
418
543
  * @returns A record carrying the context under the reserved key
544
+ *
545
+ * @example
546
+ * ```ts
547
+ * import { qualificationToRecord } from '@orkestrel/qualifier'
548
+ *
549
+ * qualificationToRecord({ cap: 500_000 }) // { qualification: { cap: 500000 } }
550
+ * ```
419
551
  */
420
552
  export declare function qualificationToRecord(context: QualificationContext): Readonly<Record<string, QualificationContext>>;
421
553
 
422
554
  /** Semantic definition validation. */
423
- export declare interface QualificationValidationResult {
424
- readonly valid: boolean;
425
- readonly errors: readonly string[];
426
- readonly warnings: readonly string[];
427
- }
555
+ export declare type QualificationValidationResult = ReasonValidationResult;
428
556
 
429
557
  /**
430
558
  * A qualifier — runs ordered passes over one reason engine and returns
431
- * pre-rating eligibility.
559
+ * eligibility.
432
560
  *
433
561
  * @remarks
434
562
  * The engine is OWNED when self-created (destroyed on `destroy()`) and borrowed
@@ -452,6 +580,8 @@ import { Subject } from '@orkestrel/reason';
452
580
  * `DEFINITION` — a qualification definition failed semantic validation.
453
581
  * `MISMATCH` — a subject is not a record or already carries the reserved
454
582
  * `qualification` key. `DESTROYED` — use of a destroyed qualifier.
583
+ * `ENGINE` — the underlying reason engine threw while running a pass (the
584
+ * original throw is preserved as `context.cause`).
455
585
  */
456
586
  export declare class QualifierError extends Error {
457
587
  readonly code: QualifierErrorCode;
@@ -460,7 +590,7 @@ import { Subject } from '@orkestrel/reason';
460
590
  }
461
591
 
462
592
  /** A coded {@link QualifierError} programmer-error code. */
463
- export declare type QualifierErrorCode = 'DEFINITION' | 'MISMATCH' | 'DESTROYED';
593
+ export declare type QualifierErrorCode = 'DEFINITION' | 'MISMATCH' | 'DESTROYED' | 'ENGINE';
464
594
 
465
595
  /** The push observation surface of a {@link QualifierInterface} (AGENTS §13). */
466
596
  export declare type QualifierEventMap = {
@@ -470,7 +600,7 @@ import { Subject } from '@orkestrel/reason';
470
600
  readonly destroy: readonly [];
471
601
  };
472
602
 
473
- /** One qualifier — owns or borrows one reason engine and returns pre-rating eligibility. */
603
+ /** One qualifier — owns or borrows one reason engine and returns eligibility. */
474
604
  export declare interface QualifierInterface {
475
605
  readonly emitter: EmitterInterface<QualifierEventMap>;
476
606
  qualify(subject: Subject, definition: QualificationDefinition): QualificationResult;
@@ -493,6 +623,15 @@ import { Subject } from '@orkestrel/reason';
493
623
  * @param id - The pass id
494
624
  * @param result - The evaluated quantitative result
495
625
  * @returns A fresh derivation
626
+ *
627
+ * @example
628
+ * ```ts
629
+ * import { quantitativeResultToDerivation } from '@orkestrel/qualifier'
630
+ *
631
+ * const result = { reasoning: 'quantitative' as const, value: 500_000, groups: [], count: 1, success: true, trace: ['cap: 500000'], errors: [] }
632
+ * quantitativeResultToDerivation('cap', result)
633
+ * // { id: 'cap', value: 500000, success: true, trace: ['cap: 500000'], errors: [] }
634
+ * ```
496
635
  */
497
636
  export declare function quantitativeResultToDerivation(id: string, result: QuantitativeResult): Derivation;
498
637
 
@@ -508,6 +647,26 @@ import { Subject } from '@orkestrel/reason';
508
647
  * @param definition - The pass definition that produced the result
509
648
  * @param result - The evaluated reason result
510
649
  * @returns The pass's working projection
650
+ *
651
+ * @example
652
+ * ```ts
653
+ * import { reasonResultToProjection } from '@orkestrel/qualifier'
654
+ * import { factorGroup, quantitativeDefinition, staticFactor } from '@orkestrel/reason'
655
+ *
656
+ * const cap = quantitativeDefinition('cap', 'TIV cap', [
657
+ * factorGroup('limit', 'sum', [staticFactor('base', 500_000)]),
658
+ * ])
659
+ * const result = {
660
+ * reasoning: 'quantitative' as const,
661
+ * value: 500_000,
662
+ * groups: [],
663
+ * count: 1,
664
+ * success: true,
665
+ * trace: [],
666
+ * errors: [],
667
+ * }
668
+ * reasonResultToProjection(cap, result) // 500000
669
+ * ```
511
670
  */
512
671
  export declare function reasonResultToProjection(definition: QualificationPass, result: ReasonResult): QualificationProjection;
513
672
 
@@ -528,7 +687,7 @@ import { Subject } from '@orkestrel/reason';
528
687
  * @param pass - The logical pass id the rule lives in
529
688
  * @param rule - The rule id whose firing this ruling reacts to
530
689
  * @param effect - The eligibility impact when the rule fires
531
- * @param input - Optional rating scope and message template
690
+ * @param input - Optional selection scope and message template
532
691
  * @returns A fresh ruling
533
692
  *
534
693
  * @example
@@ -563,6 +722,21 @@ import { Subject } from '@orkestrel/reason';
563
722
  * @param evaluator - The shared reason check evaluator
564
723
  * @param labels - Optional field-to-label overrides, keyed by dot-joined field
565
724
  * @returns A fresh finding
725
+ *
726
+ * @example
727
+ * ```ts
728
+ * import { rulingToFinding } from '@orkestrel/qualifier'
729
+ * import { atom, createEvaluator, logicalDefinition, rule } from '@orkestrel/reason'
730
+ *
731
+ * const gates = logicalDefinition('gates', 'Gates', [
732
+ * rule('licensed', [atom('licensed', 'equals', false)], atom('blocked', 'equals', true)),
733
+ * ])
734
+ * const ruling = { id: 'license', pass: 'gates', rule: 'licensed', effect: 'restriction' as const }
735
+ * const result = { reasoning: 'logical' as const, conclusion: true, rules: [{ id: 'licensed', applied: true, premises: [true], conclusion: true }], count: 1, success: true, trace: [], errors: [] }
736
+ * const finding = rulingToFinding(ruling, gates, result, { licensed: false }, createEvaluator())
737
+ *
738
+ * finding.applied // true
739
+ * ```
566
740
  */
567
741
  export declare function rulingToFinding(ruling: Ruling, pass: QualificationPass, result: LogicalResult, subject: Subject, evaluator: EvaluatorInterface, labels?: Readonly<Record<string, string>>): Finding;
568
742