@orkestrel/program 0.0.7 → 0.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/core/index.cjs +288 -80
- package/dist/src/core/index.d.cts +158 -0
- package/dist/src/core/index.d.ts +158 -0
- package/dist/src/core/index.js +285 -85
- package/package.json +15 -13
- package/dist/src/core/index.cjs.map +0 -1
- package/dist/src/core/index.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#emitter","#qualifier","#rater","#engine","#evaluator","#qualifierOwned","#raterOwned","#engineOwned","#validate","#labels","#alive","#aggregate","#subject","#destroyed","#finish","#aggregateLimits","#emitter","#programs","#qualifier","#rater","#engine","#qualifierOwned","#raterOwned","#engineOwned","#validate","#labels","#alive","#drain","#removeOne","#destroyed"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/programs/Program.ts","../../../src/core/programs/ProgramManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { Decision, Status } from './types.js'\nimport type { Eligibility } from '@orkestrel/qualifier'\n\n/** Default definition validation policy for `createProgram` / `ProgramManager.add`. */\nexport const DEFAULT_PROGRAM_VALIDATE = true\n\n/** Status tally precedence order — least to most resolved. */\nexport const STATUS_PRECEDENCE: readonly Status[] = Object.freeze([\n\t'ineligible',\n\t'referral',\n\t'conditional',\n\t'unrated',\n\t'eligible',\n])\n\n/** The deterministic authority decision for each global eligibility. */\nexport const ELIGIBILITY_DECISIONS: Readonly<Record<Eligibility, Decision>> = Object.freeze({\n\teligible: 'approved',\n\tineligible: 'denied',\n\treferral: 'submitted',\n})\n\n/** The reserved working-subject key a batch's aggregate projection is written under. */\nexport const AGGREGATE_KEY = 'aggregate'\n\n/** The reserved working-subject key the authority's outcome projection is written under. */\nexport const OUTCOME_KEY = 'outcome'\n","import type { ProgramErrorCode } from './types.js'\n\n/**\n * A coded programmer error thrown by the program layer.\n *\n * @remarks\n * `DUPLICATE` — a program id collision on `ProgramManager.add`, or a duplicate\n * authored rating-line or notice id. `MISSING` — an\n * authored notice or qualification ruling scope names no rating line.\n * `DEFINITION` — a program, qualification, rating, authority, or aggregate\n * policy failed validation. `MISMATCH` — an injected entity or a returned\n * reason result has the wrong contract. `RESERVED` — a subject already\n * carries `aggregate` or `outcome`. `DESTROYED` — use of a destroyed entity.\n */\nexport class ProgramError extends Error {\n\treadonly code: ProgramErrorCode\n\treadonly context?: unknown\n\n\tconstructor(code: ProgramErrorCode, message: string, context?: unknown) {\n\t\tsuper(message)\n\t\tthis.name = 'ProgramError'\n\t\tthis.code = code\n\t\tthis.context = context\n\t}\n}\n\n/** Narrow a caught value to a {@link ProgramError}. */\nexport function isProgramError(value: unknown): value is ProgramError {\n\treturn value instanceof ProgramError\n}\n","import type { Guard } from '@orkestrel/contract'\nimport type {\n\tAggregateDefinition,\n\tDecision,\n\tNotice,\n\tProgramDefinition,\n\tProgramEffect,\n\tStatus,\n} from './types.js'\nimport { arrayOf, isJSONValue, isString, literalOf, recordOf } from '@orkestrel/contract'\nimport { isQualificationDefinition } from '@orkestrel/qualifier'\nimport { isRatingDefinition } from '@orkestrel/rater'\nimport { isFieldPath, isLogicalDefinition } from '@orkestrel/reason'\n\n/**\n * Determine whether a value is a {@link Decision} literal.\n *\n * @param value - The candidate value\n * @returns `true` when `value` is a {@link Decision}\n *\n * @example\n * ```ts\n * import { isDecision } from '@orkestrel/program'\n *\n * isDecision('approved') // true\n * ```\n */\nexport const isDecision: Guard<Decision> = literalOf('approved', 'denied', 'submitted')\n\n/**\n * Determine whether a value is a {@link Status} literal.\n *\n * @param value - The candidate value\n * @returns `true` when `value` is a {@link Status}\n *\n * @example\n * ```ts\n * import { isStatus } from '@orkestrel/program'\n *\n * isStatus('eligible') // true\n * ```\n */\nexport const isStatus: Guard<Status> = literalOf(\n\t'ineligible',\n\t'referral',\n\t'conditional',\n\t'unrated',\n\t'eligible',\n)\n\n/**\n * Determine whether a value is a {@link ProgramEffect} literal.\n *\n * @param value - The candidate value\n * @returns `true` when `value` is a {@link ProgramEffect}\n *\n * @example\n * ```ts\n * import { isProgramEffect } from '@orkestrel/program'\n *\n * isProgramEffect('notice') // true\n * ```\n */\nexport const isProgramEffect: Guard<ProgramEffect> = literalOf('notice', 'limit')\n\n/**\n * Determine whether a value is an exact {@link Notice} record.\n *\n * @param value - The candidate value\n * @returns `true` when `value` is a {@link Notice}\n *\n * @example\n * ```ts\n * import { isNotice } from '@orkestrel/program'\n *\n * isNotice({ id: 'minimum', message: 'Minimum applies' }) // true\n * ```\n */\nexport function isNotice(value: unknown): value is Notice {\n\treturn recordOf({ id: isString, message: isString, scope: isString }, ['scope'])(value)\n}\n\n/**\n * Determine whether a value is an exact {@link AggregateDefinition} record.\n *\n * @param value - The candidate value\n * @returns `true` when `value` is an {@link AggregateDefinition}\n *\n * @example\n * ```ts\n * import { isAggregateDefinition } from '@orkestrel/program'\n *\n * isAggregateDefinition({ fields: ['amount'] }) // true\n * ```\n */\nexport function isAggregateDefinition(value: unknown): value is AggregateDefinition {\n\treturn recordOf({ fields: arrayOf(isFieldPath), by: isFieldPath, gates: isLogicalDefinition }, [\n\t\t'by',\n\t\t'gates',\n\t])(value)\n}\n\n/**\n * Determine whether a value is an exact {@link ProgramDefinition} record.\n *\n * @remarks\n * `rating` is optional — an omitted `rating` authors an eligibility-only\n * program (see {@link ProgramDefinition}).\n *\n * @param value - The candidate value\n * @returns `true` when `value` is a {@link ProgramDefinition}\n *\n * @example\n * ```ts\n * import { isProgramDefinition } from '@orkestrel/program'\n *\n * isProgramDefinition({ id: 'p', name: 'P', qualification }) // true\n * ```\n */\nexport function isProgramDefinition(value: unknown): value is ProgramDefinition {\n\treturn recordOf(\n\t\t{\n\t\t\tid: isString,\n\t\t\tname: isString,\n\t\t\tdescription: isString,\n\t\t\tqualification: isQualificationDefinition,\n\t\t\trating: isRatingDefinition,\n\t\t\tnotices: arrayOf(isNotice),\n\t\t\tauthority: isLogicalDefinition,\n\t\t\taggregate: isAggregateDefinition,\n\t\t\tmetadata: isJSONValue,\n\t\t},\n\t\t['description', 'rating', 'notices', 'authority', 'aggregate', 'metadata'],\n\t)(value)\n}\n","import type { FieldPath, JSONValue } from '@orkestrel/contract'\nimport type { Eligibility, QualificationResult, QualifierInterface } from '@orkestrel/qualifier'\nimport type { LineDefinition, RatingResult } from '@orkestrel/rater'\nimport type {\n\tEvaluatorInterface,\n\tLogicalDefinition,\n\tLogicalResult,\n\tReasonInterface,\n\tSubject,\n} from '@orkestrel/reason'\nimport type {\n\tAggregateGroup,\n\tAggregateProjection,\n\tAggregateResult,\n\tDecision,\n\tDetermination,\n\tNotice,\n\tProgramDefinition,\n\tProgramResult,\n\tProgramValidationResult,\n\tStatus,\n\tTally,\n} from './types.js'\nimport { isFiniteNumber, isRecord, resolveField } from '@orkestrel/contract'\nimport { findRule, interpolateMessage, logicalPremises } from '@orkestrel/qualifier'\nimport { findDuplicates, formatField } from '@orkestrel/reason'\nimport {\n\tAGGREGATE_KEY,\n\tELIGIBILITY_DECISIONS,\n\tOUTCOME_KEY,\n\tSTATUS_PRECEDENCE,\n} from './constants.js'\nimport { ProgramError } from './errors.js'\nimport { isProgramDefinition } from './validators.js'\n\n/**\n * Return a fresh JSON value tree that does not alias the input.\n *\n * @remarks\n * The input must be an acyclic JSON tree of bounded depth — a pathologically\n * deep tree throws the engine's `RangeError` (stack exhaustion) rather than\n * hanging. Each copied record uses `Object.defineProperty` for own-property\n * definition, which defends against prototype-pollution keys (`__proto__`).\n *\n * @param value - The JSON value to copy\n * @returns A fresh JSON value\n *\n * @example\n * ```ts\n * import { copyJSONValue } from '@orkestrel/program'\n *\n * copyJSONValue({ a: [1, 2] }) // { a: [1, 2] }, a fresh copy\n * ```\n */\nexport function copyJSONValue(value: JSONValue): JSONValue {\n\tif (value === null || typeof value !== 'object') return value\n\tif (Array.isArray(value)) return value.map(copyJSONValue)\n\tconst copy: Record<string, JSONValue> = {}\n\tfor (const [key, entry] of Object.entries(value)) {\n\t\tObject.defineProperty(copy, key, {\n\t\t\tvalue: copyJSONValue(entry),\n\t\t\tenumerable: true,\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t})\n\t}\n\treturn copy\n}\n\n/**\n * Determine whether a caller subject already carries a reserved program key.\n *\n * @remarks\n * `aggregate` and `outcome` are program-private working-subject namespaces — the\n * batch aggregate projection and the authority outcome projection are written\n * under them. A caller subject that already owns either key would silently\n * collide with a projection, so it is rejected before qualification.\n *\n * @param subject - The caller subject to check\n * @returns `true` when the subject owns `aggregate` or `outcome`\n *\n * @example\n * ```ts\n * import { hasReservedKey } from '@orkestrel/program'\n *\n * hasReservedKey({ id: 'r1' }) // false\n * hasReservedKey({ id: 'r1', aggregate: {} }) // true\n * ```\n */\nexport function hasReservedKey(subject: Readonly<Record<string, unknown>>): boolean {\n\treturn Object.hasOwn(subject, AGGREGATE_KEY) || Object.hasOwn(subject, OUTCOME_KEY)\n}\n\n/**\n * Assert a value is a valid program {@link Subject}, narrowing it in place.\n *\n * @param subject - The candidate subject to validate\n * @throws {@link ProgramError} `'MISMATCH'` when the value is not a record, or\n * `'RESERVED'` when it already carries the `aggregate` or `outcome` key\n *\n * @example\n * ```ts\n * import { assertProgramSubject } from '@orkestrel/program'\n *\n * assertProgramSubject({ id: 'r1' }) // does not throw\n * ```\n */\nexport function assertProgramSubject(subject: unknown): asserts subject is Subject {\n\tif (!isRecord(subject)) {\n\t\tthrow new ProgramError('MISMATCH', 'Program subject must be a record')\n\t}\n\tif (hasReservedKey(subject)) {\n\t\tconst key = Object.hasOwn(subject, AGGREGATE_KEY) ? AGGREGATE_KEY : OUTCOME_KEY\n\t\tthrow new ProgramError('RESERVED', `Subject contains a reserved program key '${key}'`, key)\n\t}\n}\n\n/**\n * Select the rating lines a subject may be rated on from scoped eligibility.\n *\n * @remarks\n * A scope names a rating-line id. A line survives when its scope is absent\n * (eligible by default), `eligible`, or a `condition` (which is not an\n * eligibility value and never appears here). A scoped `ineligible` or `referral`\n * removes the line BEFORE the rater is invoked — the excluded line is never\n * evaluated merely to discard its amount.\n *\n * @param lines - The program's authored rating lines\n * @param scopes - The qualification's per-scope eligibility\n * @returns The surviving line definitions, in authored order\n *\n * @example\n * ```ts\n * import { selectProgramLines } from '@orkestrel/program'\n *\n * selectProgramLines(lines, { wind: 'ineligible' }) // every line except 'wind'\n * ```\n */\nexport function selectProgramLines(\n\tlines: readonly LineDefinition[],\n\tscopes: Readonly<Record<string, Eligibility>>,\n): readonly LineDefinition[] {\n\treturn lines.filter((line) => {\n\t\tconst eligibility = scopes[line.id]\n\t\treturn eligibility !== 'ineligible' && eligibility !== 'referral'\n\t})\n}\n\n/**\n * Derive the final program {@link Status} from a definition's rating policy and\n * qualification/rating evidence.\n *\n * @remarks\n * Explicit policy, not an opaque precedence reduce (AGENTS §10): global\n * ineligibility or referral is terminal; a scoped referral yields `referral`;\n * an applied `condition` or an applied scoped `restriction` (a line was\n * removed but others rated) is `conditional`. When the definition OMITS\n * `rating` the program is eligibility-only — status resolves to `conditional`\n * or `eligible` and is NEVER `unrated`. Otherwise a subject with no successful\n * rating is `unrated`.\n *\n * @param definition - The authored program definition\n * @param qualification - The subject's qualification result\n * @param rating - The subject's rating result, when rating occurred\n * @returns The derived status\n *\n * @example\n * ```ts\n * import { deriveStatus } from '@orkestrel/program'\n *\n * deriveStatus(definition, qualification, rating) // 'eligible'\n * ```\n */\nexport function deriveStatus(\n\tdefinition: ProgramDefinition,\n\tqualification: QualificationResult,\n\trating?: RatingResult,\n): Status {\n\tif (qualification.eligibility === 'ineligible') return 'ineligible'\n\tif (qualification.eligibility === 'referral') return 'referral'\n\tif (Object.values(qualification.scopes).includes('referral')) return 'referral'\n\tconst conditional = qualification.findings.some(\n\t\t(finding) =>\n\t\t\tfinding.applied &&\n\t\t\t(finding.effect === 'condition' ||\n\t\t\t\t(finding.scope !== undefined && finding.effect === 'restriction')),\n\t)\n\tif (definition.rating === undefined) return conditional ? 'conditional' : 'eligible'\n\tif (rating === undefined || rating.lines.length === 0 || !rating.success) return 'unrated'\n\treturn conditional ? 'conditional' : 'eligible'\n}\n\n/**\n * Map a global {@link Eligibility} to its deterministic authority {@link Decision}.\n *\n * @param eligibility - The global eligibility\n * @returns The matching decision\n *\n * @example\n * ```ts\n * import { decideEligibility } from '@orkestrel/program'\n *\n * decideEligibility('eligible') // 'approved'\n * decideEligibility('referral') // 'submitted'\n * ```\n */\nexport function decideEligibility(eligibility: Eligibility): Decision {\n\treturn ELIGIBILITY_DECISIONS[eligibility]\n}\n\n/**\n * Resolve authored {@link Notice}s into unconditionally-applied `notice`\n * {@link Determination}s.\n *\n * @remarks\n * Notices are program output only — they never affect eligibility, status, line\n * selection, or the decision. Each message interpolates against the original\n * subject.\n *\n * @param notices - The authored notices\n * @param subject - The original subject notices interpolate against\n * @returns A fresh list of notice determinations\n *\n * @example\n * ```ts\n * import { buildNotices } from '@orkestrel/program'\n *\n * buildNotices([{ id: 'min', message: 'Minimum applies' }], { id: 'r1' })\n * ```\n */\nexport function buildNotices(\n\tnotices: readonly Notice[],\n\tsubject: Readonly<Record<string, unknown>>,\n): readonly Determination[] {\n\treturn notices.map((notice) => ({\n\t\tid: notice.id,\n\t\teffect: 'notice',\n\t\tapplied: true,\n\t\t...(notice.scope === undefined ? {} : { scope: notice.scope }),\n\t\tmessage: interpolateMessage(notice.message, subject),\n\t\tpremises: [],\n\t}))\n}\n\n/**\n * Convert a logical result's applied rules into `limit` {@link Determination}s.\n *\n * @remarks\n * Fires for both the per-subject authority and the batch aggregate gates — both\n * are plain {@link LogicalDefinition}s with no program-authored ruling map, so a\n * fired rule's own `description` (from `@orkestrel/reason`) is the message\n * template, interpolated against the working record the definition ran against.\n * Rich premises reuse the qualifier's {@link logicalPremises}. A rule that never\n * fires produces no determination — program has no authored ruling map to keep\n * evidence for.\n *\n * @param definition - The authority or aggregate-gate logical definition\n * @param result - The evaluated logical result\n * @param working - The working record the definition ran 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 list of `limit` determinations\n *\n * @example\n * ```ts\n * import { buildLimits } from '@orkestrel/program'\n *\n * buildLimits(authority, resolved, outcome, evaluator)\n * ```\n */\nexport function buildLimits(\n\tdefinition: LogicalDefinition,\n\tresult: LogicalResult,\n\tworking: Readonly<Record<string, unknown>>,\n\tevaluator: EvaluatorInterface,\n\tlabels?: Readonly<Record<string, string>>,\n): readonly Determination[] {\n\tconst output: Determination[] = []\n\tfor (const entry of result.rules) {\n\t\tif (!entry.applied) continue\n\t\tconst rule = findRule(definition, entry.id)\n\t\tif (rule === undefined) continue\n\t\toutput.push({\n\t\t\tid: entry.id,\n\t\t\teffect: 'limit',\n\t\t\tapplied: true,\n\t\t\t...(rule.description === undefined\n\t\t\t\t? {}\n\t\t\t\t: { message: interpolateMessage(rule.description, working) }),\n\t\t\tpremises: logicalPremises(rule, working, evaluator, labels),\n\t\t})\n\t}\n\treturn output\n}\n\n/**\n * Build the private authority outcome projection from an assembled program result.\n *\n * @remarks\n * The authority reads this record under {@link OUTCOME_KEY}; it never receives\n * the mutable internal state of either sibling engine. `total` is carried from\n * the nested rating result when rating occurred.\n *\n * @param result - The preliminary program result computed before authority runs\n * @returns A record shaped for the authority's `outcome` projection\n *\n * @example\n * ```ts\n * import { buildOutcomeProjection } from '@orkestrel/program'\n *\n * buildOutcomeProjection(result) // { id, eligibility, status, rated, scopes }\n * ```\n */\nexport function buildOutcomeProjection(result: ProgramResult): Readonly<Record<string, unknown>> {\n\tconst total = result.rating?.total\n\treturn {\n\t\tid: result.id,\n\t\teligibility: result.eligibility,\n\t\tstatus: result.status,\n\t\trated: result.rating !== undefined,\n\t\t...(total === undefined ? {} : { total }),\n\t\tscopes: { ...result.qualification.scopes },\n\t}\n}\n\n/**\n * Assemble a {@link ProgramResult} from its qualification, rating, and\n * determination parts — before or after authority.\n *\n * @remarks\n * `eligibility` mirrors the qualification. `success` is execution integrity: the\n * qualification succeeded, rating (when it ran) succeeded, and authority (when it\n * ran) produced no errors — a valid ineligible or referral outcome still\n * succeeds. `trace` and `errors` accumulate the qualification's, every rated\n * line's worksheet trail, and the authority's. A `decision` is present ONLY when\n * an authority ran (`options.authority`), the execution SUCCEEDED (`success`),\n * no `limit` determination applied, and status is not `unrated`.\n *\n * @param definition - The authored program definition\n * @param qualification - The subject's qualification result\n * @param rating - The subject's rating result, when rating occurred\n * @param determinations - The program-scoped determinations (notices, then limits)\n * @param status - The already-derived status\n * @param options - Optional authority result driving the decision projection\n * @returns A fresh program result\n *\n * @example\n * ```ts\n * import { buildProgramResult } from '@orkestrel/program'\n *\n * buildProgramResult(definition, qualification, rating, [], 'eligible')\n * ```\n */\nexport function buildProgramResult(\n\tdefinition: ProgramDefinition,\n\tqualification: QualificationResult,\n\trating: RatingResult | undefined,\n\tdeterminations: readonly Determination[],\n\tstatus: Status,\n\toptions?: { readonly authority?: LogicalResult },\n): ProgramResult {\n\tconst authority = options?.authority\n\tconst ratingTrace =\n\t\trating === undefined ? [] : rating.lines.flatMap((line) => line.worksheet.trace)\n\tconst ratingErrors =\n\t\trating === undefined ? [] : rating.lines.flatMap((line) => line.worksheet.errors)\n\tconst authorityTrace = authority === undefined ? [] : [...authority.trace]\n\tconst authorityErrors = authority === undefined ? [] : [...authority.errors]\n\tconst trace = [...qualification.trace, ...ratingTrace, ...authorityTrace]\n\tconst errors = [...qualification.errors, ...ratingErrors, ...authorityErrors]\n\tconst success =\n\t\tqualification.success &&\n\t\t(rating === undefined || rating.success) &&\n\t\tauthorityErrors.length === 0\n\tconst limited = determinations.some((entry) => entry.effect === 'limit' && entry.applied)\n\tconst decision =\n\t\tauthority !== undefined && success && !limited && status !== 'unrated'\n\t\t\t? decideEligibility(qualification.eligibility)\n\t\t\t: undefined\n\treturn {\n\t\tid: definition.id,\n\t\tname: definition.name,\n\t\teligibility: qualification.eligibility,\n\t\tstatus,\n\t\t...(decision === undefined ? {} : { decision }),\n\t\tqualification,\n\t\t...(rating === undefined ? {} : { rating }),\n\t\tdeterminations,\n\t\tsuccess,\n\t\ttrace,\n\t\terrors,\n\t}\n}\n\n/**\n * Add optional aggregate context to a private subject copy for qualification.\n *\n * @remarks\n * The original subject is returned unchanged when no aggregate context exists.\n * When context exists the helper creates a private copy under {@link AGGREGATE_KEY}\n * and defensively copies every nested record — the rater still receives the\n * original subject, never this copy.\n *\n * @param subject - The original caller subject\n * @param aggregate - The subject's aggregate projection, when a batch supplies one\n * @returns The subject, or a private copy carrying the aggregate projection\n *\n * @example\n * ```ts\n * import { buildQualificationSubject } from '@orkestrel/program'\n *\n * buildQualificationSubject({ id: 'r1' }) // { id: 'r1' }\n * ```\n */\nexport function buildQualificationSubject(\n\tsubject: Subject,\n\taggregate?: AggregateProjection,\n): Subject {\n\tif (aggregate === undefined) return subject\n\treturn {\n\t\t...subject,\n\t\t[AGGREGATE_KEY]: {\n\t\t\tcount: aggregate.count,\n\t\t\tsums: { ...aggregate.sums },\n\t\t\t...(aggregate.group === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tgroup: {\n\t\t\t\t\t\t\tkey: aggregate.group.key,\n\t\t\t\t\t\t\tcount: aggregate.group.count,\n\t\t\t\t\t\t\tsums: { ...aggregate.group.sums },\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t},\n\t}\n}\n\n/**\n * Return authored scopes (qualification ruling scopes or notice scopes) that\n * name no rating line on the program.\n *\n * @remarks\n * A scope is an opaque string to the qualifier — program alone matches it to a\n * rating-line id. A scope naming no line is a hard authoring error surfaced as\n * {@link ProgramError} `'MISSING'` at construction, regardless of the validate\n * option.\n *\n * @param definition - The program definition to check\n * @returns A fresh, deduped list of missing scope references\n *\n * @example\n * ```ts\n * import { findMissingScopes } from '@orkestrel/program'\n *\n * findMissingScopes(definition) // []\n * ```\n */\nexport function findMissingScopes(definition: ProgramDefinition): readonly string[] {\n\tconst ids = new Set((definition.rating?.lines ?? []).map((line) => line.id))\n\tconst missing = new Set<string>()\n\tfor (const ruling of definition.qualification.rulings ?? []) {\n\t\tif (ruling.scope !== undefined && !ids.has(ruling.scope)) missing.add(ruling.scope)\n\t}\n\tfor (const notice of definition.notices ?? []) {\n\t\tif (notice.scope !== undefined && !ids.has(notice.scope)) missing.add(notice.scope)\n\t}\n\treturn [...missing]\n}\n\n/**\n * Assert a program definition's always-on construction invariants — missing\n * scope references and duplicate rating-line or notice ids.\n *\n * @remarks\n * These checks run at construction regardless of `options.validate` (unlike\n * {@link validateProgramDefinition}, the standalone report-shaped validator) —\n * an authoring mistake this severe cannot silently compile.\n *\n * @param definition - The program definition to assert\n * @throws {@link ProgramError} `'MISSING'` when a ruling or notice scope names\n * no rating line\n * @throws {@link ProgramError} `'DUPLICATE'` when two rating lines or two\n * notices share an id\n *\n * @example\n * ```ts\n * import { assertProgramDefinition } from '@orkestrel/program'\n *\n * assertProgramDefinition(definition) // does not throw\n * ```\n */\nexport function assertProgramDefinition(definition: ProgramDefinition): void {\n\tconst missing = findMissingScopes(definition)\n\tif (missing.length > 0) {\n\t\tthrow new ProgramError(\n\t\t\t'MISSING',\n\t\t\t`Unknown rating line reference: ${missing.join(', ')}`,\n\t\t\tdefinition.id,\n\t\t)\n\t}\n\tconst duplicateLines = findDuplicates(definition.rating?.lines ?? [])\n\tif (duplicateLines.length > 0) {\n\t\tthrow new ProgramError(\n\t\t\t'DUPLICATE',\n\t\t\t`Duplicate rating line id: ${duplicateLines.join(', ')}`,\n\t\t\tdefinition.id,\n\t\t)\n\t}\n\tconst duplicateNotices = findDuplicates(definition.notices ?? [])\n\tif (duplicateNotices.length > 0) {\n\t\tthrow new ProgramError(\n\t\t\t'DUPLICATE',\n\t\t\t`Duplicate notice id: ${duplicateNotices.join(', ')}`,\n\t\t\tdefinition.id,\n\t\t)\n\t}\n}\n\n/**\n * Validate a program definition's shape, references, and nested definitions.\n *\n * @remarks\n * The single semantic-validation implementation used by `Program.validate`. It\n * establishes exact shape through {@link isProgramDefinition}, validates the\n * rating structurally through the rater's {@link isRatingDefinition} guard (the\n * rater exposes no `validate`), delegates qualification validation to the\n * injected qualifier and authority / aggregate-gate validation to the shared\n * reason engine, and checks scope, notice, and aggregate-field references here.\n *\n * @param definition - The program definition to validate\n * @param qualifier - The qualifier that validates the nested qualification\n * @param engine - The reason engine that validates authority and aggregate gates\n * @returns A structured validation result\n *\n * @example\n * ```ts\n * import { validateProgramDefinition } from '@orkestrel/program'\n *\n * validateProgramDefinition(definition, qualifier, engine) // { valid: true, ... }\n * ```\n */\nexport function validateProgramDefinition(\n\tdefinition: ProgramDefinition,\n\tqualifier: QualifierInterface,\n\tengine: ReasonInterface,\n): ProgramValidationResult {\n\tif (!isProgramDefinition(definition)) {\n\t\treturn { valid: false, errors: ['Program definition has an invalid shape'], warnings: [] }\n\t}\n\n\tconst errors: string[] = []\n\tconst warnings: string[] = []\n\n\tif (definition.id.length === 0) errors.push('Program id must not be empty')\n\tif (definition.name.length === 0) errors.push('Program name must not be empty')\n\n\tconst qualification = qualifier.validate(definition.qualification)\n\terrors.push(...qualification.errors.map((error) => `qualification: ${error}`))\n\twarnings.push(...qualification.warnings.map((warning) => `qualification: ${warning}`))\n\n\tconst lines = new Set((definition.rating?.lines ?? []).map((line) => line.id))\n\tif (definition.rating !== undefined && lines.size !== definition.rating.lines.length) {\n\t\terrors.push('rating: duplicate line id')\n\t}\n\tfor (const ruling of definition.qualification.rulings ?? []) {\n\t\tif (ruling.scope !== undefined && !lines.has(ruling.scope)) {\n\t\t\terrors.push(`Qualification ruling \"${ruling.id}\" references missing line \"${ruling.scope}\"`)\n\t\t}\n\t}\n\n\tconst notices = new Set<string>()\n\tfor (const notice of definition.notices ?? []) {\n\t\tif (notices.has(notice.id)) errors.push(`Duplicate notice id \"${notice.id}\"`)\n\t\tnotices.add(notice.id)\n\t\tif (notice.scope !== undefined && !lines.has(notice.scope)) {\n\t\t\terrors.push(`Notice \"${notice.id}\" references missing line \"${notice.scope}\"`)\n\t\t}\n\t}\n\n\tconst authority = definition.authority\n\tif (authority !== undefined) {\n\t\tconst validation = engine.validate(authority)\n\t\terrors.push(...validation.errors.map((error) => `authority: ${error}`))\n\t\twarnings.push(...validation.warnings.map((warning) => `authority: ${warning}`))\n\t}\n\n\tconst aggregate = definition.aggregate\n\tif (aggregate !== undefined) {\n\t\tconst fields = new Set<string>()\n\t\tfor (const field of aggregate.fields) {\n\t\t\tconst key = formatField(field)\n\t\t\tif (key.length === 0) errors.push('Aggregate fields must be non-empty')\n\t\t\tif (fields.has(key)) errors.push(`Duplicate aggregate field \"${key}\"`)\n\t\t\tfields.add(key)\n\t\t}\n\t\tif (aggregate.by !== undefined && formatField(aggregate.by).length === 0) {\n\t\t\terrors.push('Aggregate partition field must be non-empty')\n\t\t}\n\t\tif (aggregate.gates !== undefined) {\n\t\t\tconst validation = engine.validate(aggregate.gates)\n\t\t\terrors.push(...validation.errors.map((error) => `aggregate: ${error}`))\n\t\t\twarnings.push(...validation.warnings.map((warning) => `aggregate: ${warning}`))\n\t\t\tif (aggregate.fields.length === 0) {\n\t\t\t\twarnings.push('Aggregate gates are defined without aggregate fields')\n\t\t\t}\n\t\t}\n\t}\n\n\tif (definition.rating !== undefined && definition.rating.lines.length === 0) {\n\t\twarnings.push('Program rating has no lines')\n\t}\n\n\treturn { valid: errors.length === 0, errors, warnings }\n}\n\n/**\n * Coerce a subject's partition-key field to its group-key string.\n *\n * @remarks\n * The key is the resolved field coerced with `String` — `undefined` collapses\n * to the empty string, so a subject missing the field and a subject whose\n * field is literally `''` land in the SAME partition, and a numeric `1`\n * collides with the string `'1'`.\n *\n * @param subject - The subject to key\n * @param by - The partition key field\n * @returns The subject's group key\n *\n * @example\n * ```ts\n * import { formatGroupKey } from '@orkestrel/program'\n *\n * formatGroupKey({ location: 'east' }, 'location') // 'east'\n * ```\n */\nexport function formatGroupKey(subject: Subject, by: FieldPath): string {\n\treturn String(resolveField(subject, by) ?? '')\n}\n\n/**\n * Fold one subject's finite aggregate field values into a sums record.\n *\n * @remarks\n * Returns a FRESH record — `sums` is never mutated. Only finite numbers\n * contribute; a non-numeric or absent value contributes zero (never a\n * coercion). A {@link FieldPath} may be nested — `formatField` renders the\n * dot-joined key the returned record is keyed by.\n *\n * @param sums - The sums record to fold into\n * @param subject - The subject to fold in\n * @param fields - The fields to sum\n * @returns A fresh sums record with `subject`'s contribution added\n *\n * @example\n * ```ts\n * import { sumFields } from '@orkestrel/program'\n *\n * sumFields({ amount: 0 }, { amount: 5 }, ['amount']) // { amount: 5 }\n * ```\n */\nexport function sumFields(\n\tsums: Readonly<Record<string, number>>,\n\tsubject: Subject,\n\tfields: readonly FieldPath[],\n): Readonly<Record<string, number>> {\n\tconst next: Record<string, number> = { ...sums }\n\tfor (const field of fields) {\n\t\tconst key = formatField(field)\n\t\tconst value = resolveField(subject, field)\n\t\tif (isFiniteNumber(value)) next[key] = (next[key] ?? 0) + value\n\t}\n\treturn next\n}\n\n/**\n * Sum aggregate fields across a batch of subjects.\n *\n * @remarks\n * A {@link FieldPath} may be nested — a nested path sums a nested subject field\n * exactly like a top-level one, and `formatField` renders the dot-joined key the\n * returned record is keyed by. Only finite numbers contribute; a non-numeric or\n * absent value contributes zero (never a coercion).\n *\n * @param subjects - The batch of subjects\n * @param fields - The fields to sum\n * @returns A fresh record of dot-joined field to summed finite value\n *\n * @example\n * ```ts\n * import { aggregateSums } from '@orkestrel/program'\n *\n * aggregateSums([{ amount: 5 }, { amount: 3 }], ['amount']) // { amount: 8 }\n * ```\n */\nexport function aggregateSums(\n\tsubjects: readonly Subject[],\n\tfields: readonly FieldPath[],\n): Readonly<Record<string, number>> {\n\tlet sums = emptySums(fields)\n\tfor (const subject of subjects) sums = sumFields(sums, subject, fields)\n\treturn sums\n}\n\n/**\n * Partition a batch of subjects by a field, summing aggregate fields per key.\n *\n * @remarks\n * The partition key is derived by {@link formatGroupKey}. Group order follows\n * first appearance in the subject array.\n *\n * @param subjects - The batch of subjects\n * @param fields - The fields to sum within each partition\n * @param by - The partition key field; no partition is built when absent\n * @returns A fresh list of aggregate groups, or an empty list when `by` is absent\n *\n * @example\n * ```ts\n * import { aggregateGroups } from '@orkestrel/program'\n *\n * aggregateGroups([{ location: 'east', amount: 5 }], ['amount'], 'location')\n * ```\n */\nexport function aggregateGroups(\n\tsubjects: readonly Subject[],\n\tfields: readonly FieldPath[],\n\tby?: FieldPath,\n): readonly AggregateGroup[] {\n\tif (by === undefined) return []\n\tconst records = new Map<string, Subject[]>()\n\tfor (const subject of subjects) {\n\t\tconst key = formatGroupKey(subject, by)\n\t\tconst group = records.get(key)\n\t\tif (group === undefined) records.set(key, [subject])\n\t\telse group.push(subject)\n\t}\n\treturn [...records.entries()].map(([key, entries]) => ({\n\t\tkey,\n\t\tcount: entries.length,\n\t\tsums: aggregateSums(entries, fields),\n\t}))\n}\n\n/**\n * Build one subject's overall and optional group aggregate projection.\n *\n * @remarks\n * The projection carries the whole-batch `count` and `sums` plus the subject's\n * OWN partition, located by the same {@link formatGroupKey} key\n * {@link aggregateGroups} partitions under.\n *\n * @param subject - The subject to project for\n * @param count - The whole-batch subject count\n * @param sums - The whole-batch summed aggregate fields\n * @param groups - The batch partitions\n * @param by - The partition key field; no group is attached when absent\n * @returns A fresh aggregate projection\n *\n * @example\n * ```ts\n * import { buildAggregateProjection } from '@orkestrel/program'\n *\n * buildAggregateProjection(subject, 2, { amount: 8 }, groups, 'location')\n * ```\n */\nexport function buildAggregateProjection(\n\tsubject: Subject,\n\tcount: number,\n\tsums: Readonly<Record<string, number>>,\n\tgroups: readonly AggregateGroup[],\n\tby?: FieldPath,\n): AggregateProjection {\n\tconst group =\n\t\tby === undefined ? undefined : groups.find((entry) => entry.key === formatGroupKey(subject, by))\n\treturn { count, sums: { ...sums }, ...(group === undefined ? {} : { group }) }\n}\n\n/**\n * Build the reserved-key record a batch aggregate-gate definition runs against.\n *\n * @remarks\n * Unlike a per-subject {@link buildAggregateProjection}, the batch record carries\n * every `group` (a `groups` array) under {@link AGGREGATE_KEY} so a gate rule can\n * read `aggregate.sums.<field>` (overall) or a partition inside `aggregate.groups`.\n *\n * @param count - The whole-batch subject count\n * @param sums - The whole-batch summed aggregate fields\n * @param groups - The batch partitions\n * @returns A fresh record carrying the batch aggregate under {@link AGGREGATE_KEY}\n *\n * @example\n * ```ts\n * import { buildAggregateRecord } from '@orkestrel/program'\n *\n * buildAggregateRecord(2, { amount: 8 }, [])\n * ```\n */\nexport function buildAggregateRecord(\n\tcount: number,\n\tsums: Readonly<Record<string, number>>,\n\tgroups: readonly AggregateGroup[],\n): Readonly<Record<string, unknown>> {\n\treturn { [AGGREGATE_KEY]: { count, sums, groups } }\n}\n\n/**\n * Build a zero-sum record for a set of aggregate fields.\n *\n * @param fields - The fields to zero\n * @returns A fresh record of dot-joined field to `0`\n *\n * @example\n * ```ts\n * import { emptySums } from '@orkestrel/program'\n *\n * emptySums(['amount']) // { amount: 0 }\n * ```\n */\nexport function emptySums(fields: readonly FieldPath[]): Readonly<Record<string, number>> {\n\tconst sums: Record<string, number> = {}\n\tfor (const field of fields) sums[formatField(field)] = 0\n\treturn sums\n}\n\n/**\n * Complete a partial status tally record with zero entries for every missing\n * {@link Status}.\n *\n * @param entries - The partial tally entries to complete\n * @returns A record with all five statuses present\n *\n * @example\n * ```ts\n * import { completeTallies } from '@orkestrel/program'\n *\n * completeTallies({ eligible: { count: 1, sums: {} } })\n * ```\n */\nexport function completeTallies(\n\tentries: Partial<Record<Status, Tally>>,\n): Readonly<Record<Status, Tally>> {\n\treturn {\n\t\tineligible: entries.ineligible ?? { count: 0, sums: {} },\n\t\treferral: entries.referral ?? { count: 0, sums: {} },\n\t\tconditional: entries.conditional ?? { count: 0, sums: {} },\n\t\tunrated: entries.unrated ?? { count: 0, sums: {} },\n\t\teligible: entries.eligible ?? { count: 0, sums: {} },\n\t}\n}\n\n/**\n * Build complete zero status tallies in {@link STATUS_PRECEDENCE} order.\n *\n * @param fields - The fields each tally's sums are zeroed for\n * @returns A fresh, complete tally record\n *\n * @example\n * ```ts\n * import { emptyTallies } from '@orkestrel/program'\n *\n * emptyTallies(['amount'])\n * ```\n */\nexport function emptyTallies(fields: readonly FieldPath[]): Readonly<Record<Status, Tally>> {\n\tconst entries: Partial<Record<Status, Tally>> = {}\n\tfor (const status of STATUS_PRECEDENCE) entries[status] = { count: 0, sums: emptySums(fields) }\n\treturn completeTallies(entries)\n}\n\n/**\n * Add one subject's aggregate contribution to a status tally record.\n *\n * @param tallies - The tallies to update\n * @param result - The subject's program result (its `status` selects the tally)\n * @param subject - The subject to fold in\n * @param fields - The fields to sum\n * @returns A fresh, complete tally record with the subject folded in\n *\n * @example\n * ```ts\n * import { tallyProgram } from '@orkestrel/program'\n *\n * tallyProgram(tallies, result, { id: 'r1', amount: 5 }, ['amount'])\n * ```\n */\nexport function tallyProgram(\n\ttallies: Readonly<Record<Status, Tally>>,\n\tresult: ProgramResult,\n\tsubject: Subject,\n\tfields: readonly FieldPath[],\n): Readonly<Record<Status, Tally>> {\n\tconst status = result.status\n\tconst current = tallies[status]\n\tconst sums = sumFields(current.sums, subject, fields)\n\treturn completeTallies({ ...tallies, [status]: { count: current.count + 1, sums } })\n}\n\n/**\n * Assemble one batch {@link AggregateResult} from its per-subject and aggregate\n * parts.\n *\n * @remarks\n * `count` is the subject count, `trace` / `errors` accumulate every subject's\n * plus the batch aggregate-gate evaluation's (`options.gates`), and `success`\n * requires every subject execution to succeed AND the gate evaluation to have\n * produced no errors. A fired aggregate gate contributes a `limit`\n * determination, never a technical failure (a non-logical gate result is a\n * caller-facing `MISMATCH` thrown by `Program` before this assembles).\n *\n * @param definition - The authored program definition\n * @param subjects - The per-subject program results, in input order\n * @param determinations - The batch aggregate-gate `limit` determinations\n * @param groups - The batch partitions\n * @param tallies - The completed status tallies\n * @param sums - The whole-batch summed aggregate fields\n * @param options - Optional resolved aggregate-gate result\n * @returns A fresh aggregate result\n *\n * @example\n * ```ts\n * import { buildAggregateResult } from '@orkestrel/program'\n *\n * buildAggregateResult(definition, subjects, [], [], tallies, { amount: 8 })\n * ```\n */\nexport function buildAggregateResult(\n\tdefinition: ProgramDefinition,\n\tsubjects: readonly ProgramResult[],\n\tdeterminations: readonly Determination[],\n\tgroups: readonly AggregateGroup[],\n\ttallies: Readonly<Record<Status, Tally>>,\n\tsums: Readonly<Record<string, number>>,\n\toptions?: { readonly gates?: LogicalResult },\n): AggregateResult {\n\tconst gates = options?.gates\n\tconst gateTrace = gates === undefined ? [] : [...gates.trace]\n\tconst gateErrors = gates === undefined ? [] : [...gates.errors]\n\treturn {\n\t\tid: definition.id,\n\t\tname: definition.name,\n\t\tsubjects,\n\t\tdeterminations,\n\t\tgroups,\n\t\ttallies,\n\t\tcount: subjects.length,\n\t\tsums,\n\t\tsuccess: subjects.every((entry) => entry.success) && gateErrors.length === 0,\n\t\ttrace: [...subjects.flatMap((entry) => entry.trace), ...gateTrace],\n\t\terrors: [...subjects.flatMap((entry) => entry.errors), ...gateErrors],\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { QualificationResult, QualifierInterface } from '@orkestrel/qualifier'\nimport type { RaterInterface, RatingResult } from '@orkestrel/rater'\nimport type { EvaluatorInterface, LogicalResult, ReasonInterface, Subject } from '@orkestrel/reason'\nimport type {\n\tAggregateGroup,\n\tAggregateProjection,\n\tAggregateResult,\n\tDetermination,\n\tProgramDefinition,\n\tProgramEventMap,\n\tProgramInterface,\n\tProgramOptions,\n\tProgramResult,\n\tProgramValidationResult,\n} from '../types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArray } from '@orkestrel/contract'\nimport { createQualifier } from '@orkestrel/qualifier'\nimport { createRater } from '@orkestrel/rater'\nimport {\n\tcreateEvaluator,\n\tcreateLogicalReasoner,\n\tcreateQuantitativeReasoner,\n\tcreateReason,\n} from '@orkestrel/reason'\nimport { DEFAULT_PROGRAM_VALIDATE, OUTCOME_KEY } from '../constants.js'\nimport { ProgramError } from '../errors.js'\nimport {\n\taggregateGroups,\n\taggregateSums,\n\tassertProgramDefinition,\n\tassertProgramSubject,\n\tbuildAggregateProjection,\n\tbuildAggregateRecord,\n\tbuildAggregateResult,\n\tbuildLimits,\n\tbuildNotices,\n\tbuildOutcomeProjection,\n\tbuildProgramResult,\n\tbuildQualificationSubject,\n\tderiveStatus,\n\temptyTallies,\n\tselectProgramLines,\n\ttallyProgram,\n\tvalidateProgramDefinition,\n} from '../helpers.js'\n\n/**\n * One compiled program — composes one qualifier and one rater over a shared\n * reason engine and executes single subjects or aggregate-aware batches.\n *\n * @remarks\n * Qualification decides whether rating happens: a globally ineligible, referred,\n * or failed subject never reaches the rater, and a scoped ineligibility removes\n * only its line before the first rating call. The rater always receives the\n * ORIGINAL subject; the qualifier's aggregate projection stays private. When no\n * qualifier, rater, or engine is injected the program creates ONE shared\n * quantitative-plus-logical engine, injects it into the qualifier and rater it\n * creates, and destroys only what it owns. A definition failure during\n * construction (an invalid definition under `options.validate`) tears down\n * whatever the constructor had already allocated before throwing. `destroy()`\n * is idempotent and REENTRANCY-SAFE — the destroyed flag is set BEFORE any\n * teardown or the `destroy` event fires, so a listener that re-enters\n * `destroy()` is a no-op — and tears the emitter down last.\n */\nexport class Program implements ProgramInterface {\n\treadonly #emitter: Emitter<ProgramEventMap>\n\treadonly #qualifier: QualifierInterface\n\treadonly #rater: RaterInterface\n\treadonly #engine: ReasonInterface\n\treadonly #evaluator: EvaluatorInterface\n\treadonly #qualifierOwned: boolean\n\treadonly #raterOwned: boolean\n\treadonly #engineOwned: boolean\n\treadonly #validate: boolean\n\treadonly #labels: Readonly<Record<string, string>> | undefined\n\t#destroyed = false\n\n\treadonly id: string\n\treadonly name: string\n\treadonly definition: ProgramDefinition\n\n\tconstructor(definition: ProgramDefinition, options?: ProgramOptions) {\n\t\tassertProgramDefinition(definition)\n\t\tthis.id = definition.id\n\t\tthis.name = definition.name\n\t\tthis.definition = definition\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.#evaluator = createEvaluator()\n\t\tthis.#engineOwned = options?.engine === undefined\n\t\tthis.#qualifierOwned = options?.qualifier === undefined\n\t\tthis.#raterOwned = options?.rater === 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.#qualifier = options?.qualifier ?? createQualifier({ engine: this.#engine })\n\t\tthis.#rater = options?.rater ?? createRater({ engine: this.#engine })\n\t\tthis.#validate = options?.validate ?? DEFAULT_PROGRAM_VALIDATE\n\t\tthis.#labels = options?.labels\n\n\t\tif (this.#validate) {\n\t\t\tconst validation = this.validate()\n\t\t\tif (!validation.valid) {\n\t\t\t\tthis.destroy()\n\t\t\t\tthrow new ProgramError('DEFINITION', validation.errors.join('; '), definition.id)\n\t\t\t}\n\t\t}\n\t}\n\n\tget emitter(): EmitterInterface<ProgramEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\t// Array overload first (AGENTS §9.2) so a subject list resolves to the batch form.\n\texecute(subjects: readonly Subject[]): AggregateResult\n\texecute(subject: Subject): ProgramResult\n\texecute(input: Subject | readonly Subject[]): ProgramResult | AggregateResult {\n\t\tthis.#alive()\n\t\tif (isArray<Subject>(input)) return this.#aggregate(input)\n\t\treturn this.#subject(input)\n\t}\n\n\tvalidate(): ProgramValidationResult {\n\t\tthis.#alive()\n\t\treturn validateProgramDefinition(this.definition, this.#qualifier, this.#engine)\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tif (this.#qualifierOwned) this.#qualifier.destroy()\n\t\tif (this.#raterOwned) this.#rater.destroy()\n\t\tif (this.#engineOwned) this.#engine.destroy()\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#subject(subject: Subject, aggregate?: AggregateProjection): ProgramResult {\n\t\tassertProgramSubject(subject)\n\t\tconst qualified = buildQualificationSubject(subject, aggregate)\n\t\tconst qualification = this.#qualifier.qualify(qualified, this.definition.qualification)\n\t\tthis.#emitter.emit('qualify', qualification)\n\n\t\tif (!qualification.success || qualification.eligibility !== 'eligible') {\n\t\t\treturn this.#finish(subject, qualification, undefined)\n\t\t}\n\n\t\tconst lines = selectProgramLines(this.definition.rating?.lines ?? [], qualification.scopes)\n\t\tconst rating = lines.length === 0 ? undefined : this.#rater.rate(lines, subject)\n\t\tif (rating !== undefined) this.#emitter.emit('rate', rating)\n\n\t\treturn this.#finish(subject, qualification, rating)\n\t}\n\n\t#finish(\n\t\tsubject: Subject,\n\t\tqualification: QualificationResult,\n\t\trating?: RatingResult,\n\t): ProgramResult {\n\t\tconst notices = buildNotices(this.definition.notices ?? [], subject)\n\t\tfor (const notice of notices) this.#emitter.emit('determine', notice)\n\n\t\tconst status = deriveStatus(this.definition, qualification, rating)\n\t\tlet result = buildProgramResult(this.definition, qualification, rating, notices, status)\n\n\t\tconst authority = this.definition.authority\n\t\tif (authority === undefined) {\n\t\t\tthis.#emitter.emit('execute', result)\n\t\t\treturn result\n\t\t}\n\n\t\tconst outcome = { [OUTCOME_KEY]: buildOutcomeProjection(result) }\n\t\tconst resolved = this.#engine.reason(outcome, authority)\n\t\tif (resolved.reasoning !== 'logical') {\n\t\t\tthrow new ProgramError('MISMATCH', 'Authority returned non-logical reasoning', authority.id)\n\t\t}\n\n\t\tconst limits = buildLimits(authority, resolved, outcome, this.#evaluator, this.#labels)\n\t\tfor (const limit of limits) this.#emitter.emit('determine', limit)\n\n\t\tresult = buildProgramResult(\n\t\t\tthis.definition,\n\t\t\tqualification,\n\t\t\trating,\n\t\t\t[...notices, ...limits],\n\t\t\tstatus,\n\t\t\t{ authority: resolved },\n\t\t)\n\n\t\tif (result.decision !== undefined) this.#emitter.emit('decide', result.decision, result)\n\t\tthis.#emitter.emit('execute', result)\n\t\treturn result\n\t}\n\n\t#aggregate(subjects: readonly Subject[]): AggregateResult {\n\t\tfor (const subject of subjects) assertProgramSubject(subject)\n\n\t\tconst definition = this.definition.aggregate\n\t\tconst fields = [...(definition?.fields ?? [])]\n\t\tconst sums = aggregateSums(subjects, fields)\n\t\tconst groups = aggregateGroups(subjects, fields, definition?.by)\n\t\tlet tallies = emptyTallies(fields)\n\t\tconst results = subjects.map((subject) => {\n\t\t\tconst projection =\n\t\t\t\tdefinition === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: buildAggregateProjection(subject, subjects.length, sums, groups, definition.by)\n\t\t\tconst result = this.#subject(subject, projection)\n\t\t\ttallies = tallyProgram(tallies, result, subject, fields)\n\t\t\treturn result\n\t\t})\n\n\t\tconst gates = this.#aggregateLimits(subjects.length, sums, groups)\n\t\tconst result = buildAggregateResult(\n\t\t\tthis.definition,\n\t\t\tresults,\n\t\t\tgates.determinations,\n\t\t\tgroups,\n\t\t\ttallies,\n\t\t\tsums,\n\t\t\tgates.resolved === undefined ? undefined : { gates: gates.resolved },\n\t\t)\n\t\tthis.#emitter.emit('aggregate', result)\n\t\treturn result\n\t}\n\n\t#aggregateLimits(\n\t\tcount: number,\n\t\tsums: Readonly<Record<string, number>>,\n\t\tgroups: readonly AggregateGroup[],\n\t): { readonly determinations: readonly Determination[]; readonly resolved?: LogicalResult } {\n\t\tconst gates = this.definition.aggregate?.gates\n\t\tif (gates === undefined) return { determinations: [] }\n\n\t\tconst record = buildAggregateRecord(count, sums, groups)\n\t\tconst resolved = this.#engine.reason(record, gates)\n\t\tif (resolved.reasoning !== 'logical') {\n\t\t\tthrow new ProgramError('MISMATCH', 'Aggregate gates returned non-logical reasoning', gates.id)\n\t\t}\n\n\t\tconst determinations = buildLimits(gates, resolved, record, this.#evaluator, this.#labels)\n\t\tfor (const determination of determinations) this.#emitter.emit('determine', determination)\n\t\treturn { determinations, resolved }\n\t}\n\n\t#alive(): void {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new ProgramError('DESTROYED', 'Program has been destroyed', this.id)\n\t\t}\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { QualifierInterface } from '@orkestrel/qualifier'\nimport type { RaterInterface } from '@orkestrel/rater'\nimport type { ReasonInterface } from '@orkestrel/reason'\nimport type {\n\tProgramDefinition,\n\tProgramInterface,\n\tProgramManagerEventMap,\n\tProgramManagerInterface,\n\tProgramManagerOptions,\n} from '../types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { createQualifier } from '@orkestrel/qualifier'\nimport { createRater } from '@orkestrel/rater'\nimport { createLogicalReasoner, createQuantitativeReasoner, createReason } from '@orkestrel/reason'\nimport { DEFAULT_PROGRAM_VALIDATE } from '../constants.js'\nimport { ProgramError } from '../errors.js'\nimport { createProgram } from '../factories.js'\n\n/**\n * An ordered manager over compiled {@link ProgramInterface}s (AGENTS §9), sharing\n * one qualifier, rater, and reason engine across every program it compiles.\n *\n * @remarks\n * OWNS its ordered `#programs` collection and its own {@link Emitter} over\n * {@link ProgramManagerEventMap}. Creates or borrows one shared engine, qualifier,\n * and rater and injects the same instances into every compiled program. `remove`\n * destroys the programs it removes; `destroy()` removes all programs, then\n * destroys only the owned shared dependencies, and tears the emitter down LAST.\n * A seed-program failure during construction tears the manager down (destroying\n * whatever had already been compiled) before rethrowing the original error.\n * `destroy()` is REENTRANCY-SAFE — the destroyed flag is set BEFORE any teardown\n * or the `remove` / `destroy` events fire, so a `remove` listener that re-enters\n * `destroy()` is a no-op. Every call after `destroy()` throws {@link ProgramError}\n * `'DESTROYED'`.\n */\nexport class ProgramManager implements ProgramManagerInterface {\n\treadonly #emitter: Emitter<ProgramManagerEventMap>\n\treadonly #programs: ProgramInterface[] = []\n\treadonly #qualifier: QualifierInterface\n\treadonly #rater: RaterInterface\n\treadonly #engine: ReasonInterface\n\treadonly #qualifierOwned: boolean\n\treadonly #raterOwned: boolean\n\treadonly #engineOwned: boolean\n\treadonly #validate: boolean\n\treadonly #labels: Readonly<Record<string, string>> | undefined\n\t#destroyed = false\n\n\tconstructor(options?: ProgramManagerOptions) {\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.#labels = options?.labels\n\t\tthis.#engineOwned = options?.engine === undefined\n\t\tthis.#qualifierOwned = options?.qualifier === undefined\n\t\tthis.#raterOwned = options?.rater === 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.#qualifier = options?.qualifier ?? createQualifier({ engine: this.#engine })\n\t\tthis.#rater = options?.rater ?? createRater({ engine: this.#engine })\n\t\tthis.#validate = options?.validate ?? DEFAULT_PROGRAM_VALIDATE\n\n\t\ttry {\n\t\t\tfor (const definition of options?.programs ?? []) this.add(definition)\n\t\t} catch (error) {\n\t\t\tthis.destroy()\n\t\t\tthrow error\n\t\t}\n\t}\n\n\tget emitter(): EmitterInterface<ProgramManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget size(): number {\n\t\tthis.#alive()\n\t\treturn this.#programs.length\n\t}\n\n\thas(id: string): boolean {\n\t\tthis.#alive()\n\t\treturn this.#programs.some((program) => program.id === id)\n\t}\n\n\tprogram(id: string): ProgramInterface | undefined {\n\t\tthis.#alive()\n\t\treturn this.#programs.find((program) => program.id === id)\n\t}\n\n\tprograms(): readonly ProgramInterface[] {\n\t\tthis.#alive()\n\t\treturn [...this.#programs]\n\t}\n\n\tadd(definition: ProgramDefinition): ProgramInterface {\n\t\tthis.#alive()\n\t\tif (this.has(definition.id)) {\n\t\t\tthrow new ProgramError(\n\t\t\t\t'DUPLICATE',\n\t\t\t\t`Program \"${definition.id}\" already exists`,\n\t\t\t\tdefinition.id,\n\t\t\t)\n\t\t}\n\t\tconst program = createProgram(definition, {\n\t\t\tqualifier: this.#qualifier,\n\t\t\trater: this.#rater,\n\t\t\tengine: this.#engine,\n\t\t\tvalidate: this.#validate,\n\t\t\t...(this.#labels === undefined ? {} : { labels: this.#labels }),\n\t\t})\n\t\tthis.#programs.push(program)\n\t\tthis.#emitter.emit('add', program.id)\n\t\treturn program\n\t}\n\n\t// Array overload first (AGENTS §9.2) so an id list resolves to the batch form.\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(input?: string | readonly string[]): boolean | void {\n\t\tthis.#alive()\n\t\tif (input === undefined) {\n\t\t\tthis.#drain()\n\t\t\treturn\n\t\t}\n\t\tif (Array.isArray(input)) {\n\t\t\tlet removed = true\n\t\t\tfor (const id of input) removed = this.#removeOne(id) && removed\n\t\t\treturn removed\n\t\t}\n\t\tif (typeof input === 'string') return this.#removeOne(input)\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tthis.#drain()\n\t\tif (this.#qualifierOwned) this.#qualifier.destroy()\n\t\tif (this.#raterOwned) this.#rater.destroy()\n\t\tif (this.#engineOwned) this.#engine.destroy()\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#drain(): void {\n\t\tfor (const program of this.#programs.splice(0)) {\n\t\t\tprogram.destroy()\n\t\t\tthis.#emitter.emit('remove', program.id)\n\t\t}\n\t}\n\n\t#removeOne(id: string): boolean {\n\t\tconst index = this.#programs.findIndex((program) => program.id === id)\n\t\tif (index < 0) return false\n\t\tconst removed = this.#programs.splice(index, 1)[0]\n\t\tif (removed === undefined) return false\n\t\tremoved.destroy()\n\t\tthis.#emitter.emit('remove', removed.id)\n\t\treturn true\n\t}\n\n\t#alive(): void {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new ProgramError('DESTROYED', 'Program manager has been destroyed')\n\t\t}\n\t}\n}\n","import type { FieldPath } from '@orkestrel/contract'\nimport type { QualificationDefinition } from '@orkestrel/qualifier'\nimport type { RatingDefinition } from '@orkestrel/rater'\nimport type {\n\tAggregateDefinition,\n\tAggregateInput,\n\tNotice,\n\tNoticeInput,\n\tProgramDefinition,\n\tProgramInput,\n\tProgramInterface,\n\tProgramManagerInterface,\n\tProgramManagerOptions,\n\tProgramOptions,\n} from './types.js'\nimport { Program } from './programs/Program.js'\nimport { ProgramManager } from './programs/ProgramManager.js'\nimport { copyJSONValue } from './helpers.js'\n\n/**\n * Create one compiled program over a qualifier and rater.\n *\n * @remarks\n * Validates the definition at construction when `options.validate` is left at\n * its {@link DEFAULT_PROGRAM_VALIDATE} default. A standalone program creates and\n * OWNS one shared quantitative-plus-logical reason engine and injects it into the\n * qualifier and rater it creates; injected dependencies remain caller-owned.\n *\n * @param definition - The authored program definition\n * @param options - Optional injected qualifier, rater, engine, validation, labels, and emitter hooks\n * @returns A {@link ProgramInterface}\n *\n * @example\n * ```ts\n * import { createProgram, programDefinition } from '@orkestrel/program'\n *\n * const program = createProgram(programDefinition('standard', 'Standard', qualification, rating))\n * program.execute({ id: 'risk-1' })\n * program.destroy()\n * ```\n */\nexport function createProgram(\n\tdefinition: ProgramDefinition,\n\toptions?: ProgramOptions,\n): ProgramInterface {\n\treturn new Program(definition, options)\n}\n\n/**\n * Create one ordered manager over compiled programs.\n *\n * @remarks\n * Creates or borrows one shared reason engine, qualifier, and rater and injects\n * them into every compiled program, so a batch of definitions shares one engine.\n * Seed definitions are compiled in order.\n *\n * @param options - Optional injected qualifier, rater, engine, seed programs, validation, labels, and emitter hooks\n * @returns A {@link ProgramManagerInterface}\n *\n * @example\n * ```ts\n * import { createProgramManager } from '@orkestrel/program'\n *\n * const manager = createProgramManager({ programs: [definition] })\n * manager.program('standard')?.execute(subject)\n * manager.destroy()\n * ```\n */\nexport function createProgramManager(options?: ProgramManagerOptions): ProgramManagerInterface {\n\treturn new ProgramManager(options)\n}\n\n/**\n * Build a {@link ProgramDefinition}.\n *\n * @remarks\n * Copies every collection and omits absent optional keys, so the returned\n * definition is a fresh, JSON-serializable value that never aliases its inputs.\n *\n * @param id - The program id\n * @param name - The display name\n * @param qualification - The nested qualification definition\n * @param rating - The nested rating definition; omit for an eligibility-only program\n * @param input - Optional description, notices, authority, aggregate, and metadata\n * @returns A fresh program definition\n *\n * @example\n * ```ts\n * import { programDefinition } from '@orkestrel/program'\n *\n * programDefinition('standard', 'Standard', qualification, rating, { notices: [notice] })\n * ```\n */\nexport function programDefinition(\n\tid: string,\n\tname: string,\n\tqualification: QualificationDefinition,\n\trating?: RatingDefinition,\n\tinput?: ProgramInput,\n): ProgramDefinition {\n\treturn {\n\t\tid,\n\t\tname,\n\t\tqualification,\n\t\t...(rating === undefined ? {} : { rating }),\n\t\t...(input?.description === undefined ? {} : { description: input.description }),\n\t\t...(input?.notices === undefined ? {} : { notices: [...input.notices] }),\n\t\t...(input?.authority === undefined ? {} : { authority: input.authority }),\n\t\t...(input?.aggregate === undefined ? {} : { aggregate: input.aggregate }),\n\t\t...(input?.metadata === undefined ? {} : { metadata: copyJSONValue(input.metadata) }),\n\t}\n}\n\n/**\n * Build a {@link Notice}.\n *\n * @param id - The notice id\n * @param message - The message template, carrying optional `{{token}}`s\n * @param input - Optional presentation scope\n * @returns A fresh notice\n *\n * @example\n * ```ts\n * import { noticeDefinition } from '@orkestrel/program'\n *\n * noticeDefinition('minimum', 'Minimum earned premium applies')\n * ```\n */\nexport function noticeDefinition(id: string, message: string, input?: NoticeInput): Notice {\n\treturn {\n\t\tid,\n\t\tmessage,\n\t\t...(input?.scope === undefined ? {} : { scope: input.scope }),\n\t}\n}\n\n/**\n * Build an {@link AggregateDefinition}.\n *\n * @param fields - The aggregate fields to sum across a batch\n * @param input - Optional partition field and aggregate gates\n * @returns A fresh aggregate definition\n *\n * @example\n * ```ts\n * import { aggregateDefinition } from '@orkestrel/program'\n *\n * aggregateDefinition(['amount'], { by: 'location' })\n * ```\n */\nexport function aggregateDefinition(\n\tfields: readonly FieldPath[],\n\tinput?: AggregateInput,\n): AggregateDefinition {\n\treturn {\n\t\tfields: [...fields],\n\t\t...(input?.by ===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qB,SAA0D;CAC9F,OAAO,IAAI,eAAe,OAAO;AAClC;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,kBACf,IACA,MACA,eACA,QACA,OACoB;CACpB,OAAO;EACN;EACA;EACA;EACA,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO;EACzC,GAAI,OAAO,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,MAAM,YAAY;EAC7E,GAAI,OAAO,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,CAAC,GAAG,MAAM,OAAO,EAAE;EACtE,GAAI,OAAO,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,MAAM,UAAU;EACvE,GAAI,OAAO,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,MAAM,UAAU;EACvE,GAAI,OAAO,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,cAAc,MAAM,QAAQ,EAAE;CACpF;AACD;;;;;;;;;;;;;;;;AAiBA,SAAgB,iBAAiB,IAAY,SAAiB,OAA6B;CAC1F,OAAO;EACN;EACA;EACA,GAAI,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;CAC5D;AACD;;;;;;;;;;;;;;;AAgBA,SAAgB,oBACf,QACA,OACsB;CACtB,OAAO;EACN,QAAQ,CAAC,GAAG,MAAM;EAClB,GAAI,OAAO,OAAO,KAAA,IAAY,CAAC,IAAI,EAAE,IAAI,MAAM,GAAG;EAClD,GAAI,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;CAC5D;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#emitter","#qualifier","#rater","#engine","#evaluator","#qualifierOwned","#raterOwned","#engineOwned","#validate","#labels","#alive","#aggregate","#subject","#destroyed","#finish","#aggregateLimits","#emitter","#programs","#qualifier","#rater","#engine","#qualifierOwned","#raterOwned","#engineOwned","#validate","#labels","#alive","#drain","#removeOne","#destroyed"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/programs/Program.ts","../../../src/core/programs/ProgramManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { Decision, Status } from './types.js'\nimport type { Eligibility } from '@orkestrel/qualifier'\n\n/** Default definition validation policy for `createProgram` / `ProgramManager.add`. */\nexport const DEFAULT_PROGRAM_VALIDATE = true\n\n/** Status tally precedence order — least to most resolved. */\nexport const STATUS_PRECEDENCE: readonly Status[] = Object.freeze([\n\t'ineligible',\n\t'referral',\n\t'conditional',\n\t'unrated',\n\t'eligible',\n])\n\n/** The deterministic authority decision for each global eligibility. */\nexport const ELIGIBILITY_DECISIONS: Readonly<Record<Eligibility, Decision>> = Object.freeze({\n\teligible: 'approved',\n\tineligible: 'denied',\n\treferral: 'submitted',\n})\n\n/** The reserved working-subject key a batch's aggregate projection is written under. */\nexport const AGGREGATE_KEY = 'aggregate'\n\n/** The reserved working-subject key the authority's outcome projection is written under. */\nexport const OUTCOME_KEY = 'outcome'\n","import type { ProgramErrorCode } from './types.js'\n\n/**\n * A coded programmer error thrown by the program layer.\n *\n * @remarks\n * `DUPLICATE` — a program id collision on `ProgramManager.add`, or a duplicate\n * authored rating-line or notice id. `MISSING` — an\n * authored notice or qualification ruling scope names no rating line.\n * `DEFINITION` — a program, qualification, rating, authority, or aggregate\n * policy failed validation. `MISMATCH` — an injected entity or a returned\n * reason result has the wrong contract. `RESERVED` — a subject already\n * carries `aggregate` or `outcome`. `DESTROYED` — use of a destroyed entity.\n */\nexport class ProgramError extends Error {\n\treadonly code: ProgramErrorCode\n\treadonly context?: unknown\n\n\tconstructor(code: ProgramErrorCode, message: string, context?: unknown) {\n\t\tsuper(message)\n\t\tthis.name = 'ProgramError'\n\t\tthis.code = code\n\t\tthis.context = context\n\t}\n}\n\n/** Narrow a caught value to a {@link ProgramError}. */\nexport function isProgramError(value: unknown): value is ProgramError {\n\treturn value instanceof ProgramError\n}\n","import type { Guard } from '@orkestrel/contract'\nimport type {\n\tAggregateDefinition,\n\tDecision,\n\tNotice,\n\tProgramDefinition,\n\tProgramEffect,\n\tStatus,\n} from './types.js'\nimport { arrayOf, isJSONValue, isString, literalOf, recordOf } from '@orkestrel/contract'\nimport { isQualificationDefinition } from '@orkestrel/qualifier'\nimport { isRatingDefinition } from '@orkestrel/rater'\nimport { isFieldPath, isLogicalDefinition } from '@orkestrel/reason'\n\n/**\n * Determine whether a value is a {@link Decision} literal.\n *\n * @param value - The candidate value\n * @returns `true` when `value` is a {@link Decision}\n *\n * @example\n * ```ts\n * import { isDecision } from '@orkestrel/program'\n *\n * isDecision('approved') // true\n * ```\n */\nexport const isDecision: Guard<Decision> = literalOf('approved', 'denied', 'submitted')\n\n/**\n * Determine whether a value is a {@link Status} literal.\n *\n * @param value - The candidate value\n * @returns `true` when `value` is a {@link Status}\n *\n * @example\n * ```ts\n * import { isStatus } from '@orkestrel/program'\n *\n * isStatus('eligible') // true\n * ```\n */\nexport const isStatus: Guard<Status> = literalOf(\n\t'ineligible',\n\t'referral',\n\t'conditional',\n\t'unrated',\n\t'eligible',\n)\n\n/**\n * Determine whether a value is a {@link ProgramEffect} literal.\n *\n * @param value - The candidate value\n * @returns `true` when `value` is a {@link ProgramEffect}\n *\n * @example\n * ```ts\n * import { isProgramEffect } from '@orkestrel/program'\n *\n * isProgramEffect('notice') // true\n * ```\n */\nexport const isProgramEffect: Guard<ProgramEffect> = literalOf('notice', 'limit')\n\n/**\n * Determine whether a value is an exact {@link Notice} record.\n *\n * @param value - The candidate value\n * @returns `true` when `value` is a {@link Notice}\n *\n * @example\n * ```ts\n * import { isNotice } from '@orkestrel/program'\n *\n * isNotice({ id: 'minimum', message: 'Minimum applies' }) // true\n * ```\n */\nexport function isNotice(value: unknown): value is Notice {\n\treturn recordOf({ id: isString, message: isString, scope: isString }, ['scope'])(value)\n}\n\n/**\n * Determine whether a value is an exact {@link AggregateDefinition} record.\n *\n * @param value - The candidate value\n * @returns `true` when `value` is an {@link AggregateDefinition}\n *\n * @example\n * ```ts\n * import { isAggregateDefinition } from '@orkestrel/program'\n *\n * isAggregateDefinition({ fields: ['amount'] }) // true\n * ```\n */\nexport function isAggregateDefinition(value: unknown): value is AggregateDefinition {\n\treturn recordOf({ fields: arrayOf(isFieldPath), by: isFieldPath, gates: isLogicalDefinition }, [\n\t\t'by',\n\t\t'gates',\n\t])(value)\n}\n\n/**\n * Determine whether a value is an exact {@link ProgramDefinition} record.\n *\n * @remarks\n * `rating` is optional — an omitted `rating` authors an eligibility-only\n * program (see {@link ProgramDefinition}).\n *\n * @param value - The candidate value\n * @returns `true` when `value` is a {@link ProgramDefinition}\n *\n * @example\n * ```ts\n * import { isProgramDefinition } from '@orkestrel/program'\n *\n * isProgramDefinition({ id: 'p', name: 'P', qualification }) // true\n * ```\n */\nexport function isProgramDefinition(value: unknown): value is ProgramDefinition {\n\treturn recordOf(\n\t\t{\n\t\t\tid: isString,\n\t\t\tname: isString,\n\t\t\tdescription: isString,\n\t\t\tqualification: isQualificationDefinition,\n\t\t\trating: isRatingDefinition,\n\t\t\tnotices: arrayOf(isNotice),\n\t\t\tauthority: isLogicalDefinition,\n\t\t\taggregate: isAggregateDefinition,\n\t\t\tmetadata: isJSONValue,\n\t\t},\n\t\t['description', 'rating', 'notices', 'authority', 'aggregate', 'metadata'],\n\t)(value)\n}\n","import type { FieldPath, JSONValue } from '@orkestrel/contract'\nimport type { Eligibility, QualificationResult, QualifierInterface } from '@orkestrel/qualifier'\nimport type { LineDefinition, RatingResult } from '@orkestrel/rater'\nimport type {\n\tEvaluatorInterface,\n\tLogicalDefinition,\n\tLogicalResult,\n\tReasonInterface,\n\tSubject,\n} from '@orkestrel/reason'\nimport type {\n\tAggregateGroup,\n\tAggregateProjection,\n\tAggregateResult,\n\tDecision,\n\tDetermination,\n\tNotice,\n\tProgramDefinition,\n\tProgramResult,\n\tProgramValidationResult,\n\tStatus,\n\tTally,\n} from './types.js'\nimport { isFiniteNumber, isRecord, resolveField } from '@orkestrel/contract'\nimport { findRule, interpolateMessage, logicalPremises } from '@orkestrel/qualifier'\nimport { findDuplicates, formatField } from '@orkestrel/reason'\nimport {\n\tAGGREGATE_KEY,\n\tELIGIBILITY_DECISIONS,\n\tOUTCOME_KEY,\n\tSTATUS_PRECEDENCE,\n} from './constants.js'\nimport { ProgramError } from './errors.js'\nimport { isProgramDefinition } from './validators.js'\n\n/**\n * Return a fresh JSON value tree that does not alias the input.\n *\n * @remarks\n * The input must be an acyclic JSON tree of bounded depth — a pathologically\n * deep tree throws the engine's `RangeError` (stack exhaustion) rather than\n * hanging. Each copied record uses `Object.defineProperty` for own-property\n * definition, which defends against prototype-pollution keys (`__proto__`).\n *\n * @param value - The JSON value to copy\n * @returns A fresh JSON value\n *\n * @example\n * ```ts\n * import { copyJSONValue } from '@orkestrel/program'\n *\n * copyJSONValue({ a: [1, 2] }) // { a: [1, 2] }, a fresh copy\n * ```\n */\nexport function copyJSONValue(value: JSONValue): JSONValue {\n\tif (value === null || typeof value !== 'object') return value\n\tif (Array.isArray(value)) return value.map(copyJSONValue)\n\tconst copy: Record<string, JSONValue> = {}\n\tfor (const [key, entry] of Object.entries(value)) {\n\t\tObject.defineProperty(copy, key, {\n\t\t\tvalue: copyJSONValue(entry),\n\t\t\tenumerable: true,\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t})\n\t}\n\treturn copy\n}\n\n/**\n * Determine whether a caller subject already carries a reserved program key.\n *\n * @remarks\n * `aggregate` and `outcome` are program-private working-subject namespaces — the\n * batch aggregate projection and the authority outcome projection are written\n * under them. A caller subject that already owns either key would silently\n * collide with a projection, so it is rejected before qualification.\n *\n * @param subject - The caller subject to check\n * @returns `true` when the subject owns `aggregate` or `outcome`\n *\n * @example\n * ```ts\n * import { hasReservedKey } from '@orkestrel/program'\n *\n * hasReservedKey({ id: 'r1' }) // false\n * hasReservedKey({ id: 'r1', aggregate: {} }) // true\n * ```\n */\nexport function hasReservedKey(subject: Readonly<Record<string, unknown>>): boolean {\n\treturn Object.hasOwn(subject, AGGREGATE_KEY) || Object.hasOwn(subject, OUTCOME_KEY)\n}\n\n/**\n * Assert a value is a valid program {@link Subject}, narrowing it in place.\n *\n * @param subject - The candidate subject to validate\n * @throws {@link ProgramError} `'MISMATCH'` when the value is not a record, or\n * `'RESERVED'` when it already carries the `aggregate` or `outcome` key\n *\n * @example\n * ```ts\n * import { assertProgramSubject } from '@orkestrel/program'\n *\n * assertProgramSubject({ id: 'r1' }) // does not throw\n * ```\n */\nexport function assertProgramSubject(subject: unknown): asserts subject is Subject {\n\tif (!isRecord(subject)) {\n\t\tthrow new ProgramError('MISMATCH', 'Program subject must be a record')\n\t}\n\tif (hasReservedKey(subject)) {\n\t\tconst key = Object.hasOwn(subject, AGGREGATE_KEY) ? AGGREGATE_KEY : OUTCOME_KEY\n\t\tthrow new ProgramError('RESERVED', `Subject contains a reserved program key '${key}'`, key)\n\t}\n}\n\n/**\n * Select the rating lines a subject may be rated on from scoped eligibility.\n *\n * @remarks\n * A scope names a rating-line id. A line survives when its scope is absent\n * (eligible by default), `eligible`, or a `condition` (which is not an\n * eligibility value and never appears here). A scoped `ineligible` or `referral`\n * removes the line BEFORE the rater is invoked — the excluded line is never\n * evaluated merely to discard its amount.\n *\n * @param lines - The program's authored rating lines\n * @param scopes - The qualification's per-scope eligibility\n * @returns The surviving line definitions, in authored order\n *\n * @example\n * ```ts\n * import { selectProgramLines } from '@orkestrel/program'\n *\n * selectProgramLines(lines, { wind: 'ineligible' }) // every line except 'wind'\n * ```\n */\nexport function selectProgramLines(\n\tlines: readonly LineDefinition[],\n\tscopes: Readonly<Record<string, Eligibility>>,\n): readonly LineDefinition[] {\n\treturn lines.filter((line) => {\n\t\tconst eligibility = scopes[line.id]\n\t\treturn eligibility !== 'ineligible' && eligibility !== 'referral'\n\t})\n}\n\n/**\n * Derive the final program {@link Status} from a definition's rating policy and\n * qualification/rating evidence.\n *\n * @remarks\n * Explicit policy, not an opaque precedence reduce (AGENTS §10): global\n * ineligibility or referral is terminal; a scoped referral yields `referral`;\n * an applied `condition` or an applied scoped `restriction` (a line was\n * removed but others rated) is `conditional`. When the definition OMITS\n * `rating` the program is eligibility-only — status resolves to `conditional`\n * or `eligible` and is NEVER `unrated`. Otherwise a subject with no successful\n * rating is `unrated`.\n *\n * @param definition - The authored program definition\n * @param qualification - The subject's qualification result\n * @param rating - The subject's rating result, when rating occurred\n * @returns The derived status\n *\n * @example\n * ```ts\n * import { deriveStatus } from '@orkestrel/program'\n *\n * deriveStatus(definition, qualification, rating) // 'eligible'\n * ```\n */\nexport function deriveStatus(\n\tdefinition: ProgramDefinition,\n\tqualification: QualificationResult,\n\trating?: RatingResult,\n): Status {\n\tif (qualification.eligibility === 'ineligible') return 'ineligible'\n\tif (qualification.eligibility === 'referral') return 'referral'\n\tif (Object.values(qualification.scopes).includes('referral')) return 'referral'\n\tconst conditional = qualification.findings.some(\n\t\t(finding) =>\n\t\t\tfinding.applied &&\n\t\t\t(finding.effect === 'condition' ||\n\t\t\t\t(finding.scope !== undefined && finding.effect === 'restriction')),\n\t)\n\tif (definition.rating === undefined) return conditional ? 'conditional' : 'eligible'\n\tif (rating === undefined || rating.lines.length === 0 || !rating.success) return 'unrated'\n\treturn conditional ? 'conditional' : 'eligible'\n}\n\n/**\n * Map a global {@link Eligibility} to its deterministic authority {@link Decision}.\n *\n * @param eligibility - The global eligibility\n * @returns The matching decision\n *\n * @example\n * ```ts\n * import { decideEligibility } from '@orkestrel/program'\n *\n * decideEligibility('eligible') // 'approved'\n * decideEligibility('referral') // 'submitted'\n * ```\n */\nexport function decideEligibility(eligibility: Eligibility): Decision {\n\treturn ELIGIBILITY_DECISIONS[eligibility]\n}\n\n/**\n * Resolve authored {@link Notice}s into unconditionally-applied `notice`\n * {@link Determination}s.\n *\n * @remarks\n * Notices are program output only — they never affect eligibility, status, line\n * selection, or the decision. Each message interpolates against the original\n * subject.\n *\n * @param notices - The authored notices\n * @param subject - The original subject notices interpolate against\n * @returns A fresh list of notice determinations\n *\n * @example\n * ```ts\n * import { buildNotices } from '@orkestrel/program'\n *\n * buildNotices([{ id: 'min', message: 'Minimum applies' }], { id: 'r1' })\n * ```\n */\nexport function buildNotices(\n\tnotices: readonly Notice[],\n\tsubject: Readonly<Record<string, unknown>>,\n): readonly Determination[] {\n\treturn notices.map((notice) => ({\n\t\tid: notice.id,\n\t\teffect: 'notice',\n\t\tapplied: true,\n\t\t...(notice.scope === undefined ? {} : { scope: notice.scope }),\n\t\tmessage: interpolateMessage(notice.message, subject),\n\t\tpremises: [],\n\t}))\n}\n\n/**\n * Convert a logical result's applied rules into `limit` {@link Determination}s.\n *\n * @remarks\n * Fires for both the per-subject authority and the batch aggregate gates — both\n * are plain {@link LogicalDefinition}s with no program-authored ruling map, so a\n * fired rule's own `description` (from `@orkestrel/reason`) is the message\n * template, interpolated against the working record the definition ran against.\n * Rich premises reuse the qualifier's {@link logicalPremises}. A rule that never\n * fires produces no determination — program has no authored ruling map to keep\n * evidence for.\n *\n * @param definition - The authority or aggregate-gate logical definition\n * @param result - The evaluated logical result\n * @param working - The working record the definition ran 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 list of `limit` determinations\n *\n * @example\n * ```ts\n * import { buildLimits } from '@orkestrel/program'\n *\n * buildLimits(authority, resolved, outcome, evaluator)\n * ```\n */\nexport function buildLimits(\n\tdefinition: LogicalDefinition,\n\tresult: LogicalResult,\n\tworking: Readonly<Record<string, unknown>>,\n\tevaluator: EvaluatorInterface,\n\tlabels?: Readonly<Record<string, string>>,\n): readonly Determination[] {\n\tconst output: Determination[] = []\n\tfor (const entry of result.rules) {\n\t\tif (!entry.applied) continue\n\t\tconst rule = findRule(definition, entry.id)\n\t\tif (rule === undefined) continue\n\t\toutput.push({\n\t\t\tid: entry.id,\n\t\t\teffect: 'limit',\n\t\t\tapplied: true,\n\t\t\t...(rule.description === undefined\n\t\t\t\t? {}\n\t\t\t\t: { message: interpolateMessage(rule.description, working) }),\n\t\t\tpremises: logicalPremises(rule, working, evaluator, labels),\n\t\t})\n\t}\n\treturn output\n}\n\n/**\n * Build the private authority outcome projection from an assembled program result.\n *\n * @remarks\n * The authority reads this record under {@link OUTCOME_KEY}; it never receives\n * the mutable internal state of either sibling engine. `total` is carried from\n * the nested rating result when rating occurred.\n *\n * @param result - The preliminary program result computed before authority runs\n * @returns A record shaped for the authority's `outcome` projection\n *\n * @example\n * ```ts\n * import { buildOutcomeProjection } from '@orkestrel/program'\n *\n * buildOutcomeProjection(result) // { id, eligibility, status, rated, scopes }\n * ```\n */\nexport function buildOutcomeProjection(result: ProgramResult): Readonly<Record<string, unknown>> {\n\tconst total = result.rating?.total\n\treturn {\n\t\tid: result.id,\n\t\teligibility: result.eligibility,\n\t\tstatus: result.status,\n\t\trated: result.rating !== undefined,\n\t\t...(total === undefined ? {} : { total }),\n\t\tscopes: { ...result.qualification.scopes },\n\t}\n}\n\n/**\n * Assemble a {@link ProgramResult} from its qualification, rating, and\n * determination parts — before or after authority.\n *\n * @remarks\n * `eligibility` mirrors the qualification. `success` is execution integrity: the\n * qualification succeeded, rating (when it ran) succeeded, and authority (when it\n * ran) produced no errors — a valid ineligible or referral outcome still\n * succeeds. `trace` and `errors` accumulate the qualification's, every rated\n * line's worksheet trail, and the authority's. A `decision` is present ONLY when\n * an authority ran (`options.authority`), the execution SUCCEEDED (`success`),\n * no `limit` determination applied, and status is not `unrated`.\n *\n * @param definition - The authored program definition\n * @param qualification - The subject's qualification result\n * @param rating - The subject's rating result, when rating occurred\n * @param determinations - The program-scoped determinations (notices, then limits)\n * @param status - The already-derived status\n * @param options - Optional authority result driving the decision projection\n * @returns A fresh program result\n *\n * @example\n * ```ts\n * import { buildProgramResult } from '@orkestrel/program'\n *\n * buildProgramResult(definition, qualification, rating, [], 'eligible')\n * ```\n */\nexport function buildProgramResult(\n\tdefinition: ProgramDefinition,\n\tqualification: QualificationResult,\n\trating: RatingResult | undefined,\n\tdeterminations: readonly Determination[],\n\tstatus: Status,\n\toptions?: { readonly authority?: LogicalResult },\n): ProgramResult {\n\tconst authority = options?.authority\n\tconst ratingTrace =\n\t\trating === undefined ? [] : rating.lines.flatMap((line) => line.worksheet.trace)\n\tconst ratingErrors =\n\t\trating === undefined ? [] : rating.lines.flatMap((line) => line.worksheet.errors)\n\tconst authorityTrace = authority === undefined ? [] : [...authority.trace]\n\tconst authorityErrors = authority === undefined ? [] : [...authority.errors]\n\tconst trace = [...qualification.trace, ...ratingTrace, ...authorityTrace]\n\tconst errors = [...qualification.errors, ...ratingErrors, ...authorityErrors]\n\tconst success =\n\t\tqualification.success &&\n\t\t(rating === undefined || rating.success) &&\n\t\tauthorityErrors.length === 0\n\tconst limited = determinations.some((entry) => entry.effect === 'limit' && entry.applied)\n\tconst decision =\n\t\tauthority !== undefined && success && !limited && status !== 'unrated'\n\t\t\t? decideEligibility(qualification.eligibility)\n\t\t\t: undefined\n\treturn {\n\t\tid: definition.id,\n\t\tname: definition.name,\n\t\teligibility: qualification.eligibility,\n\t\tstatus,\n\t\t...(decision === undefined ? {} : { decision }),\n\t\tqualification,\n\t\t...(rating === undefined ? {} : { rating }),\n\t\tdeterminations,\n\t\tsuccess,\n\t\ttrace,\n\t\terrors,\n\t}\n}\n\n/**\n * Add optional aggregate context to a private subject copy for qualification.\n *\n * @remarks\n * The original subject is returned unchanged when no aggregate context exists.\n * When context exists the helper creates a private copy under {@link AGGREGATE_KEY}\n * and defensively copies every nested record — the rater still receives the\n * original subject, never this copy.\n *\n * @param subject - The original caller subject\n * @param aggregate - The subject's aggregate projection, when a batch supplies one\n * @returns The subject, or a private copy carrying the aggregate projection\n *\n * @example\n * ```ts\n * import { buildQualificationSubject } from '@orkestrel/program'\n *\n * buildQualificationSubject({ id: 'r1' }) // { id: 'r1' }\n * ```\n */\nexport function buildQualificationSubject(\n\tsubject: Subject,\n\taggregate?: AggregateProjection,\n): Subject {\n\tif (aggregate === undefined) return subject\n\treturn {\n\t\t...subject,\n\t\t[AGGREGATE_KEY]: {\n\t\t\tcount: aggregate.count,\n\t\t\tsums: { ...aggregate.sums },\n\t\t\t...(aggregate.group === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tgroup: {\n\t\t\t\t\t\t\tkey: aggregate.group.key,\n\t\t\t\t\t\t\tcount: aggregate.group.count,\n\t\t\t\t\t\t\tsums: { ...aggregate.group.sums },\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t},\n\t}\n}\n\n/**\n * Return authored scopes (qualification ruling scopes or notice scopes) that\n * name no rating line on the program.\n *\n * @remarks\n * A scope is an opaque string to the qualifier — program alone matches it to a\n * rating-line id. A scope naming no line is a hard authoring error surfaced as\n * {@link ProgramError} `'MISSING'` at construction, regardless of the validate\n * option.\n *\n * @param definition - The program definition to check\n * @returns A fresh, deduped list of missing scope references\n *\n * @example\n * ```ts\n * import { findMissingScopes } from '@orkestrel/program'\n *\n * findMissingScopes(definition) // []\n * ```\n */\nexport function findMissingScopes(definition: ProgramDefinition): readonly string[] {\n\tconst ids = new Set((definition.rating?.lines ?? []).map((line) => line.id))\n\tconst missing = new Set<string>()\n\tfor (const ruling of definition.qualification.rulings ?? []) {\n\t\tif (ruling.scope !== undefined && !ids.has(ruling.scope)) missing.add(ruling.scope)\n\t}\n\tfor (const notice of definition.notices ?? []) {\n\t\tif (notice.scope !== undefined && !ids.has(notice.scope)) missing.add(notice.scope)\n\t}\n\treturn [...missing]\n}\n\n/**\n * Assert a program definition's always-on construction invariants — missing\n * scope references and duplicate rating-line or notice ids.\n *\n * @remarks\n * These checks run at construction regardless of `options.validate` (unlike\n * {@link validateProgramDefinition}, the standalone report-shaped validator) —\n * an authoring mistake this severe cannot silently compile.\n *\n * @param definition - The program definition to assert\n * @throws {@link ProgramError} `'MISSING'` when a ruling or notice scope names\n * no rating line\n * @throws {@link ProgramError} `'DUPLICATE'` when two rating lines or two\n * notices share an id\n *\n * @example\n * ```ts\n * import { assertProgramDefinition } from '@orkestrel/program'\n *\n * assertProgramDefinition(definition) // does not throw\n * ```\n */\nexport function assertProgramDefinition(definition: ProgramDefinition): void {\n\tconst missing = findMissingScopes(definition)\n\tif (missing.length > 0) {\n\t\tthrow new ProgramError(\n\t\t\t'MISSING',\n\t\t\t`Unknown rating line reference: ${missing.join(', ')}`,\n\t\t\tdefinition.id,\n\t\t)\n\t}\n\tconst duplicateLines = findDuplicates(definition.rating?.lines ?? [])\n\tif (duplicateLines.length > 0) {\n\t\tthrow new ProgramError(\n\t\t\t'DUPLICATE',\n\t\t\t`Duplicate rating line id: ${duplicateLines.join(', ')}`,\n\t\t\tdefinition.id,\n\t\t)\n\t}\n\tconst duplicateNotices = findDuplicates(definition.notices ?? [])\n\tif (duplicateNotices.length > 0) {\n\t\tthrow new ProgramError(\n\t\t\t'DUPLICATE',\n\t\t\t`Duplicate notice id: ${duplicateNotices.join(', ')}`,\n\t\t\tdefinition.id,\n\t\t)\n\t}\n}\n\n/**\n * Validate a program definition's shape, references, and nested definitions.\n *\n * @remarks\n * The single semantic-validation implementation used by `Program.validate`. It\n * establishes exact shape through {@link isProgramDefinition}, validates the\n * rating structurally through the rater's {@link isRatingDefinition} guard (the\n * rater exposes no `validate`), delegates qualification validation to the\n * injected qualifier and authority / aggregate-gate validation to the shared\n * reason engine, and checks scope, notice, and aggregate-field references here.\n *\n * @param definition - The program definition to validate\n * @param qualifier - The qualifier that validates the nested qualification\n * @param engine - The reason engine that validates authority and aggregate gates\n * @returns A structured validation result\n *\n * @example\n * ```ts\n * import { validateProgramDefinition } from '@orkestrel/program'\n *\n * validateProgramDefinition(definition, qualifier, engine) // { valid: true, ... }\n * ```\n */\nexport function validateProgramDefinition(\n\tdefinition: ProgramDefinition,\n\tqualifier: QualifierInterface,\n\tengine: ReasonInterface,\n): ProgramValidationResult {\n\tif (!isProgramDefinition(definition)) {\n\t\treturn { valid: false, errors: ['Program definition has an invalid shape'], warnings: [] }\n\t}\n\n\tconst errors: string[] = []\n\tconst warnings: string[] = []\n\n\tif (definition.id.length === 0) errors.push('Program id must not be empty')\n\tif (definition.name.length === 0) errors.push('Program name must not be empty')\n\n\tconst qualification = qualifier.validate(definition.qualification)\n\terrors.push(...qualification.errors.map((error) => `qualification: ${error}`))\n\twarnings.push(...qualification.warnings.map((warning) => `qualification: ${warning}`))\n\n\tconst lines = new Set((definition.rating?.lines ?? []).map((line) => line.id))\n\tif (definition.rating !== undefined && lines.size !== definition.rating.lines.length) {\n\t\terrors.push('rating: duplicate line id')\n\t}\n\tfor (const ruling of definition.qualification.rulings ?? []) {\n\t\tif (ruling.scope !== undefined && !lines.has(ruling.scope)) {\n\t\t\terrors.push(`Qualification ruling \"${ruling.id}\" references missing line \"${ruling.scope}\"`)\n\t\t}\n\t}\n\n\tconst notices = new Set<string>()\n\tfor (const notice of definition.notices ?? []) {\n\t\tif (notices.has(notice.id)) errors.push(`Duplicate notice id \"${notice.id}\"`)\n\t\tnotices.add(notice.id)\n\t\tif (notice.scope !== undefined && !lines.has(notice.scope)) {\n\t\t\terrors.push(`Notice \"${notice.id}\" references missing line \"${notice.scope}\"`)\n\t\t}\n\t}\n\n\tconst authority = definition.authority\n\tif (authority !== undefined) {\n\t\tconst validation = engine.validate(authority)\n\t\terrors.push(...validation.errors.map((error) => `authority: ${error}`))\n\t\twarnings.push(...validation.warnings.map((warning) => `authority: ${warning}`))\n\t}\n\n\tconst aggregate = definition.aggregate\n\tif (aggregate !== undefined) {\n\t\tconst fields = new Set<string>()\n\t\tfor (const field of aggregate.fields) {\n\t\t\tconst key = formatField(field)\n\t\t\tif (key.length === 0) errors.push('Aggregate fields must be non-empty')\n\t\t\tif (fields.has(key)) errors.push(`Duplicate aggregate field \"${key}\"`)\n\t\t\tfields.add(key)\n\t\t}\n\t\tif (aggregate.by !== undefined && formatField(aggregate.by).length === 0) {\n\t\t\terrors.push('Aggregate partition field must be non-empty')\n\t\t}\n\t\tif (aggregate.gates !== undefined) {\n\t\t\tconst validation = engine.validate(aggregate.gates)\n\t\t\terrors.push(...validation.errors.map((error) => `aggregate: ${error}`))\n\t\t\twarnings.push(...validation.warnings.map((warning) => `aggregate: ${warning}`))\n\t\t\tif (aggregate.fields.length === 0) {\n\t\t\t\twarnings.push('Aggregate gates are defined without aggregate fields')\n\t\t\t}\n\t\t}\n\t}\n\n\tif (definition.rating !== undefined && definition.rating.lines.length === 0) {\n\t\twarnings.push('Program rating has no lines')\n\t}\n\n\treturn { valid: errors.length === 0, errors, warnings }\n}\n\n/**\n * Coerce a subject's partition-key field to its group-key string.\n *\n * @remarks\n * The key is the resolved field coerced with `String` — `undefined` collapses\n * to the empty string, so a subject missing the field and a subject whose\n * field is literally `''` land in the SAME partition, and a numeric `1`\n * collides with the string `'1'`.\n *\n * @param subject - The subject to key\n * @param by - The partition key field\n * @returns The subject's group key\n *\n * @example\n * ```ts\n * import { formatGroupKey } from '@orkestrel/program'\n *\n * formatGroupKey({ location: 'east' }, 'location') // 'east'\n * ```\n */\nexport function formatGroupKey(subject: Subject, by: FieldPath): string {\n\treturn String(resolveField(subject, by) ?? '')\n}\n\n/**\n * Fold one subject's finite aggregate field values into a sums record.\n *\n * @remarks\n * Returns a FRESH record — `sums` is never mutated. Only finite numbers\n * contribute; a non-numeric or absent value contributes zero (never a\n * coercion). A {@link FieldPath} may be nested — `formatField` renders the\n * dot-joined key the returned record is keyed by.\n *\n * @param sums - The sums record to fold into\n * @param subject - The subject to fold in\n * @param fields - The fields to sum\n * @returns A fresh sums record with `subject`'s contribution added\n *\n * @example\n * ```ts\n * import { sumFields } from '@orkestrel/program'\n *\n * sumFields({ amount: 0 }, { amount: 5 }, ['amount']) // { amount: 5 }\n * ```\n */\nexport function sumFields(\n\tsums: Readonly<Record<string, number>>,\n\tsubject: Subject,\n\tfields: readonly FieldPath[],\n): Readonly<Record<string, number>> {\n\tconst next: Record<string, number> = { ...sums }\n\tfor (const field of fields) {\n\t\tconst key = formatField(field)\n\t\tconst value = resolveField(subject, field)\n\t\tif (isFiniteNumber(value)) next[key] = (next[key] ?? 0) + value\n\t}\n\treturn next\n}\n\n/**\n * Sum aggregate fields across a batch of subjects.\n *\n * @remarks\n * A {@link FieldPath} may be nested — a nested path sums a nested subject field\n * exactly like a top-level one, and `formatField` renders the dot-joined key the\n * returned record is keyed by. Only finite numbers contribute; a non-numeric or\n * absent value contributes zero (never a coercion).\n *\n * @param subjects - The batch of subjects\n * @param fields - The fields to sum\n * @returns A fresh record of dot-joined field to summed finite value\n *\n * @example\n * ```ts\n * import { aggregateSums } from '@orkestrel/program'\n *\n * aggregateSums([{ amount: 5 }, { amount: 3 }], ['amount']) // { amount: 8 }\n * ```\n */\nexport function aggregateSums(\n\tsubjects: readonly Subject[],\n\tfields: readonly FieldPath[],\n): Readonly<Record<string, number>> {\n\tlet sums = emptySums(fields)\n\tfor (const subject of subjects) sums = sumFields(sums, subject, fields)\n\treturn sums\n}\n\n/**\n * Partition a batch of subjects by a field, summing aggregate fields per key.\n *\n * @remarks\n * The partition key is derived by {@link formatGroupKey}. Group order follows\n * first appearance in the subject array.\n *\n * @param subjects - The batch of subjects\n * @param fields - The fields to sum within each partition\n * @param by - The partition key field; no partition is built when absent\n * @returns A fresh list of aggregate groups, or an empty list when `by` is absent\n *\n * @example\n * ```ts\n * import { aggregateGroups } from '@orkestrel/program'\n *\n * aggregateGroups([{ location: 'east', amount: 5 }], ['amount'], 'location')\n * ```\n */\nexport function aggregateGroups(\n\tsubjects: readonly Subject[],\n\tfields: readonly FieldPath[],\n\tby?: FieldPath,\n): readonly AggregateGroup[] {\n\tif (by === undefined) return []\n\tconst records = new Map<string, Subject[]>()\n\tfor (const subject of subjects) {\n\t\tconst key = formatGroupKey(subject, by)\n\t\tconst group = records.get(key)\n\t\tif (group === undefined) records.set(key, [subject])\n\t\telse group.push(subject)\n\t}\n\treturn [...records.entries()].map(([key, entries]) => ({\n\t\tkey,\n\t\tcount: entries.length,\n\t\tsums: aggregateSums(entries, fields),\n\t}))\n}\n\n/**\n * Build one subject's overall and optional group aggregate projection.\n *\n * @remarks\n * The projection carries the whole-batch `count` and `sums` plus the subject's\n * OWN partition, located by the same {@link formatGroupKey} key\n * {@link aggregateGroups} partitions under.\n *\n * @param subject - The subject to project for\n * @param count - The whole-batch subject count\n * @param sums - The whole-batch summed aggregate fields\n * @param groups - The batch partitions\n * @param by - The partition key field; no group is attached when absent\n * @returns A fresh aggregate projection\n *\n * @example\n * ```ts\n * import { buildAggregateProjection } from '@orkestrel/program'\n *\n * buildAggregateProjection(subject, 2, { amount: 8 }, groups, 'location')\n * ```\n */\nexport function buildAggregateProjection(\n\tsubject: Subject,\n\tcount: number,\n\tsums: Readonly<Record<string, number>>,\n\tgroups: readonly AggregateGroup[],\n\tby?: FieldPath,\n): AggregateProjection {\n\tconst group =\n\t\tby === undefined ? undefined : groups.find((entry) => entry.key === formatGroupKey(subject, by))\n\treturn { count, sums: { ...sums }, ...(group === undefined ? {} : { group }) }\n}\n\n/**\n * Build the reserved-key record a batch aggregate-gate definition runs against.\n *\n * @remarks\n * Unlike a per-subject {@link buildAggregateProjection}, the batch record carries\n * every `group` (a `groups` array) under {@link AGGREGATE_KEY} so a gate rule can\n * read `aggregate.sums.<field>` (overall) or a partition inside `aggregate.groups`.\n *\n * @param count - The whole-batch subject count\n * @param sums - The whole-batch summed aggregate fields\n * @param groups - The batch partitions\n * @returns A fresh record carrying the batch aggregate under {@link AGGREGATE_KEY}\n *\n * @example\n * ```ts\n * import { buildAggregateRecord } from '@orkestrel/program'\n *\n * buildAggregateRecord(2, { amount: 8 }, [])\n * ```\n */\nexport function buildAggregateRecord(\n\tcount: number,\n\tsums: Readonly<Record<string, number>>,\n\tgroups: readonly AggregateGroup[],\n): Readonly<Record<string, unknown>> {\n\treturn { [AGGREGATE_KEY]: { count, sums, groups } }\n}\n\n/**\n * Build a zero-sum record for a set of aggregate fields.\n *\n * @param fields - The fields to zero\n * @returns A fresh record of dot-joined field to `0`\n *\n * @example\n * ```ts\n * import { emptySums } from '@orkestrel/program'\n *\n * emptySums(['amount']) // { amount: 0 }\n * ```\n */\nexport function emptySums(fields: readonly FieldPath[]): Readonly<Record<string, number>> {\n\tconst sums: Record<string, number> = {}\n\tfor (const field of fields) sums[formatField(field)] = 0\n\treturn sums\n}\n\n/**\n * Complete a partial status tally record with zero entries for every missing\n * {@link Status}.\n *\n * @param entries - The partial tally entries to complete\n * @returns A record with all five statuses present\n *\n * @example\n * ```ts\n * import { completeTallies } from '@orkestrel/program'\n *\n * completeTallies({ eligible: { count: 1, sums: {} } })\n * ```\n */\nexport function completeTallies(\n\tentries: Partial<Record<Status, Tally>>,\n): Readonly<Record<Status, Tally>> {\n\treturn {\n\t\tineligible: entries.ineligible ?? { count: 0, sums: {} },\n\t\treferral: entries.referral ?? { count: 0, sums: {} },\n\t\tconditional: entries.conditional ?? { count: 0, sums: {} },\n\t\tunrated: entries.unrated ?? { count: 0, sums: {} },\n\t\teligible: entries.eligible ?? { count: 0, sums: {} },\n\t}\n}\n\n/**\n * Build complete zero status tallies in {@link STATUS_PRECEDENCE} order.\n *\n * @param fields - The fields each tally's sums are zeroed for\n * @returns A fresh, complete tally record\n *\n * @example\n * ```ts\n * import { emptyTallies } from '@orkestrel/program'\n *\n * emptyTallies(['amount'])\n * ```\n */\nexport function emptyTallies(fields: readonly FieldPath[]): Readonly<Record<Status, Tally>> {\n\tconst entries: Partial<Record<Status, Tally>> = {}\n\tfor (const status of STATUS_PRECEDENCE) entries[status] = { count: 0, sums: emptySums(fields) }\n\treturn completeTallies(entries)\n}\n\n/**\n * Add one subject's aggregate contribution to a status tally record.\n *\n * @param tallies - The tallies to update\n * @param result - The subject's program result (its `status` selects the tally)\n * @param subject - The subject to fold in\n * @param fields - The fields to sum\n * @returns A fresh, complete tally record with the subject folded in\n *\n * @example\n * ```ts\n * import { tallyProgram } from '@orkestrel/program'\n *\n * tallyProgram(tallies, result, { id: 'r1', amount: 5 }, ['amount'])\n * ```\n */\nexport function tallyProgram(\n\ttallies: Readonly<Record<Status, Tally>>,\n\tresult: ProgramResult,\n\tsubject: Subject,\n\tfields: readonly FieldPath[],\n): Readonly<Record<Status, Tally>> {\n\tconst status = result.status\n\tconst current = tallies[status]\n\tconst sums = sumFields(current.sums, subject, fields)\n\treturn completeTallies({ ...tallies, [status]: { count: current.count + 1, sums } })\n}\n\n/**\n * Assemble one batch {@link AggregateResult} from its per-subject and aggregate\n * parts.\n *\n * @remarks\n * `count` is the subject count, `trace` / `errors` accumulate every subject's\n * plus the batch aggregate-gate evaluation's (`options.gates`), and `success`\n * requires every subject execution to succeed AND the gate evaluation to have\n * produced no errors. A fired aggregate gate contributes a `limit`\n * determination, never a technical failure (a non-logical gate result is a\n * caller-facing `MISMATCH` thrown by `Program` before this assembles).\n *\n * @param definition - The authored program definition\n * @param subjects - The per-subject program results, in input order\n * @param determinations - The batch aggregate-gate `limit` determinations\n * @param groups - The batch partitions\n * @param tallies - The completed status tallies\n * @param sums - The whole-batch summed aggregate fields\n * @param options - Optional resolved aggregate-gate result\n * @returns A fresh aggregate result\n *\n * @example\n * ```ts\n * import { buildAggregateResult } from '@orkestrel/program'\n *\n * buildAggregateResult(definition, subjects, [], [], tallies, { amount: 8 })\n * ```\n */\nexport function buildAggregateResult(\n\tdefinition: ProgramDefinition,\n\tsubjects: readonly ProgramResult[],\n\tdeterminations: readonly Determination[],\n\tgroups: readonly AggregateGroup[],\n\ttallies: Readonly<Record<Status, Tally>>,\n\tsums: Readonly<Record<string, number>>,\n\toptions?: { readonly gates?: LogicalResult },\n): AggregateResult {\n\tconst gates = options?.gates\n\tconst gateTrace = gates === undefined ? [] : [...gates.trace]\n\tconst gateErrors = gates === undefined ? [] : [...gates.errors]\n\treturn {\n\t\tid: definition.id,\n\t\tname: definition.name,\n\t\tsubjects,\n\t\tdeterminations,\n\t\tgroups,\n\t\ttallies,\n\t\tcount: subjects.length,\n\t\tsums,\n\t\tsuccess: subjects.every((entry) => entry.success) && gateErrors.length === 0,\n\t\ttrace: [...subjects.flatMap((entry) => entry.trace), ...gateTrace],\n\t\terrors: [...subjects.flatMap((entry) => entry.errors), ...gateErrors],\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { QualificationResult, QualifierInterface } from '@orkestrel/qualifier'\nimport type { RaterInterface, RatingResult } from '@orkestrel/rater'\nimport type { EvaluatorInterface, LogicalResult, ReasonInterface, Subject } from '@orkestrel/reason'\nimport type {\n\tAggregateGroup,\n\tAggregateProjection,\n\tAggregateResult,\n\tDetermination,\n\tProgramDefinition,\n\tProgramEventMap,\n\tProgramInterface,\n\tProgramOptions,\n\tProgramResult,\n\tProgramValidationResult,\n} from '../types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArray } from '@orkestrel/contract'\nimport { createQualifier } from '@orkestrel/qualifier'\nimport { createRater } from '@orkestrel/rater'\nimport {\n\tcreateEvaluator,\n\tcreateLogicalReasoner,\n\tcreateQuantitativeReasoner,\n\tcreateReason,\n} from '@orkestrel/reason'\nimport { DEFAULT_PROGRAM_VALIDATE, OUTCOME_KEY } from '../constants.js'\nimport { ProgramError } from '../errors.js'\nimport {\n\taggregateGroups,\n\taggregateSums,\n\tassertProgramDefinition,\n\tassertProgramSubject,\n\tbuildAggregateProjection,\n\tbuildAggregateRecord,\n\tbuildAggregateResult,\n\tbuildLimits,\n\tbuildNotices,\n\tbuildOutcomeProjection,\n\tbuildProgramResult,\n\tbuildQualificationSubject,\n\tderiveStatus,\n\temptyTallies,\n\tselectProgramLines,\n\ttallyProgram,\n\tvalidateProgramDefinition,\n} from '../helpers.js'\n\n/**\n * One compiled program — composes one qualifier and one rater over a shared\n * reason engine and executes single subjects or aggregate-aware batches.\n *\n * @remarks\n * Qualification decides whether rating happens: a globally ineligible, referred,\n * or failed subject never reaches the rater, and a scoped ineligibility removes\n * only its line before the first rating call. The rater always receives the\n * ORIGINAL subject; the qualifier's aggregate projection stays private. When no\n * qualifier, rater, or engine is injected the program creates ONE shared\n * quantitative-plus-logical engine, injects it into the qualifier and rater it\n * creates, and destroys only what it owns. A definition failure during\n * construction (an invalid definition under `options.validate`) tears down\n * whatever the constructor had already allocated before throwing. `destroy()`\n * is idempotent and REENTRANCY-SAFE — the destroyed flag is set BEFORE any\n * teardown or the `destroy` event fires, so a listener that re-enters\n * `destroy()` is a no-op — and tears the emitter down last.\n */\nexport class Program implements ProgramInterface {\n\treadonly #emitter: Emitter<ProgramEventMap>\n\treadonly #qualifier: QualifierInterface\n\treadonly #rater: RaterInterface\n\treadonly #engine: ReasonInterface\n\treadonly #evaluator: EvaluatorInterface\n\treadonly #qualifierOwned: boolean\n\treadonly #raterOwned: boolean\n\treadonly #engineOwned: boolean\n\treadonly #validate: boolean\n\treadonly #labels: Readonly<Record<string, string>> | undefined\n\t#destroyed = false\n\n\treadonly id: string\n\treadonly name: string\n\treadonly definition: ProgramDefinition\n\n\tconstructor(definition: ProgramDefinition, options?: ProgramOptions) {\n\t\tassertProgramDefinition(definition)\n\t\tthis.id = definition.id\n\t\tthis.name = definition.name\n\t\tthis.definition = definition\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.#evaluator = createEvaluator()\n\t\tthis.#engineOwned = options?.engine === undefined\n\t\tthis.#qualifierOwned = options?.qualifier === undefined\n\t\tthis.#raterOwned = options?.rater === 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.#qualifier = options?.qualifier ?? createQualifier({ engine: this.#engine })\n\t\tthis.#rater = options?.rater ?? createRater({ engine: this.#engine })\n\t\tthis.#validate = options?.validate ?? DEFAULT_PROGRAM_VALIDATE\n\t\tthis.#labels = options?.labels\n\n\t\tif (this.#validate) {\n\t\t\tconst validation = this.validate()\n\t\t\tif (!validation.valid) {\n\t\t\t\tthis.destroy()\n\t\t\t\tthrow new ProgramError('DEFINITION', validation.errors.join('; '), definition.id)\n\t\t\t}\n\t\t}\n\t}\n\n\tget emitter(): EmitterInterface<ProgramEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\t// Array overload first (AGENTS §9.2) so a subject list resolves to the batch form.\n\texecute(subjects: readonly Subject[]): AggregateResult\n\texecute(subject: Subject): ProgramResult\n\texecute(input: Subject | readonly Subject[]): ProgramResult | AggregateResult {\n\t\tthis.#alive()\n\t\tif (isArray<Subject>(input)) return this.#aggregate(input)\n\t\treturn this.#subject(input)\n\t}\n\n\tvalidate(): ProgramValidationResult {\n\t\tthis.#alive()\n\t\treturn validateProgramDefinition(this.definition, this.#qualifier, this.#engine)\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tif (this.#qualifierOwned) this.#qualifier.destroy()\n\t\tif (this.#raterOwned) this.#rater.destroy()\n\t\tif (this.#engineOwned) this.#engine.destroy()\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#subject(subject: Subject, aggregate?: AggregateProjection): ProgramResult {\n\t\tassertProgramSubject(subject)\n\t\tconst qualified = buildQualificationSubject(subject, aggregate)\n\t\tconst qualification = this.#qualifier.qualify(qualified, this.definition.qualification)\n\t\tthis.#emitter.emit('qualify', qualification)\n\n\t\tif (!qualification.success || qualification.eligibility !== 'eligible') {\n\t\t\treturn this.#finish(subject, qualification, undefined)\n\t\t}\n\n\t\tconst lines = selectProgramLines(this.definition.rating?.lines ?? [], qualification.scopes)\n\t\tconst rating = lines.length === 0 ? undefined : this.#rater.rate(lines, subject)\n\t\tif (rating !== undefined) this.#emitter.emit('rate', rating)\n\n\t\treturn this.#finish(subject, qualification, rating)\n\t}\n\n\t#finish(\n\t\tsubject: Subject,\n\t\tqualification: QualificationResult,\n\t\trating?: RatingResult,\n\t): ProgramResult {\n\t\tconst notices = buildNotices(this.definition.notices ?? [], subject)\n\t\tfor (const notice of notices) this.#emitter.emit('determine', notice)\n\n\t\tconst status = deriveStatus(this.definition, qualification, rating)\n\t\tlet result = buildProgramResult(this.definition, qualification, rating, notices, status)\n\n\t\tconst authority = this.definition.authority\n\t\tif (authority === undefined) {\n\t\t\tthis.#emitter.emit('execute', result)\n\t\t\treturn result\n\t\t}\n\n\t\tconst outcome = { [OUTCOME_KEY]: buildOutcomeProjection(result) }\n\t\tconst resolved = this.#engine.reason(outcome, authority)\n\t\tif (resolved.reasoning !== 'logical') {\n\t\t\tthrow new ProgramError('MISMATCH', 'Authority returned non-logical reasoning', authority.id)\n\t\t}\n\n\t\tconst limits = buildLimits(authority, resolved, outcome, this.#evaluator, this.#labels)\n\t\tfor (const limit of limits) this.#emitter.emit('determine', limit)\n\n\t\tresult = buildProgramResult(\n\t\t\tthis.definition,\n\t\t\tqualification,\n\t\t\trating,\n\t\t\t[...notices, ...limits],\n\t\t\tstatus,\n\t\t\t{ authority: resolved },\n\t\t)\n\n\t\tif (result.decision !== undefined) this.#emitter.emit('decide', result.decision, result)\n\t\tthis.#emitter.emit('execute', result)\n\t\treturn result\n\t}\n\n\t#aggregate(subjects: readonly Subject[]): AggregateResult {\n\t\tfor (const subject of subjects) assertProgramSubject(subject)\n\n\t\tconst definition = this.definition.aggregate\n\t\tconst fields = [...(definition?.fields ?? [])]\n\t\tconst sums = aggregateSums(subjects, fields)\n\t\tconst groups = aggregateGroups(subjects, fields, definition?.by)\n\t\tlet tallies = emptyTallies(fields)\n\t\tconst results = subjects.map((subject) => {\n\t\t\tconst projection =\n\t\t\t\tdefinition === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: buildAggregateProjection(subject, subjects.length, sums, groups, definition.by)\n\t\t\tconst result = this.#subject(subject, projection)\n\t\t\ttallies = tallyProgram(tallies, result, subject, fields)\n\t\t\treturn result\n\t\t})\n\n\t\tconst gates = this.#aggregateLimits(subjects.length, sums, groups)\n\t\tconst result = buildAggregateResult(\n\t\t\tthis.definition,\n\t\t\tresults,\n\t\t\tgates.determinations,\n\t\t\tgroups,\n\t\t\ttallies,\n\t\t\tsums,\n\t\t\tgates.resolved === undefined ? undefined : { gates: gates.resolved },\n\t\t)\n\t\tthis.#emitter.emit('aggregate', result)\n\t\treturn result\n\t}\n\n\t#aggregateLimits(\n\t\tcount: number,\n\t\tsums: Readonly<Record<string, number>>,\n\t\tgroups: readonly AggregateGroup[],\n\t): { readonly determinations: readonly Determination[]; readonly resolved?: LogicalResult } {\n\t\tconst gates = this.definition.aggregate?.gates\n\t\tif (gates === undefined) return { determinations: [] }\n\n\t\tconst record = buildAggregateRecord(count, sums, groups)\n\t\tconst resolved = this.#engine.reason(record, gates)\n\t\tif (resolved.reasoning !== 'logical') {\n\t\t\tthrow new ProgramError('MISMATCH', 'Aggregate gates returned non-logical reasoning', gates.id)\n\t\t}\n\n\t\tconst determinations = buildLimits(gates, resolved, record, this.#evaluator, this.#labels)\n\t\tfor (const determination of determinations) this.#emitter.emit('determine', determination)\n\t\treturn { determinations, resolved }\n\t}\n\n\t#alive(): void {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new ProgramError('DESTROYED', 'Program has been destroyed', this.id)\n\t\t}\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { QualifierInterface } from '@orkestrel/qualifier'\nimport type { RaterInterface } from '@orkestrel/rater'\nimport type { ReasonInterface } from '@orkestrel/reason'\nimport type {\n\tProgramDefinition,\n\tProgramInterface,\n\tProgramManagerEventMap,\n\tProgramManagerInterface,\n\tProgramManagerOptions,\n} from '../types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { createQualifier } from '@orkestrel/qualifier'\nimport { createRater } from '@orkestrel/rater'\nimport { createLogicalReasoner, createQuantitativeReasoner, createReason } from '@orkestrel/reason'\nimport { DEFAULT_PROGRAM_VALIDATE } from '../constants.js'\nimport { ProgramError } from '../errors.js'\nimport { createProgram } from '../factories.js'\n\n/**\n * An ordered manager over compiled {@link ProgramInterface}s (AGENTS §9), sharing\n * one qualifier, rater, and reason engine across every program it compiles.\n *\n * @remarks\n * OWNS its ordered `#programs` collection and its own {@link Emitter} over\n * {@link ProgramManagerEventMap}. Creates or borrows one shared engine, qualifier,\n * and rater and injects the same instances into every compiled program. `remove`\n * destroys the programs it removes; `destroy()` removes all programs, then\n * destroys only the owned shared dependencies, and tears the emitter down LAST.\n * A seed-program failure during construction tears the manager down (destroying\n * whatever had already been compiled) before rethrowing the original error.\n * `destroy()` is REENTRANCY-SAFE — the destroyed flag is set BEFORE any teardown\n * or the `remove` / `destroy` events fire, so a `remove` listener that re-enters\n * `destroy()` is a no-op. Every call after `destroy()` throws {@link ProgramError}\n * `'DESTROYED'`.\n */\nexport class ProgramManager implements ProgramManagerInterface {\n\treadonly #emitter: Emitter<ProgramManagerEventMap>\n\treadonly #programs: ProgramInterface[] = []\n\treadonly #qualifier: QualifierInterface\n\treadonly #rater: RaterInterface\n\treadonly #engine: ReasonInterface\n\treadonly #qualifierOwned: boolean\n\treadonly #raterOwned: boolean\n\treadonly #engineOwned: boolean\n\treadonly #validate: boolean\n\treadonly #labels: Readonly<Record<string, string>> | undefined\n\t#destroyed = false\n\n\tconstructor(options?: ProgramManagerOptions) {\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.#labels = options?.labels\n\t\tthis.#engineOwned = options?.engine === undefined\n\t\tthis.#qualifierOwned = options?.qualifier === undefined\n\t\tthis.#raterOwned = options?.rater === 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.#qualifier = options?.qualifier ?? createQualifier({ engine: this.#engine })\n\t\tthis.#rater = options?.rater ?? createRater({ engine: this.#engine })\n\t\tthis.#validate = options?.validate ?? DEFAULT_PROGRAM_VALIDATE\n\n\t\ttry {\n\t\t\tfor (const definition of options?.programs ?? []) this.add(definition)\n\t\t} catch (error) {\n\t\t\tthis.destroy()\n\t\t\tthrow error\n\t\t}\n\t}\n\n\tget emitter(): EmitterInterface<ProgramManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget size(): number {\n\t\tthis.#alive()\n\t\treturn this.#programs.length\n\t}\n\n\thas(id: string): boolean {\n\t\tthis.#alive()\n\t\treturn this.#programs.some((program) => program.id === id)\n\t}\n\n\tprogram(id: string): ProgramInterface | undefined {\n\t\tthis.#alive()\n\t\treturn this.#programs.find((program) => program.id === id)\n\t}\n\n\tprograms(): readonly ProgramInterface[] {\n\t\tthis.#alive()\n\t\treturn [...this.#programs]\n\t}\n\n\tadd(definition: ProgramDefinition): ProgramInterface {\n\t\tthis.#alive()\n\t\tif (this.has(definition.id)) {\n\t\t\tthrow new ProgramError(\n\t\t\t\t'DUPLICATE',\n\t\t\t\t`Program \"${definition.id}\" already exists`,\n\t\t\t\tdefinition.id,\n\t\t\t)\n\t\t}\n\t\tconst program = createProgram(definition, {\n\t\t\tqualifier: this.#qualifier,\n\t\t\trater: this.#rater,\n\t\t\tengine: this.#engine,\n\t\t\tvalidate: this.#validate,\n\t\t\t...(this.#labels === undefined ? {} : { labels: this.#labels }),\n\t\t})\n\t\tthis.#programs.push(program)\n\t\tthis.#emitter.emit('add', program.id)\n\t\treturn program\n\t}\n\n\t// Array overload first (AGENTS §9.2) so an id list resolves to the batch form.\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(input?: string | readonly string[]): boolean | void {\n\t\tthis.#alive()\n\t\tif (input === undefined) {\n\t\t\tthis.#drain()\n\t\t\treturn\n\t\t}\n\t\tif (Array.isArray(input)) {\n\t\t\tlet removed = true\n\t\t\tfor (const id of input) removed = this.#removeOne(id) && removed\n\t\t\treturn removed\n\t\t}\n\t\tif (typeof input === 'string') return this.#removeOne(input)\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tthis.#drain()\n\t\tif (this.#qualifierOwned) this.#qualifier.destroy()\n\t\tif (this.#raterOwned) this.#rater.destroy()\n\t\tif (this.#engineOwned) this.#engine.destroy()\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#drain(): void {\n\t\tfor (const program of this.#programs.splice(0)) {\n\t\t\tprogram.destroy()\n\t\t\tthis.#emitter.emit('remove', program.id)\n\t\t}\n\t}\n\n\t#removeOne(id: string): boolean {\n\t\tconst index = this.#programs.findIndex((program) => program.id === id)\n\t\tif (index < 0) return false\n\t\tconst removed = this.#programs.splice(index, 1)[0]\n\t\tif (removed === undefined) return false\n\t\tremoved.destroy()\n\t\tthis.#emitter.emit('remove', removed.id)\n\t\treturn true\n\t}\n\n\t#alive(): void {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new ProgramError('DESTROYED', 'Program manager has been destroyed')\n\t\t}\n\t}\n}\n","import type { FieldPath } from '@orkestrel/contract'\nimport type { QualificationDefinition } from '@orkestrel/qualifier'\nimport type { RatingDefinition } from '@orkestrel/rater'\nimport type {\n\tAggregateDefinition,\n\tAggregateInput,\n\tNotice,\n\tNoticeInput,\n\tProgramDefinition,\n\tProgramInput,\n\tProgramInterface,\n\tProgramManagerInterface,\n\tProgramManagerOptions,\n\tProgramOptions,\n} from './types.js'\nimport { Program } from './programs/Program.js'\nimport { ProgramManager } from './programs/ProgramManager.js'\nimport { copyJSONValue } from './helpers.js'\n\n/**\n * Create one compiled program over a qualifier and rater.\n *\n * @remarks\n * Validates the definition at construction when `options.validate` is left at\n * its {@link DEFAULT_PROGRAM_VALIDATE} default. A standalone program creates and\n * OWNS one shared quantitative-plus-logical reason engine and injects it into the\n * qualifier and rater it creates; injected dependencies remain caller-owned.\n *\n * @param definition - The authored program definition\n * @param options - Optional injected qualifier, rater, engine, validation, labels, and emitter hooks\n * @returns A {@link ProgramInterface}\n *\n * @example\n * ```ts\n * import { createProgram, programDefinition } from '@orkestrel/program'\n *\n * const program = createProgram(programDefinition('standard', 'Standard', qualification, rating))\n * program.execute({ id: 'risk-1' })\n * program.destroy()\n * ```\n */\nexport function createProgram(\n\tdefinition: ProgramDefinition,\n\toptions?: ProgramOptions,\n): ProgramInterface {\n\treturn new Program(definition, options)\n}\n\n/**\n * Create one ordered manager over compiled programs.\n *\n * @remarks\n * Creates or borrows one shared reason engine, qualifier, and rater and injects\n * them into every compiled program, so a batch of definitions shares one engine.\n * Seed definitions are compiled in order.\n *\n * @param options - Optional injected qualifier, rater, engine, seed programs, validation, labels, and emitter hooks\n * @returns A {@link ProgramManagerInterface}\n *\n * @example\n * ```ts\n * import { createProgramManager } from '@orkestrel/program'\n *\n * const manager = createProgramManager({ programs: [definition] })\n * manager.program('standard')?.execute(subject)\n * manager.destroy()\n * ```\n */\nexport function createProgramManager(options?: ProgramManagerOptions): ProgramManagerInterface {\n\treturn new ProgramManager(options)\n}\n\n/**\n * Build a {@link ProgramDefinition}.\n *\n * @remarks\n * Copies every collection and omits absent optional keys, so the returned\n * definition is a fresh, JSON-serializable value that never aliases its inputs.\n *\n * @param id - The program id\n * @param name - The display name\n * @param qualification - The nested qualification definition\n * @param rating - The nested rating definition; omit for an eligibility-only program\n * @param input - Optional description, notices, authority, aggregate, and metadata\n * @returns A fresh program definition\n *\n * @example\n * ```ts\n * import { programDefinition } from '@orkestrel/program'\n *\n * programDefinition('standard', 'Standard', qualification, rating, { notices: [notice] })\n * ```\n */\nexport function programDefinition(\n\tid: string,\n\tname: string,\n\tqualification: QualificationDefinition,\n\trating?: RatingDefinition,\n\tinput?: ProgramInput,\n): ProgramDefinition {\n\treturn {\n\t\tid,\n\t\tname,\n\t\tqualification,\n\t\t...(rating === undefined ? {} : { rating }),\n\t\t...(input?.description === undefined ? {} : { description: input.description }),\n\t\t...(input?.notices === undefined ? {} : { notices: [...input.notices] }),\n\t\t...(input?.authority === undefined ? {} : { authority: input.authority }),\n\t\t...(input?.aggregate === undefined ? {} : { aggregate: input.aggregate }),\n\t\t...(input?.metadata === undefined ? {} : { metadata: copyJSONValue(input.metadata) }),\n\t}\n}\n\n/**\n * Build a {@link Notice}.\n *\n * @param id - The notice id\n * @param message - The message template, carrying optional `{{token}}`s\n * @param input - Optional presentation scope\n * @returns A fresh notice\n *\n * @example\n * ```ts\n * import { noticeDefinition } from '@orkestrel/program'\n *\n * noticeDefinition('minimum', 'Minimum earned premium applies')\n * ```\n */\nexport function noticeDefinition(id: string, message: string, input?: NoticeInput): Notice {\n\treturn {\n\t\tid,\n\t\tmessage,\n\t\t...(input?.scope === undefined ? {} : { scope: input.scope }),\n\t}\n}\n\n/**\n * Build an {@link AggregateDefinition}.\n *\n * @param fields - The aggregate fields to sum across a batch\n * @param input - Optional partition field and aggregate gates\n * @returns A fresh aggregate definition\n *\n * @example\n * ```ts\n * import { aggregateDefinition } from '@orkestrel/program'\n *\n * aggregateDefinition(['amount'], { by: 'location' })\n * ```\n */\nexport function aggregateDefinition(\n\tfields: readonly FieldPath[],\n\tinput?: AggregateInput,\n): AggregateDefinition {\n\treturn {\n\t\tfields: [...fields],\n\t\t...(input?.by === undefined ? {} : { by: input.by }),\n\t\t...(input?.gates === undefined ? {} : { gates: input.gates }),\n\t}\n}\n"],"mappings":";;;;;;;AAIA,IAAa,2BAA2B;;AAGxC,IAAa,oBAAuC,OAAO,OAAO;CACjE;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,IAAa,wBAAiE,OAAO,OAAO;CAC3F,UAAU;CACV,YAAY;CACZ,UAAU;AACX,CAAC;;AAGD,IAAa,gBAAgB;;AAG7B,IAAa,cAAc;;;;;;;;;;;;;;;ACZ3B,IAAa,eAAb,cAAkC,MAAM;CACvC;CACA;CAEA,YAAY,MAAwB,SAAiB,SAAmB;EACvE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAAU;CAChB;AACD;;AAGA,SAAg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