@orkestrel/study 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/helpers.ts","../../../src/core/validators.ts","../../../src/core/errors.ts","../../../src/core/parsers.ts","../../../src/core/engines/helpers.ts","../../../src/core/engines/StudyControl.ts","../../../src/core/engines/StudyScope.ts","../../../src/core/engines/StudyDeadline.ts","../../../src/core/engines/StudyRequest.ts","../../../src/core/engines/StudyMeter.ts","../../../src/core/engines/StudyTrialLease.ts","../../../src/core/engines/StudySeries.ts","../../../src/core/agents/helpers.ts","../../../src/core/agents/validators.ts","../../../src/core/agents/StudyAgentObserver.ts","../../../src/core/agents/StudyAgentJudge.ts"],"sourcesContent":["import type { StudyCause, StudyLayer, StudyRole } from './types.js'\n\n/**\n * Keys the own self-identity every study error stamps on itself.\n * @remarks\n * The global symbol registry lets every package, ESM, CommonJS and captured copy read the same\n * key. The registry makes the key discoverable; it is a recognition mechanism, not an\n * unforgeable provenance marker.\n */\nexport const STUDY_ERROR_BRAND = Symbol.for('@orkestrel/study.error')\n\n/** Caps a declared trial population before schedule allocation. */\nexport const STUDY_TRIALS = 4096\n\n/** Caps a declared scenario horizon before execution. */\nexport const STUDY_GOALS = 4096\n\n/** Restricts identifiers to portable path-safe names. */\nexport const STUDY_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n\n/** Lists every measured request role in report order. */\nexport const STUDY_ROLES: readonly StudyRole[] = Object.freeze([\n\t'agent',\n\t'judge',\n\t'summary',\n\t'metadata',\n\t'tool',\n])\n\n/** Lists every ceiling a run can stop at in report order. */\nexport const STUDY_LAYERS: readonly StudyLayer[] = Object.freeze([\n\t'scope',\n\t'window',\n\t'custody',\n\t'meter',\n\t'budget',\n\t'model',\n])\n\n/** Lists every operational ending in report order. */\nexport const STUDY_CAUSES: readonly StudyCause[] = Object.freeze([\n\t'capacity',\n\t'infrastructure',\n\t'deadline',\n\t'interrupted',\n\t'content',\n])\n","import type {\n\tStudyDefinition,\n\tStudyGrading,\n\tStudyManifest,\n\tStudyProfile,\n\tStudyRubric,\n\tStudyScenario,\n\tStudyScore,\n\tStudyStop,\n\tStudyTrial,\n} from './types.js'\nimport type { JSONValue } from '@orkestrel/contract'\nimport { holds, canonicalStringify, isRecord } from '@orkestrel/contract'\nimport { StudyError } from './errors.js'\nimport {\n\tisStudyDefinition,\n\tisStudyGrading,\n\tisStudyProfile,\n\tisStudyRubric,\n\tisStudyScenario,\n} from './validators.js'\n\n/**\n * Copies the own entries of a record that hold a value, in their original order.\n * @param value - The record whose undefined entries are absent declarations\n * @returns A new record without the undefined entries\n * @example\n * ```ts\n * omitStudyAbsent({ context: 512, recap: undefined }) // { context: 512 }\n * ```\n */\nexport function omitStudyAbsent(value: object): Readonly<Record<string, unknown>> {\n\treturn Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined))\n}\n\n/**\n * Omits every undefined optional declaration so the profile has one JSON form.\n * @param profile - The validated profile whose optional leaves may be undefined\n * @returns The profile fields with absent qualification, settings, provider, judge and recap removed\n * @example\n * ```ts\n * normalizeStudyProfile(profile) // no `recap` key when the room declares none\n * ```\n */\nexport function normalizeStudyProfile(profile: StudyProfile): Readonly<Record<string, unknown>> {\n\tconst { provider, qualification, settings, room, ...required } = profile\n\treturn {\n\t\t...required,\n\t\troom: omitStudyAbsent(room),\n\t\t...(provider === undefined\n\t\t\t? {}\n\t\t\t: { provider: { ...omitStudyAbsent(provider), digest: omitStudyAbsent(provider.digest) } }),\n\t\t...(qualification === undefined ? {} : { qualification }),\n\t\t...(settings === undefined ? {} : { settings }),\n\t}\n}\n\n/**\n * Projects a stop onto JSON with every unreported reading as null.\n * @param stop - The ceiling that stopped a run\n * @returns The stop's layer, id, and readings, with an undefined `max` or `consumed` as null\n * @example\n * ```ts\n * studyStopToJSON({ layer: 'model', id: 'num_predict', max: 2048, consumed: undefined })\n * // { layer: 'model', id: 'num_predict', max: 2048, consumed: null }\n * ```\n */\nexport function studyStopToJSON(stop: StudyStop): JSONValue {\n\treturn {\n\t\tlayer: stop.layer,\n\t\tid: stop.id,\n\t\tmax: stop.max ?? null,\n\t\tconsumed: stop.consumed ?? null,\n\t}\n}\n\n/**\n * Matches exact own enumerable data keys without evaluating accessors.\n * @param value - The candidate record\n * @param required - Required keys\n * @param optional - Allowed optional keys\n * @returns True if the record has exactly the allowed data keys; false otherwise\n * @example Check exact keys\n * ```ts\n * import { matchesStudyKeys } from '@orkestrel/study'\n *\n * matchesStudyKeys({ id: 'one' }, ['id']) // true\n * ```\n */\nexport function matchesStudyKeys(\n\tvalue: unknown,\n\trequired: readonly string[],\n\toptional: readonly string[] = [],\n): boolean {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst keys = Reflect.ownKeys(value)\n\t\treturn (\n\t\t\trequired.every((key) => Object.hasOwn(value, key)) &&\n\t\t\tkeys.every((key) => {\n\t\t\t\tif (typeof key !== 'string' || (!required.includes(key) && !optional.includes(key)))\n\t\t\t\t\treturn false\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key)\n\t\t\t\treturn (\n\t\t\t\t\tdescriptor !== undefined &&\n\t\t\t\t\tdescriptor.enumerable === true &&\n\t\t\t\t\tObject.hasOwn(descriptor, 'value')\n\t\t\t\t)\n\t\t\t})\n\t\t)\n\t})\n}\n\n/**\n * Builds a bounded schedule from explicit repetition rows and declared scenarios.\n * @param definition - The frozen population declaration\n * @param scenarios - The complete scenario declarations\n * @returns Owned trials in repetition, scenario and row-arm order\n * @throws StudyError - Thrown when the population or scenario set is invalid\n * @example\n * ```ts\n * buildStudySchedule(definition, scenarios)\n * ```\n */\nexport function buildStudySchedule(\n\tdefinition: StudyDefinition,\n\tscenarios: readonly StudyScenario[],\n): readonly StudyTrial[] {\n\tif (!isStudyDefinition(definition) || !scenarios.every(isStudyScenario))\n\t\tthrow new StudyError('CONFIG', 'Invalid study population')\n\tconst ids = new Set(scenarios.map((scenario) => scenario.id))\n\tif (\n\t\tids.size !== scenarios.length ||\n\t\tids.size !== definition.scenarios.length ||\n\t\t!definition.scenarios.every((id) => ids.has(id))\n\t)\n\t\tthrow new StudyError('CONFIG', 'Scenario declarations must match the population exactly')\n\treturn Object.freeze(\n\t\t[...definition.order.entries()].flatMap(([repetition, row]) =>\n\t\t\t[...definition.scenarios.entries()].flatMap(([scenario, id]) =>\n\t\t\t\trow.map((arm): StudyTrial =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tid: `r${repetition + 1}-s${scenario + 1}-a${definition.arms.indexOf(arm) + 1}`,\n\t\t\t\t\t\tscenario: id,\n\t\t\t\t\t\tarm,\n\t\t\t\t\t\trepetition,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t)\n}\n\n/**\n * Validates grading coverage and request room against the declared study inputs.\n * @param definition - The population declaration\n * @param scenarios - The complete scenario declarations\n * @param rubric - The independently held grading declaration\n * @param profile - The execution bounds and model room\n * @returns Nothing when every cross-input invariant holds\n * @throws StudyError - Thrown when any input or cross-reference is invalid\n * @example\n * ```ts\n * validateStudyInputs(definition, scenarios, rubric, profile)\n * ```\n */\nexport function validateStudyInputs(\n\tdefinition: StudyDefinition,\n\tscenarios: readonly StudyScenario[],\n\trubric: StudyRubric,\n\tprofile: StudyProfile,\n): void {\n\tbuildStudySchedule(definition, scenarios)\n\tif (!isStudyRubric(rubric) || !isStudyProfile(profile))\n\t\tthrow new StudyError('CONFIG', 'Invalid rubric or profile')\n\tif (\n\t\tprofile.bounds.request.tokens > profile.room.context - profile.room.safety ||\n\t\tprofile.room.output > profile.bounds.request.tokens\n\t)\n\t\tthrow new StudyError('CONFIG', 'Request allowance does not fit the model room')\n\tfor (const criterion of rubric.criteria) {\n\t\tconst scenario = scenarios.find((entry) => entry.id === criterion.scenario)\n\t\tif (scenario === undefined || !scenario.goals.some((goal) => goal.id === criterion.goal))\n\t\t\tthrow new StudyError('CONFIG', 'Criterion references an undeclared goal')\n\t\tif (definition.purpose === 'mechanism' && criterion.method === 'semantic')\n\t\t\tthrow new StudyError('CONFIG', 'Mechanism studies cannot establish semantic quality')\n\t}\n\tconst covered = new Set(\n\t\trubric.criteria.map(\n\t\t\t(criterion) => canonicalStringify([criterion.scenario, criterion.goal]) ?? '',\n\t\t),\n\t)\n\tfor (const scenario of scenarios) {\n\t\tfor (const goal of scenario.goals) {\n\t\t\tif (!covered.has(canonicalStringify([scenario.id, goal.id]) ?? ''))\n\t\t\t\tthrow new StudyError('CONFIG', 'Every declared goal needs a criterion')\n\t\t}\n\t}\n}\n\n/**\n * Computes arm intervals over the complete declared criterion horizon.\n * @param manifest - The sealed population and schedule\n * @param rubric - The criterion declaration\n * @param grading - Judgments bound to the complete scheduled attempt set\n * @returns Whole-horizon scores in declared arm order\n * @throws StudyError - Thrown when schedule, attempts or judgments are incompatible\n * @example\n * ```ts\n * computeStudyScores(manifest, rubric, grading)\n * ```\n */\nexport function computeStudyScores(\n\tmanifest: StudyManifest,\n\trubric: StudyRubric,\n\tgrading: StudyGrading,\n): readonly StudyScore[] {\n\tif (!isStudyRubric(rubric) || !isStudyGrading(grading))\n\t\tthrow new StudyError('EVIDENCE', 'Invalid rubric or grading')\n\tconst expected = buildStudySchedule(manifest.definition, manifest.scenarios)\n\tif (canonicalStringify(expected) !== canonicalStringify(manifest.schedule))\n\t\tthrow new StudyError('EVIDENCE', 'Manifest schedule differs from the declared population')\n\tconst trials = new Map(expected.map((trial) => [trial.id, trial]))\n\tif (\n\t\tgrading.attempts.length !== expected.length ||\n\t\t!grading.attempts.every((id) => trials.has(id))\n\t)\n\t\tthrow new StudyError('EVIDENCE', 'Grading attempts differ from the declared schedule')\n\tconst criteria = new Map(rubric.criteria.map((criterion) => [criterion.id, criterion]))\n\tfor (const scenario of manifest.scenarios) {\n\t\tfor (const goal of scenario.goals) {\n\t\t\tif (\n\t\t\t\t!rubric.criteria.some(\n\t\t\t\t\t(criterion) => criterion.scenario === scenario.id && criterion.goal === goal.id,\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow new StudyError('EVIDENCE', 'Rubric omits a declared goal')\n\t\t}\n\t}\n\tfor (const criterion of rubric.criteria) {\n\t\tif (\n\t\t\t!manifest.scenarios.some(\n\t\t\t\t(scenario) =>\n\t\t\t\t\tscenario.id === criterion.scenario &&\n\t\t\t\t\tscenario.goals.some((goal) => goal.id === criterion.goal),\n\t\t\t) ||\n\t\t\t(manifest.definition.purpose === 'mechanism' && criterion.method === 'semantic')\n\t\t)\n\t\t\tthrow new StudyError('EVIDENCE', 'Criterion is incompatible with the study')\n\t}\n\tconst keyed = grading.judgments.map((judgment) => ({\n\t\tjudgment,\n\t\tkey: canonicalStringify([judgment.trial, judgment.criterion]) ?? '',\n\t}))\n\t// Reversed so the earliest index of each key is the one the lookup retains.\n\tconst firsts = new Map([...keyed.entries()].reverse().map(([index, { key }]) => [key, index]))\n\tfor (const [index, { judgment, key }] of keyed.entries()) {\n\t\tconst trial = trials.get(judgment.trial)\n\t\tconst criterion = criteria.get(judgment.criterion)\n\t\tif (\n\t\t\ttrial === undefined ||\n\t\t\tcriterion === undefined ||\n\t\t\tcriterion.scenario !== trial.scenario ||\n\t\t\tfirsts.get(key) !== index\n\t\t)\n\t\t\tthrow new StudyError('EVIDENCE', 'Duplicate or foreign trial criterion judgment')\n\t\tif (\n\t\t\tcriterion.method === 'semantic'\n\t\t\t\t? judgment.method !== 'human' && judgment.method !== 'model'\n\t\t\t\t: judgment.method !== criterion.method\n\t\t)\n\t\t\tthrow new StudyError('EVIDENCE', 'Judgment method differs from the criterion')\n\t}\n\tconst judgments = new Map(keyed.map(({ key, judgment }) => [key, judgment]))\n\treturn Object.freeze(\n\t\tmanifest.definition.arms.map((arm): StudyScore => {\n\t\t\tconst pairs = expected\n\t\t\t\t.filter((trial) => trial.arm === arm)\n\t\t\t\t.flatMap((trial) =>\n\t\t\t\t\trubric.criteria\n\t\t\t\t\t\t.filter((criterion) => criterion.scenario === trial.scenario)\n\t\t\t\t\t\t.map((criterion) => ({\n\t\t\t\t\t\t\tcriterion,\n\t\t\t\t\t\t\tjudgment: judgments.get(canonicalStringify([trial.id, criterion.id]) ?? ''),\n\t\t\t\t\t\t})),\n\t\t\t\t)\n\t\t\tconst refuted = pairs.filter(({ judgment }) => judgment?.verdict === 'unsuccessful')\n\t\t\tconst total = pairs.length\n\t\t\tconst achieved = pairs.filter(({ judgment }) => judgment?.verdict === 'achieved').length\n\t\t\tconst unsuccessful = refuted.length\n\t\t\tconst critical = refuted.filter(({ criterion }) => criterion.critical).length\n\t\t\tconst unknown = total - achieved - unsuccessful\n\t\t\treturn Object.freeze({\n\t\t\t\tarm,\n\t\t\t\ttotal,\n\t\t\t\tachieved,\n\t\t\t\tunsuccessful,\n\t\t\t\tunknown,\n\t\t\t\tcritical,\n\t\t\t\tlower: achieved / total,\n\t\t\t\tupper: (achieved + unknown) / total,\n\t\t\t\tcoverage: (achieved + unsuccessful) / total,\n\t\t\t})\n\t\t}),\n\t)\n}\n","import type {\n\tStudyBounds,\n\tStudyCause,\n\tStudyDefinition,\n\tStudyCriterion,\n\tStudyErrorCode,\n\tStudyGrading,\n\tStudyJudgment,\n\tStudyLabeling,\n\tStudyGoal,\n\tStudyLimit,\n\tStudyProduct,\n\tStudyProfile,\n\tStudyProvider,\n\tStudyLayer,\n\tStudyRole,\n\tStudyRoom,\n\tStudyScenario,\n\tStudyRubric,\n\tStudyStop,\n\tStudyUsage,\n} from './types.js'\nimport type { Guard } from '@orkestrel/contract'\nimport {\n\tholds,\n\tcanonicalStringify,\n\tisArray,\n\tisFiniteNumber,\n\tisJSONValue,\n\tisNonEmptyString,\n\tisRecord,\n\tliteralOf,\n} from '@orkestrel/contract'\nimport { MAX_TIMEOUT_MS } from '@orkestrel/timeout'\nimport {\n\tSTUDY_CAUSES,\n\tSTUDY_GOALS,\n\tSTUDY_LAYERS,\n\tSTUDY_NAME,\n\tSTUDY_ROLES,\n\tSTUDY_TRIALS,\n} from './constants.js'\nimport { matchesStudyKeys } from './helpers.js'\n\n/** Checks whether a value names a measured request role. */\nexport const isStudyRole: Guard<StudyRole> = literalOf(STUDY_ROLES)\n\n/** Checks whether a value names an operational ending. */\nexport const isStudyCause: Guard<StudyCause> = literalOf(STUDY_CAUSES)\n\n/** Checks whether a value names a ceiling a run can stop at. */\nexport const isStudyLayer: Guard<StudyLayer> = literalOf(STUDY_LAYERS)\n\n/**\n * Checks whether a value is the exact record of a ceiling that stopped a run.\n * @remarks\n * The guard accepts exact own data keys: `layer` and `id` are required and `max` and `consumed` are\n * optional. `max` and `consumed` are each undefined or a finite number. Finite foreign readings,\n * including negative and fractional values, retain the source's measurement unchanged.\n * @param value - The candidate stop\n * @returns True if the layer is known, the id is nonempty, and every reading is absent or finite; false otherwise\n * @example\n * ```ts\n * isStudyStop({ layer: 'scope', id: 'Goal tokens', max: 100, consumed: 120 }) // true\n * ```\n */\nexport function isStudyStop(value: unknown): value is StudyStop {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['layer', 'id'], ['max', 'consumed']) &&\n\t\t\tisStudyLayer(value.layer) &&\n\t\t\tisNonEmptyString(value.id) &&\n\t\t\t['max', 'consumed'].every((key) => value[key] === undefined || isFiniteNumber(value[key])),\n\t)\n}\n\n/**\n * Checks whether an identifier is portable and bounded.\n * @param value - The candidate identifier\n * @returns True if it is a portable study identifier; false otherwise\n * @example\n * ```ts\n * isStudyName('memory') // true\n * ```\n */\nexport function isStudyName(value: unknown): value is string {\n\treturn typeof value === 'string' && value.length <= 128 && STUDY_NAME.test(value)\n}\n\n/**\n * Checks whether all allowances are positive safe integers within timer bounds.\n * @param value - The candidate limit\n * @returns True if it defines finite positive allowances; false otherwise\n * @example\n * ```ts\n * isStudyLimit({ duration: 1000, calls: 1, tokens: 100, bytes: 1024 }) // true\n * ```\n */\nexport function isStudyLimit(value: unknown): value is StudyLimit {\n\treturn holds(() => {\n\t\tif (!isRecord(value) || !matchesStudyKeys(value, ['duration', 'calls', 'tokens', 'bytes']))\n\t\t\treturn false\n\t\treturn (\n\t\t\t['duration', 'calls', 'tokens', 'bytes'].every(\n\t\t\t\t(key) =>\n\t\t\t\t\ttypeof value[key] === 'number' && Number.isSafeInteger(value[key]) && value[key] > 0,\n\t\t\t) &&\n\t\t\ttypeof value.duration === 'number' &&\n\t\t\tvalue.duration <= MAX_TIMEOUT_MS\n\t\t)\n\t})\n}\n\n/**\n * Checks whether nested scopes admit no larger allowance than their parent.\n * @param value - The candidate bounds\n * @returns True if every nested allowance is ordered; false otherwise\n * @example\n * ```ts\n * isStudyBounds({}) // false\n * ```\n */\nexport function isStudyBounds(value: unknown): value is StudyBounds {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(value, ['request', 'goal', 'trial', 'series']) ||\n\t\t\t!isStudyLimit(value.request) ||\n\t\t\t!isStudyLimit(value.goal) ||\n\t\t\t!isStudyLimit(value.trial) ||\n\t\t\t!isStudyLimit(value.series)\n\t\t)\n\t\t\treturn false\n\t\tconst limits = [value.request, value.goal, value.trial, value.series]\n\t\tfor (const [index, limit] of limits.entries()) {\n\t\t\tconst next = limits[index + 1]\n\t\t\tif (next === undefined) continue\n\t\t\tif (\n\t\t\t\tlimit.duration > next.duration ||\n\t\t\t\tlimit.calls > next.calls ||\n\t\t\t\tlimit.tokens > next.tokens ||\n\t\t\t\tlimit.bytes > next.bytes\n\t\t\t)\n\t\t\t\treturn false\n\t\t}\n\t\treturn value.request.calls === 1\n\t})\n}\n\n/**\n * Checks whether a goal has a bounded identifier and exact JSON input.\n * @param value - The candidate goal\n * @returns True if the goal is valid; false otherwise\n * @example\n * ```ts\n * isStudyGoal({ id: 'write', input: { text: 'hello' } }) // true\n * ```\n */\nexport function isStudyGoal(value: unknown): value is StudyGoal {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['id', 'input']) &&\n\t\t\tisStudyName(value.id) &&\n\t\t\tisJSONValue(value.input)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a scenario declares a nonempty horizon with unique goal ids.\n * @param value - The candidate scenario\n * @returns True if the scenario has a valid horizon; false otherwise\n * @example\n * ```ts\n * isStudyScenario({ id: 'shift', goals: [{ id: 'handoff', input: 'Prepare handoff' }] }) // true\n * ```\n */\nexport function isStudyScenario(value: unknown): value is StudyScenario {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(value, ['id', 'goals']) ||\n\t\t\t!isStudyName(value.id) ||\n\t\t\t!isArray(value.goals)\n\t\t)\n\t\t\treturn false\n\t\treturn (\n\t\t\tvalue.goals.length > 0 &&\n\t\t\tvalue.goals.length <= STUDY_GOALS &&\n\t\t\tvalue.goals.every(isStudyGoal) &&\n\t\t\tnew Set(value.goals.map((goal) => goal.id)).size === value.goals.length &&\n\t\t\tisJSONValue(value.goals)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a study freezes a complete arm order for every repetition.\n * @param value - The candidate definition\n * @returns True if its population and repetition orders are valid; false otherwise\n * @example\n * ```ts\n * isStudyDefinition({ name: 'tools' }) // false\n * ```\n */\nexport function isStudyDefinition(value: unknown): value is StudyDefinition {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!isJSONValue(value) ||\n\t\t\t!matchesStudyKeys(value, [\n\t\t\t\t'name',\n\t\t\t\t'version',\n\t\t\t\t'question',\n\t\t\t\t'purpose',\n\t\t\t\t'driver',\n\t\t\t\t'arms',\n\t\t\t\t'scenarios',\n\t\t\t\t'order',\n\t\t\t\t'retries',\n\t\t\t\t'rubric',\n\t\t\t]) ||\n\t\t\t!isStudyName(value.name) ||\n\t\t\t!isStudyName(value.driver) ||\n\t\t\t!isNonEmptyString(value.version) ||\n\t\t\t!isNonEmptyString(value.question) ||\n\t\t\t(value.purpose !== 'mechanism' &&\n\t\t\t\tvalue.purpose !== 'quality' &&\n\t\t\t\tvalue.purpose !== 'capacity') ||\n\t\t\t!isArray(value.arms) ||\n\t\t\tvalue.arms.length === 0 ||\n\t\t\t!value.arms.every(isStudyName) ||\n\t\t\tnew Set(value.arms).size !== value.arms.length ||\n\t\t\t!isArray(value.scenarios) ||\n\t\t\tvalue.scenarios.length === 0 ||\n\t\t\t!value.scenarios.every(isStudyName) ||\n\t\t\tnew Set(value.scenarios).size !== value.scenarios.length ||\n\t\t\t!isArray(value.order) ||\n\t\t\t!isJSONValue(value.order) ||\n\t\t\tvalue.order.length === 0 ||\n\t\t\tvalue.retries !== 0 ||\n\t\t\t!isNonEmptyString(value.rubric)\n\t\t)\n\t\t\treturn false\n\t\tconst arms = value.arms\n\t\tif (arms.length * value.scenarios.length * value.order.length > STUDY_TRIALS) return false\n\t\treturn value.order.every(\n\t\t\t(order) =>\n\t\t\t\tisArray(order) &&\n\t\t\t\torder.length === arms.length &&\n\t\t\t\tnew Set(order).size === arms.length &&\n\t\t\t\torder.every((arm) => typeof arm === 'string' && arms.includes(arm)),\n\t\t)\n\t})\n}\n\n/**\n * Checks whether generation room leaves positive context for input.\n * @param value - The candidate room\n * @returns True if input, output and safety allowances fit and any declared recap fits; false otherwise\n * @example\n * ```ts\n * isStudyRoom({ context: 20480, output: 8192, safety: 512, recap: 2048, think: true }) // true\n * isStudyRoom({ context: 20480, output: 8192, safety: 512, think: true }) // true\n * ```\n */\nexport function isStudyRoom(value: unknown): value is StudyRoom {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(value, ['context', 'output', 'safety', 'think'], ['recap']) ||\n\t\t\ttypeof value.think !== 'boolean'\n\t\t)\n\t\t\treturn false\n\t\tconst declared = value.recap === undefined ? [] : ['recap']\n\t\tif (\n\t\t\t!['context', 'output', 'safety', ...declared].every(\n\t\t\t\t(key) =>\n\t\t\t\t\ttypeof value[key] === 'number' && Number.isSafeInteger(value[key]) && value[key] > 0,\n\t\t\t)\n\t\t)\n\t\t\treturn false\n\t\treturn (\n\t\t\ttypeof value.context === 'number' &&\n\t\t\ttypeof value.output === 'number' &&\n\t\t\ttypeof value.safety === 'number' &&\n\t\t\tvalue.output + value.safety < value.context &&\n\t\t\t(value.recap === undefined ||\n\t\t\t\t(typeof value.recap === 'number' && value.recap + value.safety < value.context))\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a provider declaration names artifacts, an HTTP origin and models.\n * @param value - The candidate provider declaration\n * @returns True if the declaration has a supported origin, nonempty names, and a judge declared with its digest or not at all; false otherwise\n * @example\n * ```ts\n * isStudyProvider({ entry: 'dist/index.js' }) // false\n * ```\n */\nexport function isStudyProvider(value: unknown): value is StudyProvider {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(value, ['entry', 'url', 'model', 'digest'], ['judge']) ||\n\t\t\t!['entry', 'url', 'model'].every((key) => isNonEmptyString(value[key])) ||\n\t\t\ttypeof value.url !== 'string' ||\n\t\t\t!isRecord(value.digest) ||\n\t\t\t!matchesStudyKeys(value.digest, ['model'], ['judge']) ||\n\t\t\t!isStudyDigest(value.digest.model) ||\n\t\t\t(value.judge === undefined) !== (value.digest.judge === undefined) ||\n\t\t\t(value.judge !== undefined &&\n\t\t\t\t(!isNonEmptyString(value.judge) || !isStudyDigest(value.digest.judge)))\n\t\t)\n\t\t\treturn false\n\t\tconst url = new URL(value.url)\n\t\treturn (\n\t\t\t['http:', 'https:'].includes(url.protocol) &&\n\t\t\turl.username === '' &&\n\t\t\turl.password === '' &&\n\t\t\turl.search === '' &&\n\t\t\turl.hash === '' &&\n\t\t\turl.pathname === '/'\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a profile carries finite bounds and an optional explicit provider.\n * @param value - The candidate profile\n * @returns True if the profile is structurally valid; false otherwise\n * @example\n * ```ts\n * isStudyProfile({ name: 'local' }) // false\n * ```\n */\nexport function isStudyProfile(value: unknown): value is StudyProfile {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(\n\t\t\t\tvalue,\n\t\t\t\t['name', 'agent', 'subject', 'roots', 'bounds', 'room'],\n\t\t\t\t['provider', 'qualification', 'settings'],\n\t\t\t) &&\n\t\t\tisStudyName(value.name) &&\n\t\t\tisNonEmptyString(value.agent) &&\n\t\t\tisArray(value.roots) &&\n\t\t\tisJSONValue(value.roots) &&\n\t\t\tvalue.roots.length > 0 &&\n\t\t\tvalue.roots.every((root) => typeof root === 'string' && root.trim().length > 0) &&\n\t\t\tnew Set(value.roots).size === value.roots.length &&\n\t\t\tisNonEmptyString(value.subject) &&\n\t\t\tisStudyBounds(value.bounds) &&\n\t\t\tisStudyRoom(value.room) &&\n\t\t\t(value.provider === undefined || isStudyProvider(value.provider)) &&\n\t\t\t(value.qualification === undefined || isNonEmptyString(value.qualification)) &&\n\t\t\t(value.settings === undefined || (isRecord(value.settings) && isJSONValue(value.settings)))\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a byte identity is a lowercase SHA-256 digest.\n * @param value - The candidate identity\n * @returns True if it has exactly 64 hexadecimal digits; false otherwise\n * @example\n * ```ts\n * isStudyDigest('a'.repeat(64)) // true\n * ```\n */\nexport function isStudyDigest(value: unknown): value is string {\n\treturn typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)\n}\n\n/**\n * Checks whether a timestamp is a canonical UTC millisecond instant.\n * @param value - The candidate timestamp\n * @returns True if it is a valid canonical timestamp; false otherwise\n * @example\n * ```ts\n * isStudyTimestamp('2026-10-14T12:00:00.000Z') // true\n * ```\n */\nexport function isStudyTimestamp(value: unknown): value is string {\n\treturn holds(() => {\n\t\treturn (\n\t\t\ttypeof value === 'string' &&\n\t\t\t/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/.test(value) &&\n\t\t\tnew Date(value).toISOString() === value\n\t\t)\n\t})\n}\n\n/**\n * Checks whether request usage contains nonnegative safe measurements.\n * @param value - The candidate usage\n * @returns True if the role and every known measurement are valid; false otherwise\n * @example\n * ```ts\n * isStudyUsage({ role: 'tool', calls: 0, bytes: 0, duration: 0 }) // true\n * ```\n */\nexport function isStudyUsage(value: unknown): value is StudyUsage {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['role', 'calls', 'duration'], ['tokens', 'bytes']) &&\n\t\t\tisStudyRole(value.role) &&\n\t\t\t['calls', 'duration'].every(\n\t\t\t\t(key) =>\n\t\t\t\t\ttypeof value[key] === 'number' && Number.isSafeInteger(value[key]) && value[key] >= 0,\n\t\t\t) &&\n\t\t\t(value.bytes === undefined ||\n\t\t\t\t(typeof value.bytes === 'number' &&\n\t\t\t\t\tNumber.isSafeInteger(value.bytes) &&\n\t\t\t\t\tvalue.bytes >= 0)) &&\n\t\t\t(value.tokens === undefined ||\n\t\t\t\t(typeof value.tokens === 'number' &&\n\t\t\t\t\tNumber.isSafeInteger(value.tokens) &&\n\t\t\t\t\tvalue.tokens >= 0))\n\t\t)\n\t})\n}\n\n/**\n * Checks a retained public product without awarding task achievement.\n * @param value - The candidate product\n * @returns True if the product carries JSON output and partial status; false otherwise\n * @example\n * ```ts\n * isStudyProduct({ value: { answer: 1 }, partial: true }) // true\n * ```\n */\nexport function isStudyProduct(value: unknown): value is StudyProduct {\n\treturn holds(\n\t\t() => isRecord(value) && typeof value.partial === 'boolean' && isJSONValue(value.value),\n\t)\n}\n\n/**\n * Checks whether a criterion declares exact grading inputs and references.\n * @param value - The candidate criterion\n * @returns True if its structural grading declaration is valid; false otherwise\n * @example\n * ```ts\n * isStudyCriterion({ id: 'saved', scenario: 'shift', goal: 'write', method: 'state', critical: true, assertion: true }) // true\n * ```\n */\nexport function isStudyCriterion(value: unknown): value is StudyCriterion {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['id', 'scenario', 'goal', 'method', 'critical', 'assertion']) &&\n\t\t\tisStudyName(value.id) &&\n\t\t\tisStudyName(value.scenario) &&\n\t\t\tisStudyName(value.goal) &&\n\t\t\t(value.method === 'state' || value.method === 'trace' || value.method === 'semantic') &&\n\t\t\ttypeof value.critical === 'boolean' &&\n\t\t\tisJSONValue(value.assertion)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a rubric declares nonempty criteria with unique identities.\n * @param value - The candidate rubric\n * @returns True if its version and criteria are valid; false otherwise\n * @example\n * ```ts\n * isStudyRubric({ version: '1', criteria: [] }) // false\n * ```\n */\nexport function isStudyRubric(value: unknown): value is StudyRubric {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['version', 'criteria']) &&\n\t\t\ttypeof value.version === 'string' &&\n\t\t\tvalue.version.trim().length > 0 &&\n\t\t\tisArray(value.criteria) &&\n\t\t\tvalue.criteria.length > 0 &&\n\t\t\tvalue.criteria.every(isStudyCriterion) &&\n\t\t\tnew Set(value.criteria.map((criterion) => criterion.id)).size === value.criteria.length &&\n\t\t\tisJSONValue(value.criteria)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a judgment carries a supported verdict and evidence references.\n * @param value - The candidate judgment\n * @returns True if the judgment is attributable and structurally valid; false otherwise\n * @example\n * ```ts\n * isStudyJudgment({ trial: 'r1-s1-a1', criterion: 'saved', verdict: 'unknown', method: 'state', reason: 'No evidence', references: [] }) // true\n * ```\n */\nexport function isStudyJudgment(value: unknown): value is StudyJudgment {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, [\n\t\t\t\t'trial',\n\t\t\t\t'criterion',\n\t\t\t\t'verdict',\n\t\t\t\t'method',\n\t\t\t\t'reason',\n\t\t\t\t'references',\n\t\t\t]) &&\n\t\t\tisStudyName(value.trial) &&\n\t\t\tisStudyName(value.criterion) &&\n\t\t\t(value.verdict === 'achieved' ||\n\t\t\t\tvalue.verdict === 'unsuccessful' ||\n\t\t\t\tvalue.verdict === 'unknown') &&\n\t\t\t(value.method === 'state' ||\n\t\t\t\tvalue.method === 'trace' ||\n\t\t\t\tvalue.method === 'human' ||\n\t\t\t\tvalue.method === 'model') &&\n\t\t\ttypeof value.reason === 'string' &&\n\t\t\tvalue.reason.trim().length > 0 &&\n\t\t\tisArray(value.references) &&\n\t\t\tisJSONValue(value.references) &&\n\t\t\tvalue.references.every(\n\t\t\t\t(reference) => typeof reference === 'string' && reference.trim().length > 0,\n\t\t\t) &&\n\t\t\tnew Set(value.references).size === value.references.length &&\n\t\t\t(value.verdict === 'unknown' || value.references.length > 0)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether imported semantic labels have accountable packet provenance.\n * @param value - The candidate labels\n * @returns True if provenance, usage and semantic judgments are valid; false otherwise\n * @example\n * ```ts\n * isStudyLabeling({}) // false\n * ```\n */\nexport function isStudyLabeling(value: unknown): value is StudyLabeling {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['packet', 'labeler', 'version', 'created', 'usage', 'judgments']) &&\n\t\t\tisStudyDigest(value.packet) &&\n\t\t\ttypeof value.labeler === 'string' &&\n\t\t\tvalue.labeler.trim().length > 0 &&\n\t\t\ttypeof value.version === 'string' &&\n\t\t\tvalue.version.trim().length > 0 &&\n\t\t\tisStudyTimestamp(value.created) &&\n\t\t\tisArray(value.usage) &&\n\t\t\tReflect.ownKeys(value.usage).length === value.usage.length + 1 &&\n\t\t\tArray.from(value.usage).every(isStudyUsage) &&\n\t\t\tisArray(value.judgments) &&\n\t\t\tvalue.judgments.every(isStudyJudgment) &&\n\t\t\tvalue.judgments.every(\n\t\t\t\t(judgment) => judgment.method === 'human' || judgment.method === 'model',\n\t\t\t) &&\n\t\t\tnew Set(\n\t\t\t\tvalue.judgments.map((judgment) => canonicalStringify([judgment.trial, judgment.criterion])),\n\t\t\t).size === value.judgments.length &&\n\t\t\tisJSONValue(value.judgments)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a value names a supported study error code.\n * @param value - The candidate code\n * @returns True if it is a declared study error code; false otherwise\n * @example\n * ```ts\n * isStudyErrorCode('CONFIG') // true\n * ```\n */\nexport function isStudyErrorCode(value: unknown): value is StudyErrorCode {\n\treturn (\n\t\tvalue === 'CONFIG' ||\n\t\tvalue === 'EVIDENCE' ||\n\t\tvalue === 'CUSTODY' ||\n\t\tvalue === 'CAPACITY' ||\n\t\tvalue === 'FAULT' ||\n\t\tvalue === 'DEADLINE'\n\t)\n}\n\n/**\n * Checks whether grading binds accountable judgments to unique attempt identities.\n * @param value - The candidate grading\n * @returns True if its identities, attempts and judgments are valid; false otherwise\n * @example\n * ```ts\n * isStudyGrading({}) // false\n * ```\n */\nexport function isStudyGrading(value: unknown): value is StudyGrading {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(\n\t\t\t\tvalue,\n\t\t\t\t['result', 'rubric', 'grader', 'instrument', 'attempts', 'judgments'],\n\t\t\t\t['labels', 'packet'],\n\t\t\t) &&\n\t\t\tisStudyDigest(value.result) &&\n\t\t\tisStudyDigest(value.rubric) &&\n\t\t\tisStudyDigest(value.instrument) &&\n\t\t\ttypeof value.grader === 'string' &&\n\t\t\tvalue.grader.trim().length > 0 &&\n\t\t\t(value.labels === undefined || isStudyDigest(value.labels)) &&\n\t\t\t(value.packet === undefined || isStudyDigest(value.packet)) &&\n\t\t\tisArray(value.attempts) &&\n\t\t\tisJSONValue(value.attempts) &&\n\t\t\tvalue.attempts.every(isStudyName) &&\n\t\t\tnew Set(value.attempts).size === value.attempts.length &&\n\t\t\tisArray(value.judgments) &&\n\t\t\tvalue.judgments.every(isStudyJudgment) &&\n\t\t\tnew Set(\n\t\t\t\tvalue.judgments.map((judgment) => canonicalStringify([judgment.trial, judgment.criterion])),\n\t\t\t).size === value.judgments.length &&\n\t\t\tisJSONValue(value.judgments)\n\t\t)\n\t})\n}\n","import type { StudyErrorCode, StudyFailure } from './types.js'\nimport { holds, isError } from '@orkestrel/contract'\nimport { STUDY_ERROR_BRAND } from './constants.js'\nimport { isStudyErrorCode } from './validators.js'\n\n/** Reports a study contract or operational failure with a stable code. */\nexport class StudyError extends Error {\n\treadonly code: StudyErrorCode\n\treadonly failure: StudyFailure | undefined\n\n\t/**\n\t * Records the failing boundary and optional operational attribution.\n\t * @param code - The machine-readable boundary\n\t * @param message - The specific failure\n\t * @param failure - The optional operational reading\n\t */\n\tconstructor(code: StudyErrorCode, message: string, failure?: StudyFailure) {\n\t\tsuper(message)\n\t\tObject.defineProperty(this, STUDY_ERROR_BRAND, { value: this, configurable: true })\n\t\tthis.name = 'StudyError'\n\t\tthis.code = code\n\t\tthis.failure = failure\n\t}\n}\n\n/**\n * Narrows a caught value to an attributable study error.\n * @remarks\n * Recognition combines the native `Error` base, a subclass prototype, the fixed name, a declared\n * study code, and an own {@link STUDY_ERROR_BRAND} descriptor whose value is the error itself.\n * The global key is recognized across package, ESM, CommonJS and captured module copies; it is\n * not unforgeable provenance. A transparent proxy is refused because its forwarded descriptor\n * stores the target, and an unbranded copy, an inherited brand, or a property-only lookalike\n * stays outside the type. Hostile property access returns false instead of throwing.\n * @param value - The caught value\n * @returns True if the value is a study error; false otherwise\n * @example\n * ```ts\n * isStudyError(new StudyError('CONFIG', 'missing definition')) // true\n * ```\n */\nexport function isStudyError(value: unknown): value is StudyError {\n\treturn (\n\t\tisError(value) &&\n\t\tholds(\n\t\t\t() =>\n\t\t\t\tObject.getPrototypeOf(value) !== Error.prototype &&\n\t\t\t\tvalue.name === 'StudyError' &&\n\t\t\t\tObject.getOwnPropertyDescriptor(value, STUDY_ERROR_BRAND)?.value === value &&\n\t\t\t\t'code' in value &&\n\t\t\t\tisStudyErrorCode(value.code),\n\t\t)\n\t)\n}\n","import type {\n\tStudyDefinition,\n\tStudyGrading,\n\tStudyLabeling,\n\tStudyProfile,\n\tStudyRubric,\n\tStudyScenario,\n} from './types.js'\nimport { cloneJSONValue, isFiniteNumber } from '@orkestrel/contract'\nimport { StudyError } from './errors.js'\nimport { normalizeStudyProfile } from './helpers.js'\nimport {\n\tisStudyDefinition,\n\tisStudyGrading,\n\tisStudyLabeling,\n\tisStudyProfile,\n\tisStudyRubric,\n\tisStudyScenario,\n} from './validators.js'\n\n/**\n * Parses a foreign reading into a number a stop can retain.\n * @param value - The unknown reading a source reports\n * @returns The value when it is a finite number; undefined otherwise\n * @example\n * ```ts\n * parseStudyReading(2048) // 2048\n * parseStudyReading(Number.NaN) // undefined\n * ```\n */\nexport function parseStudyReading(value: unknown): number | undefined {\n\treturn isFiniteNumber(value) ? value : undefined\n}\n\n/**\n * Parses a definition into an independent frozen validated snapshot.\n * @param value - The unknown configuration\n * @returns The owned study definition\n * @throws StudyError - Thrown when configuration is invalid or cannot be owned\n * @example\n * ```ts\n * parseStudyDefinition(configuration)\n * ```\n */\nexport function parseStudyDefinition(value: unknown): StudyDefinition {\n\ttry {\n\t\tif (!isStudyDefinition(value)) throw new StudyError('CONFIG', 'Invalid study definition')\n\t\tconst snapshot = cloneJSONValue(value)\n\t\tif (isStudyDefinition(snapshot)) return snapshot\n\t} catch {\n\t\tthrow new StudyError('CONFIG', 'Invalid or unreadable study definition')\n\t}\n\tthrow new StudyError('CONFIG', 'Invalid study definition snapshot')\n}\n\n/**\n * Parses a scenario into an independent frozen validated snapshot.\n * @param value - The unknown configuration\n * @returns The owned scenario and goal inputs\n * @throws StudyError - Thrown when configuration is invalid or cannot be owned\n * @example\n * ```ts\n * parseStudyScenario({ id: 'shift', goals: [{ id: 'write', input: {} }] })\n * ```\n */\nexport function parseStudyScenario(value: unknown): StudyScenario {\n\ttry {\n\t\tif (!isStudyScenario(value)) throw new StudyError('CONFIG', 'Invalid study scenario')\n\t\tconst snapshot = cloneJSONValue(value)\n\t\tif (isStudyScenario(snapshot)) return snapshot\n\t} catch {\n\t\tthrow new StudyError('CONFIG', 'Invalid or unreadable study scenario')\n\t}\n\tthrow new StudyError('CONFIG', 'Invalid study scenario snapshot')\n}\n\n/**\n * Parses a profile into an independent frozen validated snapshot.\n * @param value - The unknown configuration\n * @returns The owned profile with absent optional settings preserved\n * @throws StudyError - Thrown when configuration is invalid or cannot be owned\n * @example\n * ```ts\n * parseStudyProfile(configuration)\n * ```\n */\nexport function parseStudyProfile(value: unknown): StudyProfile {\n\ttry {\n\t\tif (!isStudyProfile(value)) throw new StudyError('CONFIG', 'Invalid study profile')\n\t\tconst snapshot = cloneJSONValue(normalizeStudyProfile(value))\n\t\tif (isStudyProfile(snapshot)) return snapshot\n\t} catch {\n\t\tthrow new StudyError('CONFIG', 'Invalid or unreadable study profile')\n\t}\n\tthrow new StudyError('CONFIG', 'Invalid study profile snapshot')\n}\n\n/**\n * Parses a rubric into an independent frozen validated snapshot.\n * @param value - The unknown grading declaration\n * @returns The owned rubric and assertion inputs\n * @throws StudyError - Thrown when configuration is invalid or cannot be owned\n * @example\n * ```ts\n * parseStudyRubric(configuration)\n * ```\n */\nexport function parseStudyRubric(value: unknown): StudyRubric {\n\ttry {\n\t\tif (!isStudyRubric(value)) throw new StudyError('CONFIG', 'Invalid study rubric')\n\t\tconst snapshot = cloneJSONValue(value)\n\t\tif (isStudyRubric(snapshot)) return snapshot\n\t} catch {\n\t\tthrow new StudyError('CONFIG', 'Invalid or unreadable study rubric')\n\t}\n\tthrow new StudyError('CONFIG', 'Invalid study rubric snapshot')\n}\n\n/**\n * Parses grading into an independent frozen validated evidence snapshot.\n * @param value - The unknown grading evidence\n * @returns The owned grading identity and judgments\n * @throws StudyError - Thrown when evidence is invalid or cannot be owned\n * @example\n * ```ts\n * parseStudyGrading(evidence)\n * ```\n */\nexport function parseStudyGrading(value: unknown): StudyGrading {\n\ttry {\n\t\tif (!isStudyGrading(value)) throw new StudyError('EVIDENCE', 'Invalid study grading')\n\t\tconst { labels, packet, ...required } = value\n\t\tconst snapshot = cloneJSONValue({\n\t\t\t...required,\n\t\t\t...(labels === undefined ? {} : { labels }),\n\t\t\t...(packet === undefined ? {} : { packet }),\n\t\t})\n\t\tif (isStudyGrading(snapshot)) return snapshot\n\t} catch {\n\t\tthrow new StudyError('EVIDENCE', 'Invalid or unreadable study grading')\n\t}\n\tthrow new StudyError('EVIDENCE', 'Invalid study grading snapshot')\n}\n\n/**\n * Parses semantic labels into an independent frozen validated evidence snapshot.\n * @param value - The unknown imported labels\n * @returns The owned packet provenance, usage and judgments\n * @throws StudyError - Thrown when evidence is invalid or cannot be owned\n * @example\n * ```ts\n * parseStudyLabeling(evidence)\n * ```\n */\nexport function parseStudyLabeling(value: unknown): StudyLabeling {\n\ttry {\n\t\tif (!isStudyLabeling(value)) throw new StudyError('EVIDENCE', 'Invalid study labels')\n\t\tconst snapshot = cloneJSONValue({\n\t\t\t...value,\n\t\t\tusage: value.usage.map(({ tokens, bytes, ...usage }) => ({\n\t\t\t\t...usage,\n\t\t\t\t...(tokens === undefined ? {} : { tokens }),\n\t\t\t\t...(bytes === undefined ? {} : { bytes }),\n\t\t\t})),\n\t\t})\n\t\tif (isStudyLabeling(snapshot)) return snapshot\n\t} catch {\n\t\tthrow new StudyError('EVIDENCE', 'Invalid or unreadable study labels')\n\t}\n\tthrow new StudyError('EVIDENCE', 'Invalid study labels snapshot')\n}\n","import type { BudgetInterface } from '@orkestrel/budget'\nimport type {\n\tStudyCharge,\n\tStudyFailure,\n\tStudyRole,\n\tStudyStop,\n\tStudyTicket,\n\tStudyUsage,\n} from '../types.js'\nimport { isBudgetError } from '@orkestrel/budget'\nimport { attempt, isError, isNonEmptyString } from '@orkestrel/contract'\nimport { isStudyError, StudyError } from '../errors.js'\nimport { parseStudyReading } from '../parsers.js'\n\n/** Converts an operational reading to its throwable boundary.\n * @param failure - The retained operational reading.\n * @returns An error preserving the reading's cause and responsibility.\n */\nexport function failureToStudyError(failure: StudyFailure): StudyError {\n\treturn new StudyError(\n\t\tfailure.cause === 'capacity' ? 'CAPACITY' : failure.cause === 'deadline' ? 'DEADLINE' : 'FAULT',\n\t\tfailure.message,\n\t\tfailure,\n\t)\n}\n\n/** Reads an operational error without inventing a task verdict.\n * @remarks\n * A branded `BudgetError` from any copy of the budget package reads as a `budget` stop, because the\n * error alone does not prove which budget object raised it; the Agent record names a `meter` stop.\n * An unbranded lookalike reads as an infrastructure failure.\n * @param error - The caught error.\n * @returns Existing attribution, the capacity a branded budget error names, the cause a bare\n * capacity or deadline code names, or an infrastructure failure.\n */\nexport function readStudyFailure(error: unknown): StudyFailure {\n\tif (isStudyError(error)) {\n\t\tconst { failure, code, message } = error\n\t\tif (failure !== undefined) return failure\n\t\tif (code === 'CAPACITY') return { cause: 'capacity', message, role: undefined, stop: undefined }\n\t\tif (code === 'DEADLINE') return { cause: 'deadline', message, role: undefined, stop: undefined }\n\t}\n\tif (isBudgetError(error)) {\n\t\tconst reading = attempt(() => {\n\t\t\tconst context = error.context\n\t\t\treturn {\n\t\t\t\tid: context.id,\n\t\t\t\tmax: context.max,\n\t\t\t\tconsumed: context.consumed,\n\t\t\t\tmessage: error.message,\n\t\t\t}\n\t\t})\n\t\tif (reading.success)\n\t\t\treturn {\n\t\t\t\tcause: 'capacity',\n\t\t\t\tmessage: reading.value.message,\n\t\t\t\trole: undefined,\n\t\t\t\tstop: {\n\t\t\t\t\tlayer: 'budget',\n\t\t\t\t\tid: isNonEmptyString(reading.value.id) ? reading.value.id : 'Agent budget',\n\t\t\t\t\tmax: parseStudyReading(reading.value.max),\n\t\t\t\t\tconsumed: parseStudyReading(reading.value.consumed),\n\t\t\t\t},\n\t\t\t}\n\t}\n\treturn {\n\t\tcause: 'infrastructure',\n\t\tmessage: isError(error) ? error.message : 'Study operation rejected without an Error',\n\t\trole: undefined,\n\t\tstop: undefined,\n\t}\n}\n\n/**\n * Computes the stop of a request whose actual usage crossed the ceiling it was admitted under.\n * @param charge - The request's admitted ceilings\n * @param usage - The request's measured usage\n * @returns The `scope` stop for the first quantity, tokens then bytes, whose known usage exceeds its admitted ceiling; undefined when none does\n * @example\n * ```ts\n * computeStudyAdmittedStop({ role: 'agent', tokens: 10, bytes: 100 }, usage) // { layer: 'scope', id: 'Admitted tokens', max: 10, consumed: 12 }\n * ```\n */\nexport function computeStudyAdmittedStop(\n\tcharge: StudyCharge,\n\tusage: StudyUsage,\n): StudyStop | undefined {\n\tif (usage.tokens !== undefined && usage.tokens > charge.tokens)\n\t\treturn { layer: 'scope', id: 'Admitted tokens', max: charge.tokens, consumed: usage.tokens }\n\tif (usage.bytes !== undefined && usage.bytes > charge.bytes)\n\t\treturn { layer: 'scope', id: 'Admitted bytes', max: charge.bytes, consumed: usage.bytes }\n\treturn undefined\n}\n\n/**\n * Computes the stop of a product the output allowances cannot hold.\n * @param bytes - The encoded size of the product's value\n * @param limit - The goal's byte allowance\n * @param outputs - The trial and series output budgets, in the order they refuse\n * @returns The `Goal bytes` stop when the goal allowance refuses, else the stop of the first budget whose remaining room is below the product, with its tally including the refused product; undefined when every allowance holds it\n * @example\n * ```ts\n * computeStudyOutputStop(2048, 1024, []) // { layer: 'scope', id: 'Goal bytes', max: 1024, consumed: 2048 }\n * ```\n */\nexport function computeStudyOutputStop(\n\tbytes: number,\n\tlimit: number,\n\toutputs: ReadonlyArray<BudgetInterface<number>>,\n): StudyStop | undefined {\n\tif (bytes > limit) return { layer: 'scope', id: 'Goal bytes', max: limit, consumed: bytes }\n\tconst refusal = outputs.find((budget) => bytes > budget.remaining)\n\treturn refusal === undefined\n\t\t? undefined\n\t\t: { layer: 'scope', id: refusal.id, max: refusal.max, consumed: refusal.consumed + bytes }\n}\n\n/**\n * Records an error that escaped admitted work as the failure of its ticket.\n * @param ticket - The admitted request whose work escaped\n * @param error - The caught value, read through `readStudyFailure`\n * @param role - The responsibility that replaces any role the reading carries; Default: the carried role, else the ticket's admitted role\n * @remarks\n * A ticket that already settled or whose signal aborted is left untouched, because its owner\n * already holds the failure. A remote ticket's aborted signal does not mean it settled locally,\n * so the parent's ownership is respected rather than inferred as local settlement. A refusal\n * thrown by the ticket's own settlement propagates.\n * @throws Thrown when the ticket's settlement refuses the failure.\n * @example Fail an escaped request\n * ```ts\n * import type { StudyTicket } from '@orkestrel/study'\n * import { failStudyTicket } from '@orkestrel/study'\n *\n * declare const ticket: StudyTicket\n *\n * failStudyTicket(ticket, new Error('Provider refused'), 'tool')\n * ```\n */\nexport function failStudyTicket(ticket: StudyTicket, error: unknown, role?: StudyRole): void {\n\tif (ticket.settled || ticket.signal.aborted) return\n\tconst failure = readStudyFailure(error)\n\tticket.fail(role === undefined ? failure : { ...failure, role })\n}\n","import type { StudyFailure } from '../types.js'\nimport type { StudyControlInterface } from './types.js'\nimport { Abort } from '@orkestrel/abort'\nimport { failureToStudyError } from './helpers.js'\n\n/** Retains the first operational failure while bounding asynchronous waits. */\nexport class StudyControl implements StudyControlInterface {\n\t#abort: Abort\n\t#listeners = new Abort()\n\t#failure: StudyFailure | undefined\n\n\t/** Links cancellation to the caller without assigning it a task verdict.\n\t * @param signal - Optional parent cancellation.\n\t */\n\tconstructor(signal?: AbortSignal) {\n\t\tthis.#abort = new Abort(signal === undefined ? undefined : { signal })\n\t\tif (this.#abort.aborted) this.#interrupt()\n\t\telse\n\t\t\tthis.#abort.signal.addEventListener('abort', () => this.#interrupt(), {\n\t\t\t\tonce: true,\n\t\t\t\tsignal: this.#listeners.signal,\n\t\t\t})\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.#abort.signal\n\t}\n\tget failure(): StudyFailure | undefined {\n\t\treturn this.#failure\n\t}\n\n\t/** Latches an operational failure and cancels all linked work.\n\t * @param failure - The first attribution to preserve.\n\t */\n\tfail(failure: StudyFailure): void {\n\t\tif (this.#failure !== undefined) return\n\t\tthis.#failure = Object.freeze({\n\t\t\t...failure,\n\t\t\tstop: failure.stop === undefined ? undefined : Object.freeze({ ...failure.stop }),\n\t\t})\n\t\tthis.#abort.abort(failureToStudyError(this.#failure))\n\t}\n\n\t/** Races work against cancellation and removes its listener after either ending.\n\t * @param work - Already-started work whose rejection remains observed after cancellation.\n\t * @returns The work's result if it settles before cancellation.\n\t * @throws Thrown with the retained operational attribution when cancelled.\n\t */\n\twait<T>(work: PromiseLike<T>): Promise<T> {\n\t\tconst listeners = new Abort()\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tPromise.resolve(work).then(resolve, reject)\n\t\t\tif (this.#abort.aborted) reject(this.#reason())\n\t\t\telse\n\t\t\t\tthis.#abort.signal.addEventListener('abort', () => reject(this.#reason()), {\n\t\t\t\t\tonce: true,\n\t\t\t\t\tsignal: listeners.signal,\n\t\t\t\t})\n\t\t}).finally(() => listeners.abort())\n\t}\n\n\t/** Removes the lifecycle listener without changing the retained failure. */\n\tclose(): void {\n\t\tthis.#listeners.abort()\n\t}\n\n\t#reason(): Error {\n\t\treturn failureToStudyError(\n\t\t\tthis.#failure ?? {\n\t\t\t\tcause: 'interrupted',\n\t\t\t\tmessage: 'Study interrupted',\n\t\t\t\trole: undefined,\n\t\t\t\tstop: undefined,\n\t\t\t},\n\t\t)\n\t}\n\n\t#interrupt(): void {\n\t\tif (this.#failure === undefined)\n\t\t\tthis.fail({\n\t\t\t\tcause: 'interrupted',\n\t\t\t\tmessage: 'Study interrupted by parent cancellation',\n\t\t\t\trole: undefined,\n\t\t\t\tstop: undefined,\n\t\t\t})\n\t}\n}\n","import type { StudyCharge, StudyFailure, StudyUsage } from '../types.js'\nimport type { StudyScopeInterface, StudyScopeOptions } from './types.js'\nimport { Abort } from '@orkestrel/abort'\nimport { Budget } from '@orkestrel/budget'\nimport { Timeout } from '@orkestrel/timeout'\nimport { StudyError } from '../errors.js'\nimport { isStudyLimit } from '../validators.js'\nimport { failureToStudyError } from './helpers.js'\n\n/** Reserves finite request ceilings around cumulative actual budgets and one deadline. */\nexport class StudyScope implements StudyScopeInterface {\n\t#options: StudyScopeOptions\n\t#calls: Budget<number>\n\t#tokens: Budget<number>\n\t#bytes: Budget<number>\n\t#timeout: Timeout\n\t#listeners = new Abort()\n\treadonly #pending = new Map<symbol, StudyCharge>()\n\t#started = performance.now()\n\t#closed = false\n\n\t/** Starts a timed scope with independent counters.\n\t * @param options - Finite limit, shared failure owner, and diagnostic label.\n\t */\n\tconstructor(options: StudyScopeOptions) {\n\t\tif (!isStudyLimit(options.limit)) throw new StudyError('CONFIG', 'Invalid study scope limit')\n\t\tthis.#options = { ...options, limit: { ...options.limit } }\n\t\tthis.#calls = new Budget({ max: options.limit.calls, consumer: (value: number) => value })\n\t\tthis.#tokens = new Budget({ max: options.limit.tokens, consumer: (value: number) => value })\n\t\tthis.#bytes = new Budget({ max: options.limit.bytes, consumer: (value: number) => value })\n\t\tthis.#timeout = new Timeout({ ms: options.limit.duration })\n\t\tthis.#timeout.signal.addEventListener('abort', () => this.#expire(), {\n\t\t\tonce: true,\n\t\t\tsignal: this.#listeners.signal,\n\t\t})\n\t\tthis.#timeout.start()\n\t}\n\n\t/** Checks cumulative consumption and every pending ceiling before admission.\n\t * @param charge - One prospective request's ceilings.\n\t * @throws Thrown when this scope cannot admit the request.\n\t */\n\tcheck(charge?: StudyCharge): void {\n\t\tthis.#checkTime()\n\t\tif (this.#closed) throw new StudyError('FAULT', 'Study scope is closed')\n\t\tconst prior = this.#options.control.failure\n\t\tif (prior !== undefined) throw failureToStudyError(prior)\n\t\tif (charge === undefined) return\n\t\tconst pending = [...this.#pending.values()]\n\t\tconst tokens = pending.reduce((total, entry) => total + entry.tokens, 0)\n\t\tconst bytes = pending.reduce((total, entry) => total + entry.bytes, 0)\n\t\tconst { label, limit } = this.#options\n\t\tconst refusal = [\n\t\t\t{\n\t\t\t\tid: `${label} calls`,\n\t\t\t\trefused: this.#calls.remaining - this.#pending.size < 1,\n\t\t\t\tmax: limit.calls,\n\t\t\t\tconsumed: this.#calls.consumed + this.#pending.size + 1,\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: `${label} tokens`,\n\t\t\t\trefused: this.#tokens.remaining - tokens < charge.tokens,\n\t\t\t\tmax: limit.tokens,\n\t\t\t\tconsumed: this.#tokens.consumed + tokens + charge.tokens,\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: `${label} bytes`,\n\t\t\t\trefused: this.#bytes.remaining - bytes < charge.bytes,\n\t\t\t\tmax: limit.bytes,\n\t\t\t\tconsumed: this.#bytes.consumed + bytes + charge.bytes,\n\t\t\t},\n\t\t].find((entry) => entry.refused)\n\t\tif (refusal !== undefined) {\n\t\t\tconst failure: StudyFailure = {\n\t\t\t\tcause: 'capacity',\n\t\t\t\tmessage: `${label} allowance cannot admit the request`,\n\t\t\t\trole: charge.role,\n\t\t\t\tstop: { layer: 'scope', id: refusal.id, max: refusal.max, consumed: refusal.consumed },\n\t\t\t}\n\t\t\tthis.#options.control.fail(failure)\n\t\t\tthrow failureToStudyError(failure)\n\t\t}\n\t}\n\n\t/** Reserves one request after the enclosing meter checked all scopes.\n\t * @param id - The request's unique reservation identity.\n\t * @param charge - Its admitted ceilings.\n\t */\n\treserve(id: symbol, charge: StudyCharge): void {\n\t\tif (this.#pending.has(id)) throw new StudyError('FAULT', 'Duplicate study reservation')\n\t\tthis.#pending.set(id, { ...charge })\n\t}\n\n\t/** Commits known charges while retaining ceilings for missing measurements.\n\t * @param id - The pending reservation identity.\n\t * @param usage - The request's retained public measurements.\n\t */\n\tsettle(id: symbol, usage: StudyUsage): void {\n\t\tconst charge = this.#pending.get(id)\n\t\tif (charge === undefined) throw new StudyError('FAULT', 'Study reservation is not pending')\n\t\tthis.#pending.delete(id)\n\t\tthis.#calls.consume(1)\n\t\tthis.#tokens.consume(Math.min(charge.tokens, usage.tokens ?? charge.tokens))\n\t\tthis.#bytes.consume(Math.min(charge.bytes, usage.bytes ?? charge.bytes))\n\t}\n\n\t/** Checks deadline attribution before clearing the timer. */\n\tclose(): void {\n\t\tif (this.#closed) return\n\t\tthis.#checkTime()\n\t\tthis.#closed = true\n\t\tthis.#listeners.abort()\n\t\tthis.#timeout.clear()\n\t}\n\n\t#checkTime(): void {\n\t\tif (\n\t\t\t!this.#closed &&\n\t\t\t(this.#timeout.expired || performance.now() - this.#started >= this.#options.limit.duration)\n\t\t)\n\t\t\tthis.#expire()\n\t}\n\n\t#expire(): void {\n\t\tthis.#options.control.fail({\n\t\t\tcause: 'deadline',\n\t\t\tmessage: `${this.#options.label} deadline expired`,\n\t\t\trole: undefined,\n\t\t\tstop: {\n\t\t\t\tlayer: 'scope',\n\t\t\t\tid: `${this.#options.label} duration`,\n\t\t\t\tmax: this.#options.limit.duration,\n\t\t\t\tconsumed: Math.ceil(performance.now() - this.#started),\n\t\t\t},\n\t\t})\n\t}\n}\n","import type { StudyDeadlineInterface, StudyDeadlineOptions } from './types.js'\nimport { StudyControl } from './StudyControl.js'\nimport { StudyScope } from './StudyScope.js'\n\n/** Bounds each independent operation with a fresh failure owner and deadline. */\nexport class StudyDeadline implements StudyDeadlineInterface {\n\t#options: StudyDeadlineOptions\n\n\t/** Retains the deadline without starting a timer.\n\t * @param options - Finite duration in milliseconds and diagnostic label.\n\t */\n\tconstructor(options: StudyDeadlineOptions) {\n\t\tthis.#options = { ...options }\n\t}\n\n\t/** Waits for work under a fresh failure owner and releases its timer and listener.\n\t * @param work - Already-started work whose late rejection remains observed.\n\t * @returns The work's result when it settles before the deadline.\n\t * @throws Thrown for an invalid duration, the work's own rejection, or the labelled deadline.\n\t */\n\tasync wait<T>(work: PromiseLike<T>): Promise<T> {\n\t\tconst control = new StudyControl()\n\t\tconst scope = this.#open(control, work)\n\t\ttry {\n\t\t\tconst result = await control.wait(work)\n\t\t\tscope.check()\n\t\t\treturn result\n\t\t} finally {\n\t\t\tscope.close()\n\t\t\tcontrol.close()\n\t\t}\n\t}\n\n\t// Opens the deadline scope; an invalid duration closes the owner and keeps the work's late rejection observed.\n\t#open(control: StudyControl, work: PromiseLike<unknown>): StudyScope {\n\t\ttry {\n\t\t\treturn new StudyScope({\n\t\t\t\tlimit: { duration: this.#options.duration, calls: 1, tokens: 1, bytes: 1 },\n\t\t\t\tcontrol,\n\t\t\t\tlabel: this.#options.label,\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tPromise.resolve(work).catch(() => undefined)\n\t\t\tcontrol.close()\n\t\t\tthrow error\n\t\t}\n\t}\n}\n","import type { StudyFailure, StudyTicket, StudyUsage } from '../types.js'\nimport type { StudyRequestOptions } from './types.js'\nimport { Abort, linkSignal } from '@orkestrel/abort'\nimport { Timeout } from '@orkestrel/timeout'\nimport { StudyError } from '../errors.js'\nimport { isStudyUsage } from '../validators.js'\nimport { computeStudyAdmittedStop, failureToStudyError } from './helpers.js'\n\n/** Settles an admitted request once and propagates operational failure to its owner. */\nexport class StudyRequest implements StudyTicket {\n\t#options: StudyRequestOptions\n\t#timeout: Timeout\n\t#signal: AbortSignal\n\t#listeners = new Abort()\n\t#started = performance.now()\n\t#settled = false\n\n\t/** Starts the request deadline after its enclosing scopes reserve capacity.\n\t * @param options - Admitted ceilings, request deadline, and settlement callback.\n\t */\n\tconstructor(options: StudyRequestOptions) {\n\t\tthis.#options = { ...options, charge: { ...options.charge } }\n\t\tthis.#timeout = new Timeout({ ms: options.duration })\n\t\tthis.#signal = linkSignal(this.#timeout.signal, options.control.signal)\n\t\tthis.#signal.addEventListener('abort', () => this.#abort(), {\n\t\t\tonce: true,\n\t\t\tsignal: this.#listeners.signal,\n\t\t})\n\t\tthis.#timeout.start()\n\t\tif (this.#signal.aborted) this.#abort()\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.#signal\n\t}\n\tget settled(): boolean {\n\t\treturn this.#settled\n\t}\n\n\t/** Retains actual measurements and refuses invalid or excessive charges.\n\t * @param usage - Measurements attributed to exactly this request.\n\t * @throws Thrown when settlement is late, repeated, invalid, or beyond admission.\n\t */\n\tfinish(usage: StudyUsage): void {\n\t\tthis.#checkPending()\n\t\tif (!isStudyUsage(usage) || usage.role !== this.#options.charge.role || usage.calls !== 1) {\n\t\t\tconst failure: StudyFailure = {\n\t\t\t\tcause: 'infrastructure',\n\t\t\t\tmessage: 'Request usage is invalid or misattributed',\n\t\t\t\trole: this.#options.charge.role,\n\t\t\t\tstop: undefined,\n\t\t\t}\n\t\t\tthis.fail(failure)\n\t\t\tthrow failureToStudyError(failure)\n\t\t}\n\t\tconst elapsed = performance.now() - this.#started\n\t\tconst admitted = computeStudyAdmittedStop(this.#options.charge, usage)\n\t\tconst failure: StudyFailure | undefined =\n\t\t\tthis.#timeout.expired ||\n\t\t\telapsed >= this.#options.duration ||\n\t\t\tusage.duration > this.#options.duration\n\t\t\t\t? {\n\t\t\t\t\t\tcause: 'deadline',\n\t\t\t\t\t\tmessage: 'Request deadline expired',\n\t\t\t\t\t\trole: usage.role,\n\t\t\t\t\t\tstop: {\n\t\t\t\t\t\t\tlayer: 'scope',\n\t\t\t\t\t\t\tid: 'Request duration',\n\t\t\t\t\t\t\tmax: this.#options.duration,\n\t\t\t\t\t\t\tconsumed: Math.ceil(Math.max(elapsed, usage.duration)),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: admitted !== undefined\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcause: 'capacity',\n\t\t\t\t\t\t\tmessage: 'Request usage exceeded its admitted ceiling',\n\t\t\t\t\t\t\trole: usage.role,\n\t\t\t\t\t\t\tstop: admitted,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined\n\t\tthis.#complete(usage)\n\t\tif (failure !== undefined) {\n\t\t\tthis.#options.control.fail(failure)\n\t\t\tthrow failureToStudyError(failure)\n\t\t}\n\t}\n\n\t/** Retains unknown cost conservatively and latches the first operational failure.\n\t * @param failure - The operational request failure.\n\t * @throws Thrown when this request was already settled.\n\t */\n\tfail(failure: StudyFailure): void {\n\t\tthis.#checkPending()\n\t\tthis.#complete({\n\t\t\trole: this.#options.charge.role,\n\t\t\tcalls: 1,\n\t\t\ttokens: undefined,\n\t\t\tbytes: undefined,\n\t\t\tduration: Math.ceil(performance.now() - this.#started),\n\t\t})\n\t\tthis.#options.control.fail({ ...failure, role: failure.role ?? this.#options.charge.role })\n\t}\n\n\t#complete(usage: StudyUsage): void {\n\t\tthis.#settled = true\n\t\tthis.#listeners.abort()\n\t\tthis.#timeout.clear()\n\t\tthis.#options.settle(Object.freeze({ ...usage }))\n\t}\n\n\t#checkPending(): void {\n\t\tif (this.#settled) {\n\t\t\tthis.#options.control.fail({\n\t\t\t\tcause: 'infrastructure',\n\t\t\t\tmessage: 'Request settlement is late or repeated',\n\t\t\t\trole: this.#options.charge.role,\n\t\t\t\tstop: undefined,\n\t\t\t})\n\t\t\tthrow new StudyError(\n\t\t\t\t'FAULT',\n\t\t\t\t'Request settlement is late or repeated',\n\t\t\t\tthis.#options.control.failure,\n\t\t\t)\n\t\t}\n\t}\n\n\t#abort(): void {\n\t\tif (this.#settled) return\n\t\tconst expired = this.#timeout.expired\n\t\tthis.fail(\n\t\t\tthis.#options.control.failure ?? {\n\t\t\t\tcause: expired ? 'deadline' : 'interrupted',\n\t\t\t\tmessage: expired ? 'Request deadline expired' : 'Request interrupted',\n\t\t\t\trole: this.#options.charge.role,\n\t\t\t\tstop: expired\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tlayer: 'scope',\n\t\t\t\t\t\t\tid: 'Request duration',\n\t\t\t\t\t\t\tmax: this.#options.duration,\n\t\t\t\t\t\t\tconsumed: Math.ceil(performance.now() - this.#started),\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t},\n\t\t)\n\t}\n}\n","import type { StudyCharge, StudyFailure, StudyTicket, StudyUsage } from '../types.js'\nimport type { StudyMeterInterface, StudyMeterOptions } from './types.js'\nimport { StudyError } from '../errors.js'\nimport { isStudyLimit, isStudyRole } from '../validators.js'\nimport { failureToStudyError } from './helpers.js'\nimport { StudyRequest } from './StudyRequest.js'\n\n/** Admits request ceilings across every enclosing scope before dispatch. */\nexport class StudyMeter implements StudyMeterInterface {\n\t#options: StudyMeterOptions\n\treadonly #pending = new Set<symbol>()\n\t#usage: readonly StudyUsage[] = []\n\t#closed = false\n\n\t/** Holds the goal's shared admission scopes.\n\t * @param options - Request bound, enclosing scopes, and shared failure owner.\n\t */\n\tconstructor(options: StudyMeterOptions) {\n\t\tif (\n\t\t\t!isStudyLimit(options.request) ||\n\t\t\toptions.request.calls !== 1 ||\n\t\t\toptions.scopes.length === 0\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Invalid request admission bounds')\n\t\tthis.#options = { ...options, request: { ...options.request }, scopes: [...options.scopes] }\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.#options.control.signal\n\t}\n\tget usage(): readonly StudyUsage[] {\n\t\treturn Object.freeze([...this.#usage])\n\t}\n\n\t/** Reserves one request atomically across all enclosing allowances.\n\t * @param charge - Safe integer token and byte ceilings with the request's role.\n\t * @returns A request ticket that must settle before the goal completes.\n\t * @throws Thrown before dispatch if the request exceeds available capacity.\n\t */\n\tadmit(charge: StudyCharge): StudyTicket {\n\t\tif (this.#closed) throw new StudyError('FAULT', 'Study meter is closed')\n\t\tif (this.#options.control.failure !== undefined)\n\t\t\tthrow failureToStudyError(this.#options.control.failure)\n\t\tif (\n\t\t\t!isStudyRole(charge.role) ||\n\t\t\t!Number.isSafeInteger(charge.tokens) ||\n\t\t\tcharge.tokens < 0 ||\n\t\t\t!Number.isSafeInteger(charge.bytes) ||\n\t\t\tcharge.bytes < 0\n\t\t) {\n\t\t\tconst failure: StudyFailure = {\n\t\t\t\tcause: 'infrastructure',\n\t\t\t\tmessage: 'Request admission requires safe nonnegative ceilings',\n\t\t\t\trole: undefined,\n\t\t\t\tstop: undefined,\n\t\t\t}\n\t\t\tthis.#options.control.fail(failure)\n\t\t\tthrow failureToStudyError(failure)\n\t\t}\n\t\tconst { request } = this.#options\n\t\tif (charge.tokens > request.tokens || charge.bytes > request.bytes) {\n\t\t\tconst tokens = charge.tokens > request.tokens\n\t\t\tconst failure: StudyFailure = {\n\t\t\t\tcause: 'capacity',\n\t\t\t\tmessage: 'Request ceiling exceeds the request allowance',\n\t\t\t\trole: charge.role,\n\t\t\t\tstop: {\n\t\t\t\t\tlayer: 'scope',\n\t\t\t\t\tid: tokens ? 'Request tokens' : 'Request bytes',\n\t\t\t\t\tmax: tokens ? request.tokens : request.bytes,\n\t\t\t\t\tconsumed: tokens ? charge.tokens : charge.bytes,\n\t\t\t\t},\n\t\t\t}\n\t\t\tthis.#options.control.fail(failure)\n\t\t\tthrow failureToStudyError(failure)\n\t\t}\n\t\tfor (const scope of this.#options.scopes) scope.check(charge)\n\t\tconst id = Symbol('request')\n\t\tfor (const scope of this.#options.scopes) scope.reserve(id, charge)\n\t\tthis.#pending.add(id)\n\t\treturn new StudyRequest({\n\t\t\tcharge,\n\t\t\tduration: this.#options.request.duration,\n\t\t\tcontrol: this.#options.control,\n\t\t\tsettle: (usage) => {\n\t\t\t\tfor (const scope of this.#options.scopes) scope.settle(id, usage)\n\t\t\t\tthis.#pending.delete(id)\n\t\t\t\tthis.#usage = [...this.#usage, usage]\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Refuses unfinished requests before closing a goal's admission boundary. */\n\tclose(): void {\n\t\tif (this.#closed) return\n\t\tthis.#closed = true\n\t\tif (this.#pending.size > 0)\n\t\t\tthis.#options.control.fail({\n\t\t\t\tcause: 'infrastructure',\n\t\t\t\tmessage: 'Goal completed with unsettled requests',\n\t\t\t\trole: undefined,\n\t\t\t\tstop: undefined,\n\t\t\t})\n\t}\n}\n","import type {\n\tStudyFailure,\n\tStudySeriesOptions,\n\tStudySessionInterface,\n\tStudySinkInterface,\n\tStudyTrial,\n} from '../types.js'\nimport type { StudyControl } from './StudyControl.js'\nimport type { StudyDeadline } from './StudyDeadline.js'\nimport { StudyError } from '../errors.js'\nimport { failureToStudyError, readStudyFailure } from './helpers.js'\nimport { StudyScope } from './StudyScope.js'\n\n/** Holds one trial's evidence custody, admission scope and driver session from opening to cleanup. */\nexport class StudyTrialLease {\n\treadonly #trial: StudyTrial\n\treadonly #options: StudySeriesOptions\n\treadonly #control: StudyControl\n\treadonly #series: StudyScope\n\treadonly #deadline: StudyDeadline\n\t#scope: StudyScope | undefined\n\t#evidence: StudySinkInterface | undefined\n\t#opening: Promise<StudySessionInterface> | undefined\n\t#session: StudySessionInterface | undefined\n\n\t/** Binds one scheduled trial to the series' owned inputs, failure owner, series scope and cleanup deadline.\n\t * @param trial - The scheduled trial.\n\t * @param options - The series' owned manifest, driver and store.\n\t * @param control - The series failure owner.\n\t * @param series - The series admission scope.\n\t * @param deadline - The custody and cleanup deadline.\n\t */\n\tconstructor(\n\t\ttrial: StudyTrial,\n\t\toptions: StudySeriesOptions,\n\t\tcontrol: StudyControl,\n\t\tseries: StudyScope,\n\t\tdeadline: StudyDeadline,\n\t) {\n\t\tthis.#trial = trial\n\t\tthis.#options = options\n\t\tthis.#control = control\n\t\tthis.#series = series\n\t\tthis.#deadline = deadline\n\t}\n\n\t/** Reports the trial scope once opened; undefined when the trial inherited a failure. */\n\tget scope(): StudyScope | undefined {\n\t\treturn this.#scope\n\t}\n\n\t/** Reports the trial's evidence sink once custody started. */\n\tget evidence(): StudySinkInterface | undefined {\n\t\treturn this.#evidence\n\t}\n\n\t/** Reports the driver session once it opened. */\n\tget session(): StudySessionInterface | undefined {\n\t\treturn this.#session\n\t}\n\n\t/** Starts evidence custody and, unless a failure is latched, opens the trial scope and driver session.\n\t * @returns Nothing after the session opened, or after custody alone started under a latched failure.\n\t * @throws StudyError - Thrown with code `CUSTODY` when custody refuses the trial; thrown for a series or trial limit or an opening failure.\n\t */\n\tasync open(): Promise<void> {\n\t\tconst control = this.#control\n\t\tif (control.failure !== undefined) {\n\t\t\tthis.#evidence = await this.#start()\n\t\t\treturn\n\t\t}\n\t\tthis.#series.check()\n\t\tconst scope = new StudyScope({\n\t\t\tlimit: this.#options.manifest.bounds.trial,\n\t\t\tcontrol,\n\t\t\tlabel: 'Trial',\n\t\t})\n\t\tthis.#scope = scope\n\t\tthis.#evidence = await this.#start()\n\t\tthis.#series.check()\n\t\tscope.check()\n\t\tconst opening = this.#launch()\n\t\tthis.#opening = opening\n\t\tthis.#session = await control.wait(opening)\n\t}\n\n\t/** Closes the opened session, or a session that opened late, then the trial scope.\n\t * @returns The cleanup failure, or undefined when cleanup succeeded or repeated the latched failure.\n\t */\n\tasync close(): Promise<StudyFailure | undefined> {\n\t\tconst cleanup = await this.#release()\n\t\tthis.#scope?.close()\n\t\treturn cleanup\n\t}\n\n\t// Closes the session or awaits and closes a late opening; a session close failure is latched, a late one only reported when it differs.\n\tasync #release(): Promise<StudyFailure | undefined> {\n\t\tconst session = this.#session\n\t\tconst opening = this.#opening\n\t\tif (session !== undefined) {\n\t\t\ttry {\n\t\t\t\tawait this.#deadline.wait(session.close())\n\t\t\t\treturn undefined\n\t\t\t} catch (error) {\n\t\t\t\tconst cleanup = readStudyFailure(error)\n\t\t\t\tthis.#control.fail(cleanup)\n\t\t\t\treturn cleanup\n\t\t\t}\n\t\t}\n\t\tif (opening === undefined) return undefined\n\t\ttry {\n\t\t\tconst late = await this.#deadline.wait(opening)\n\t\t\tawait this.#deadline.wait(late.close())\n\t\t\treturn undefined\n\t\t} catch (error) {\n\t\t\tconst late = readStudyFailure(error)\n\t\t\treturn late.message !== this.#control.failure?.message ? late : undefined\n\t\t}\n\t}\n\n\t// Opens the driver session; a failure latched while it opened closes it and refuses.\n\tasync #launch(): Promise<StudySessionInterface> {\n\t\tconst control = this.#control\n\t\tconst session = await this.#options.driver.open(this.#trial, control.signal)\n\t\tif (control.failure !== undefined) {\n\t\t\tawait this.#deadline.wait(session.close())\n\t\t\tthrow failureToStudyError(control.failure)\n\t\t}\n\t\treturn session\n\t}\n\n\t// Starts evidence custody; a refusal latches the failure and surfaces as a custody error.\n\tasync #start(): Promise<StudySinkInterface> {\n\t\tconst control = this.#control\n\t\ttry {\n\t\t\tconst pending = this.#options.store.start(this.#trial)\n\t\t\treturn control.failure === undefined\n\t\t\t\t? await control.wait(pending)\n\t\t\t\t: await this.#deadline.wait(pending)\n\t\t} catch (error) {\n\t\t\tcontrol.fail(readStudyFailure(error))\n\t\t\tconst failure = control.failure ?? readStudyFailure(error)\n\t\t\tthrow new StudyError('CUSTODY', failure.message, failure)\n\t\t}\n\t}\n}\n","import type {\n\tStudyAttempt,\n\tStudyFailure,\n\tStudyGoal,\n\tStudyObservation,\n\tStudyProduct,\n\tStudyScenario,\n\tStudySeriesOptions,\n\tStudySessionInterface,\n\tStudySinkInterface,\n\tStudyTrial,\n} from '../types.js'\nimport { Budget } from '@orkestrel/budget'\nimport { canonicalStringify, cloneJSONValue } from '@orkestrel/contract'\nimport { isStudyError, StudyError } from '../errors.js'\nimport { buildStudySchedule } from '../helpers.js'\nimport { isStudyBounds, isStudyProduct } from '../validators.js'\nimport { computeStudyOutputStop, readStudyFailure } from './helpers.js'\nimport { StudyControl } from './StudyControl.js'\nimport { StudyDeadline } from './StudyDeadline.js'\nimport { StudyMeter } from './StudyMeter.js'\nimport { StudyScope } from './StudyScope.js'\nimport { StudyTrialLease } from './StudyTrialLease.js'\n\n/** Executes a frozen serial study schedule with finite admission and sticky failures. */\nexport class StudySeries {\n\t#options: StudySeriesOptions\n\t#executed = false\n\n\t/** Owns the declared inputs while retaining the concrete driver and custody store.\n\t * @param options - Frozen manifest, concrete adapters, and parent cancellation.\n\t */\n\tconstructor(options: StudySeriesOptions) {\n\t\tthis.#options = { ...options, manifest: structuredClone(options.manifest) }\n\t}\n\n\t/** Runs every declared trial once and retains explicit unexecuted observations after failure.\n\t * Custody rejection leaves the run unsealed; callers must seal only a fulfilled execution.\n\t * @returns Ordered terminal attempts without task success labels.\n\t * @throws Thrown for invalid configuration or failed or timed out custody operations.\n\t */\n\tasync execute(): Promise<readonly StudyAttempt[]> {\n\t\tif (this.#executed) throw new StudyError('CONFIG', 'Study series can execute only once')\n\t\tthis.#executed = true\n\t\tconst manifest = this.#options.manifest\n\t\tconst expected = buildStudySchedule(manifest.definition, manifest.scenarios)\n\t\tif (\n\t\t\t!isStudyBounds(manifest.bounds) ||\n\t\t\tcanonicalStringify(expected) !== canonicalStringify(manifest.schedule)\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Study manifest schedule or bounds are invalid')\n\t\tconst control = new StudyControl(this.#options.signal)\n\t\tconst scope = new StudyScope({ limit: manifest.bounds.series, control, label: 'Series' })\n\t\tconst deadline = new StudyDeadline({\n\t\t\tduration: manifest.bounds.request.duration,\n\t\t\tlabel: 'Custody or cleanup',\n\t\t})\n\t\tconst output = new Budget({\n\t\t\tid: 'Series output',\n\t\t\tmax: manifest.bounds.series.bytes,\n\t\t\tconsumer: (bytes: number) => bytes,\n\t\t})\n\t\tconst attempts: StudyAttempt[] = []\n\t\ttry {\n\t\t\tfor (const trial of manifest.schedule)\n\t\t\t\tattempts.push(await this.#executeTrial(trial, control, scope, output, deadline))\n\t\t} finally {\n\t\t\tscope.close()\n\t\t\tcontrol.close()\n\t\t}\n\t\treturn Object.freeze(attempts)\n\t}\n\n\tasync #executeTrial(\n\t\ttrial: StudyTrial,\n\t\tcontrol: StudyControl,\n\t\tseries: StudyScope,\n\t\toutput: Budget<number>,\n\t\tdeadline: StudyDeadline,\n\t): Promise<StudyAttempt> {\n\t\tconst started = performance.now()\n\t\tconst scenario = this.#options.manifest.scenarios.find((entry) => entry.id === trial.scenario)\n\t\tif (scenario === undefined) throw new StudyError('CONFIG', 'Scheduled scenario is absent')\n\t\tconst prior = control.failure\n\t\tconst lease = new StudyTrialLease(trial, this.#options, control, series, deadline)\n\t\tconst executed = await this.#executeGoals(scenario, lease, control, series, output)\n\t\tconst cleanup = await this.#release(lease, control, series)\n\t\tconst failure = control.failure\n\t\tconst observations: readonly StudyObservation[] = [\n\t\t\t...executed,\n\t\t\t...scenario.goals.slice(executed.length).map((goal): StudyObservation => {\n\t\t\t\tconst unexecuted: StudyFailure =\n\t\t\t\t\tfailure === undefined\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tcause: 'infrastructure',\n\t\t\t\t\t\t\t\tmessage: 'Goal unexecuted because the trial did not open',\n\t\t\t\t\t\t\t\trole: undefined,\n\t\t\t\t\t\t\t\tstop: undefined,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: { ...failure, message: `Goal unexecuted: ${failure.message}` }\n\t\t\t\treturn Object.freeze({\n\t\t\t\t\tgoal: goal.id,\n\t\t\t\t\tproduct: undefined,\n\t\t\t\t\tfailure: unexecuted,\n\t\t\t\t\tusage: Object.freeze([]),\n\t\t\t\t\tduration: 0,\n\t\t\t\t\texecuted: false,\n\t\t\t\t})\n\t\t\t}),\n\t\t]\n\t\tconst attempt: StudyAttempt = Object.freeze({\n\t\t\ttrial,\n\t\t\tobservations: Object.freeze(observations),\n\t\t\tfailure:\n\t\t\t\tcleanup !== undefined &&\n\t\t\t\tfailure !== undefined &&\n\t\t\t\t(prior !== undefined || failure.message !== cleanup.message)\n\t\t\t\t\t? { ...failure, message: `${failure.message}; cleanup: ${cleanup.message}` }\n\t\t\t\t\t: failure,\n\t\t\tduration: Math.ceil(performance.now() - started),\n\t\t\t// The trial entered execution unless it inherited a terminal series failure at its\n\t\t\t// boundary. This does not claim that driver.open ran.\n\t\t\texecuted: prior === undefined,\n\t\t})\n\t\ttry {\n\t\t\tawait deadline.wait(this.#options.store.finish(attempt))\n\t\t\tif (attempt.failure === undefined) series.check()\n\t\t} catch (error) {\n\t\t\tcontrol.fail(readStudyFailure(error))\n\t\t\tconst custody = control.failure ?? readStudyFailure(error)\n\t\t\tthrow new StudyError('CUSTODY', custody.message, custody)\n\t\t}\n\t\treturn attempt\n\t}\n\n\t// Opens the lease and executes each goal while the trial stays open; a custody refusal releases the lease before it propagates.\n\tasync #executeGoals(\n\t\tscenario: StudyScenario,\n\t\tlease: StudyTrialLease,\n\t\tcontrol: StudyControl,\n\t\tseries: StudyScope,\n\t\toutput: Budget<number>,\n\t): Promise<readonly StudyObservation[]> {\n\t\tconst observations: StudyObservation[] = []\n\t\ttry {\n\t\t\tawait lease.open()\n\t\t\tconst trialOutput = new Budget({\n\t\t\t\tid: 'Trial output',\n\t\t\t\tmax: this.#options.manifest.bounds.trial.bytes,\n\t\t\t\tconsumer: (bytes: number) => bytes,\n\t\t\t})\n\t\t\tfor (const goal of scenario.goals) {\n\t\t\t\tconst { session, scope, evidence } = lease\n\t\t\t\tif (\n\t\t\t\t\tcontrol.failure !== undefined ||\n\t\t\t\t\tsession === undefined ||\n\t\t\t\t\tscope === undefined ||\n\t\t\t\t\tevidence === undefined\n\t\t\t\t)\n\t\t\t\t\tbreak\n\t\t\t\tseries.check()\n\t\t\t\tscope.check()\n\t\t\t\tobservations.push(\n\t\t\t\t\tawait this.#executeGoal(\n\t\t\t\t\t\tgoal,\n\t\t\t\t\t\tsession,\n\t\t\t\t\t\tevidence,\n\t\t\t\t\t\tcontrol,\n\t\t\t\t\t\t[scope, series],\n\t\t\t\t\t\t[trialOutput, output],\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (isStudyError(error) && error.code === 'CUSTODY') {\n\t\t\t\tawait this.#release(lease, control, series)\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tcontrol.fail(readStudyFailure(error))\n\t\t}\n\t\treturn observations\n\t}\n\n\t// Closes the lease, then rechecks the series ceiling, and returns the lease's cleanup failure.\n\tasync #release(\n\t\tlease: StudyTrialLease,\n\t\tcontrol: StudyControl,\n\t\tseries: StudyScope,\n\t): Promise<StudyFailure | undefined> {\n\t\tconst cleanup = await lease.close()\n\t\ttry {\n\t\t\tseries.check()\n\t\t} catch (error) {\n\t\t\tcontrol.fail(readStudyFailure(error))\n\t\t}\n\t\treturn cleanup\n\t}\n\n\tasync #executeGoal(\n\t\tgoal: StudyGoal,\n\t\tsession: StudySessionInterface,\n\t\tevidence: StudySinkInterface,\n\t\tcontrol: StudyControl,\n\t\tparents: readonly StudyScope[],\n\t\toutputs: ReadonlyArray<Budget<number>>,\n\t): Promise<StudyObservation> {\n\t\tconst started = performance.now()\n\t\tconst bounds = this.#options.manifest.bounds\n\t\tconst scope = new StudyScope({ limit: bounds.goal, control, label: 'Goal' })\n\t\tconst meter = new StudyMeter({ request: bounds.request, scopes: [scope, ...parents], control })\n\t\tconst product = await this.#produce(\n\t\t\tgoal,\n\t\t\tsession,\n\t\t\tevidence,\n\t\t\tcontrol,\n\t\t\tscope,\n\t\t\tmeter,\n\t\t\tparents,\n\t\t\toutputs,\n\t\t)\n\t\treturn Object.freeze({\n\t\t\tgoal: goal.id,\n\t\t\tproduct,\n\t\t\tfailure: control.failure,\n\t\t\tusage: meter.usage,\n\t\t\tduration: Math.ceil(performance.now() - started),\n\t\t\texecuted: true,\n\t\t})\n\t}\n\n\t// Runs one goal and closes its meter and scope; a late check failure leaves the retained product in place.\n\tasync #produce(\n\t\tgoal: StudyGoal,\n\t\tsession: StudySessionInterface,\n\t\tevidence: StudySinkInterface,\n\t\tcontrol: StudyControl,\n\t\tscope: StudyScope,\n\t\tmeter: StudyMeter,\n\t\tparents: readonly StudyScope[],\n\t\toutputs: ReadonlyArray<Budget<number>>,\n\t): Promise<StudyProduct | undefined> {\n\t\tconst bounds = this.#options.manifest.bounds\n\t\ttry {\n\t\t\tconst value: unknown = await control.wait(\n\t\t\t\tsession.execute(goal, { signal: control.signal, meter, evidence }),\n\t\t\t)\n\t\t\tif (!isStudyProduct(value))\n\t\t\t\tthrow new StudyError('FAULT', 'Driver returned no valid study product')\n\t\t\tconst candidate = Object.freeze({\n\t\t\t\tvalue: cloneJSONValue(value.value),\n\t\t\t\tpartial: value.partial,\n\t\t\t})\n\t\t\tconst bytes = new TextEncoder().encode(JSON.stringify(candidate.value)).byteLength\n\t\t\tconst stop = computeStudyOutputStop(bytes, bounds.goal.bytes, outputs)\n\t\t\tconst product = stop === undefined ? candidate : undefined\n\t\t\ttry {\n\t\t\t\tfor (const parent of parents) parent.check()\n\t\t\t\tscope.check()\n\t\t\t\tif (stop !== undefined) {\n\t\t\t\t\tcontrol.fail({\n\t\t\t\t\t\tcause: 'capacity',\n\t\t\t\t\t\tmessage: 'Study product exceeded its output allowance',\n\t\t\t\t\t\trole: undefined,\n\t\t\t\t\t\tstop,\n\t\t\t\t\t})\n\t\t\t\t} else for (const budget of outputs) budget.consume(bytes)\n\t\t\t} catch (error) {\n\t\t\t\tcontrol.fail(readStudyFailure(error))\n\t\t\t}\n\t\t\treturn product\n\t\t} catch (error) {\n\t\t\tcontrol.fail(readStudyFailure(error))\n\t\t\treturn undefined\n\t\t} finally {\n\t\t\tmeter.close()\n\t\t\tscope.close()\n\t\t}\n\t}\n}\n","import type { JSONValue } from '@orkestrel/contract'\nimport type { LedgerGauge, ProviderResult, RequestMeasure } from '@orkestrel/agent'\nimport type { StudyRole, StudyStop } from '../types.js'\nimport type { StudyAgentDispatch, StudyAgentRuntime } from './types.js'\nimport { attempt, isNonEmptyString, isObject } from '@orkestrel/contract'\nimport { StudyError } from '../errors.js'\nimport { parseStudyReading } from '../parsers.js'\n\n/**\n * Prices a runtime estimate through an explicit gauge.\n * @param gauge - The declared scale and overhead\n * @param estimate - The runtime's estimate of one complete request\n * @returns The projected prompt tokens, rounded up\n */\nexport function projectStudyAgentRequest(gauge: LedgerGauge, estimate: number): number {\n\treturn Math.ceil(gauge.overhead + gauge.scale * estimate)\n}\n\n/**\n * Checks that a successful provider call reported a usable actual prompt count.\n * @remarks\n * The check compares nothing with a forecast; room enforcement stays with the transport.\n * @param usage - The usage a successful provider call reported\n * @param role - The responsibility whose request was dispatched; the failure retains it\n * @returns Nothing when the prompt count is finite and positive\n * @throws StudyError - Thrown with code `FAULT` when the prompt count is missing, not finite, or not positive\n */\nexport function validateStudyAgentUsage(usage: ProviderResult['usage'], role: StudyRole): void {\n\tconst prompt = usage?.prompt\n\tif (typeof prompt !== 'number' || !Number.isFinite(prompt) || prompt <= 0) {\n\t\tconst message = 'Gauged request returned no usable prompt count'\n\t\tthrow new StudyError('FAULT', message, {\n\t\t\tcause: 'infrastructure',\n\t\t\tmessage,\n\t\t\trole,\n\t\t\tstop: undefined,\n\t\t})\n\t}\n}\n\n/**\n * Translates only a nominal Agent window refusal into the attributable capacity failure.\n * @remarks\n * The failure's stop is the `window` layer with the id `Agent window`; its `max` is the window and\n * its `consumed` the measured request, each read from the error's context when it is a finite\n * number.\n * @param error - The caught or reported value\n * @param runtime - The admitted Agent namespace owning the nominal guard\n * @returns A capacity StudyError for an Agent `WINDOW` error; every other value with its identity\n */\nexport function translateStudyAgentError(\n\terror: unknown,\n\truntime: Pick<StudyAgentRuntime, 'isAgentError'>,\n): unknown {\n\tif (!runtime.isAgentError(error) || error.code !== 'WINDOW') return error\n\tconst context = error.context\n\treturn new StudyError('CAPACITY', error.message, {\n\t\tcause: 'capacity',\n\t\tmessage: error.message,\n\t\trole: 'agent',\n\t\tstop: {\n\t\t\tlayer: 'window',\n\t\t\tid: 'Agent window',\n\t\t\tmax: parseStudyReading(context?.max),\n\t\t\tconsumed: parseStudyReading(context?.consumed),\n\t\t},\n\t})\n}\n\n/**\n * Translates an Agent run's stop record into the attributable capacity failure of the layer that stopped it.\n * @remarks\n * The record is foreign data from the admitted runtime, so the helper reads it once, each member\n * once, inside one contained boundary, and validates only the members it dereferences. A `meter`\n * or `budget` stop always leaves the run partial; a `model` stop is a complete answer, so a\n * consumer whose role admits a `length` finish keeps it. The consumer throws the returned error\n * when its policy refuses the stop. A `model` stop reports no cap because the Agent does not see\n * one; its `consumed` is the completion the stopped call reported, when finite.\n * @param stop - The `stop` member of an Agent or Ledger result\n * @returns Undefined when `stop` is undefined; a `CAPACITY` StudyError with role `agent` and the Agent layer for a meter, budget, or model stop; a `FAULT` StudyError with role `agent` for a malformed record\n * @example\n * ```ts\n * translateStudyAgentStop({ layer: 'meter', id: 'meter', max: 2000, consumed: 2001 })\n * // a CAPACITY StudyError whose failure.stop is { layer: 'meter', id: 'meter', max: 2000, consumed: 2001 }\n * ```\n */\nexport function translateStudyAgentStop(stop: unknown): StudyError | undefined {\n\tif (stop === undefined) return undefined\n\tconst reading = attempt((): StudyStop | undefined => {\n\t\tif (!isObject(stop)) return undefined\n\t\tconst layer: unknown = Reflect.get(stop, 'layer')\n\t\tconst id: unknown = Reflect.get(stop, 'id')\n\t\tif (!isNonEmptyString(id)) return undefined\n\t\tif (layer === 'meter' || layer === 'budget') {\n\t\t\tconst max: unknown = Reflect.get(stop, 'max')\n\t\t\tconst consumed: unknown = Reflect.get(stop, 'consumed')\n\t\t\tconst limit = parseStudyReading(max)\n\t\t\tconst used = parseStudyReading(consumed)\n\t\t\treturn limit === undefined || used === undefined\n\t\t\t\t? undefined\n\t\t\t\t: { layer, id, max: limit, consumed: used }\n\t\t}\n\t\tif (layer === 'model') {\n\t\t\tconst usage: unknown = Reflect.get(stop, 'usage')\n\t\t\treturn {\n\t\t\t\tlayer,\n\t\t\t\tid,\n\t\t\t\tmax: undefined,\n\t\t\t\tconsumed: isObject(usage) ? parseStudyReading(Reflect.get(usage, 'completion')) : undefined,\n\t\t\t}\n\t\t}\n\t\treturn undefined\n\t})\n\tconst parsed = reading.success ? reading.value : undefined\n\tif (parsed === undefined) {\n\t\tconst message = 'Agent stop record is malformed'\n\t\treturn new StudyError('FAULT', message, {\n\t\t\tcause: 'infrastructure',\n\t\t\tmessage,\n\t\t\trole: 'agent',\n\t\t\tstop: undefined,\n\t\t})\n\t}\n\tconst message =\n\t\tparsed.layer === 'meter'\n\t\t\t? 'Agent meter allowance reached its ceiling'\n\t\t\t: parsed.layer === 'budget'\n\t\t\t\t? 'Agent budget reached its ceiling'\n\t\t\t\t: 'Agent model reached its own token limit'\n\treturn new StudyError('CAPACITY', message, {\n\t\tcause: 'capacity',\n\t\tmessage,\n\t\trole: 'agent',\n\t\tstop: parsed,\n\t})\n}\n\n/**\n * Projects a request's structural components onto plain JSON without storing a total.\n * @param measure - The runtime's disjoint per-message, tools and schema estimates\n * @returns The same components in request order\n */\nexport function buildStudyAgentParts(measure: RequestMeasure): JSONValue {\n\treturn {\n\t\tmessages: measure.messages.map((message) => ({\n\t\t\tid: message.id,\n\t\t\trole: message.role,\n\t\t\tcontent: message.content,\n\t\t\tframing: message.framing,\n\t\t\tcalls: message.calls,\n\t\t\tthinking: message.thinking,\n\t\t\timages: message.images,\n\t\t})),\n\t\ttools: measure.tools,\n\t\tschema: measure.schema,\n\t}\n}\n\n/**\n * Builds the evidence join of a wire request to its canonical dispatch.\n * @param dispatch - The measured dispatch, or undefined when the caller measured none\n * @returns The dispatch id and revision, each null when unknown\n */\nexport function buildStudyAgentDispatch(\n\tdispatch: StudyAgentDispatch | undefined,\n): Readonly<Record<string, JSONValue>> {\n\treturn { canonical: dispatch?.id ?? null, revision: dispatch?.revision ?? null }\n}\n","import type { StudyAgentRuntime } from './types.js'\nimport { holds, isObject } from '@orkestrel/contract'\n\n/**\n * Checks whether a namespace exposes the Agent capabilities the instrumentation invokes.\n * @remarks\n * The guard reads only `estimateRequest`, `measureRequest`, and `isAgentError`, so a namespace\n * without Ledger or conversation factories passes. A throwing accessor returns false.\n * @param value - The admitted namespace\n * @returns True if every required capability is a function; false otherwise\n */\nexport function isStudyAgentRuntime(value: unknown): value is StudyAgentRuntime {\n\treturn holds(\n\t\t() =>\n\t\t\tisObject(value) &&\n\t\t\t'estimateRequest' in value &&\n\t\t\ttypeof value.estimateRequest === 'function' &&\n\t\t\t'measureRequest' in value &&\n\t\t\ttypeof value.measureRequest === 'function' &&\n\t\t\t'isAgentError' in value &&\n\t\t\ttypeof value.isAgentError === 'function',\n\t)\n}\n","import type {\n\tMessage,\n\tProviderDelta,\n\tProviderInterface,\n\tProviderRequest,\n\tProviderResult,\n\tProviderStreamOptions,\n\tThinkingReplay,\n} from '@orkestrel/agent'\nimport type { StudyAgentObserverOptions } from './types.js'\nimport { projectStudyAgentRequest, validateStudyAgentUsage } from './helpers.js'\n\n/** Reads each Agent request's size before delegating it unchanged to the real provider. */\nexport class StudyAgentObserver implements ProviderInterface {\n\treadonly #options: StudyAgentObserverOptions\n\n\t/** Binds the real provider, the measuring runtime, the explicit gauge and usage policy, and the reading recorder.\n\t * @param options - Delegate, measurement seam, and policies.\n\t */\n\tconstructor(options: StudyAgentObserverOptions) {\n\t\tthis.#options = { ...options }\n\t}\n\n\t/** Reports the delegate's trace label. */\n\tget id(): string {\n\t\treturn this.#options.provider.id\n\t}\n\n\t/** Reports the delegate's backend name. */\n\tget name(): string {\n\t\treturn this.#options.provider.name\n\t}\n\n\t/** Reports the delegate's thinking replay policy; an absent policy is the declared `none`. */\n\tget replay(): ThinkingReplay {\n\t\treturn this.#options.provider.replay ?? 'none'\n\t}\n\n\t/** Records one reading, then awaits the real generation.\n\t * @param messages - The conversation sent.\n\t * @param signal - Bounds the request.\n\t * @param tools - The tools advertised this turn.\n\t * @param options - The per-call options.\n\t * @returns The real provider's result.\n\t */\n\tasync generate(\n\t\tmessages: readonly Message[],\n\t\tsignal: AbortSignal,\n\t\ttools?: ProviderRequest['tools'],\n\t\toptions?: ProviderStreamOptions,\n\t): Promise<ProviderResult> {\n\t\tthis.#measure(messages, tools, options)\n\t\tconst result = await this.#options.provider.generate(messages, signal, tools, options)\n\t\tif (this.#options.enforced && !signal.aborted) validateStudyAgentUsage(result.usage, 'agent')\n\t\treturn result\n\t}\n\n\t/** Records one reading, then relays the real stream.\n\t * @param messages - The conversation sent.\n\t * @param signal - Bounds the request.\n\t * @param tools - The tools advertised this turn.\n\t * @param options - The per-call options.\n\t * @returns The real deltas and result.\n\t */\n\tstream(\n\t\tmessages: readonly Message[],\n\t\tsignal: AbortSignal,\n\t\ttools?: ProviderRequest['tools'],\n\t\toptions?: ProviderStreamOptions,\n\t): AsyncGenerator<ProviderDelta, ProviderResult> {\n\t\tthis.#measure(messages, tools, options)\n\t\treturn this.#relay(this.#options.provider.stream(messages, signal, tools, options), signal)\n\t}\n\n\t// Forms the pre-encoding request exactly as the Agent window measures it: omitted members stay omitted.\n\t#measure(\n\t\tmessages: readonly Message[],\n\t\ttools: ProviderRequest['tools'],\n\t\toptions: ProviderStreamOptions | undefined,\n\t): void {\n\t\tconst request: ProviderRequest = {\n\t\t\tmessages,\n\t\t\t...(tools === undefined ? {} : { tools }),\n\t\t\t...(options === undefined ? {} : { options }),\n\t\t}\n\t\tconst estimate = this.#options.runtime.estimateRequest(request)\n\t\tconst gauge = this.#options.gauge\n\t\tconst projected = gauge === undefined ? undefined : projectStudyAgentRequest(gauge, estimate)\n\t\tthis.#options.record({ estimate, projected }, request)\n\t}\n\n\tasync *#relay(\n\t\tsource: AsyncGenerator<ProviderDelta, ProviderResult>,\n\t\tsignal: AbortSignal,\n\t): AsyncGenerator<ProviderDelta, ProviderResult> {\n\t\tconst result = yield* source\n\t\tif (this.#options.enforced && !signal.aborted) validateStudyAgentUsage(result.usage, 'agent')\n\t\treturn result\n\t}\n}\n","import type { JudgeInterface, JudgeRequest, JudgeResult } from '@orkestrel/agent'\nimport type { StudyLatchInterface } from './types.js'\n\n/** Latches a real judge's failure before an enclosing runtime can treat it as absent. */\nexport class StudyAgentJudge implements JudgeInterface {\n\treadonly #judge: JudgeInterface\n\treadonly #latch: StudyLatchInterface\n\n\t/** Binds a real public judge to the trial's failure owner.\n\t * @param judge - The admitted judge every question is delegated to.\n\t * @param latch - The owner that retains the first operational failure.\n\t */\n\tconstructor(judge: JudgeInterface, latch: StudyLatchInterface) {\n\t\tthis.#judge = judge\n\t\tthis.#latch = latch\n\t}\n\n\t/** Reports the delegate's trace label. */\n\tget id(): string {\n\t\treturn this.#judge.id\n\t}\n\n\t/** Reports the delegate's backend name. */\n\tget name(): string {\n\t\treturn this.#judge.name\n\t}\n\n\t/** Reports the delegate's model identity. */\n\tget model(): string {\n\t\treturn this.#judge.model\n\t}\n\n\t/** Refuses dispatch after a retained failure and retains a thrown failure with its identity.\n\t * @param request - The real classification request.\n\t * @param signal - The caller's cancellation.\n\t * @returns The unmodified judge result.\n\t */\n\tasync ask(request: JudgeRequest, signal: AbortSignal): Promise<JudgeResult> {\n\t\tthis.#latch.check()\n\t\ttry {\n\t\t\treturn await this.#judge.ask(request, signal)\n\t\t} catch (error) {\n\t\t\tthis.#latch.fail(error)\n\t\t\tthrow error\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AASA,IAAa,oBAAoB,OAAO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,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ;EAC5C;EACA,MAAM,WAAW,KAAK,SAAS,QAAQ,gBAAgB,OAAO;EAC9D,MAAM,QAAQ,KAAK,SAAS;EAC5B,MAAM,YAAY,UAAU,KAAA,IAAY,KAAA,IAAY,yBAAyB,OAAO,QAAQ;EAC5F,KAAK,SAAS,OAAO;GAAE;GAAU;EAAU,GAAG,OAAO;CACtD;CAEA,OAAO,OACN,QACA,QACgD;EAChD,MAAM,SAAS,OAAO;EACtB,IAAI,KAAK,SAAS,YAAY,CAAC,OAAO,SAAS,wBAAwB,OAAO,OAAO,OAAO;EAC5F,OAAO;CACR;AACD;;;;AC/FA,IAAa,kBAAb,MAAuD;CACtD;CACA;;;;;CAMA,YAAY,OAAuB,OAA4B;EAC9D,KAAK,SAAS;EACd,KAAK,SAAS;CACf;;CAGA,IAAI,KAAa;EAChB,OAAO,KAAK,OAAO;CACpB;;CAGA,IAAI,OAAe;EAClB,OAAO,KAAK,OAAO;CACpB;;CAGA,IAAI,QAAgB;EACnB,OAAO,KAAK,OAAO;CACpB;;;;;;CAOA,MAAM,IAAI,SAAuB,QAA2C;EAC3E,KAAK,OAAO,MAAM;EAClB,IAAI;GACH,OAAO,MAAM,KAAK,OAAO,IAAI,SAAS,MAAM;EAC7C,SAAS,OAAO;GACf,KAAK,OAAO,KAAK,KAAK;GACtB,MAAM;EACP;CACD;AACD"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/helpers.ts","../../../src/core/validators.ts","../../../src/core/errors.ts","../../../src/core/parsers.ts","../../../src/core/engines/helpers.ts","../../../src/core/engines/StudyControl.ts","../../../src/core/engines/StudyScope.ts","../../../src/core/engines/StudyDeadline.ts","../../../src/core/engines/StudyRequest.ts","../../../src/core/engines/StudyMeter.ts","../../../src/core/engines/StudyTrialLease.ts","../../../src/core/engines/StudySeries.ts","../../../src/core/agents/helpers.ts","../../../src/core/agents/validators.ts","../../../src/core/agents/StudyAgentObserver.ts","../../../src/core/agents/StudyAgentJudge.ts"],"sourcesContent":["import type { StudyCause, StudyLayer, StudyRole } from './types.js'\n\n/**\n * Keys the own self-identity every study error stamps on itself.\n * @remarks\n * The global symbol registry lets every package, ESM, CommonJS and captured copy read the same\n * key. The registry makes the key discoverable; it is a recognition mechanism, not an\n * unforgeable provenance marker.\n */\nexport const STUDY_ERROR_BRAND = Symbol.for('@orkestrel/study.error')\n\n/** Caps a declared trial population before schedule allocation. */\nexport const STUDY_TRIALS = 4096\n\n/** Caps a declared scenario horizon before execution. */\nexport const STUDY_GOALS = 4096\n\n/** Restricts identifiers to portable path-safe names. */\nexport const STUDY_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n\n/** Lists every measured request role in report order. */\nexport const STUDY_ROLES: readonly StudyRole[] = Object.freeze([\n\t'agent',\n\t'judge',\n\t'summary',\n\t'metadata',\n\t'tool',\n])\n\n/** Lists every ceiling a run can stop at in report order. */\nexport const STUDY_LAYERS: readonly StudyLayer[] = Object.freeze([\n\t'scope',\n\t'window',\n\t'custody',\n\t'meter',\n\t'budget',\n\t'model',\n])\n\n/** Lists every operational ending in report order. */\nexport const STUDY_CAUSES: readonly StudyCause[] = Object.freeze([\n\t'capacity',\n\t'infrastructure',\n\t'deadline',\n\t'interrupted',\n\t'content',\n])\n","import type {\n\tStudyDefinition,\n\tStudyGrading,\n\tStudyManifest,\n\tStudyProfile,\n\tStudyRubric,\n\tStudyScenario,\n\tStudyScore,\n\tStudyStop,\n\tStudyTrial,\n} from './types.js'\nimport type { JSONValue } from '@orkestrel/contract'\nimport { holds, canonicalStringify, isRecord } from '@orkestrel/contract'\nimport { StudyError } from './errors.js'\nimport {\n\tisStudyDefinition,\n\tisStudyGrading,\n\tisStudyProfile,\n\tisStudyRubric,\n\tisStudyScenario,\n} from './validators.js'\n\n/**\n * Copies the own entries of a record that hold a value, in their original order.\n * @param value - The record whose undefined entries are absent declarations\n * @returns A new record without the undefined entries\n * @example\n * ```ts\n * omitStudyAbsent({ context: 512, recap: undefined }) // { context: 512 }\n * ```\n */\nexport function omitStudyAbsent(value: object): Readonly<Record<string, unknown>> {\n\treturn Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined))\n}\n\n/**\n * Omits every undefined optional declaration so the profile has one JSON form.\n * @param profile - The validated profile whose optional leaves may be undefined\n * @returns The profile fields with absent qualification, settings, provider, judge and recap removed\n * @example\n * ```ts\n * normalizeStudyProfile(profile) // no `recap` key when the room declares none\n * ```\n */\nexport function normalizeStudyProfile(profile: StudyProfile): Readonly<Record<string, unknown>> {\n\tconst { provider, qualification, settings, room, ...required } = profile\n\treturn {\n\t\t...required,\n\t\troom: omitStudyAbsent(room),\n\t\t...(provider === undefined\n\t\t\t? {}\n\t\t\t: { provider: { ...omitStudyAbsent(provider), digest: omitStudyAbsent(provider.digest) } }),\n\t\t...(qualification === undefined ? {} : { qualification }),\n\t\t...(settings === undefined ? {} : { settings }),\n\t}\n}\n\n/**\n * Projects a stop onto JSON with every unreported reading as null.\n * @param stop - The ceiling that stopped a run\n * @returns The stop's layer, id, and readings, with an undefined `max` or `consumed` as null\n * @example\n * ```ts\n * studyStopToJSON({ layer: 'model', id: 'num_predict', max: 2048, consumed: undefined })\n * // { layer: 'model', id: 'num_predict', max: 2048, consumed: null }\n * ```\n */\nexport function studyStopToJSON(stop: StudyStop): JSONValue {\n\treturn {\n\t\tlayer: stop.layer,\n\t\tid: stop.id,\n\t\tmax: stop.max ?? null,\n\t\tconsumed: stop.consumed ?? null,\n\t}\n}\n\n/**\n * Matches exact own enumerable data keys without evaluating accessors.\n * @param value - The candidate record\n * @param required - Required keys\n * @param optional - Allowed optional keys\n * @returns True if the record has exactly the allowed data keys; false otherwise\n * @example Check exact keys\n * ```ts\n * import { matchesStudyKeys } from '@orkestrel/study'\n *\n * matchesStudyKeys({ id: 'one' }, ['id']) // true\n * ```\n */\nexport function matchesStudyKeys(\n\tvalue: unknown,\n\trequired: readonly string[],\n\toptional: readonly string[] = [],\n): boolean {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst keys = Reflect.ownKeys(value)\n\t\treturn (\n\t\t\trequired.every((key) => Object.hasOwn(value, key)) &&\n\t\t\tkeys.every((key) => {\n\t\t\t\tif (typeof key !== 'string' || (!required.includes(key) && !optional.includes(key)))\n\t\t\t\t\treturn false\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key)\n\t\t\t\treturn (\n\t\t\t\t\tdescriptor !== undefined &&\n\t\t\t\t\tdescriptor.enumerable === true &&\n\t\t\t\t\tObject.hasOwn(descriptor, 'value')\n\t\t\t\t)\n\t\t\t})\n\t\t)\n\t})\n}\n\n/**\n * Builds a bounded schedule from explicit repetition rows and declared scenarios.\n * @param definition - The frozen population declaration\n * @param scenarios - The complete scenario declarations\n * @returns Owned trials in repetition, scenario and row-arm order\n * @throws StudyError - Thrown when the population or scenario set is invalid\n * @example\n * ```ts\n * buildStudySchedule(definition, scenarios)\n * ```\n */\nexport function buildStudySchedule(\n\tdefinition: StudyDefinition,\n\tscenarios: readonly StudyScenario[],\n): readonly StudyTrial[] {\n\tif (!isStudyDefinition(definition) || !scenarios.every(isStudyScenario))\n\t\tthrow new StudyError('CONFIG', 'Invalid study population')\n\tconst ids = new Set(scenarios.map((scenario) => scenario.id))\n\tif (\n\t\tids.size !== scenarios.length ||\n\t\tids.size !== definition.scenarios.length ||\n\t\t!definition.scenarios.every((id) => ids.has(id))\n\t)\n\t\tthrow new StudyError('CONFIG', 'Scenario declarations must match the population exactly')\n\treturn Object.freeze(\n\t\t[...definition.order.entries()].flatMap(([repetition, row]) =>\n\t\t\t[...definition.scenarios.entries()].flatMap(([scenario, id]) =>\n\t\t\t\trow.map((arm): StudyTrial =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tid: `r${repetition + 1}-s${scenario + 1}-a${definition.arms.indexOf(arm) + 1}`,\n\t\t\t\t\t\tscenario: id,\n\t\t\t\t\t\tarm,\n\t\t\t\t\t\trepetition,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t)\n}\n\n/**\n * Validates grading coverage and request room against the declared study inputs.\n * @param definition - The population declaration\n * @param scenarios - The complete scenario declarations\n * @param rubric - The independently held grading declaration\n * @param profile - The execution bounds and model room\n * @returns Nothing when every cross-input invariant holds\n * @throws StudyError - Thrown when any input or cross-reference is invalid, or a quality study has no capacity qualification\n * @example\n * ```ts\n * validateStudyInputs(definition, scenarios, rubric, profile)\n * ```\n */\nexport function validateStudyInputs(\n\tdefinition: StudyDefinition,\n\tscenarios: readonly StudyScenario[],\n\trubric: StudyRubric,\n\tprofile: StudyProfile,\n): void {\n\tbuildStudySchedule(definition, scenarios)\n\tif (!isStudyRubric(rubric) || !isStudyProfile(profile))\n\t\tthrow new StudyError('CONFIG', 'Invalid rubric or profile')\n\tif (\n\t\tprofile.bounds.request.tokens > profile.room.context - profile.room.safety ||\n\t\tprofile.room.output > profile.bounds.request.tokens\n\t)\n\t\tthrow new StudyError('CONFIG', 'Request allowance does not fit the model room')\n\tfor (const criterion of rubric.criteria) {\n\t\tconst scenario = scenarios.find((entry) => entry.id === criterion.scenario)\n\t\tif (scenario === undefined || !scenario.goals.some((goal) => goal.id === criterion.goal))\n\t\t\tthrow new StudyError('CONFIG', 'Criterion references an undeclared goal')\n\t\tif (definition.purpose === 'mechanism' && criterion.method === 'semantic')\n\t\t\tthrow new StudyError('CONFIG', 'Mechanism studies cannot establish semantic quality')\n\t}\n\tconst covered = new Set(\n\t\trubric.criteria.map(\n\t\t\t(criterion) => canonicalStringify([criterion.scenario, criterion.goal]) ?? '',\n\t\t),\n\t)\n\tfor (const scenario of scenarios) {\n\t\tfor (const goal of scenario.goals) {\n\t\t\tif (!covered.has(canonicalStringify([scenario.id, goal.id]) ?? ''))\n\t\t\t\tthrow new StudyError('CONFIG', 'Every declared goal needs a criterion')\n\t\t}\n\t}\n\tif (definition.purpose === 'quality' && profile.qualification === undefined)\n\t\tthrow new StudyError('CONFIG', 'Quality studies require a capacity qualification')\n}\n\n/**\n * Computes arm intervals over the complete declared criterion horizon.\n * @param manifest - The sealed population and schedule\n * @param rubric - The criterion declaration\n * @param grading - Judgments bound to the complete scheduled attempt set\n * @returns Whole-horizon scores in declared arm order\n * @throws StudyError - Thrown when schedule, attempts or judgments are incompatible\n * @example\n * ```ts\n * computeStudyScores(manifest, rubric, grading)\n * ```\n */\nexport function computeStudyScores(\n\tmanifest: StudyManifest,\n\trubric: StudyRubric,\n\tgrading: StudyGrading,\n): readonly StudyScore[] {\n\tif (!isStudyRubric(rubric) || !isStudyGrading(grading))\n\t\tthrow new StudyError('EVIDENCE', 'Invalid rubric or grading')\n\tconst expected = buildStudySchedule(manifest.definition, manifest.scenarios)\n\tif (canonicalStringify(expected) !== canonicalStringify(manifest.schedule))\n\t\tthrow new StudyError('EVIDENCE', 'Manifest schedule differs from the declared population')\n\tconst trials = new Map(expected.map((trial) => [trial.id, trial]))\n\tif (\n\t\tgrading.attempts.length !== expected.length ||\n\t\t!grading.attempts.every((id) => trials.has(id))\n\t)\n\t\tthrow new StudyError('EVIDENCE', 'Grading attempts differ from the declared schedule')\n\tconst criteria = new Map(rubric.criteria.map((criterion) => [criterion.id, criterion]))\n\tfor (const scenario of manifest.scenarios) {\n\t\tfor (const goal of scenario.goals) {\n\t\t\tif (\n\t\t\t\t!rubric.criteria.some(\n\t\t\t\t\t(criterion) => criterion.scenario === scenario.id && criterion.goal === goal.id,\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow new StudyError('EVIDENCE', 'Rubric omits a declared goal')\n\t\t}\n\t}\n\tfor (const criterion of rubric.criteria) {\n\t\tif (\n\t\t\t!manifest.scenarios.some(\n\t\t\t\t(scenario) =>\n\t\t\t\t\tscenario.id === criterion.scenario &&\n\t\t\t\t\tscenario.goals.some((goal) => goal.id === criterion.goal),\n\t\t\t) ||\n\t\t\t(manifest.definition.purpose === 'mechanism' && criterion.method === 'semantic')\n\t\t)\n\t\t\tthrow new StudyError('EVIDENCE', 'Criterion is incompatible with the study')\n\t}\n\tconst keyed = grading.judgments.map((judgment) => ({\n\t\tjudgment,\n\t\tkey: canonicalStringify([judgment.trial, judgment.criterion]) ?? '',\n\t}))\n\t// Reversed so the earliest index of each key is the one the lookup retains.\n\tconst firsts = new Map([...keyed.entries()].reverse().map(([index, { key }]) => [key, index]))\n\tfor (const [index, { judgment, key }] of keyed.entries()) {\n\t\tconst trial = trials.get(judgment.trial)\n\t\tconst criterion = criteria.get(judgment.criterion)\n\t\tif (\n\t\t\ttrial === undefined ||\n\t\t\tcriterion === undefined ||\n\t\t\tcriterion.scenario !== trial.scenario ||\n\t\t\tfirsts.get(key) !== index\n\t\t)\n\t\t\tthrow new StudyError('EVIDENCE', 'Duplicate or foreign trial criterion judgment')\n\t\tif (\n\t\t\tcriterion.method === 'semantic'\n\t\t\t\t? judgment.method !== 'human' && judgment.method !== 'model'\n\t\t\t\t: judgment.method !== criterion.method\n\t\t)\n\t\t\tthrow new StudyError('EVIDENCE', 'Judgment method differs from the criterion')\n\t}\n\tconst judgments = new Map(keyed.map(({ key, judgment }) => [key, judgment]))\n\treturn Object.freeze(\n\t\tmanifest.definition.arms.map((arm): StudyScore => {\n\t\t\tconst pairs = expected\n\t\t\t\t.filter((trial) => trial.arm === arm)\n\t\t\t\t.flatMap((trial) =>\n\t\t\t\t\trubric.criteria\n\t\t\t\t\t\t.filter((criterion) => criterion.scenario === trial.scenario)\n\t\t\t\t\t\t.map((criterion) => ({\n\t\t\t\t\t\t\tcriterion,\n\t\t\t\t\t\t\tjudgment: judgments.get(canonicalStringify([trial.id, criterion.id]) ?? ''),\n\t\t\t\t\t\t})),\n\t\t\t\t)\n\t\t\tconst refuted = pairs.filter(({ judgment }) => judgment?.verdict === 'unsuccessful')\n\t\t\tconst total = pairs.length\n\t\t\tconst achieved = pairs.filter(({ judgment }) => judgment?.verdict === 'achieved').length\n\t\t\tconst unsuccessful = refuted.length\n\t\t\tconst critical = refuted.filter(({ criterion }) => criterion.critical).length\n\t\t\tconst unknown = total - achieved - unsuccessful\n\t\t\treturn Object.freeze({\n\t\t\t\tarm,\n\t\t\t\ttotal,\n\t\t\t\tachieved,\n\t\t\t\tunsuccessful,\n\t\t\t\tunknown,\n\t\t\t\tcritical,\n\t\t\t\tlower: achieved / total,\n\t\t\t\tupper: (achieved + unknown) / total,\n\t\t\t\tcoverage: (achieved + unsuccessful) / total,\n\t\t\t})\n\t\t}),\n\t)\n}\n","import type {\n\tStudyBounds,\n\tStudyCause,\n\tStudyDefinition,\n\tStudyCriterion,\n\tStudyErrorCode,\n\tStudyGrading,\n\tStudyJudgment,\n\tStudyLabeling,\n\tStudyGoal,\n\tStudyLimit,\n\tStudyProduct,\n\tStudyProfile,\n\tStudyProvider,\n\tStudyLayer,\n\tStudyRole,\n\tStudyRoom,\n\tStudyScenario,\n\tStudyRubric,\n\tStudyStop,\n\tStudyUsage,\n} from './types.js'\nimport type { Guard } from '@orkestrel/contract'\nimport {\n\tholds,\n\tcanonicalStringify,\n\tisArray,\n\tisFiniteNumber,\n\tisJSONValue,\n\tisNonEmptyString,\n\tisRecord,\n\tliteralOf,\n} from '@orkestrel/contract'\nimport { MAX_TIMEOUT_MS } from '@orkestrel/timeout'\nimport {\n\tSTUDY_CAUSES,\n\tSTUDY_GOALS,\n\tSTUDY_LAYERS,\n\tSTUDY_NAME,\n\tSTUDY_ROLES,\n\tSTUDY_TRIALS,\n} from './constants.js'\nimport { matchesStudyKeys } from './helpers.js'\n\n/** Checks whether a value names a measured request role. */\nexport const isStudyRole: Guard<StudyRole> = literalOf(STUDY_ROLES)\n\n/** Checks whether a value names an operational ending. */\nexport const isStudyCause: Guard<StudyCause> = literalOf(STUDY_CAUSES)\n\n/** Checks whether a value names a ceiling a run can stop at. */\nexport const isStudyLayer: Guard<StudyLayer> = literalOf(STUDY_LAYERS)\n\n/**\n * Checks whether a value is the exact record of a ceiling that stopped a run.\n * @remarks\n * The guard accepts exact own data keys: `layer` and `id` are required and `max` and `consumed` are\n * optional. `max` and `consumed` are each undefined or a finite number. Finite foreign readings,\n * including negative and fractional values, retain the source's measurement unchanged.\n * @param value - The candidate stop\n * @returns True if the layer is known, the id is nonempty, and every reading is absent or finite; false otherwise\n * @example\n * ```ts\n * isStudyStop({ layer: 'scope', id: 'Goal tokens', max: 100, consumed: 120 }) // true\n * ```\n */\nexport function isStudyStop(value: unknown): value is StudyStop {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['layer', 'id'], ['max', 'consumed']) &&\n\t\t\tisStudyLayer(value.layer) &&\n\t\t\tisNonEmptyString(value.id) &&\n\t\t\t['max', 'consumed'].every((key) => value[key] === undefined || isFiniteNumber(value[key])),\n\t)\n}\n\n/**\n * Checks whether an identifier is portable and bounded.\n * @param value - The candidate identifier\n * @returns True if it is a portable study identifier; false otherwise\n * @example\n * ```ts\n * isStudyName('memory') // true\n * ```\n */\nexport function isStudyName(value: unknown): value is string {\n\treturn typeof value === 'string' && value.length <= 128 && STUDY_NAME.test(value)\n}\n\n/**\n * Checks whether all allowances are positive safe integers within timer bounds.\n * @param value - The candidate limit\n * @returns True if it defines finite positive allowances; false otherwise\n * @example\n * ```ts\n * isStudyLimit({ duration: 1000, calls: 1, tokens: 100, bytes: 1024 }) // true\n * ```\n */\nexport function isStudyLimit(value: unknown): value is StudyLimit {\n\treturn holds(() => {\n\t\tif (!isRecord(value) || !matchesStudyKeys(value, ['duration', 'calls', 'tokens', 'bytes']))\n\t\t\treturn false\n\t\treturn (\n\t\t\t['duration', 'calls', 'tokens', 'bytes'].every(\n\t\t\t\t(key) =>\n\t\t\t\t\ttypeof value[key] === 'number' && Number.isSafeInteger(value[key]) && value[key] > 0,\n\t\t\t) &&\n\t\t\ttypeof value.duration === 'number' &&\n\t\t\tvalue.duration <= MAX_TIMEOUT_MS\n\t\t)\n\t})\n}\n\n/**\n * Checks whether nested scopes admit no larger allowance than their parent.\n * @param value - The candidate bounds\n * @returns True if every nested allowance is ordered; false otherwise\n * @example\n * ```ts\n * isStudyBounds({}) // false\n * ```\n */\nexport function isStudyBounds(value: unknown): value is StudyBounds {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(value, ['request', 'goal', 'trial', 'series']) ||\n\t\t\t!isStudyLimit(value.request) ||\n\t\t\t!isStudyLimit(value.goal) ||\n\t\t\t!isStudyLimit(value.trial) ||\n\t\t\t!isStudyLimit(value.series)\n\t\t)\n\t\t\treturn false\n\t\tconst limits = [value.request, value.goal, value.trial, value.series]\n\t\tfor (const [index, limit] of limits.entries()) {\n\t\t\tconst next = limits[index + 1]\n\t\t\tif (next === undefined) continue\n\t\t\tif (\n\t\t\t\tlimit.duration > next.duration ||\n\t\t\t\tlimit.calls > next.calls ||\n\t\t\t\tlimit.tokens > next.tokens ||\n\t\t\t\tlimit.bytes > next.bytes\n\t\t\t)\n\t\t\t\treturn false\n\t\t}\n\t\treturn value.request.calls === 1\n\t})\n}\n\n/**\n * Checks whether a goal has a bounded identifier and exact JSON input.\n * @param value - The candidate goal\n * @returns True if the goal is valid; false otherwise\n * @example\n * ```ts\n * isStudyGoal({ id: 'write', input: { text: 'hello' } }) // true\n * ```\n */\nexport function isStudyGoal(value: unknown): value is StudyGoal {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['id', 'input']) &&\n\t\t\tisStudyName(value.id) &&\n\t\t\tisJSONValue(value.input)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a scenario declares a nonempty horizon with unique goal ids.\n * @param value - The candidate scenario\n * @returns True if the scenario has a valid horizon; false otherwise\n * @example\n * ```ts\n * isStudyScenario({ id: 'shift', goals: [{ id: 'handoff', input: 'Prepare handoff' }] }) // true\n * ```\n */\nexport function isStudyScenario(value: unknown): value is StudyScenario {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(value, ['id', 'goals']) ||\n\t\t\t!isStudyName(value.id) ||\n\t\t\t!isArray(value.goals)\n\t\t)\n\t\t\treturn false\n\t\treturn (\n\t\t\tvalue.goals.length > 0 &&\n\t\t\tvalue.goals.length <= STUDY_GOALS &&\n\t\t\tvalue.goals.every(isStudyGoal) &&\n\t\t\tnew Set(value.goals.map((goal) => goal.id)).size === value.goals.length &&\n\t\t\tisJSONValue(value.goals)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a study freezes a complete arm order for every repetition.\n * @param value - The candidate definition\n * @returns True if its population and repetition orders are valid; false otherwise\n * @example\n * ```ts\n * isStudyDefinition({ name: 'tools' }) // false\n * ```\n */\nexport function isStudyDefinition(value: unknown): value is StudyDefinition {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!isJSONValue(value) ||\n\t\t\t!matchesStudyKeys(value, [\n\t\t\t\t'name',\n\t\t\t\t'version',\n\t\t\t\t'question',\n\t\t\t\t'purpose',\n\t\t\t\t'driver',\n\t\t\t\t'arms',\n\t\t\t\t'scenarios',\n\t\t\t\t'order',\n\t\t\t\t'retries',\n\t\t\t\t'rubric',\n\t\t\t]) ||\n\t\t\t!isStudyName(value.name) ||\n\t\t\t!isStudyName(value.driver) ||\n\t\t\t!isNonEmptyString(value.version) ||\n\t\t\t!isNonEmptyString(value.question) ||\n\t\t\t(value.purpose !== 'mechanism' &&\n\t\t\t\tvalue.purpose !== 'quality' &&\n\t\t\t\tvalue.purpose !== 'capacity') ||\n\t\t\t!isArray(value.arms) ||\n\t\t\tvalue.arms.length === 0 ||\n\t\t\t!value.arms.every(isStudyName) ||\n\t\t\tnew Set(value.arms).size !== value.arms.length ||\n\t\t\t!isArray(value.scenarios) ||\n\t\t\tvalue.scenarios.length === 0 ||\n\t\t\t!value.scenarios.every(isStudyName) ||\n\t\t\tnew Set(value.scenarios).size !== value.scenarios.length ||\n\t\t\t!isArray(value.order) ||\n\t\t\t!isJSONValue(value.order) ||\n\t\t\tvalue.order.length === 0 ||\n\t\t\tvalue.retries !== 0 ||\n\t\t\t!isNonEmptyString(value.rubric)\n\t\t)\n\t\t\treturn false\n\t\tconst arms = value.arms\n\t\tif (arms.length * value.scenarios.length * value.order.length > STUDY_TRIALS) return false\n\t\treturn value.order.every(\n\t\t\t(order) =>\n\t\t\t\tisArray(order) &&\n\t\t\t\torder.length === arms.length &&\n\t\t\t\tnew Set(order).size === arms.length &&\n\t\t\t\torder.every((arm) => typeof arm === 'string' && arms.includes(arm)),\n\t\t)\n\t})\n}\n\n/**\n * Checks whether generation room leaves positive context for input.\n * @param value - The candidate room\n * @returns True if input, output and safety allowances fit and any declared recap fits; false otherwise\n * @example\n * ```ts\n * isStudyRoom({ context: 20480, output: 8192, safety: 512, recap: 2048, think: true }) // true\n * isStudyRoom({ context: 20480, output: 8192, safety: 512, think: true }) // true\n * ```\n */\nexport function isStudyRoom(value: unknown): value is StudyRoom {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(value, ['context', 'output', 'safety', 'think'], ['recap']) ||\n\t\t\ttypeof value.think !== 'boolean'\n\t\t)\n\t\t\treturn false\n\t\tconst declared = value.recap === undefined ? [] : ['recap']\n\t\tif (\n\t\t\t!['context', 'output', 'safety', ...declared].every(\n\t\t\t\t(key) =>\n\t\t\t\t\ttypeof value[key] === 'number' && Number.isSafeInteger(value[key]) && value[key] > 0,\n\t\t\t)\n\t\t)\n\t\t\treturn false\n\t\treturn (\n\t\t\ttypeof value.context === 'number' &&\n\t\t\ttypeof value.output === 'number' &&\n\t\t\ttypeof value.safety === 'number' &&\n\t\t\tvalue.output + value.safety < value.context &&\n\t\t\t(value.recap === undefined ||\n\t\t\t\t(typeof value.recap === 'number' && value.recap + value.safety < value.context))\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a provider declaration names artifacts, an HTTP origin and models.\n * @param value - The candidate provider declaration\n * @returns True if the declaration has a supported origin, nonempty names, and a judge declared with its digest or not at all; false otherwise\n * @example\n * ```ts\n * isStudyProvider({ entry: 'dist/index.js' }) // false\n * ```\n */\nexport function isStudyProvider(value: unknown): value is StudyProvider {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(value, ['entry', 'url', 'model', 'digest'], ['judge']) ||\n\t\t\t!['entry', 'url', 'model'].every((key) => isNonEmptyString(value[key])) ||\n\t\t\ttypeof value.url !== 'string' ||\n\t\t\t!isRecord(value.digest) ||\n\t\t\t!matchesStudyKeys(value.digest, ['model'], ['judge']) ||\n\t\t\t!isStudyDigest(value.digest.model) ||\n\t\t\t(value.judge === undefined) !== (value.digest.judge === undefined) ||\n\t\t\t(value.judge !== undefined &&\n\t\t\t\t(!isNonEmptyString(value.judge) || !isStudyDigest(value.digest.judge)))\n\t\t)\n\t\t\treturn false\n\t\tconst url = new URL(value.url)\n\t\treturn (\n\t\t\t['http:', 'https:'].includes(url.protocol) &&\n\t\t\turl.username === '' &&\n\t\t\turl.password === '' &&\n\t\t\turl.search === '' &&\n\t\t\turl.hash === '' &&\n\t\t\turl.pathname === '/'\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a profile carries finite bounds and an optional explicit provider.\n * @param value - The candidate profile\n * @returns True if the profile is structurally valid; false otherwise\n * @example\n * ```ts\n * isStudyProfile({ name: 'local' }) // false\n * ```\n */\nexport function isStudyProfile(value: unknown): value is StudyProfile {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(\n\t\t\t\tvalue,\n\t\t\t\t['name', 'agent', 'subject', 'roots', 'bounds', 'room'],\n\t\t\t\t['provider', 'qualification', 'settings'],\n\t\t\t) &&\n\t\t\tisStudyName(value.name) &&\n\t\t\tisNonEmptyString(value.agent) &&\n\t\t\tisArray(value.roots) &&\n\t\t\tisJSONValue(value.roots) &&\n\t\t\tvalue.roots.length > 0 &&\n\t\t\tvalue.roots.every((root) => typeof root === 'string' && root.trim().length > 0) &&\n\t\t\tnew Set(value.roots).size === value.roots.length &&\n\t\t\tisNonEmptyString(value.subject) &&\n\t\t\tisStudyBounds(value.bounds) &&\n\t\t\tisStudyRoom(value.room) &&\n\t\t\t(value.provider === undefined || isStudyProvider(value.provider)) &&\n\t\t\t(value.qualification === undefined || isNonEmptyString(value.qualification)) &&\n\t\t\t(value.settings === undefined || (isRecord(value.settings) && isJSONValue(value.settings)))\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a byte identity is a lowercase SHA-256 digest.\n * @param value - The candidate identity\n * @returns True if it has exactly 64 hexadecimal digits; false otherwise\n * @example\n * ```ts\n * isStudyDigest('a'.repeat(64)) // true\n * ```\n */\nexport function isStudyDigest(value: unknown): value is string {\n\treturn typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)\n}\n\n/**\n * Checks whether a timestamp is a canonical UTC millisecond instant.\n * @param value - The candidate timestamp\n * @returns True if it is a valid canonical timestamp; false otherwise\n * @example\n * ```ts\n * isStudyTimestamp('2026-10-14T12:00:00.000Z') // true\n * ```\n */\nexport function isStudyTimestamp(value: unknown): value is string {\n\treturn holds(() => {\n\t\treturn (\n\t\t\ttypeof value === 'string' &&\n\t\t\t/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/.test(value) &&\n\t\t\tnew Date(value).toISOString() === value\n\t\t)\n\t})\n}\n\n/**\n * Checks whether request usage contains nonnegative safe measurements.\n * @param value - The candidate usage\n * @returns True if the role and every known measurement are valid; false otherwise\n * @example\n * ```ts\n * isStudyUsage({ role: 'tool', calls: 0, bytes: 0, duration: 0 }) // true\n * ```\n */\nexport function isStudyUsage(value: unknown): value is StudyUsage {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['role', 'calls', 'duration'], ['tokens', 'bytes']) &&\n\t\t\tisStudyRole(value.role) &&\n\t\t\t['calls', 'duration'].every(\n\t\t\t\t(key) =>\n\t\t\t\t\ttypeof value[key] === 'number' && Number.isSafeInteger(value[key]) && value[key] >= 0,\n\t\t\t) &&\n\t\t\t(value.bytes === undefined ||\n\t\t\t\t(typeof value.bytes === 'number' &&\n\t\t\t\t\tNumber.isSafeInteger(value.bytes) &&\n\t\t\t\t\tvalue.bytes >= 0)) &&\n\t\t\t(value.tokens === undefined ||\n\t\t\t\t(typeof value.tokens === 'number' &&\n\t\t\t\t\tNumber.isSafeInteger(value.tokens) &&\n\t\t\t\t\tvalue.tokens >= 0))\n\t\t)\n\t})\n}\n\n/**\n * Checks a retained public product without awarding task achievement.\n * @param value - The candidate product\n * @returns True if the product carries JSON output and partial status; false otherwise\n * @example\n * ```ts\n * isStudyProduct({ value: { answer: 1 }, partial: true }) // true\n * ```\n */\nexport function isStudyProduct(value: unknown): value is StudyProduct {\n\treturn holds(\n\t\t() => isRecord(value) && typeof value.partial === 'boolean' && isJSONValue(value.value),\n\t)\n}\n\n/**\n * Checks whether a criterion declares exact grading inputs and references.\n * @param value - The candidate criterion\n * @returns True if its structural grading declaration is valid; false otherwise\n * @example\n * ```ts\n * isStudyCriterion({ id: 'saved', scenario: 'shift', goal: 'write', method: 'state', critical: true, assertion: true }) // true\n * ```\n */\nexport function isStudyCriterion(value: unknown): value is StudyCriterion {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['id', 'scenario', 'goal', 'method', 'critical', 'assertion']) &&\n\t\t\tisStudyName(value.id) &&\n\t\t\tisStudyName(value.scenario) &&\n\t\t\tisStudyName(value.goal) &&\n\t\t\t(value.method === 'state' || value.method === 'trace' || value.method === 'semantic') &&\n\t\t\ttypeof value.critical === 'boolean' &&\n\t\t\tisJSONValue(value.assertion)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a rubric declares nonempty criteria with unique identities.\n * @param value - The candidate rubric\n * @returns True if its version and criteria are valid; false otherwise\n * @example\n * ```ts\n * isStudyRubric({ version: '1', criteria: [] }) // false\n * ```\n */\nexport function isStudyRubric(value: unknown): value is StudyRubric {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['version', 'criteria']) &&\n\t\t\ttypeof value.version === 'string' &&\n\t\t\tvalue.version.trim().length > 0 &&\n\t\t\tisArray(value.criteria) &&\n\t\t\tvalue.criteria.length > 0 &&\n\t\t\tvalue.criteria.every(isStudyCriterion) &&\n\t\t\tnew Set(value.criteria.map((criterion) => criterion.id)).size === value.criteria.length &&\n\t\t\tisJSONValue(value.criteria)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a judgment carries a supported verdict and evidence references.\n * @param value - The candidate judgment\n * @returns True if the judgment is attributable and structurally valid; false otherwise\n * @example\n * ```ts\n * isStudyJudgment({ trial: 'r1-s1-a1', criterion: 'saved', verdict: 'unknown', method: 'state', reason: 'No evidence', references: [] }) // true\n * ```\n */\nexport function isStudyJudgment(value: unknown): value is StudyJudgment {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, [\n\t\t\t\t'trial',\n\t\t\t\t'criterion',\n\t\t\t\t'verdict',\n\t\t\t\t'method',\n\t\t\t\t'reason',\n\t\t\t\t'references',\n\t\t\t]) &&\n\t\t\tisStudyName(value.trial) &&\n\t\t\tisStudyName(value.criterion) &&\n\t\t\t(value.verdict === 'achieved' ||\n\t\t\t\tvalue.verdict === 'unsuccessful' ||\n\t\t\t\tvalue.verdict === 'unknown') &&\n\t\t\t(value.method === 'state' ||\n\t\t\t\tvalue.method === 'trace' ||\n\t\t\t\tvalue.method === 'human' ||\n\t\t\t\tvalue.method === 'model') &&\n\t\t\ttypeof value.reason === 'string' &&\n\t\t\tvalue.reason.trim().length > 0 &&\n\t\t\tisArray(value.references) &&\n\t\t\tisJSONValue(value.references) &&\n\t\t\tvalue.references.every(\n\t\t\t\t(reference) => typeof reference === 'string' && reference.trim().length > 0,\n\t\t\t) &&\n\t\t\tnew Set(value.references).size === value.references.length &&\n\t\t\t(value.verdict === 'unknown' || value.references.length > 0)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether imported semantic labels have accountable packet provenance.\n * @param value - The candidate labels\n * @returns True if provenance, usage and semantic judgments are valid; false otherwise\n * @example\n * ```ts\n * isStudyLabeling({}) // false\n * ```\n */\nexport function isStudyLabeling(value: unknown): value is StudyLabeling {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['packet', 'labeler', 'version', 'created', 'usage', 'judgments']) &&\n\t\t\tisStudyDigest(value.packet) &&\n\t\t\ttypeof value.labeler === 'string' &&\n\t\t\tvalue.labeler.trim().length > 0 &&\n\t\t\ttypeof value.version === 'string' &&\n\t\t\tvalue.version.trim().length > 0 &&\n\t\t\tisStudyTimestamp(value.created) &&\n\t\t\tisArray(value.usage) &&\n\t\t\tReflect.ownKeys(value.usage).length === value.usage.length + 1 &&\n\t\t\tArray.from(value.usage).every(isStudyUsage) &&\n\t\t\tisArray(value.judgments) &&\n\t\t\tvalue.judgments.every(isStudyJudgment) &&\n\t\t\tvalue.judgments.every(\n\t\t\t\t(judgment) => judgment.method === 'human' || judgment.method === 'model',\n\t\t\t) &&\n\t\t\tnew Set(\n\t\t\t\tvalue.judgments.map((judgment) => canonicalStringify([judgment.trial, judgment.criterion])),\n\t\t\t).size === value.judgments.length &&\n\t\t\tisJSONValue(value.judgments)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a value names a supported study error code.\n * @param value - The candidate code\n * @returns True if it is a declared study error code; false otherwise\n * @example\n * ```ts\n * isStudyErrorCode('CONFIG') // true\n * ```\n */\nexport function isStudyErrorCode(value: unknown): value is StudyErrorCode {\n\treturn (\n\t\tvalue === 'CONFIG' ||\n\t\tvalue === 'EVIDENCE' ||\n\t\tvalue === 'CUSTODY' ||\n\t\tvalue === 'CAPACITY' ||\n\t\tvalue === 'FAULT' ||\n\t\tvalue === 'DEADLINE'\n\t)\n}\n\n/**\n * Checks whether grading binds accountable judgments to unique attempt identities.\n * @param value - The candidate grading\n * @returns True if its identities, attempts and judgments are valid; false otherwise\n * @example\n * ```ts\n * isStudyGrading({}) // false\n * ```\n */\nexport function isStudyGrading(value: unknown): value is StudyGrading {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(\n\t\t\t\tvalue,\n\t\t\t\t['result', 'rubric', 'grader', 'instrument', 'attempts', 'judgments'],\n\t\t\t\t['labels', 'packet'],\n\t\t\t) &&\n\t\t\tisStudyDigest(value.result) &&\n\t\t\tisStudyDigest(value.rubric) &&\n\t\t\tisStudyDigest(value.instrument) &&\n\t\t\ttypeof value.grader === 'string' &&\n\t\t\tvalue.grader.trim().length > 0 &&\n\t\t\t(value.labels === undefined || isStudyDigest(value.labels)) &&\n\t\t\t(value.packet === undefined || isStudyDigest(value.packet)) &&\n\t\t\tisArray(value.attempts) &&\n\t\t\tisJSONValue(value.attempts) &&\n\t\t\tvalue.attempts.every(isStudyName) &&\n\t\t\tnew Set(value.attempts).size === value.attempts.length &&\n\t\t\tisArray(value.judgments) &&\n\t\t\tvalue.judgments.every(isStudyJudgment) &&\n\t\t\tnew Set(\n\t\t\t\tvalue.judgments.map((judgment) => canonicalStringify([judgment.trial, judgment.criterion])),\n\t\t\t).size === value.judgments.length &&\n\t\t\tisJSONValue(value.judgments)\n\t\t)\n\t})\n}\n","import type { StudyErrorCode, StudyFailure } from './types.js'\nimport { holds, INTRINSICS, isError, isFiniteNumber, isObject } from '@orkestrel/contract'\nimport { STUDY_ERROR_BRAND } from './constants.js'\nimport { isStudyCause, isStudyErrorCode, isStudyLayer, isStudyRole } from './validators.js'\n\n/** Reports a study contract or operational failure with a stable code. */\nexport class StudyError extends Error {\n\treadonly code: StudyErrorCode\n\treadonly failure: StudyFailure | undefined\n\n\t/**\n\t * Records the failing boundary and optional operational attribution.\n\t * @param code - The machine-readable boundary\n\t * @param message - The specific failure\n\t * @param failure - The optional operational reading\n\t */\n\tconstructor(code: StudyErrorCode, message: string, failure?: StudyFailure) {\n\t\tsuper(message)\n\t\tINTRINSICS.define(this, STUDY_ERROR_BRAND, {\n\t\t\tvalue: this,\n\t\t\tenumerable: false,\n\t\t\twritable: false,\n\t\t\tconfigurable: true,\n\t\t})\n\t\tthis.name = 'StudyError'\n\t\tthis.code = code\n\t\tthis.failure = failure\n\t}\n}\n\n/**\n * Narrows a caught value to a branded study error with valid failure attribution.\n * @remarks\n * Recognition combines the native `Error` base, a subclass prototype, a declared study code,\n * valid optional failure members, and an own {@link STUDY_ERROR_BRAND} descriptor whose value is\n * the error itself. Subclasses can replace the name.\n * The global key is recognized across package, ESM, CommonJS and captured module copies; it is\n * not unforgeable provenance. A transparent proxy is refused because its forwarded descriptor\n * stores the target, and an unbranded copy, an inherited brand, or a property-only lookalike\n * stays outside the type. Hostile property access returns false instead of throwing.\n * @param value - The caught value\n * @returns True if the value is a study error; false otherwise\n * @example\n * ```ts\n * isStudyError(new StudyError('CONFIG', 'missing definition')) // true\n * ```\n */\nexport function isStudyError(value: unknown): value is StudyError {\n\treturn holds(() => {\n\t\tif (!isError(value) || INTRINSICS.prototype(value) === INTRINSICS.error.prototype) return false\n\t\tconst brand: unknown = INTRINSICS.describe(value, STUDY_ERROR_BRAND)?.value\n\t\tconst code: unknown = INTRINSICS.reflect.read(value, 'code')\n\t\tconst failure: unknown = INTRINSICS.reflect.read(value, 'failure')\n\t\tif (\n\t\t\tbrand !== value ||\n\t\t\t!isStudyErrorCode(code) ||\n\t\t\ttypeof INTRINSICS.reflect.read(value, 'name') !== 'string' ||\n\t\t\ttypeof INTRINSICS.reflect.read(value, 'message') !== 'string'\n\t\t)\n\t\t\treturn false\n\t\tif (failure === undefined) return true\n\t\tif (!isObject(failure)) return false\n\t\tconst cause: unknown = INTRINSICS.reflect.read(failure, 'cause')\n\t\tconst message: unknown = INTRINSICS.reflect.read(failure, 'message')\n\t\tconst role: unknown = INTRINSICS.reflect.read(failure, 'role')\n\t\tconst stop: unknown = INTRINSICS.reflect.read(failure, 'stop')\n\t\tif (\n\t\t\t!isStudyCause(cause) ||\n\t\t\ttypeof message !== 'string' ||\n\t\t\t(role !== undefined && !isStudyRole(role))\n\t\t)\n\t\t\treturn false\n\t\tif (stop === undefined) return true\n\t\tif (!isObject(stop)) return false\n\t\tconst layer: unknown = INTRINSICS.reflect.read(stop, 'layer')\n\t\tconst id: unknown = INTRINSICS.reflect.read(stop, 'id')\n\t\tconst max: unknown = INTRINSICS.reflect.read(stop, 'max')\n\t\tconst consumed: unknown = INTRINSICS.reflect.read(stop, 'consumed')\n\t\treturn (\n\t\t\tisStudyLayer(layer) &&\n\t\t\ttypeof id === 'string' &&\n\t\t\t(max === undefined || isFiniteNumber(max)) &&\n\t\t\t(consumed === undefined || isFiniteNumber(consumed))\n\t\t)\n\t})\n}\n","import type {\n\tStudyDefinition,\n\tStudyGrading,\n\tStudyLabeling,\n\tStudyProfile,\n\tStudyRubric,\n\tStudyScenario,\n} from './types.js'\nimport { cloneJSONValue, isFiniteNumber } from '@orkestrel/contract'\nimport { StudyError } from './errors.js'\nimport { normalizeStudyProfile } from './helpers.js'\nimport {\n\tisStudyDefinition,\n\tisStudyGrading,\n\tisStudyLabeling,\n\tisStudyProfile,\n\tisStudyRubric,\n\tisStudyScenario,\n} from './validators.js'\n\n/**\n * Parses a foreign reading into a number a stop can retain.\n * @param value - The unknown reading a source reports\n * @returns The value when it is a finite number; undefined otherwise\n * @example\n * ```ts\n * parseStudyReading(2048) // 2048\n * parseStudyReading(Number.NaN) // undefined\n * ```\n */\nexport function parseStudyReading(value: unknown): number | undefined {\n\treturn isFiniteNumber(value) ? value : undefined\n}\n\n/**\n * Parses a definition into an independent frozen validated snapshot.\n * @param value - The unknown configuration\n * @returns The owned study definition\n * @throws StudyError - Thrown when configuration is invalid or cannot be owned\n * @example\n * ```ts\n * parseStudyDefinition(configuration)\n * ```\n */\nexport function parseStudyDefinition(value: unknown): StudyDefinition {\n\ttry {\n\t\tif (!isStudyDefinition(value)) throw new StudyError('CONFIG', 'Invalid study definition')\n\t\tconst snapshot = cloneJSONValue(value)\n\t\tif (isStudyDefinition(snapshot)) return snapshot\n\t} catch {\n\t\tthrow new StudyError('CONFIG', 'Invalid or unreadable study definition')\n\t}\n\tthrow new StudyError('CONFIG', 'Invalid study definition snapshot')\n}\n\n/**\n * Parses a scenario into an independent frozen validated snapshot.\n * @param value - The unknown configuration\n * @returns The owned scenario and goal inputs\n * @throws StudyError - Thrown when configuration is invalid or cannot be owned\n * @example\n * ```ts\n * parseStudyScenario({ id: 'shift', goals: [{ id: 'write', input: {} }] })\n * ```\n */\nexport function parseStudyScenario(value: unknown): StudyScenario {\n\ttry {\n\t\tif (!isStudyScenario(value)) throw new StudyError('CONFIG', 'Invalid study scenario')\n\t\tconst snapshot = cloneJSONValue(value)\n\t\tif (isStudyScenario(snapshot)) return snapshot\n\t} catch {\n\t\tthrow new StudyError('CONFIG', 'Invalid or unreadable study scenario')\n\t}\n\tthrow new StudyError('CONFIG', 'Invalid study scenario snapshot')\n}\n\n/**\n * Parses a profile into an independent frozen validated snapshot.\n * @param value - The unknown configuration\n * @returns The owned profile with absent optional settings preserved\n * @throws StudyError - Thrown when configuration is invalid or cannot be owned\n * @example\n * ```ts\n * parseStudyProfile(configuration)\n * ```\n */\nexport function parseStudyProfile(value: unknown): StudyProfile {\n\ttry {\n\t\tif (!isStudyProfile(value)) throw new StudyError('CONFIG', 'Invalid study profile')\n\t\tconst snapshot = cloneJSONValue(normalizeStudyProfile(value))\n\t\tif (isStudyProfile(snapshot)) return snapshot\n\t} catch {\n\t\tthrow new StudyError('CONFIG', 'Invalid or unreadable study profile')\n\t}\n\tthrow new StudyError('CONFIG', 'Invalid study profile snapshot')\n}\n\n/**\n * Parses a rubric into an independent frozen validated snapshot.\n * @param value - The unknown grading declaration\n * @returns The owned rubric and assertion inputs\n * @throws StudyError - Thrown when configuration is invalid or cannot be owned\n * @example\n * ```ts\n * parseStudyRubric(configuration)\n * ```\n */\nexport function parseStudyRubric(value: unknown): StudyRubric {\n\ttry {\n\t\tif (!isStudyRubric(value)) throw new StudyError('CONFIG', 'Invalid study rubric')\n\t\tconst snapshot = cloneJSONValue(value)\n\t\tif (isStudyRubric(snapshot)) return snapshot\n\t} catch {\n\t\tthrow new StudyError('CONFIG', 'Invalid or unreadable study rubric')\n\t}\n\tthrow new StudyError('CONFIG', 'Invalid study rubric snapshot')\n}\n\n/**\n * Parses grading into an independent frozen validated evidence snapshot.\n * @param value - The unknown grading evidence\n * @returns The owned grading identity and judgments\n * @throws StudyError - Thrown when evidence is invalid or cannot be owned\n * @example\n * ```ts\n * parseStudyGrading(evidence)\n * ```\n */\nexport function parseStudyGrading(value: unknown): StudyGrading {\n\ttry {\n\t\tif (!isStudyGrading(value)) throw new StudyError('EVIDENCE', 'Invalid study grading')\n\t\tconst { labels, packet, ...required } = value\n\t\tconst snapshot = cloneJSONValue({\n\t\t\t...required,\n\t\t\t...(labels === undefined ? {} : { labels }),\n\t\t\t...(packet === undefined ? {} : { packet }),\n\t\t})\n\t\tif (isStudyGrading(snapshot)) return snapshot\n\t} catch {\n\t\tthrow new StudyError('EVIDENCE', 'Invalid or unreadable study grading')\n\t}\n\tthrow new StudyError('EVIDENCE', 'Invalid study grading snapshot')\n}\n\n/**\n * Parses semantic labels into an independent frozen validated evidence snapshot.\n * @param value - The unknown imported labels\n * @returns The owned packet provenance, usage and judgments\n * @throws StudyError - Thrown when evidence is invalid or cannot be owned\n * @example\n * ```ts\n * parseStudyLabeling(evidence)\n * ```\n */\nexport function parseStudyLabeling(value: unknown): StudyLabeling {\n\ttry {\n\t\tif (!isStudyLabeling(value)) throw new StudyError('EVIDENCE', 'Invalid study labels')\n\t\tconst snapshot = cloneJSONValue({\n\t\t\t...value,\n\t\t\tusage: value.usage.map(({ tokens, bytes, ...usage }) => ({\n\t\t\t\t...usage,\n\t\t\t\t...(tokens === undefined ? {} : { tokens }),\n\t\t\t\t...(bytes === undefined ? {} : { bytes }),\n\t\t\t})),\n\t\t})\n\t\tif (isStudyLabeling(snapshot)) return snapshot\n\t} catch {\n\t\tthrow new StudyError('EVIDENCE', 'Invalid or unreadable study labels')\n\t}\n\tthrow new StudyError('EVIDENCE', 'Invalid study labels snapshot')\n}\n","import type { BudgetInterface } from '@orkestrel/budget'\nimport type {\n\tStudyCharge,\n\tStudyFailure,\n\tStudyRole,\n\tStudyStop,\n\tStudyTicket,\n\tStudyUsage,\n} from '../types.js'\nimport { isBudgetError } from '@orkestrel/budget'\nimport { attempt, isError, isNonEmptyString } from '@orkestrel/contract'\nimport { isStudyError, StudyError } from '../errors.js'\nimport { parseStudyReading } from '../parsers.js'\n\n/** Converts an operational reading to its throwable boundary.\n * @param failure - The retained operational reading.\n * @returns An error preserving the reading's cause and responsibility.\n */\nexport function failureToStudyError(failure: StudyFailure): StudyError {\n\treturn new StudyError(\n\t\tfailure.cause === 'capacity' ? 'CAPACITY' : failure.cause === 'deadline' ? 'DEADLINE' : 'FAULT',\n\t\tfailure.message,\n\t\tfailure,\n\t)\n}\n\n/** Reads an operational error without inventing a task verdict.\n * @remarks\n * A branded `BudgetError` from any copy of the budget package reads as a `budget` stop, because the\n * error alone does not prove which budget object raised it; the Agent record names a `meter` stop.\n * An unbranded lookalike reads as an infrastructure failure.\n * @param error - The caught error.\n * @returns Existing attribution, the capacity a branded budget error names, the cause a bare\n * capacity or deadline code names, or an infrastructure failure.\n */\nexport function readStudyFailure(error: unknown): StudyFailure {\n\tif (isStudyError(error)) {\n\t\tconst { failure, code, message } = error\n\t\tif (failure !== undefined) return failure\n\t\tif (code === 'CAPACITY') return { cause: 'capacity', message, role: undefined, stop: undefined }\n\t\tif (code === 'DEADLINE') return { cause: 'deadline', message, role: undefined, stop: undefined }\n\t}\n\tif (isBudgetError(error)) {\n\t\tconst reading = attempt(() => {\n\t\t\tconst context = error.context\n\t\t\treturn {\n\t\t\t\tid: context.id,\n\t\t\t\tmax: context.max,\n\t\t\t\tconsumed: context.consumed,\n\t\t\t\tmessage: error.message,\n\t\t\t}\n\t\t})\n\t\tif (reading.success)\n\t\t\treturn {\n\t\t\t\tcause: 'capacity',\n\t\t\t\tmessage: reading.value.message,\n\t\t\t\trole: undefined,\n\t\t\t\tstop: {\n\t\t\t\t\tlayer: 'budget',\n\t\t\t\t\tid: isNonEmptyString(reading.value.id) ? reading.value.id : 'Agent budget',\n\t\t\t\t\tmax: parseStudyReading(reading.value.max),\n\t\t\t\t\tconsumed: parseStudyReading(reading.value.consumed),\n\t\t\t\t},\n\t\t\t}\n\t}\n\treturn {\n\t\tcause: 'infrastructure',\n\t\tmessage: isError(error) ? error.message : 'Study operation rejected without an Error',\n\t\trole: undefined,\n\t\tstop: undefined,\n\t}\n}\n\n/**\n * Computes the stop of a request whose actual usage crossed the ceiling it was admitted under.\n * @param charge - The request's admitted ceilings\n * @param usage - The request's measured usage\n * @returns The `scope` stop for the first quantity, tokens then bytes, whose known usage exceeds its admitted ceiling; undefined when none does\n * @example\n * ```ts\n * computeStudyAdmittedStop({ role: 'agent', tokens: 10, bytes: 100 }, usage) // { layer: 'scope', id: 'Admitted tokens', max: 10, consumed: 12 }\n * ```\n */\nexport function computeStudyAdmittedStop(\n\tcharge: StudyCharge,\n\tusage: StudyUsage,\n): StudyStop | undefined {\n\tif (usage.tokens !== undefined && usage.tokens > charge.tokens)\n\t\treturn { layer: 'scope', id: 'Admitted tokens', max: charge.tokens, consumed: usage.tokens }\n\tif (usage.bytes !== undefined && usage.bytes > charge.bytes)\n\t\treturn { layer: 'scope', id: 'Admitted bytes', max: charge.bytes, consumed: usage.bytes }\n\treturn undefined\n}\n\n/**\n * Computes the stop of a product the output allowances cannot hold.\n * @param bytes - The encoded size of the product's value\n * @param limit - The goal's byte allowance\n * @param outputs - The trial and series output budgets, in the order they refuse\n * @returns The `Goal bytes` stop when the goal allowance refuses, else the stop of the first budget whose remaining room is below the product, with its tally including the refused product; undefined when every allowance holds it\n * @example\n * ```ts\n * computeStudyOutputStop(2048, 1024, []) // { layer: 'scope', id: 'Goal bytes', max: 1024, consumed: 2048 }\n * ```\n */\nexport function computeStudyOutputStop(\n\tbytes: number,\n\tlimit: number,\n\toutputs: ReadonlyArray<BudgetInterface<number>>,\n): StudyStop | undefined {\n\tif (bytes > limit) return { layer: 'scope', id: 'Goal bytes', max: limit, consumed: bytes }\n\tconst refusal = outputs.find((budget) => bytes > budget.remaining)\n\treturn refusal === undefined\n\t\t? undefined\n\t\t: { layer: 'scope', id: refusal.id, max: refusal.max, consumed: refusal.consumed + bytes }\n}\n\n/**\n * Records an error that escaped admitted work as the failure of its ticket.\n * @param ticket - The admitted request whose work escaped\n * @param error - The caught value, read through `readStudyFailure`\n * @param role - The responsibility that replaces any role the reading carries; Default: the carried role, else the ticket's admitted role\n * @remarks\n * A ticket that already settled or whose signal aborted is left untouched, because its owner\n * already holds the failure. A remote ticket's aborted signal does not mean it settled locally,\n * so the parent's ownership is respected rather than inferred as local settlement. A refusal\n * thrown by the ticket's own settlement propagates.\n * @throws Thrown when the ticket's settlement refuses the failure.\n * @example Fail an escaped request\n * ```ts\n * import type { StudyTicket } from '@orkestrel/study'\n * import { failStudyTicket } from '@orkestrel/study'\n *\n * declare const ticket: StudyTicket\n *\n * failStudyTicket(ticket, new Error('Provider refused'), 'tool')\n * ```\n */\nexport function failStudyTicket(ticket: StudyTicket, error: unknown, role?: StudyRole): void {\n\tif (ticket.settled || ticket.signal.aborted) return\n\tconst failure = readStudyFailure(error)\n\tticket.fail(role === undefined ? failure : { ...failure, role })\n}\n","import type { StudyFailure } from '../types.js'\nimport type { StudyControlInterface } from './types.js'\nimport { Abort } from '@orkestrel/abort'\nimport { failureToStudyError } from './helpers.js'\n\n/** Retains the first operational failure while bounding asynchronous waits. */\nexport class StudyControl implements StudyControlInterface {\n\t#abort: Abort\n\t#listeners = new Abort()\n\t#failure: StudyFailure | undefined\n\n\t/** Links cancellation to the caller without assigning it a task verdict.\n\t * @param signal - Optional parent cancellation.\n\t */\n\tconstructor(signal?: AbortSignal) {\n\t\tthis.#abort = new Abort(signal === undefined ? undefined : { signal })\n\t\tif (this.#abort.aborted) this.#interrupt()\n\t\telse\n\t\t\tthis.#abort.signal.addEventListener('abort', () => this.#interrupt(), {\n\t\t\t\tonce: true,\n\t\t\t\tsignal: this.#listeners.signal,\n\t\t\t})\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.#abort.signal\n\t}\n\tget failure(): StudyFailure | undefined {\n\t\treturn this.#failure\n\t}\n\n\t/** Latches an operational failure and cancels all linked work.\n\t * @param failure - The first attribution to preserve.\n\t */\n\tfail(failure: StudyFailure): void {\n\t\tif (this.#failure !== undefined) return\n\t\tthis.#failure = Object.freeze({\n\t\t\t...failure,\n\t\t\tstop: failure.stop === undefined ? undefined : Object.freeze({ ...failure.stop }),\n\t\t})\n\t\tthis.#abort.abort(failureToStudyError(this.#failure))\n\t}\n\n\t/** Races work against cancellation and removes its listener after either ending.\n\t * @param work - Already-started work whose rejection remains observed after cancellation.\n\t * @returns The work's result if it settles before cancellation.\n\t * @throws Thrown with the retained operational attribution when cancelled.\n\t */\n\twait<T>(work: PromiseLike<T>): Promise<T> {\n\t\tconst listeners = new Abort()\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tPromise.resolve(work).then(resolve, reject)\n\t\t\tif (this.#abort.aborted) reject(this.#reason())\n\t\t\telse\n\t\t\t\tthis.#abort.signal.addEventListener('abort', () => reject(this.#reason()), {\n\t\t\t\t\tonce: true,\n\t\t\t\t\tsignal: listeners.signal,\n\t\t\t\t})\n\t\t}).finally(() => listeners.abort())\n\t}\n\n\t/** Removes the lifecycle listener without changing the retained failure. */\n\tclose(): void {\n\t\tthis.#listeners.abort()\n\t}\n\n\t#reason(): Error {\n\t\treturn failureToStudyError(\n\t\t\tthis.#failure ?? {\n\t\t\t\tcause: 'interrupted',\n\t\t\t\tmessage: 'Study interrupted',\n\t\t\t\trole: undefined,\n\t\t\t\tstop: undefined,\n\t\t\t},\n\t\t)\n\t}\n\n\t#interrupt(): void {\n\t\tif (this.#failure === undefined)\n\t\t\tthis.fail({\n\t\t\t\tcause: 'interrupted',\n\t\t\t\tmessage: 'Study interrupted by parent cancellation',\n\t\t\t\trole: undefined,\n\t\t\t\tstop: undefined,\n\t\t\t})\n\t}\n}\n","import type { StudyCharge, StudyFailure, StudyUsage } from '../types.js'\nimport type { StudyScopeInterface, StudyScopeOptions } from './types.js'\nimport { Abort } from '@orkestrel/abort'\nimport { Budget } from '@orkestrel/budget'\nimport { Timeout } from '@orkestrel/timeout'\nimport { StudyError } from '../errors.js'\nimport { isStudyLimit } from '../validators.js'\nimport { failureToStudyError } from './helpers.js'\n\n/** Reserves finite request ceilings around cumulative actual budgets and one deadline. */\nexport class StudyScope implements StudyScopeInterface {\n\t#options: StudyScopeOptions\n\t#calls: Budget<number>\n\t#tokens: Budget<number>\n\t#bytes: Budget<number>\n\t#timeout: Timeout\n\t#listeners = new Abort()\n\treadonly #pending = new Map<symbol, StudyCharge>()\n\t#started = performance.now()\n\t#closed = false\n\n\t/** Starts a timed scope with independent counters.\n\t * @param options - Finite limit, shared failure owner, and diagnostic label.\n\t */\n\tconstructor(options: StudyScopeOptions) {\n\t\tif (!isStudyLimit(options.limit)) throw new StudyError('CONFIG', 'Invalid study scope limit')\n\t\tthis.#options = { ...options, limit: { ...options.limit } }\n\t\tthis.#calls = new Budget({ max: options.limit.calls, consumer: (value: number) => value })\n\t\tthis.#tokens = new Budget({ max: options.limit.tokens, consumer: (value: number) => value })\n\t\tthis.#bytes = new Budget({ max: options.limit.bytes, consumer: (value: number) => value })\n\t\tthis.#timeout = new Timeout({ ms: options.limit.duration })\n\t\tthis.#timeout.signal.addEventListener('abort', () => this.#expire(), {\n\t\t\tonce: true,\n\t\t\tsignal: this.#listeners.signal,\n\t\t})\n\t\tthis.#timeout.start()\n\t}\n\n\t/** Checks cumulative consumption and every pending ceiling before admission.\n\t * @param charge - One prospective request's ceilings.\n\t * @throws Thrown when this scope cannot admit the request.\n\t */\n\tcheck(charge?: StudyCharge): void {\n\t\tthis.#checkTime()\n\t\tif (this.#closed) throw new StudyError('FAULT', 'Study scope is closed')\n\t\tconst prior = this.#options.control.failure\n\t\tif (prior !== undefined) throw failureToStudyError(prior)\n\t\tif (charge === undefined) return\n\t\tconst pending = [...this.#pending.values()]\n\t\tconst tokens = pending.reduce((total, entry) => total + entry.tokens, 0)\n\t\tconst bytes = pending.reduce((total, entry) => total + entry.bytes, 0)\n\t\tconst { label, limit } = this.#options\n\t\tconst refusal = [\n\t\t\t{\n\t\t\t\tid: `${label} calls`,\n\t\t\t\trefused: this.#calls.remaining - this.#pending.size < 1,\n\t\t\t\tmax: limit.calls,\n\t\t\t\tconsumed: this.#calls.consumed + this.#pending.size + 1,\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: `${label} tokens`,\n\t\t\t\trefused: this.#tokens.remaining - tokens < charge.tokens,\n\t\t\t\tmax: limit.tokens,\n\t\t\t\tconsumed: this.#tokens.consumed + tokens + charge.tokens,\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: `${label} bytes`,\n\t\t\t\trefused: this.#bytes.remaining - bytes < charge.bytes,\n\t\t\t\tmax: limit.bytes,\n\t\t\t\tconsumed: this.#bytes.consumed + bytes + charge.bytes,\n\t\t\t},\n\t\t].find((entry) => entry.refused)\n\t\tif (refusal !== undefined) {\n\t\t\tconst failure: StudyFailure = {\n\t\t\t\tcause: 'capacity',\n\t\t\t\tmessage: `${label} allowance cannot admit the request`,\n\t\t\t\trole: charge.role,\n\t\t\t\tstop: { layer: 'scope', id: refusal.id, max: refusal.max, consumed: refusal.consumed },\n\t\t\t}\n\t\t\tthis.#options.control.fail(failure)\n\t\t\tthrow failureToStudyError(failure)\n\t\t}\n\t}\n\n\t/** Reserves one request after the enclosing meter checked all scopes.\n\t * @param id - The request's unique reservation identity.\n\t * @param charge - Its admitted ceilings.\n\t */\n\treserve(id: symbol, charge: StudyCharge): void {\n\t\tif (this.#pending.has(id)) throw new StudyError('FAULT', 'Duplicate study reservation')\n\t\tthis.#pending.set(id, { ...charge })\n\t}\n\n\t/** Commits known charges while retaining ceilings for missing measurements.\n\t * @param id - The pending reservation identity.\n\t * @param usage - The request's retained public measurements.\n\t */\n\tsettle(id: symbol, usage: StudyUsage): void {\n\t\tconst charge = this.#pending.get(id)\n\t\tif (charge === undefined) throw new StudyError('FAULT', 'Study reservation is not pending')\n\t\tthis.#pending.delete(id)\n\t\tthis.#calls.consume(1)\n\t\tthis.#tokens.consume(Math.min(charge.tokens, usage.tokens ?? charge.tokens))\n\t\tthis.#bytes.consume(Math.min(charge.bytes, usage.bytes ?? charge.bytes))\n\t}\n\n\t/** Checks deadline attribution before clearing the timer. */\n\tclose(): void {\n\t\tif (this.#closed) return\n\t\tthis.#checkTime()\n\t\tthis.#closed = true\n\t\tthis.#listeners.abort()\n\t\tthis.#timeout.clear()\n\t}\n\n\t#checkTime(): void {\n\t\tif (\n\t\t\t!this.#closed &&\n\t\t\t(this.#timeout.expired || performance.now() - this.#started >= this.#options.limit.duration)\n\t\t)\n\t\t\tthis.#expire()\n\t}\n\n\t#expire(): void {\n\t\tthis.#options.control.fail({\n\t\t\tcause: 'deadline',\n\t\t\tmessage: `${this.#options.label} deadline expired`,\n\t\t\trole: undefined,\n\t\t\tstop: {\n\t\t\t\tlayer: 'scope',\n\t\t\t\tid: `${this.#options.label} duration`,\n\t\t\t\tmax: this.#options.limit.duration,\n\t\t\t\tconsumed: Math.ceil(performance.now() - this.#started),\n\t\t\t},\n\t\t})\n\t}\n}\n","import type { StudyDeadlineInterface, StudyDeadlineOptions } from './types.js'\nimport { StudyControl } from './StudyControl.js'\nimport { StudyScope } from './StudyScope.js'\n\n/** Bounds each independent operation with a fresh failure owner and deadline. */\nexport class StudyDeadline implements StudyDeadlineInterface {\n\t#options: StudyDeadlineOptions\n\n\t/** Retains the deadline without starting a timer.\n\t * @param options - Finite duration in milliseconds and diagnostic label.\n\t */\n\tconstructor(options: StudyDeadlineOptions) {\n\t\tthis.#options = { ...options }\n\t}\n\n\t/** Waits for work under a fresh failure owner and releases its timer and listener.\n\t * @param work - Already-started work whose late rejection remains observed.\n\t * @returns The work's result when it settles before the deadline.\n\t * @throws Thrown for an invalid duration, the work's own rejection, or the labelled deadline.\n\t */\n\tasync wait<T>(work: PromiseLike<T>): Promise<T> {\n\t\tconst control = new StudyControl()\n\t\tconst scope = this.#open(control, work)\n\t\ttry {\n\t\t\tconst result = await control.wait(work)\n\t\t\tscope.check()\n\t\t\treturn result\n\t\t} finally {\n\t\t\tscope.close()\n\t\t\tcontrol.close()\n\t\t}\n\t}\n\n\t// Opens the deadline scope; an invalid duration closes the owner and keeps the work's late rejection observed.\n\t#open(control: StudyControl, work: PromiseLike<unknown>): StudyScope {\n\t\ttry {\n\t\t\treturn new StudyScope({\n\t\t\t\tlimit: { duration: this.#options.duration, calls: 1, tokens: 1, bytes: 1 },\n\t\t\t\tcontrol,\n\t\t\t\tlabel: this.#options.label,\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tPromise.resolve(work).catch(() => undefined)\n\t\t\tcontrol.close()\n\t\t\tthrow error\n\t\t}\n\t}\n}\n","import type { StudyFailure, StudyTicket, StudyUsage } from '../types.js'\nimport type { StudyRequestOptions } from './types.js'\nimport { Abort, linkSignal } from '@orkestrel/abort'\nimport { Timeout } from '@orkestrel/timeout'\nimport { StudyError } from '../errors.js'\nimport { isStudyUsage } from '../validators.js'\nimport { computeStudyAdmittedStop, failureToStudyError } from './helpers.js'\n\n/** Settles an admitted request once and propagates operational failure to its owner. */\nexport class StudyRequest implements StudyTicket {\n\t#options: StudyRequestOptions\n\t#timeout: Timeout\n\t#signal: AbortSignal\n\t#listeners = new Abort()\n\t#started = performance.now()\n\t#settled = false\n\n\t/** Starts the request deadline after its enclosing scopes reserve capacity.\n\t * @param options - Admitted ceilings, request deadline, and settlement callback.\n\t */\n\tconstructor(options: StudyRequestOptions) {\n\t\tthis.#options = { ...options, charge: { ...options.charge } }\n\t\tthis.#timeout = new Timeout({ ms: options.duration })\n\t\tthis.#signal = linkSignal(this.#timeout.signal, options.control.signal)\n\t\tthis.#signal.addEventListener('abort', () => this.#abort(), {\n\t\t\tonce: true,\n\t\t\tsignal: this.#listeners.signal,\n\t\t})\n\t\tthis.#timeout.start()\n\t\tif (this.#signal.aborted) this.#abort()\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.#signal\n\t}\n\tget settled(): boolean {\n\t\treturn this.#settled\n\t}\n\n\t/** Retains actual measurements and refuses invalid or excessive charges.\n\t * @param usage - Measurements attributed to exactly this request.\n\t * @throws Thrown when settlement is late, repeated, invalid, or beyond admission.\n\t */\n\tfinish(usage: StudyUsage): void {\n\t\tthis.#checkPending()\n\t\tif (!isStudyUsage(usage) || usage.role !== this.#options.charge.role || usage.calls !== 1) {\n\t\t\tconst failure: StudyFailure = {\n\t\t\t\tcause: 'infrastructure',\n\t\t\t\tmessage: 'Request usage is invalid or misattributed',\n\t\t\t\trole: this.#options.charge.role,\n\t\t\t\tstop: undefined,\n\t\t\t}\n\t\t\tthis.fail(failure)\n\t\t\tthrow failureToStudyError(failure)\n\t\t}\n\t\tconst elapsed = performance.now() - this.#started\n\t\tconst admitted = computeStudyAdmittedStop(this.#options.charge, usage)\n\t\tconst failure: StudyFailure | undefined =\n\t\t\tthis.#timeout.expired ||\n\t\t\telapsed >= this.#options.duration ||\n\t\t\tusage.duration > this.#options.duration\n\t\t\t\t? {\n\t\t\t\t\t\tcause: 'deadline',\n\t\t\t\t\t\tmessage: 'Request deadline expired',\n\t\t\t\t\t\trole: usage.role,\n\t\t\t\t\t\tstop: {\n\t\t\t\t\t\t\tlayer: 'scope',\n\t\t\t\t\t\t\tid: 'Request duration',\n\t\t\t\t\t\t\tmax: this.#options.duration,\n\t\t\t\t\t\t\tconsumed: Math.ceil(Math.max(elapsed, usage.duration)),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: admitted !== undefined\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcause: 'capacity',\n\t\t\t\t\t\t\tmessage: 'Request usage exceeded its admitted ceiling',\n\t\t\t\t\t\t\trole: usage.role,\n\t\t\t\t\t\t\tstop: admitted,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined\n\t\tthis.#complete(usage)\n\t\tif (failure !== undefined) {\n\t\t\tthis.#options.control.fail(failure)\n\t\t\tthrow failureToStudyError(failure)\n\t\t}\n\t}\n\n\t/** Retains unknown cost conservatively and latches the first operational failure.\n\t * @param failure - The operational request failure.\n\t * @throws Thrown when this request was already settled.\n\t */\n\tfail(failure: StudyFailure): void {\n\t\tthis.#checkPending()\n\t\tthis.#complete({\n\t\t\trole: this.#options.charge.role,\n\t\t\tcalls: 1,\n\t\t\ttokens: undefined,\n\t\t\tbytes: undefined,\n\t\t\tduration: Math.ceil(performance.now() - this.#started),\n\t\t})\n\t\tthis.#options.control.fail({ ...failure, role: failure.role ?? this.#options.charge.role })\n\t}\n\n\t#complete(usage: StudyUsage): void {\n\t\tthis.#settled = true\n\t\tthis.#listeners.abort()\n\t\tthis.#timeout.clear()\n\t\tthis.#options.settle(Object.freeze({ ...usage }))\n\t}\n\n\t#checkPending(): void {\n\t\tif (this.#settled) {\n\t\t\tthis.#options.control.fail({\n\t\t\t\tcause: 'infrastructure',\n\t\t\t\tmessage: 'Request settlement is late or repeated',\n\t\t\t\trole: this.#options.charge.role,\n\t\t\t\tstop: undefined,\n\t\t\t})\n\t\t\tthrow new StudyError(\n\t\t\t\t'FAULT',\n\t\t\t\t'Request settlement is late or repeated',\n\t\t\t\tthis.#options.control.failure,\n\t\t\t)\n\t\t}\n\t}\n\n\t#abort(): void {\n\t\tif (this.#settled) return\n\t\tconst expired = this.#timeout.expired\n\t\tthis.fail(\n\t\t\tthis.#options.control.failure ?? {\n\t\t\t\tcause: expired ? 'deadline' : 'interrupted',\n\t\t\t\tmessage: expired ? 'Request deadline expired' : 'Request interrupted',\n\t\t\t\trole: this.#options.charge.role,\n\t\t\t\tstop: expired\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tlayer: 'scope',\n\t\t\t\t\t\t\tid: 'Request duration',\n\t\t\t\t\t\t\tmax: this.#options.duration,\n\t\t\t\t\t\t\tconsumed: Math.ceil(performance.now() - this.#started),\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t},\n\t\t)\n\t}\n}\n","import type { StudyCharge, StudyFailure, StudyTicket, StudyUsage } from '../types.js'\nimport type { StudyMeterInterface, StudyMeterOptions } from './types.js'\nimport { StudyError } from '../errors.js'\nimport { isStudyLimit, isStudyRole } from '../validators.js'\nimport { failureToStudyError } from './helpers.js'\nimport { StudyRequest } from './StudyRequest.js'\n\n/** Admits request ceilings across every enclosing scope before dispatch. */\nexport class StudyMeter implements StudyMeterInterface {\n\t#options: StudyMeterOptions\n\treadonly #pending = new Set<symbol>()\n\t#usage: readonly StudyUsage[] = []\n\t#closed = false\n\n\t/** Holds the goal's shared admission scopes.\n\t * @param options - Request bound, enclosing scopes, and shared failure owner.\n\t */\n\tconstructor(options: StudyMeterOptions) {\n\t\tif (\n\t\t\t!isStudyLimit(options.request) ||\n\t\t\toptions.request.calls !== 1 ||\n\t\t\toptions.scopes.length === 0\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Invalid request admission bounds')\n\t\tthis.#options = { ...options, request: { ...options.request }, scopes: [...options.scopes] }\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.#options.control.signal\n\t}\n\tget usage(): readonly StudyUsage[] {\n\t\treturn Object.freeze([...this.#usage])\n\t}\n\n\t/** Reserves one request atomically across all enclosing allowances.\n\t * @param charge - Safe integer token and byte ceilings with the request's role.\n\t * @returns A request ticket that must settle before the goal completes.\n\t * @throws Thrown before dispatch if the request exceeds available capacity.\n\t */\n\tadmit(charge: StudyCharge): StudyTicket {\n\t\tif (this.#closed) throw new StudyError('FAULT', 'Study meter is closed')\n\t\tif (this.#options.control.failure !== undefined)\n\t\t\tthrow failureToStudyError(this.#options.control.failure)\n\t\tif (\n\t\t\t!isStudyRole(charge.role) ||\n\t\t\t!Number.isSafeInteger(charge.tokens) ||\n\t\t\tcharge.tokens < 0 ||\n\t\t\t!Number.isSafeInteger(charge.bytes) ||\n\t\t\tcharge.bytes < 0\n\t\t) {\n\t\t\tconst failure: StudyFailure = {\n\t\t\t\tcause: 'infrastructure',\n\t\t\t\tmessage: 'Request admission requires safe nonnegative ceilings',\n\t\t\t\trole: undefined,\n\t\t\t\tstop: undefined,\n\t\t\t}\n\t\t\tthis.#options.control.fail(failure)\n\t\t\tthrow failureToStudyError(failure)\n\t\t}\n\t\tconst { request } = this.#options\n\t\tif (charge.tokens > request.tokens || charge.bytes > request.bytes) {\n\t\t\tconst tokens = charge.tokens > request.tokens\n\t\t\tconst failure: StudyFailure = {\n\t\t\t\tcause: 'capacity',\n\t\t\t\tmessage: 'Request ceiling exceeds the request allowance',\n\t\t\t\trole: charge.role,\n\t\t\t\tstop: {\n\t\t\t\t\tlayer: 'scope',\n\t\t\t\t\tid: tokens ? 'Request tokens' : 'Request bytes',\n\t\t\t\t\tmax: tokens ? request.tokens : request.bytes,\n\t\t\t\t\tconsumed: tokens ? charge.tokens : charge.bytes,\n\t\t\t\t},\n\t\t\t}\n\t\t\tthis.#options.control.fail(failure)\n\t\t\tthrow failureToStudyError(failure)\n\t\t}\n\t\tfor (const scope of this.#options.scopes) scope.check(charge)\n\t\tconst id = Symbol('request')\n\t\tfor (const scope of this.#options.scopes) scope.reserve(id, charge)\n\t\tthis.#pending.add(id)\n\t\treturn new StudyRequest({\n\t\t\tcharge,\n\t\t\tduration: this.#options.request.duration,\n\t\t\tcontrol: this.#options.control,\n\t\t\tsettle: (usage) => {\n\t\t\t\tfor (const scope of this.#options.scopes) scope.settle(id, usage)\n\t\t\t\tthis.#pending.delete(id)\n\t\t\t\tthis.#usage = [...this.#usage, usage]\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Refuses unfinished requests before closing a goal's admission boundary. */\n\tclose(): void {\n\t\tif (this.#closed) return\n\t\tthis.#closed = true\n\t\tif (this.#pending.size > 0)\n\t\t\tthis.#options.control.fail({\n\t\t\t\tcause: 'infrastructure',\n\t\t\t\tmessage: 'Goal completed with unsettled requests',\n\t\t\t\trole: undefined,\n\t\t\t\tstop: undefined,\n\t\t\t})\n\t}\n}\n","import type {\n\tStudyFailure,\n\tStudySeriesOptions,\n\tStudySessionInterface,\n\tStudySinkInterface,\n\tStudyTrial,\n} from '../types.js'\nimport type { StudyControl } from './StudyControl.js'\nimport type { StudyDeadline } from './StudyDeadline.js'\nimport { StudyError } from '../errors.js'\nimport { failureToStudyError, readStudyFailure } from './helpers.js'\nimport { StudyScope } from './StudyScope.js'\n\n/** Holds one trial's evidence custody, admission scope and driver session from opening to cleanup. */\nexport class StudyTrialLease {\n\treadonly #trial: StudyTrial\n\treadonly #options: StudySeriesOptions\n\treadonly #control: StudyControl\n\treadonly #series: StudyScope\n\treadonly #deadline: StudyDeadline\n\t#scope: StudyScope | undefined\n\t#evidence: StudySinkInterface | undefined\n\t#opening: Promise<StudySessionInterface> | undefined\n\t#session: StudySessionInterface | undefined\n\n\t/** Binds one scheduled trial to the series' owned inputs, failure owner, series scope and cleanup deadline.\n\t * @param trial - The scheduled trial.\n\t * @param options - The series' owned manifest, driver and store.\n\t * @param control - The series failure owner.\n\t * @param series - The series admission scope.\n\t * @param deadline - The custody and cleanup deadline.\n\t */\n\tconstructor(\n\t\ttrial: StudyTrial,\n\t\toptions: StudySeriesOptions,\n\t\tcontrol: StudyControl,\n\t\tseries: StudyScope,\n\t\tdeadline: StudyDeadline,\n\t) {\n\t\tthis.#trial = trial\n\t\tthis.#options = options\n\t\tthis.#control = control\n\t\tthis.#series = series\n\t\tthis.#deadline = deadline\n\t}\n\n\t/** Reports the trial scope once opened; undefined when the trial inherited a failure. */\n\tget scope(): StudyScope | undefined {\n\t\treturn this.#scope\n\t}\n\n\t/** Reports the trial's evidence sink once custody started. */\n\tget evidence(): StudySinkInterface | undefined {\n\t\treturn this.#evidence\n\t}\n\n\t/** Reports the driver session once it opened. */\n\tget session(): StudySessionInterface | undefined {\n\t\treturn this.#session\n\t}\n\n\t/** Starts evidence custody and, unless a failure is latched, opens the trial scope and driver session.\n\t * @returns Nothing after the session opened, or after custody alone started under a latched failure.\n\t * @throws StudyError - Thrown with code `CUSTODY` when custody refuses the trial; thrown for a series or trial limit or an opening failure.\n\t */\n\tasync open(): Promise<void> {\n\t\tconst control = this.#control\n\t\tif (control.failure !== undefined) {\n\t\t\tthis.#evidence = await this.#start()\n\t\t\treturn\n\t\t}\n\t\tthis.#series.check()\n\t\tconst scope = new StudyScope({\n\t\t\tlimit: this.#options.manifest.bounds.trial,\n\t\t\tcontrol,\n\t\t\tlabel: 'Trial',\n\t\t})\n\t\tthis.#scope = scope\n\t\tthis.#evidence = await this.#start()\n\t\tthis.#series.check()\n\t\tscope.check()\n\t\tconst opening = this.#launch()\n\t\tthis.#opening = opening\n\t\tthis.#session = await control.wait(opening)\n\t}\n\n\t/** Closes the opened session, or a session that opened late, then the trial scope.\n\t * @returns The cleanup failure, or undefined when cleanup succeeded or repeated the latched failure.\n\t */\n\tasync close(): Promise<StudyFailure | undefined> {\n\t\tconst cleanup = await this.#release()\n\t\tthis.#scope?.close()\n\t\treturn cleanup\n\t}\n\n\t// Closes the session or awaits and closes a late opening; a session close failure is latched, a late one only reported when it differs.\n\tasync #release(): Promise<StudyFailure | undefined> {\n\t\tconst session = this.#session\n\t\tconst opening = this.#opening\n\t\tif (session !== undefined) {\n\t\t\ttry {\n\t\t\t\tawait this.#deadline.wait(session.close())\n\t\t\t\treturn undefined\n\t\t\t} catch (error) {\n\t\t\t\tconst cleanup = readStudyFailure(error)\n\t\t\t\tthis.#control.fail(cleanup)\n\t\t\t\treturn cleanup\n\t\t\t}\n\t\t}\n\t\tif (opening === undefined) return undefined\n\t\ttry {\n\t\t\tconst late = await this.#deadline.wait(opening)\n\t\t\tawait this.#deadline.wait(late.close())\n\t\t\treturn undefined\n\t\t} catch (error) {\n\t\t\tconst late = readStudyFailure(error)\n\t\t\treturn late.message !== this.#control.failure?.message ? late : undefined\n\t\t}\n\t}\n\n\t// Opens the driver session; a failure latched while it opened closes it and refuses.\n\tasync #launch(): Promise<StudySessionInterface> {\n\t\tconst control = this.#control\n\t\tconst session = await this.#options.driver.open(this.#trial, control.signal)\n\t\tif (control.failure !== undefined) {\n\t\t\tawait this.#deadline.wait(session.close())\n\t\t\tthrow failureToStudyError(control.failure)\n\t\t}\n\t\treturn session\n\t}\n\n\t// Starts evidence custody; a refusal latches the failure and surfaces as a custody error.\n\tasync #start(): Promise<StudySinkInterface> {\n\t\tconst control = this.#control\n\t\ttry {\n\t\t\tconst pending = this.#options.store.start(this.#trial)\n\t\t\treturn control.failure === undefined\n\t\t\t\t? await control.wait(pending)\n\t\t\t\t: await this.#deadline.wait(pending)\n\t\t} catch (error) {\n\t\t\tcontrol.fail(readStudyFailure(error))\n\t\t\tconst failure = control.failure ?? readStudyFailure(error)\n\t\t\tthrow new StudyError('CUSTODY', failure.message, failure)\n\t\t}\n\t}\n}\n","import type {\n\tStudyAttempt,\n\tStudyFailure,\n\tStudyGoal,\n\tStudyObservation,\n\tStudyProduct,\n\tStudyScenario,\n\tStudySeriesOptions,\n\tStudySessionInterface,\n\tStudySinkInterface,\n\tStudyTrial,\n} from '../types.js'\nimport { Budget } from '@orkestrel/budget'\nimport { canonicalStringify, cloneJSONValue } from '@orkestrel/contract'\nimport { isStudyError, StudyError } from '../errors.js'\nimport { buildStudySchedule } from '../helpers.js'\nimport { isStudyBounds, isStudyProduct } from '../validators.js'\nimport { computeStudyOutputStop, readStudyFailure } from './helpers.js'\nimport { StudyControl } from './StudyControl.js'\nimport { StudyDeadline } from './StudyDeadline.js'\nimport { StudyMeter } from './StudyMeter.js'\nimport { StudyScope } from './StudyScope.js'\nimport { StudyTrialLease } from './StudyTrialLease.js'\n\n/** Executes a frozen serial study schedule with finite admission and sticky failures. */\nexport class StudySeries {\n\t#options: StudySeriesOptions\n\t#executed = false\n\n\t/** Owns the declared inputs while retaining the concrete driver and custody store.\n\t * @param options - Frozen manifest, concrete adapters, and parent cancellation.\n\t */\n\tconstructor(options: StudySeriesOptions) {\n\t\tthis.#options = { ...options, manifest: structuredClone(options.manifest) }\n\t}\n\n\t/** Runs every declared trial once and retains explicit unexecuted observations after failure.\n\t * Custody rejection leaves the run unsealed; callers must seal only a fulfilled execution.\n\t * @returns Ordered terminal attempts without task success labels.\n\t * @throws Thrown for invalid configuration or failed or timed out custody operations.\n\t */\n\tasync execute(): Promise<readonly StudyAttempt[]> {\n\t\tif (this.#executed) throw new StudyError('CONFIG', 'Study series can execute only once')\n\t\tthis.#executed = true\n\t\tconst manifest = this.#options.manifest\n\t\tconst expected = buildStudySchedule(manifest.definition, manifest.scenarios)\n\t\tif (\n\t\t\t!isStudyBounds(manifest.bounds) ||\n\t\t\tcanonicalStringify(expected) !== canonicalStringify(manifest.schedule)\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Study manifest schedule or bounds are invalid')\n\t\tconst control = new StudyControl(this.#options.signal)\n\t\tconst scope = new StudyScope({ limit: manifest.bounds.series, control, label: 'Series' })\n\t\tconst deadline = new StudyDeadline({\n\t\t\tduration: manifest.bounds.request.duration,\n\t\t\tlabel: 'Custody or cleanup',\n\t\t})\n\t\tconst output = new Budget({\n\t\t\tid: 'Series output',\n\t\t\tmax: manifest.bounds.series.bytes,\n\t\t\tconsumer: (bytes: number) => bytes,\n\t\t})\n\t\tconst attempts: StudyAttempt[] = []\n\t\ttry {\n\t\t\tfor (const trial of manifest.schedule)\n\t\t\t\tattempts.push(await this.#executeTrial(trial, control, scope, output, deadline))\n\t\t} finally {\n\t\t\tscope.close()\n\t\t\tcontrol.close()\n\t\t}\n\t\treturn Object.freeze(attempts)\n\t}\n\n\tasync #executeTrial(\n\t\ttrial: StudyTrial,\n\t\tcontrol: StudyControl,\n\t\tseries: StudyScope,\n\t\toutput: Budget<number>,\n\t\tdeadline: StudyDeadline,\n\t): Promise<StudyAttempt> {\n\t\tconst started = performance.now()\n\t\tconst scenario = this.#options.manifest.scenarios.find((entry) => entry.id === trial.scenario)\n\t\tif (scenario === undefined) throw new StudyError('CONFIG', 'Scheduled scenario is absent')\n\t\tconst prior = control.failure\n\t\tconst lease = new StudyTrialLease(trial, this.#options, control, series, deadline)\n\t\tconst executed = await this.#executeGoals(scenario, lease, control, series, output)\n\t\tconst cleanup = await this.#release(lease, control, series)\n\t\tconst failure = control.failure\n\t\tconst observations: readonly StudyObservation[] = [\n\t\t\t...executed,\n\t\t\t...scenario.goals.slice(executed.length).map((goal): StudyObservation => {\n\t\t\t\tconst unexecuted: StudyFailure =\n\t\t\t\t\tfailure === undefined\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tcause: 'infrastructure',\n\t\t\t\t\t\t\t\tmessage: 'Goal unexecuted because the trial did not open',\n\t\t\t\t\t\t\t\trole: undefined,\n\t\t\t\t\t\t\t\tstop: undefined,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: { ...failure, message: `Goal unexecuted: ${failure.message}` }\n\t\t\t\treturn Object.freeze({\n\t\t\t\t\tgoal: goal.id,\n\t\t\t\t\tproduct: undefined,\n\t\t\t\t\tfailure: unexecuted,\n\t\t\t\t\tusage: Object.freeze([]),\n\t\t\t\t\tduration: 0,\n\t\t\t\t\texecuted: false,\n\t\t\t\t})\n\t\t\t}),\n\t\t]\n\t\tconst attempt: StudyAttempt = Object.freeze({\n\t\t\ttrial,\n\t\t\tobservations: Object.freeze(observations),\n\t\t\tfailure:\n\t\t\t\tcleanup !== undefined &&\n\t\t\t\tfailure !== undefined &&\n\t\t\t\t(prior !== undefined || failure.message !== cleanup.message)\n\t\t\t\t\t? { ...failure, message: `${failure.message}; cleanup: ${cleanup.message}` }\n\t\t\t\t\t: failure,\n\t\t\tduration: Math.ceil(performance.now() - started),\n\t\t\t// The trial entered execution unless it inherited a terminal series failure at its\n\t\t\t// boundary. This does not claim that driver.open ran.\n\t\t\texecuted: prior === undefined,\n\t\t})\n\t\ttry {\n\t\t\tawait deadline.wait(this.#options.store.finish(attempt))\n\t\t\tif (attempt.failure === undefined) series.check()\n\t\t} catch (error) {\n\t\t\tcontrol.fail(readStudyFailure(error))\n\t\t\tconst custody = control.failure ?? readStudyFailure(error)\n\t\t\tthrow new StudyError('CUSTODY', custody.message, custody)\n\t\t}\n\t\treturn attempt\n\t}\n\n\t// Opens the lease and executes each goal while the trial stays open; a custody refusal releases the lease before it propagates.\n\tasync #executeGoals(\n\t\tscenario: StudyScenario,\n\t\tlease: StudyTrialLease,\n\t\tcontrol: StudyControl,\n\t\tseries: StudyScope,\n\t\toutput: Budget<number>,\n\t): Promise<readonly StudyObservation[]> {\n\t\tconst observations: StudyObservation[] = []\n\t\ttry {\n\t\t\tawait lease.open()\n\t\t\tconst trialOutput = new Budget({\n\t\t\t\tid: 'Trial output',\n\t\t\t\tmax: this.#options.manifest.bounds.trial.bytes,\n\t\t\t\tconsumer: (bytes: number) => bytes,\n\t\t\t})\n\t\t\tfor (const goal of scenario.goals) {\n\t\t\t\tconst { session, scope, evidence } = lease\n\t\t\t\tif (\n\t\t\t\t\tcontrol.failure !== undefined ||\n\t\t\t\t\tsession === undefined ||\n\t\t\t\t\tscope === undefined ||\n\t\t\t\t\tevidence === undefined\n\t\t\t\t)\n\t\t\t\t\tbreak\n\t\t\t\tseries.check()\n\t\t\t\tscope.check()\n\t\t\t\tobservations.push(\n\t\t\t\t\tawait this.#executeGoal(\n\t\t\t\t\t\tgoal,\n\t\t\t\t\t\tsession,\n\t\t\t\t\t\tevidence,\n\t\t\t\t\t\tcontrol,\n\t\t\t\t\t\t[scope, series],\n\t\t\t\t\t\t[trialOutput, output],\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (isStudyError(error) && error.code === 'CUSTODY') {\n\t\t\t\tawait this.#release(lease, control, series)\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tcontrol.fail(readStudyFailure(error))\n\t\t}\n\t\treturn observations\n\t}\n\n\t// Closes the lease, then rechecks the series ceiling, and returns the lease's cleanup failure.\n\tasync #release(\n\t\tlease: StudyTrialLease,\n\t\tcontrol: StudyControl,\n\t\tseries: StudyScope,\n\t): Promise<StudyFailure | undefined> {\n\t\tconst cleanup = await lease.close()\n\t\ttry {\n\t\t\tseries.check()\n\t\t} catch (error) {\n\t\t\tcontrol.fail(readStudyFailure(error))\n\t\t}\n\t\treturn cleanup\n\t}\n\n\tasync #executeGoal(\n\t\tgoal: StudyGoal,\n\t\tsession: StudySessionInterface,\n\t\tevidence: StudySinkInterface,\n\t\tcontrol: StudyControl,\n\t\tparents: readonly StudyScope[],\n\t\toutputs: ReadonlyArray<Budget<number>>,\n\t): Promise<StudyObservation> {\n\t\tconst started = performance.now()\n\t\tconst bounds = this.#options.manifest.bounds\n\t\tconst scope = new StudyScope({ limit: bounds.goal, control, label: 'Goal' })\n\t\tconst meter = new StudyMeter({ request: bounds.request, scopes: [scope, ...parents], control })\n\t\tconst product = await this.#produce(\n\t\t\tgoal,\n\t\t\tsession,\n\t\t\tevidence,\n\t\t\tcontrol,\n\t\t\tscope,\n\t\t\tmeter,\n\t\t\tparents,\n\t\t\toutputs,\n\t\t)\n\t\treturn Object.freeze({\n\t\t\tgoal: goal.id,\n\t\t\tproduct,\n\t\t\tfailure: control.failure,\n\t\t\tusage: meter.usage,\n\t\t\tduration: Math.ceil(performance.now() - started),\n\t\t\texecuted: true,\n\t\t})\n\t}\n\n\t// Runs one goal and closes its meter and scope; a late check failure leaves the retained product in place.\n\tasync #produce(\n\t\tgoal: StudyGoal,\n\t\tsession: StudySessionInterface,\n\t\tevidence: StudySinkInterface,\n\t\tcontrol: StudyControl,\n\t\tscope: StudyScope,\n\t\tmeter: StudyMeter,\n\t\tparents: readonly StudyScope[],\n\t\toutputs: ReadonlyArray<Budget<number>>,\n\t): Promise<StudyProduct | undefined> {\n\t\tconst bounds = this.#options.manifest.bounds\n\t\ttry {\n\t\t\tconst value: unknown = await control.wait(\n\t\t\t\tsession.execute(goal, { signal: control.signal, meter, evidence }),\n\t\t\t)\n\t\t\tif (!isStudyProduct(value))\n\t\t\t\tthrow new StudyError('FAULT', 'Driver returned no valid study product')\n\t\t\tconst candidate = Object.freeze({\n\t\t\t\tvalue: cloneJSONValue(value.value),\n\t\t\t\tpartial: value.partial,\n\t\t\t})\n\t\t\tconst bytes = new TextEncoder().encode(JSON.stringify(candidate.value)).byteLength\n\t\t\tconst stop = computeStudyOutputStop(bytes, bounds.goal.bytes, outputs)\n\t\t\tconst product = stop === undefined ? candidate : undefined\n\t\t\ttry {\n\t\t\t\tfor (const parent of parents) parent.check()\n\t\t\t\tscope.check()\n\t\t\t\tif (stop !== undefined) {\n\t\t\t\t\tcontrol.fail({\n\t\t\t\t\t\tcause: 'capacity',\n\t\t\t\t\t\tmessage: 'Study product exceeded its output allowance',\n\t\t\t\t\t\trole: undefined,\n\t\t\t\t\t\tstop,\n\t\t\t\t\t})\n\t\t\t\t} else for (const budget of outputs) budget.consume(bytes)\n\t\t\t} catch (error) {\n\t\t\t\tcontrol.fail(readStudyFailure(error))\n\t\t\t}\n\t\t\treturn product\n\t\t} catch (error) {\n\t\t\tcontrol.fail(readStudyFailure(error))\n\t\t\treturn undefined\n\t\t} finally {\n\t\t\tmeter.close()\n\t\t\tscope.close()\n\t\t}\n\t}\n}\n","import type { JSONValue } from '@orkestrel/contract'\nimport type { LedgerGauge, ProviderResult, RequestMeasure } from '@orkestrel/agent'\nimport type { StudyRole, StudyStop } from '../types.js'\nimport type { StudyAgentDispatch, StudyAgentRuntime } from './types.js'\nimport { attempt, isNonEmptyString, isObject } from '@orkestrel/contract'\nimport { StudyError } from '../errors.js'\nimport { parseStudyReading } from '../parsers.js'\n\n/**\n * Prices a runtime estimate through an explicit gauge.\n * @param gauge - The declared scale and overhead\n * @param estimate - The runtime's estimate of one complete request\n * @returns The projected prompt tokens, rounded up\n */\nexport function projectStudyAgentRequest(gauge: LedgerGauge, estimate: number): number {\n\treturn Math.ceil(gauge.overhead + gauge.scale * estimate)\n}\n\n/**\n * Checks that a successful provider call reported a usable actual prompt count.\n * @remarks\n * The check compares nothing with a forecast; room enforcement stays with the transport.\n * @param usage - The usage a successful provider call reported\n * @param role - The responsibility whose request was dispatched; the failure retains it\n * @returns Nothing when the prompt count is finite and positive\n * @throws StudyError - Thrown with code `FAULT` when the prompt count is missing, not finite, or not positive\n */\nexport function validateStudyAgentUsage(usage: ProviderResult['usage'], role: StudyRole): void {\n\tconst prompt = usage?.prompt\n\tif (typeof prompt !== 'number' || !Number.isFinite(prompt) || prompt <= 0) {\n\t\tconst message = 'Gauged request returned no usable prompt count'\n\t\tthrow new StudyError('FAULT', message, {\n\t\t\tcause: 'infrastructure',\n\t\t\tmessage,\n\t\t\trole,\n\t\t\tstop: undefined,\n\t\t})\n\t}\n}\n\n/**\n * Translates only a nominal Agent window refusal into the attributable capacity failure.\n * @remarks\n * The failure's stop is the `window` layer with the id `Agent window`; its `max` is the window and\n * its `consumed` the measured request, each read from the error's context when it is a finite\n * number.\n * @param error - The caught or reported value\n * @param runtime - The admitted Agent namespace owning the nominal guard\n * @returns A capacity StudyError for an Agent `WINDOW` error; every other value with its identity\n */\nexport function translateStudyAgentError(\n\terror: unknown,\n\truntime: Pick<StudyAgentRuntime, 'isAgentError'>,\n): unknown {\n\tif (!runtime.isAgentError(error) || error.code !== 'WINDOW') return error\n\tconst context = error.context\n\treturn new StudyError('CAPACITY', error.message, {\n\t\tcause: 'capacity',\n\t\tmessage: error.message,\n\t\trole: 'agent',\n\t\tstop: {\n\t\t\tlayer: 'window',\n\t\t\tid: 'Agent window',\n\t\t\tmax: parseStudyReading(context?.max),\n\t\t\tconsumed: parseStudyReading(context?.consumed),\n\t\t},\n\t})\n}\n\n/**\n * Translates an Agent run's stop record into the attributable capacity failure of the layer that stopped it.\n * @remarks\n * The record is foreign data from the admitted runtime, so the helper reads it once, each member\n * once, inside one contained boundary, and validates only the members it dereferences. A `meter`\n * or `budget` stop always leaves the run partial; a `model` stop is a complete answer, so a\n * consumer whose role admits a `length` finish keeps it. The consumer throws the returned error\n * when its policy refuses the stop. A `model` stop reports no cap because the Agent does not see\n * one; its `consumed` is the completion the stopped call reported, when finite.\n * @param stop - The `stop` member of an Agent or Ledger result\n * @returns Undefined when `stop` is undefined; a `CAPACITY` StudyError with role `agent` and the Agent layer for a meter, budget, or model stop; a `FAULT` StudyError with role `agent` for a malformed record\n * @example\n * ```ts\n * translateStudyAgentStop({ layer: 'meter', id: 'meter', max: 2000, consumed: 2001 })\n * // a CAPACITY StudyError whose failure.stop is { layer: 'meter', id: 'meter', max: 2000, consumed: 2001 }\n * ```\n */\nexport function translateStudyAgentStop(stop: unknown): StudyError | undefined {\n\tif (stop === undefined) return undefined\n\tconst reading = attempt((): StudyStop | undefined => {\n\t\tif (!isObject(stop)) return undefined\n\t\tconst layer: unknown = Reflect.get(stop, 'layer')\n\t\tconst id: unknown = Reflect.get(stop, 'id')\n\t\tif (!isNonEmptyString(id)) return undefined\n\t\tif (layer === 'meter' || layer === 'budget') {\n\t\t\tconst max: unknown = Reflect.get(stop, 'max')\n\t\t\tconst consumed: unknown = Reflect.get(stop, 'consumed')\n\t\t\tconst limit = parseStudyReading(max)\n\t\t\tconst used = parseStudyReading(consumed)\n\t\t\treturn limit === undefined || used === undefined\n\t\t\t\t? undefined\n\t\t\t\t: { layer, id, max: limit, consumed: used }\n\t\t}\n\t\tif (layer === 'model') {\n\t\t\tconst usage: unknown = Reflect.get(stop, 'usage')\n\t\t\treturn {\n\t\t\t\tlayer,\n\t\t\t\tid,\n\t\t\t\tmax: undefined,\n\t\t\t\tconsumed: isObject(usage) ? parseStudyReading(Reflect.get(usage, 'completion')) : undefined,\n\t\t\t}\n\t\t}\n\t\treturn undefined\n\t})\n\tconst parsed = reading.success ? reading.value : undefined\n\tif (parsed === undefined) {\n\t\tconst message = 'Agent stop record is malformed'\n\t\treturn new StudyError('FAULT', message, {\n\t\t\tcause: 'infrastructure',\n\t\t\tmessage,\n\t\t\trole: 'agent',\n\t\t\tstop: undefined,\n\t\t})\n\t}\n\tconst message =\n\t\tparsed.layer === 'meter'\n\t\t\t? 'Agent meter allowance reached its ceiling'\n\t\t\t: parsed.layer === 'budget'\n\t\t\t\t? 'Agent budget reached its ceiling'\n\t\t\t\t: 'Agent model reached its own token limit'\n\treturn new StudyError('CAPACITY', message, {\n\t\tcause: 'capacity',\n\t\tmessage,\n\t\trole: 'agent',\n\t\tstop: parsed,\n\t})\n}\n\n/**\n * Projects a request's structural components onto plain JSON without storing a total.\n * @param measure - The runtime's disjoint per-message, tools and schema estimates\n * @returns The same components in request order\n */\nexport function buildStudyAgentParts(measure: RequestMeasure): JSONValue {\n\treturn {\n\t\tmessages: measure.messages.map((message) => ({\n\t\t\tid: message.id,\n\t\t\trole: message.role,\n\t\t\tcontent: message.content,\n\t\t\tframing: message.framing,\n\t\t\tcalls: message.calls,\n\t\t\tthinking: message.thinking,\n\t\t\timages: message.images,\n\t\t})),\n\t\ttools: measure.tools,\n\t\tschema: measure.schema,\n\t}\n}\n\n/**\n * Builds the evidence join of a wire request to its canonical dispatch.\n * @param dispatch - The measured dispatch, or undefined when the caller measured none\n * @returns The dispatch id and revision, each null when unknown\n */\nexport function buildStudyAgentDispatch(\n\tdispatch: StudyAgentDispatch | undefined,\n): Readonly<Record<string, JSONValue>> {\n\treturn { canonical: dispatch?.id ?? null, revision: dispatch?.revision ?? null }\n}\n","import type { StudyAgentRuntime } from './types.js'\nimport type { LedgerGauge } from '@orkestrel/agent'\nimport { holds, isFiniteNumber, isObject } from '@orkestrel/contract'\n\n/**\n * Checks whether a value is a gauge with a finite positive scale and a finite nonnegative overhead.\n * @param value - The candidate gauge; additional members are admitted\n * @returns True if the gauge readings are finite and within their bounds; false otherwise\n * @example\n * ```ts\n * isStudyAgentGauge({ scale: 1, overhead: 0 }) // true\n * ```\n */\nexport function isStudyAgentGauge(value: unknown): value is LedgerGauge {\n\treturn holds(() => {\n\t\tif (!isObject(value) || !('scale' in value) || !('overhead' in value)) return false\n\t\tconst { scale, overhead } = value\n\t\treturn isFiniteNumber(scale) && scale > 0 && isFiniteNumber(overhead) && overhead >= 0\n\t})\n}\n\n/**\n * Checks whether a namespace exposes the Agent capabilities the instrumentation invokes.\n * @remarks\n * The guard reads only `estimateRequest`, `measureRequest`, and `isAgentError`, so a namespace\n * without Ledger or conversation factories passes. A throwing accessor returns false.\n * @param value - The admitted namespace\n * @returns True if every required capability is a function; false otherwise\n */\nexport function isStudyAgentRuntime(value: unknown): value is StudyAgentRuntime {\n\treturn holds(\n\t\t() =>\n\t\t\tisObject(value) &&\n\t\t\t'estimateRequest' in value &&\n\t\t\ttypeof value.estimateRequest === 'function' &&\n\t\t\t'measureRequest' in value &&\n\t\t\ttypeof value.measureRequest === 'function' &&\n\t\t\t'isAgentError' in value &&\n\t\t\ttypeof value.isAgentError === 'function',\n\t)\n}\n","import type {\n\tMessage,\n\tProviderDelta,\n\tProviderInterface,\n\tProviderRequest,\n\tProviderResult,\n\tProviderStreamOptions,\n\tThinkingReplay,\n} from '@orkestrel/agent'\nimport type { StudyAgentObserverOptions } from './types.js'\nimport { projectStudyAgentRequest, validateStudyAgentUsage } from './helpers.js'\n\n/** Reads each Agent request's size before delegating it unchanged to the real provider. */\nexport class StudyAgentObserver implements ProviderInterface {\n\treadonly #options: StudyAgentObserverOptions\n\n\t/** Binds the real provider, the measuring runtime, the explicit gauge and usage policy, and the reading recorder.\n\t * @param options - Delegate, measurement seam, and policies.\n\t */\n\tconstructor(options: StudyAgentObserverOptions) {\n\t\tthis.#options = { ...options }\n\t}\n\n\t/** Reports the delegate's trace label. */\n\tget id(): string {\n\t\treturn this.#options.provider.id\n\t}\n\n\t/** Reports the delegate's backend name. */\n\tget name(): string {\n\t\treturn this.#options.provider.name\n\t}\n\n\t/** Reports the delegate's thinking replay policy; an absent policy is the declared `none`. */\n\tget replay(): ThinkingReplay {\n\t\treturn this.#options.provider.replay ?? 'none'\n\t}\n\n\t/** Records one reading, then awaits the real generation.\n\t * @param messages - The conversation sent.\n\t * @param signal - Bounds the request.\n\t * @param tools - The tools advertised this turn.\n\t * @param options - The per-call options.\n\t * @returns The real provider's result.\n\t */\n\tasync generate(\n\t\tmessages: readonly Message[],\n\t\tsignal: AbortSignal,\n\t\ttools?: ProviderRequest['tools'],\n\t\toptions?: ProviderStreamOptions,\n\t): Promise<ProviderResult> {\n\t\tthis.#measure(messages, tools, options)\n\t\tconst result = await this.#options.provider.generate(messages, signal, tools, options)\n\t\tif (this.#options.enforced && !signal.aborted) validateStudyAgentUsage(result.usage, 'agent')\n\t\treturn result\n\t}\n\n\t/** Records one reading, then relays the real stream.\n\t * @param messages - The conversation sent.\n\t * @param signal - Bounds the request.\n\t * @param tools - The tools advertised this turn.\n\t * @param options - The per-call options.\n\t * @returns The real deltas and result.\n\t */\n\tstream(\n\t\tmessages: readonly Message[],\n\t\tsignal: AbortSignal,\n\t\ttools?: ProviderRequest['tools'],\n\t\toptions?: ProviderStreamOptions,\n\t): AsyncGenerator<ProviderDelta, ProviderResult> {\n\t\tthis.#measure(messages, tools, options)\n\t\treturn this.#relay(this.#options.provider.stream(messages, signal, tools, options), signal)\n\t}\n\n\t// Forms the pre-encoding request exactly as the Agent window measures it: omitted members stay omitted.\n\t#measure(\n\t\tmessages: readonly Message[],\n\t\ttools: ProviderRequest['tools'],\n\t\toptions: ProviderStreamOptions | undefined,\n\t): void {\n\t\tconst request: ProviderRequest = {\n\t\t\tmessages,\n\t\t\t...(tools === undefined ? {} : { tools }),\n\t\t\t...(options === undefined ? {} : { options }),\n\t\t}\n\t\tconst estimate = this.#options.runtime.estimateRequest(request)\n\t\tconst gauge = this.#options.gauge\n\t\tconst projected = gauge === undefined ? undefined : projectStudyAgentRequest(gauge, estimate)\n\t\tthis.#options.record({ estimate, projected }, request)\n\t}\n\n\tasync *#relay(\n\t\tsource: AsyncGenerator<ProviderDelta, ProviderResult>,\n\t\tsignal: AbortSignal,\n\t): AsyncGenerator<ProviderDelta, ProviderResult> {\n\t\tconst result = yield* source\n\t\tif (this.#options.enforced && !signal.aborted) validateStudyAgentUsage(result.usage, 'agent')\n\t\treturn result\n\t}\n}\n","import type { JudgeInterface, JudgeRequest, JudgeResult } from '@orkestrel/agent'\nimport type { StudyLatchInterface } from './types.js'\n\n/** Latches a real judge's failure before an enclosing runtime can treat it as absent. */\nexport class StudyAgentJudge implements JudgeInterface {\n\treadonly #judge: JudgeInterface\n\treadonly #latch: StudyLatchInterface\n\n\t/** Binds a real public judge to the trial's failure owner.\n\t * @param judge - The admitted judge every question is delegated to.\n\t * @param latch - The owner that retains the first operational failure.\n\t */\n\tconstructor(judge: JudgeInterface, latch: StudyLatchInterface) {\n\t\tthis.#judge = judge\n\t\tthis.#latch = latch\n\t}\n\n\t/** Reports the delegate's trace label. */\n\tget id(): string {\n\t\treturn this.#judge.id\n\t}\n\n\t/** Reports the delegate's backend name. */\n\tget name(): string {\n\t\treturn this.#judge.name\n\t}\n\n\t/** Reports the delegate's model identity. */\n\tget model(): string {\n\t\treturn this.#judge.model\n\t}\n\n\t/** Refuses dispatch after a retained failure and retains a thrown failure with its identity.\n\t * @param request - The real classification request.\n\t * @param signal - The caller's cancellation.\n\t * @returns The unmodified judge result.\n\t */\n\tasync ask(request: JudgeRequest, signal: AbortSignal): Promise<JudgeResult> {\n\t\tthis.#latch.check()\n\t\ttry {\n\t\t\treturn await this.#judge.ask(request, signal)\n\t\t} catch (error) {\n\t\t\tthis.#latch.fail(error)\n\t\t\tthrow error\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AASA,IAAa,oBAAoB,OAAO,IAAI,wBAAwB;;AAGpE,IAAa,eAAe;;AAG5B,IAAa,cAAc;;AAG3B,IAAa,aAAa;;AAG1B,IAAa,cAAoC,OAAO,OAAO;CAC9D;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,IAAa,eAAsC,OAAO,OAAO;CAChE;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,IAAa,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