@orkestrel/study 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["holds","isRecord","canonicalStringify","literalOf","holds","isRecord","isNonEmptyString","isFiniteNumber","MAX_TIMEOUT_MS","isJSONValue","isArray","canonicalStringify","isError","holds","relative","sep","isAbsolute","createHash","canonicalStringify","parseJSON","holds","isRecord","isArray","canonicalStringify","isJSONValue","isNonEmptyString","holds","isRecord","isArray","isInstance","readSync","isAbsolute","resolve","realpathSync","lstatSync","openSync","fstatSync","isBuiltin","join","fileURLToPath","basename","extname","stripTypeScriptTypes","pathToFileURL","join","isRecord","isNonEmptyString","extname","randomUUID","pathToFileURL","isAbsolute","resolve","realpathSync","lstatSync","opendirSync","resolve","parse","relative","sep","lstat","join","dirname","open","constants","readdir","parseJSON","attempt","canonicalStringify","resolve","dirname","mkdir","join","canonicalStringify","open","isFiniteNumber","cloneJSONValue","join","lstat","readdir","mkdir","canonicalStringify","isAbsolute","resolve","join","parseJSON","isAbsolute","resolve","isBudgetError","attempt","isNonEmptyString","isError","Abort","Abort","Budget","Timeout","Abort","Timeout","linkSignal","canonicalStringify","Budget","cloneJSONValue","isJSONValue","canonicalStringify","dirname","realpathSync","join","existsSync","readFileSync","isRecord","createRequire","delay","execFileSync","isAbsolute","dirname","readFileSync","holds","isRecord","isJSONValue","isAbsolute","mkdtemp","join","fork","isRecord","execFile","fork","isRecord","isJSONValue","isRecord","resolve","join","randomUUID","mkdtemp","rm","parseJSON","arrayOf","isString","isArray","isAbsolute","mkdir","isRecord","isRecord","isRecord","arrayOf","isString","dirname","isArray","isRecord","spawn","isRecord","attempt","canonicalStringify","isObject","isArray","isRecord","holds","isRecord","isArray","isToolCall","isJSONValue","isFiniteNumber","isJSONValue","cloneJSONValue","randomUUID","isArray","cloneJSONValue","isBudgetError","isRecord","canonicalStringify","parseJSON","isInteger","isArray","isObject","attempt","isBudgetError","parseJSON","isRecord"],"sources":["../../../src/core/constants.ts","../../../src/core/helpers.ts","../../../src/core/validators.ts","../../../src/core/errors.ts","../../../src/server/helpers.ts","../../../src/server/stores/constants.ts","../../../src/server/stores/validators.ts","../../../src/server/adapters/validators.ts","../../../src/server/adapters/helpers.ts","../../../src/server/artifacts/constants.ts","../../../src/server/artifacts/errors.ts","../../../src/server/artifacts/helpers.ts","../../../src/server/artifacts/Resolution.ts","../../../src/server/artifacts/ArtifactLoader.ts","../../../src/server/stores/helpers.ts","../../../src/server/stores/StudyEvidenceSink.ts","../../../src/server/stores/StudyResultStore.ts","../../../src/core/parsers.ts","../../../src/server/stores/StudyGradingStore.ts","../../../src/server/commands/constants.ts","../../../src/server/commands/helpers.ts","../../../src/server/commands/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/server/processes/constants.ts","../../../src/server/processes/helpers.ts","../../../src/server/processes/StudyArtifactLoader.ts","../../../src/server/processes/validators.ts","../../../src/server/processes/StudyChannel.ts","../../../src/server/processes/StudyProcessGoal.ts","../../../src/server/processes/StudyProcessSession.ts","../../../src/server/processes/StudyProcessDriver.ts","../../../src/server/processes/StudyTaskChild.ts","../../../src/server/processes/StudyTask.ts","../../../src/server/commands/StudyCommand.ts","../../../src/server/processes/StudyRemoteTicket.ts","../../../src/server/processes/StudyRemoteMeter.ts","../../../src/server/processes/StudyWorker.ts","../../../src/server/processes/StudyTaskWorker.ts","../../../src/server/launchers/constants.ts","../../../src/server/launchers/StudyLaunchChild.ts","../../../src/server/launchers/StudyLauncher.ts","../../../src/server/launchers/StudyCLI.ts","../../../src/server/agents/helpers.ts","../../../src/server/agents/validators.ts","../../../src/core/agents/helpers.ts","../../../src/server/agents/StudyAgentTraceGoal.ts","../../../src/server/agents/StudyAgentTrace.ts","../../../src/server/agents/StudyAgentSummary.ts","../../../src/server/agents/StudyAgentScriptGoal.ts","../../../src/server/agents/StudyAgentScript.ts","../../../src/server/ollama/helpers.ts","../../../src/server/ollama/cloners.ts","../../../src/server/ollama/StudyOllamaExchange.ts","../../../src/server/ollama/StudyOllamaGoal.ts","../../../src/server/ollama/StudyOllamaTransport.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 { canonicalStringify, parseJSON } from '@orkestrel/contract'\nimport { createHash } from 'node:crypto'\nimport { isAbsolute, relative, sep } from 'node:path'\nimport { StudyError } from '../core/errors.js'\n\n/** Checks strict lexical containment under a selected directory.\n * @param root - The canonical directory.\n * @param path - The candidate absolute file.\n * @returns True if the file is below the directory; false otherwise.\n */\nexport function containsArtifact(root: string, path: string): boolean {\n\tconst location = relative(root, path)\n\treturn (\n\t\tlocation !== '' &&\n\t\tlocation !== '..' &&\n\t\t!location.startsWith(`..${sep}`) &&\n\t\t!isAbsolute(location)\n\t)\n}\n\n/**\n * Computes the lowercase SHA-256 identity of exact bytes or UTF-8 text.\n * @param input - The retained bytes, or text identified by its UTF-8 bytes\n * @returns The lowercase hexadecimal digest\n * @example Identify captured bytes\n * ```ts\n * import { hashStudyBytes } from '@orkestrel/study/server'\n *\n * hashStudyBytes('retained evidence')\n * ```\n */\nexport function hashStudyBytes(input: string | Uint8Array): string {\n\treturn createHash('sha256').update(input).digest('hex')\n}\n\n/**\n * Encodes deterministic JSON bytes without synthesizing execution metadata.\n * @param value - The validated record\n * @returns The exact canonical UTF-8 bytes\n * @throws StudyError - Thrown when the record cannot be serialized\n * @example Encode custody bytes\n * ```ts\n * import { encodeStudyJSON } from '@orkestrel/study/server'\n *\n * encodeStudyJSON({ id: 1 })\n * ```\n */\nexport function encodeStudyJSON(value: unknown): Uint8Array {\n\tconst wire = JSON.stringify(value)\n\tconst text = wire === undefined ? undefined : canonicalStringify(parseJSON(wire))\n\tif (text === undefined) throw new StudyError('EVIDENCE', 'Record cannot be encoded')\n\treturn Buffer.from(`${text}\\n`, 'utf8')\n}\n\n/**\n * Decodes strict UTF-8 custody bytes and parses their JSON text.\n * @param bytes - The exact retained bytes\n * @returns The parsed value, or undefined when the text is not JSON\n * @throws TypeError - Thrown when the bytes are not valid UTF-8\n * @example\n * ```ts\n * decodeStudyJSON(new TextEncoder().encode('{\"id\":1}')) // { id: 1 }\n * ```\n */\nexport function decodeStudyJSON(bytes: Uint8Array): unknown {\n\treturn parseJSON(new TextDecoder('utf-8', { fatal: true }).decode(bytes))\n}\n","/** Limits untrusted metadata before JSON parsing or file allocation. */\nexport const STUDY_CUSTODY_BYTES = 16 * 1024 * 1024\n\n/** Rejects names that Windows reserves even on other hosts. */\nexport const STUDY_RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i\n\n/** Discloses the limits of neutral identifiers when public text remains visible. */\nexport const STUDY_PACKET_DISCLOSURE =\n\t'Identifiers omit treatment and model names. Input and product text may still reveal design details.'\n","import type {\n\tStudyAttempt,\n\tStudyEvidence,\n\tStudyFailure,\n\tStudyManifest,\n\tStudyObservation,\n\tStudyTrial,\n} from '../../core/types.js'\nimport type { StudyFile, StudySeal } from './types.js'\nimport {\n\tholds,\n\tcanonicalStringify,\n\tisArray,\n\tisJSONValue,\n\tisNonEmptyString,\n\tisRecord,\n} from '@orkestrel/contract'\nimport { buildStudySchedule, matchesStudyKeys } from '../../core/helpers.js'\nimport {\n\tisStudyBounds,\n\tisStudyCause,\n\tisStudyDefinition,\n\tisStudyDigest,\n\tisStudyName,\n\tisStudyRole,\n\tisStudyScenario,\n\tisStudyStop,\n\tisStudyTimestamp,\n\tisStudyUsage,\n} from '../../core/validators.js'\nimport { STUDY_RESERVED_NAME } from './constants.js'\n\n/**\n * Checks whether a trial name is portable on all supported hosts.\n * @param value - The candidate name\n * @returns True if the name is portable; false otherwise\n * @example\n * ```ts\n * isStudyCustodyName('r1-s1-a1') // true\n * ```\n */\nexport function isStudyCustodyName(value: unknown): value is string {\n\treturn isStudyName(value) && !STUDY_RESERVED_NAME.test(value)\n}\n\n/**\n * Checks whether a manifest exactly binds its declared population and identities.\n * @param value - The candidate manifest\n * @returns True if the manifest is valid; false otherwise\n * @example\n * ```ts\n * isStudyCustodyManifest({}) // false\n * ```\n */\nexport function isStudyCustodyManifest(value: unknown): value is StudyManifest {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(\n\t\t\t\tvalue,\n\t\t\t\t['id', 'created', 'definition', 'scenarios', 'identity', 'schedule', 'bounds', 'host'],\n\t\t\t\t['qualification'],\n\t\t\t) ||\n\t\t\t!isStudyCustodyName(value.id) ||\n\t\t\t!isStudyTimestamp(value.created) ||\n\t\t\t!isStudyDefinition(value.definition) ||\n\t\t\t!isArray(value.scenarios) ||\n\t\t\t!value.scenarios.every(isStudyScenario) ||\n\t\t\t!isStudyBounds(value.bounds) ||\n\t\t\t!isRecord(value.identity) ||\n\t\t\t!matchesStudyKeys(\n\t\t\t\tvalue.identity,\n\t\t\t\t['agent', 'subject', 'instrument', 'fixtures', 'profile'],\n\t\t\t\t['provider'],\n\t\t\t) ||\n\t\t\t(value.identity.provider !== undefined && !isStudyDigest(value.identity.provider)) ||\n\t\t\t(value.qualification !== undefined && !isStudyDigest(value.qualification)) ||\n\t\t\t!isRecord(value.host) ||\n\t\t\t!Object.values(value.host).every((entry) => typeof entry === 'string') ||\n\t\t\t!isArray(value.schedule)\n\t\t)\n\t\t\treturn false\n\t\tconst identity = value.identity\n\t\tif (\n\t\t\t!['agent', 'subject', 'instrument', 'fixtures', 'profile'].every((key) =>\n\t\t\t\tisStudyDigest(identity[key]),\n\t\t\t)\n\t\t)\n\t\t\treturn false\n\t\tconst schedule = buildStudySchedule(value.definition, value.scenarios)\n\t\treturn (\n\t\t\tvalue.schedule.every(isStudyCustodyTrial) &&\n\t\t\tcanonicalStringify(schedule) === canonicalStringify(value.schedule)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a scheduled trial has exact valid identity fields.\n * @param value - The candidate trial\n * @returns True if its identity is valid; false otherwise\n * @example\n * ```ts\n * isStudyCustodyTrial({}) // false\n * ```\n */\nexport function isStudyCustodyTrial(value: unknown): value is StudyTrial {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['id', 'scenario', 'arm', 'repetition']) &&\n\t\t\tisStudyCustodyName(value.id) &&\n\t\t\tisStudyName(value.scenario) &&\n\t\t\tisStudyName(value.arm) &&\n\t\t\ttypeof value.repetition === 'number' &&\n\t\t\tNumber.isSafeInteger(value.repetition) &&\n\t\t\tvalue.repetition >= 0\n\t\t)\n\t})\n}\n\n/**\n * Checks whether evidence is exact JSON with a declared event and goal name.\n * @param value - The candidate evidence\n * @returns True if evidence is valid; false otherwise\n * @example\n * ```ts\n * isStudyCustodyEvidence({ event: 'saved', goal: 'write', value: true }) // true\n * ```\n */\nexport function isStudyCustodyEvidence(value: unknown): value is StudyEvidence {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['event', 'goal', 'value']) &&\n\t\t\tisStudyName(value.event) &&\n\t\t\tisStudyName(value.goal) &&\n\t\t\tisJSONValue(value.value)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a failure carries exact attributable operational fields.\n * @remarks\n * `role` and `stop` are optional keys. A `stop` is valid only on a `capacity` or `deadline` failure,\n * and it must satisfy `isStudyStop`; a failure sealed before the `stop` member existed has no key.\n * @param value - The candidate failure\n * @returns True if the failure is valid; false otherwise\n * @example\n * ```ts\n * isStudyCustodyFailure({}) // false\n * ```\n */\nexport function isStudyCustodyFailure(value: unknown): value is StudyFailure {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['cause', 'message'], ['role', 'stop']) &&\n\t\t\tisStudyCause(value.cause) &&\n\t\t\tisNonEmptyString(value.message) &&\n\t\t\t(value.role === undefined || isStudyRole(value.role)) &&\n\t\t\t(value.stop === undefined ||\n\t\t\t\t((value.cause === 'capacity' || value.cause === 'deadline') && isStudyStop(value.stop)))\n\t\t)\n\t})\n}\n\n/**\n * Checks whether an observation preserves output or an explicit unexecuted failure.\n * @param value - The candidate observation\n * @returns True if the observation is valid, with an executed fact or an unexecuted fact that holds a failure and no product, usage or duration; false otherwise\n * @example\n * ```ts\n * isStudyCustodyObservation({}) // false\n * ```\n */\nexport function isStudyCustodyObservation(value: unknown): value is StudyObservation {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(value, ['goal', 'usage', 'duration', 'executed'], ['product', 'failure']) ||\n\t\t\t!isStudyName(value.goal) ||\n\t\t\t!isArray(value.usage) ||\n\t\t\t!value.usage.every(isStudyUsage) ||\n\t\t\ttypeof value.duration !== 'number' ||\n\t\t\t!Number.isSafeInteger(value.duration) ||\n\t\t\tvalue.duration < 0 ||\n\t\t\t(value.failure !== undefined && !isStudyCustodyFailure(value.failure)) ||\n\t\t\ttypeof value.executed !== 'boolean' ||\n\t\t\t(value.executed === false &&\n\t\t\t\t(value.product !== undefined ||\n\t\t\t\t\tvalue.failure === undefined ||\n\t\t\t\t\tvalue.usage.length !== 0 ||\n\t\t\t\t\tvalue.duration !== 0))\n\t\t)\n\t\t\treturn false\n\t\tif (value.product === undefined) return value.failure !== undefined\n\t\treturn (\n\t\t\tisRecord(value.product) &&\n\t\t\tmatchesStudyKeys(value.product, ['value', 'partial']) &&\n\t\t\tisJSONValue(value.product.value) &&\n\t\t\ttypeof value.product.partial === 'boolean'\n\t\t)\n\t})\n}\n\n/**\n * Checks whether an attempt terminally accounts for the exact scheduled goal horizon.\n * @param value - The candidate attempt\n * @param manifest - The authoritative declaration\n * @returns True if the terminal record is compatible and its execution facts are consistent; false otherwise\n * @remarks\n * Executed goals form a prefix of the horizon and an executed goal with a failure ends it.\n * An unexecuted attempt holds only unexecuted goals, and an attempt without a failure holds only\n * executed goals that did not fail.\n * @example\n * ```ts\n * isStudyCustodyAttempt({}, manifest) // false\n * ```\n */\nexport function isStudyCustodyAttempt(\n\tvalue: unknown,\n\tmanifest: StudyManifest,\n): value is StudyAttempt {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(value, ['trial', 'observations', 'duration', 'executed'], ['failure']) ||\n\t\t\t!isStudyCustodyTrial(value.trial) ||\n\t\t\t!isArray(value.observations) ||\n\t\t\t!value.observations.every(isStudyCustodyObservation) ||\n\t\t\ttypeof value.duration !== 'number' ||\n\t\t\t!Number.isSafeInteger(value.duration) ||\n\t\t\tvalue.duration < 0 ||\n\t\t\t(value.failure !== undefined && !isStudyCustodyFailure(value.failure))\n\t\t)\n\t\t\treturn false\n\t\tconst identity = value.trial\n\t\tconst trial = manifest.schedule.find((entry) => entry.id === identity.id)\n\t\tconst scenario = manifest.scenarios.find((entry) => entry.id === identity.scenario)\n\t\tif (\n\t\t\ttrial === undefined ||\n\t\t\tscenario === undefined ||\n\t\t\tcanonicalStringify(trial) !== canonicalStringify(value.trial) ||\n\t\t\tvalue.observations.length !== scenario.goals.length ||\n\t\t\t!value.observations.every(\n\t\t\t\t(observation, index) => observation.goal === scenario.goals[index]?.id,\n\t\t\t)\n\t\t)\n\t\t\treturn false\n\t\tconst executed = value.executed\n\t\tif (typeof executed !== 'boolean') return false\n\t\t// A terminal record without a failure holds only executed goals that did not fail.\n\t\tif (\n\t\t\tvalue.failure === undefined &&\n\t\t\t!value.observations.every((entry) => entry.executed && entry.failure === undefined)\n\t\t)\n\t\t\treturn false\n\t\t// An executed goal needs an executed attempt and no earlier goal that was unexecuted or failed,\n\t\t// so it lies at or before the first goal that was unexecuted or failed. A hole reads as an\n\t\t// absent observation, which refuses the record, as visiting every position does.\n\t\tconst observations = Array.from(value.observations)\n\t\tconst stop = observations.findIndex(\n\t\t\t(observation) => !observation.executed || observation.failure !== undefined,\n\t\t)\n\t\treturn observations.every(\n\t\t\t(observation, index) => !observation.executed || (executed && (stop === -1 || index <= stop)),\n\t\t)\n\t})\n}\n\n/**\n * Checks whether an execution file inventory entry is path-safe and bounded.\n * @param value - The candidate entry\n * @returns True if the entry is valid; false otherwise\n * @example\n * ```ts\n * isStudyCustodyFile({}) // false\n * ```\n */\nexport function isStudyCustodyFile(value: unknown): value is StudyFile {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['path', 'bytes', 'digest']) &&\n\t\t\ttypeof value.path === 'string' &&\n\t\t\t(value.path === 'manifest.json' ||\n\t\t\t\t/^trials\\/[a-z0-9]+(?:-[a-z0-9]+)*\\/(?:evidence.jsonl|attempt.json)$/.test(value.path)) &&\n\t\t\tvalue.path.split('/').every((name) => !STUDY_RESERVED_NAME.test(name)) &&\n\t\t\ttypeof value.bytes === 'number' &&\n\t\t\tNumber.isSafeInteger(value.bytes) &&\n\t\t\tvalue.bytes >= 0 &&\n\t\t\tisStudyDigest(value.digest)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a seal has an exact unique execution inventory.\n * @param value - The candidate seal\n * @returns True if the seal is structurally valid; false otherwise\n * @example\n * ```ts\n * isStudyCustodySeal({}) // false\n * ```\n */\nexport function isStudyCustodySeal(value: unknown): value is StudySeal {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['result', 'id', 'files']) &&\n\t\t\tisStudyCustodyName(value.result) &&\n\t\t\tisStudyDigest(value.id) &&\n\t\t\tisArray(value.files) &&\n\t\t\tvalue.files.length > 0 &&\n\t\t\tvalue.files.every(isStudyCustodyFile) &&\n\t\t\tnew Set(value.files.map((entry) => entry.path)).size === value.files.length\n\t\t)\n\t})\n}\n","import type { StudyAdapterInterface } from './types.js'\nimport { holds } from '@orkestrel/contract'\n\n/** Checks whether a factory returned the complete consumer adapter contract.\n * @param value - The unknown factory result.\n * @returns True if validation, construction, and grading are callable; false otherwise.\n * @example Refuse an incomplete adapter\n * ```ts\n * import { isStudyAdapter } from '@orkestrel/study/server'\n *\n * isStudyAdapter({}) // false\n * ```\n */\nexport function isStudyAdapter(value: unknown): value is StudyAdapterInterface {\n\treturn holds(() => {\n\t\treturn (\n\t\t\ttypeof value === 'object' &&\n\t\t\tvalue !== null &&\n\t\t\t'validate' in value &&\n\t\t\ttypeof value.validate === 'function' &&\n\t\t\t'driver' in value &&\n\t\t\ttypeof value.driver === 'function' &&\n\t\t\t'grade' in value &&\n\t\t\ttypeof value.grade === 'function'\n\t\t)\n\t})\n}\n","import type { StudyEvidence, StudyJudgment } from '../../core/types.js'\nimport type {\n\tStudyAdapterInterface,\n\tStudyAdjudication,\n\tStudyGradeFunction,\n\tStudyGradeTarget,\n\tStudyReference,\n} from './types.js'\nimport { isArray, isRecord } from '@orkestrel/contract'\nimport { StudyError } from '../../core/errors.js'\nimport { isStudyJudgment, isStudyRubric } from '../../core/validators.js'\nimport {\n\tisStudyCustodyAttempt,\n\tisStudyCustodyEvidence,\n\tisStudyCustodyManifest,\n} from '../stores/validators.js'\nimport { isStudyAdapter } from './validators.js'\n\n/** Reads a complete adapter from an admitted module namespace.\n * @param namespace - The captured consumer module.\n * @returns The validated adapter instance.\n */\nexport function readStudyAdapter(namespace: unknown): StudyAdapterInterface {\n\tif (!isRecord(namespace) || typeof namespace.createStudyAdapter !== 'function')\n\t\tthrow new StudyError('CONFIG', 'Consumer module must export createStudyAdapter')\n\tconst adapter: unknown = namespace.createStudyAdapter()\n\tif (!isStudyAdapter(adapter))\n\t\tthrow new StudyError('CONFIG', 'Consumer factory returned an incomplete study adapter')\n\treturn adapter\n}\n\n/**\n * Renders a citation of one retained trial file or evidence row.\n * @param target - The declared pair whose retained observations the citation must name\n * @param reference - The attempt file, the evidence file, or one zero-based evidence row\n * @returns The retained path, with a one-based row position for an evidence row\n * @throws StudyError - Thrown when the trial was not retained, or the citation names a row that does not exist or a row of the attempt file\n * @example Cite a retained evidence row\n * ```ts\n * import type { StudyGradeTarget } from '@orkestrel/study/server'\n * import { buildStudyReference } from '@orkestrel/study/server'\n *\n * declare const target: StudyGradeTarget\n *\n * buildStudyReference(target, { file: 'evidence', row: 0 }) // 'trials/r1-s1-a1/evidence.jsonl#1'\n * ```\n */\nexport function buildStudyReference(target: StudyGradeTarget, reference: StudyReference): string {\n\tif (!isRecord(reference)) throw new StudyError('EVIDENCE', 'Grading reference must be a record')\n\tif (target.attempt === undefined)\n\t\tthrow new StudyError('EVIDENCE', 'Grading reference names a trial that was not retained')\n\tif (reference.file !== 'attempt' && reference.file !== 'evidence')\n\t\tthrow new StudyError('EVIDENCE', 'Grading reference names an unknown retained file')\n\tconst file = reference.file === 'attempt' ? 'attempt.json' : 'evidence.jsonl'\n\tconst path = `trials/${target.trial.id}/${file}`\n\tif (reference.row === undefined) return path\n\tif (\n\t\treference.file !== 'evidence' ||\n\t\t!Number.isSafeInteger(reference.row) ||\n\t\treference.row < 0 ||\n\t\treference.row >= target.evidence.length ||\n\t\t!isStudyCustodyEvidence(target.evidence[reference.row])\n\t)\n\t\tthrow new StudyError('EVIDENCE', 'Grading reference names a retained row that does not exist')\n\treturn `${path}#${reference.row + 1}`\n}\n\n/**\n * Grades every declared trial and criterion pair through the consumer's predicate.\n * @param input - The sealed declaration, retained attempts, retained evidence, and independent rubric\n * @param grade - The consumer's domain predicate; it supplies each verdict, method, reason, and citation\n * @returns One judgment for each declared pair, in schedule then rubric order, with one-based evidence references\n * @remarks\n * The traversal validates its input at this boundary, so a direct call retains the checks the\n * host also makes. A trial without a retained attempt still receives a judgment: the predicate\n * sees no attempt and no evidence, and missing evidence stays whatever verdict the consumer\n * reads from it. The traversal never decides success, and it cites nothing the retained\n * evidence cannot back.\n * @throws StudyError - Thrown when the rubric, declaration, attempts, or evidence are invalid or foreign, when a criterion names an undeclared goal, or when a reading is not a valid judgment\n * @example Grade retained evidence with a consumer predicate\n * ```ts\n * import type { StudyAdjudication, StudyGradeFunction } from '@orkestrel/study/server'\n * import { gradeStudyEvidence } from '@orkestrel/study/server'\n *\n * declare const input: StudyAdjudication\n * declare const grade: StudyGradeFunction\n *\n * gradeStudyEvidence(input, grade)\n * ```\n */\nexport function gradeStudyEvidence(\n\tinput: StudyAdjudication,\n\tgrade: StudyGradeFunction,\n): readonly StudyJudgment[] {\n\tif (!isRecord(input)) throw new StudyError('CONFIG', 'Invalid grading input')\n\tconst { manifest, rubric, attempts, evidence } = input\n\tif (!isStudyRubric(rubric)) throw new StudyError('CONFIG', 'Invalid grading rubric')\n\tif (!isStudyCustodyManifest(manifest))\n\t\tthrow new StudyError('CONFIG', 'Invalid grading manifest or schedule')\n\tconst schedule = manifest.schedule\n\tif (!isArray(attempts) || !attempts.every((attempt) => isStudyCustodyAttempt(attempt, manifest)))\n\t\tthrow new StudyError('EVIDENCE', 'Invalid or duplicate grading attempts')\n\tconst retained = new Map(attempts.map((attempt) => [attempt.trial.id, attempt]))\n\tif (retained.size !== attempts.length)\n\t\tthrow new StudyError('EVIDENCE', 'Invalid or duplicate grading attempts')\n\tconst known = new Set(schedule.map((trial) => trial.id))\n\tif (\n\t\t!isRecord(evidence) ||\n\t\t!Object.entries(evidence).every(\n\t\t\t([id, rows]) =>\n\t\t\t\tknown.has(id) && isArray(rows) && Array.from(rows).every(isStudyCustodyEvidence),\n\t\t)\n\t)\n\t\tthrow new StudyError('EVIDENCE', 'Invalid or foreign grading evidence')\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)\n\t\t\tthrow new StudyError('CONFIG', 'Grading criterion references an undeclared goal')\n\t}\n\t// Iterators pull each trial and criterion only after the preceding predicate returned, so a\n\t// predicate that edits the caller's live arrays changes what the next judgment names.\n\treturn Object.freeze(\n\t\tschedule\n\t\t\t.values()\n\t\t\t.flatMap((trial) => {\n\t\t\t\tconst attempt = retained.get(trial.id)\n\t\t\t\tconst rows: readonly StudyEvidence[] =\n\t\t\t\t\tattempt === undefined ? Object.freeze([]) : (evidence[trial.id] ?? Object.freeze([]))\n\t\t\t\treturn rubric.criteria\n\t\t\t\t\t.values()\n\t\t\t\t\t.filter((criterion) => criterion.scenario === trial.scenario)\n\t\t\t\t\t.map((criterion): StudyJudgment => {\n\t\t\t\t\t\tconst target: StudyGradeTarget = Object.freeze({\n\t\t\t\t\t\t\ttrial,\n\t\t\t\t\t\t\tcriterion,\n\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\tevidence: rows,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tconst reading = grade(target)\n\t\t\t\t\t\tif (!isRecord(reading) || !isArray(reading.references))\n\t\t\t\t\t\t\tthrow new StudyError('EVIDENCE', 'Grading predicate returned an invalid reading')\n\t\t\t\t\t\tconst judgment = {\n\t\t\t\t\t\t\ttrial: trial.id,\n\t\t\t\t\t\t\tcriterion: criterion.id,\n\t\t\t\t\t\t\tverdict: reading.verdict,\n\t\t\t\t\t\t\tmethod: reading.method,\n\t\t\t\t\t\t\treason: reading.reason,\n\t\t\t\t\t\t\treferences: Object.freeze(\n\t\t\t\t\t\t\t\treading.references.map((reference) => buildStudyReference(target, reference)),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!isStudyJudgment(judgment))\n\t\t\t\t\t\t\tthrow new StudyError('EVIDENCE', 'Grading predicate returned an invalid judgment')\n\t\t\t\t\t\treturn Object.freeze(judgment)\n\t\t\t\t\t})\n\t\t\t})\n\t\t\t.toArray(),\n\t)\n}\n","/** Bounds admitted files before another capture is allocated. */\nexport const ARTIFACT_FILES = 8192\n\n/** Bounds all captured input bytes to 128 MiB. */\nexport const ARTIFACT_BYTES = 128 * 1024 * 1024\n\n/** Bounds one captured input file to 16 MiB. */\nexport const ARTIFACT_FILE_BYTES = 16 * 1024 * 1024\n\n/** Bounds all visited directory entries, including ignored assets. */\nexport const ARTIFACT_VISITS = 32768\n\n/** Bounds directory nesting below each selected root. */\nexport const ARTIFACT_DEPTH = 64\n\n/** Bounds selected package roots before traversal begins. */\nexport const ARTIFACT_ROOTS = 128\n","import { isInstance } from '@orkestrel/contract'\n\n/** Reports an invalid or drifted artifact inventory. */\nexport class ArtifactError extends Error {\n\treadonly code = 'ARTIFACT' as const\n\n\t/** Records the refused artifact boundary.\n\t * @param message - The specific refusal.\n\t */\n\tconstructor(message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'ArtifactError'\n\t}\n}\n\n/** Narrows a caught value to an artifact refusal.\n * @param value - The caught value.\n * @returns True if the value is an artifact error; false otherwise.\n */\nexport function isArtifactError(value: unknown): value is ArtifactError {\n\treturn isInstance(value, ArtifactError)\n}\n","import type { Dir, Dirent } from 'node:fs'\nimport type { ArtifactSource } from './types.js'\nimport { closeSync, fstatSync, lstatSync, openSync, readSync, realpathSync } from 'node:fs'\nimport { isAbsolute, resolve } from 'node:path'\nimport { hashStudyBytes } from '../helpers.js'\nimport { ARTIFACT_FILE_BYTES } from './constants.js'\nimport { ArtifactError } from './errors.js'\n\n/** Fills a buffer from an open descriptor, one positioned read at a time.\n * @param descriptor - The open file descriptor to read.\n * @param target - The buffer to fill.\n * @param offset - The position in the file and the buffer to continue from; Default: 0.\n * @returns The bytes read, as the whole buffer when the file filled it or as its leading part when the file ended first.\n */\nexport function readArtifactBytes(descriptor: number, target: Buffer, offset = 0): Buffer {\n\tif (offset >= target.length) return target\n\tconst count = readSync(descriptor, target, offset, target.length - offset, offset)\n\treturn count === 0\n\t\t? target.subarray(0, offset)\n\t\t: readArtifactBytes(descriptor, target, offset + count)\n}\n\n/** Iterates the remaining entries of an open directory handle lazily, in read order.\n * @param handle - The open synchronous directory handle; the caller owns it and closes it.\n * @returns Each remaining entry until the handle reports the end. An entry is read only when the consumer asks for it, so a consumer that stops early leaves the rest unread.\n */\nexport function* iterateArtifactEntries(handle: Dir): Generator<Dirent, void> {\n\tfor (;;) {\n\t\tconst entry = handle.readSync()\n\t\tif (entry === null) return\n\t\tyield entry\n\t}\n}\n\n/** Reads a bounded regular file only through its canonical absolute path.\n * @param path - The absolute path to inspect.\n * @param maximum - The remaining capture budget; Default: 16 MiB.\n * @returns Captured bytes with their identity.\n * @throws Thrown when the path is linked, noncanonical, oversized, or changes while read.\n */\nexport function readArtifact(path: string, maximum = ARTIFACT_FILE_BYTES): ArtifactSource {\n\tif (\n\t\t!Number.isSafeInteger(maximum) ||\n\t\tmaximum < 0 ||\n\t\t!isAbsolute(path) ||\n\t\tresolve(path) !== path ||\n\t\trealpathSync(path) !== path ||\n\t\t!lstatSync(path).isFile()\n\t) {\n\t\tthrow new ArtifactError(`Artifact requires a canonical regular file and byte budget: ${path}`)\n\t}\n\tconst descriptor = openSync(path, 'r')\n\ttry {\n\t\tconst before = fstatSync(descriptor)\n\t\tif (!before.isFile() || before.size > Math.min(maximum, ARTIFACT_FILE_BYTES))\n\t\t\tthrow new ArtifactError(`Artifact byte limit exceeded: ${path}`)\n\t\tconst source = readArtifactBytes(descriptor, Buffer.alloc(before.size))\n\t\tif (source.length !== before.size)\n\t\t\tthrow new ArtifactError(`Artifact file drifted while reading: ${path}`)\n\t\tconst after = fstatSync(descriptor)\n\t\tif (\n\t\t\tbefore.size !== after.size ||\n\t\t\tbefore.mtimeMs !== after.mtimeMs ||\n\t\t\tbefore.ctimeMs !== after.ctimeMs ||\n\t\t\trealpathSync(path) !== path ||\n\t\t\t!lstatSync(path).isFile()\n\t\t)\n\t\t\tthrow new ArtifactError(`Artifact file drifted while reading: ${path}`)\n\t\treturn { path, digest: hashStudyBytes(source), size: source.byteLength, source }\n\t} finally {\n\t\tcloseSync(descriptor)\n\t}\n}\n","import type {\n\tLoadHookContext,\n\tLoadFnOutput,\n\tResolveHookContext,\n\tResolveFnOutput,\n} from 'node:module'\nimport type {\n\tArtifactHookInput,\n\tArtifactLoadHandler,\n\tArtifactResolveHandler,\n\tArtifactSource,\n} from './types.js'\nimport { isBuiltin, stripTypeScriptTypes } from 'node:module'\nimport { basename, extname, join } from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { containsArtifact } from '../helpers.js'\nimport { ArtifactError } from './errors.js'\nimport { readArtifact } from './helpers.js'\n\n/** Enforces captured inventory membership at every synchronous native import edge. */\nexport class Resolution {\n\t#input: ArtifactHookInput\n\t#files: ReadonlyMap<string, ArtifactSource>\n\n\t/** Retains the trusted captured inventory and its private namespace.\n\t * @param input - Captured built bytes and separate source selection.\n\t */\n\tconstructor(input: ArtifactHookInput) {\n\t\tthis.#input = input\n\t\tthis.#files = new Map(input.files.map((file) => [file.path, file]))\n\t}\n\n\t/** Resolves native edges with source-local JavaScript-to-TypeScript substitution.\n\t * @param specifier - The requested native specifier.\n\t * @param context - Node's resolution context.\n\t * @param next - The remaining native resolution chain.\n\t * @returns An admitted URL in the captured namespace.\n\t */\n\tresolve(\n\t\tspecifier: string,\n\t\tcontext: ResolveHookContext,\n\t\tnext: ArtifactResolveHandler,\n\t): ResolveFnOutput {\n\t\tconst parent = context.parentURL === undefined ? undefined : new URL(context.parentURL)\n\t\tconst initial = specifier.startsWith('file:') ? new URL(specifier) : undefined\n\t\tif (\n\t\t\tparent?.searchParams.get('artifact') !== this.#input.token &&\n\t\t\tinitial?.searchParams.get('artifact') !== this.#input.token\n\t\t)\n\t\t\treturn next(specifier, context)\n\t\tif (isBuiltin(specifier)) {\n\t\t\tconst instrument = this.#input.instrument\n\t\t\tconst trusted =\n\t\t\t\tinstrument !== undefined &&\n\t\t\t\tparent?.protocol === 'file:' &&\n\t\t\t\tcontainsArtifact(join(instrument, 'dist'), fileURLToPath(parent)) &&\n\t\t\t\tthis.#files.has(fileURLToPath(parent))\n\t\t\tif (\n\t\t\t\t!trusted &&\n\t\t\t\t['module', 'vm', 'worker_threads', 'child_process', 'cluster'].includes(\n\t\t\t\t\tspecifier.replace(/^node:/, ''),\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow new ArtifactError(`Artifact alternate loader is unsupported: ${specifier}`)\n\t\t\treturn next(specifier, context)\n\t\t}\n\t\tfor (const file of this.#input.files) {\n\t\t\tif (basename(file.path) === 'package.json' && readArtifact(file.path).digest !== file.digest)\n\t\t\t\tthrow new ArtifactError(`Artifact manifest drifted: ${file.path}`)\n\t\t}\n\t\tconst source = this.#input.source\n\t\tconst target = this.#locate(specifier, parent, initial)\n\t\tif (\n\t\t\tsource !== undefined &&\n\t\t\ttarget?.protocol === 'file:' &&\n\t\t\tcontainsArtifact(source.root, fileURLToPath(target))\n\t\t) {\n\t\t\tif (\n\t\t\t\tparent !== undefined &&\n\t\t\t\t(parent.protocol !== 'file:' || !containsArtifact(source.root, fileURLToPath(parent))) &&\n\t\t\t\tinitial?.searchParams.get('artifact') !== this.#input.token\n\t\t\t)\n\t\t\t\tthrow new ArtifactError('Artifact built modules cannot import consumer sources')\n\t\t\tif (\n\t\t\t\ttarget.hash !== '' ||\n\t\t\t\t(target.search !== '' && target.search !== `?artifact=${this.#input.token}`)\n\t\t\t)\n\t\t\t\tthrow new ArtifactError(`Artifact source URL is unsupported: ${target.href}`)\n\t\t\tconst file = this.#files.get(fileURLToPath(target))\n\t\t\tif (file === undefined || !['.ts', '.mts', '.js', '.mjs'].includes(extname(file.path)))\n\t\t\t\tthrow new ArtifactError(`Artifact source dependency is not admitted: ${target.href}`)\n\t\t\tif (readArtifact(file.path).digest !== file.digest)\n\t\t\t\tthrow new ArtifactError(`Artifact dependency drifted: ${file.path}`)\n\t\t\ttarget.searchParams.set('artifact', this.#input.token)\n\t\t\treturn {\n\t\t\t\turl: target.href,\n\t\t\t\tformat: 'module',\n\t\t\t\tshortCircuit: true,\n\t\t\t}\n\t\t}\n\t\tconst result = next(specifier, context)\n\t\tconst url = new URL(result.url)\n\t\tif (\n\t\t\turl.protocol !== 'file:' ||\n\t\t\turl.hash !== '' ||\n\t\t\t(url.search !== '' && url.search !== `?artifact=${this.#input.token}`)\n\t\t)\n\t\t\tthrow new ArtifactError(`Artifact URL is unsupported: ${result.url}`)\n\t\turl.search = ''\n\t\tconst file = this.#files.get(fileURLToPath(url))\n\t\tif (\n\t\t\tfile === undefined ||\n\t\t\t(source !== undefined && containsArtifact(source.root, file.path)) ||\n\t\t\t!['.js', '.mjs', '.json'].includes(extname(file.path)) ||\n\t\t\t(result.format !== 'module' && result.format !== 'json')\n\t\t)\n\t\t\tthrow new ArtifactError(`Artifact dependency is not admitted ESM: ${result.url}`)\n\t\tif (this.#input.excluded?.includes(file.path) === true)\n\t\t\tthrow new ArtifactError(`Artifact module is excluded: ${file.path}`)\n\t\tif (readArtifact(file.path).digest !== file.digest)\n\t\t\tthrow new ArtifactError(`Artifact dependency drifted: ${file.path}`)\n\t\turl.searchParams.set('artifact', this.#input.token)\n\t\treturn { ...result, url: url.href }\n\t}\n\n\t/** Returns captured bytes after verifying their live disk identity.\n\t * @param href - Node's resolved URL.\n\t * @param context - Node's load context.\n\t * @param next - The remaining native load chain.\n\t * @returns Captured ESM, JSON, or native strip-only TypeScript output.\n\t */\n\tload(href: string, context: LoadHookContext, next: ArtifactLoadHandler): LoadFnOutput {\n\t\tconst url = new URL(href)\n\t\tif (url.searchParams.get('artifact') !== this.#input.token) return next(href, context)\n\t\turl.search = ''\n\t\tconst file = this.#files.get(fileURLToPath(url))\n\t\tif (file === undefined || (context.format !== 'module' && context.format !== 'json'))\n\t\t\tthrow new ArtifactError(`Artifact load is unsupported: ${href}`)\n\t\tif (readArtifact(file.path).digest !== file.digest)\n\t\t\tthrow new ArtifactError(`Artifact dependency drifted: ${file.path}`)\n\t\tconst extension = extname(file.path)\n\t\treturn {\n\t\t\tformat: context.format,\n\t\t\tsource:\n\t\t\t\textension === '.ts' || extension === '.mts'\n\t\t\t\t\t? stripTypeScriptTypes(Buffer.from(file.source).toString('utf8'), { mode: 'strip' })\n\t\t\t\t\t: new Uint8Array(file.source),\n\t\t\tshortCircuit: true,\n\t\t}\n\t}\n\n\t// Locates a source-local relative edge, substituting the captured TypeScript twin of a\n\t// JavaScript specifier; any other edge keeps its initial target.\n\t#locate(specifier: string, parent: URL | undefined, initial: URL | undefined): URL | undefined {\n\t\tconst source = this.#input.source\n\t\tif (\n\t\t\tsource === undefined ||\n\t\t\tparent?.protocol !== 'file:' ||\n\t\t\t!containsArtifact(source.root, fileURLToPath(parent)) ||\n\t\t\t!(specifier.startsWith('./') || specifier.startsWith('../'))\n\t\t)\n\t\t\treturn initial\n\t\tconst target = new URL(specifier, parent)\n\t\tif (target.search !== '' || target.hash !== '')\n\t\t\tthrow new ArtifactError(`Artifact source URL is unsupported: ${specifier}`)\n\t\tconst path = fileURLToPath(target)\n\t\tif (!containsArtifact(source.root, path))\n\t\t\tthrow new ArtifactError(`Artifact source dependency escapes its root: ${specifier}`)\n\t\tconst extension = extname(path)\n\t\tif (extension !== '.js' && extension !== '.mjs') return target\n\t\tconst substitute = `${path.slice(0, -extension.length)}${extension === '.js' ? '.ts' : '.mts'}`\n\t\tif (!this.#files.has(substitute)) return target\n\t\tif (this.#files.has(path))\n\t\t\tthrow new ArtifactError(`Artifact source target is ambiguous: ${path}`)\n\t\treturn pathToFileURL(substitute)\n\t}\n}\n","import type {\n\tArtifactInventory,\n\tArtifactLoaderOptions,\n\tArtifactPackage,\n\tArtifactSource,\n\tArtifactTally,\n} from './types.js'\nimport { isNonEmptyString, isRecord } from '@orkestrel/contract'\nimport { randomUUID } from 'node:crypto'\nimport { lstatSync, opendirSync, realpathSync } from 'node:fs'\nimport { registerHooks, stripTypeScriptTypes } from 'node:module'\nimport { extname, isAbsolute, join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport {\n\tARTIFACT_BYTES,\n\tARTIFACT_DEPTH,\n\tARTIFACT_FILES,\n\tARTIFACT_ROOTS,\n\tARTIFACT_VISITS,\n} from './constants.js'\nimport { containsArtifact, hashStudyBytes } from '../helpers.js'\nimport { ArtifactError } from './errors.js'\nimport { iterateArtifactEntries, readArtifact } from './helpers.js'\nimport { Resolution } from './Resolution.js'\n\n/** Captures built ESM and a separate strip-only consumer adapter in a fresh worker.\n * @remarks\n * Loads trusted code, not a hostile-code sandbox. Native process APIs, eval and external\n * services are not replayed. One inventory may load per process; terminate it afterwards.\n */\nexport class ArtifactLoader {\n\tstatic #active = false\n\t#options: ArtifactLoaderOptions\n\t#inventory: ArtifactInventory | undefined\n\t#sources: readonly ArtifactSource[] = []\n\t#token: string | undefined\n\n\t/** Captures selections without reading or executing selected modules.\n\t * @param options - Canonical built selections and optional consumer source selection.\n\t */\n\tconstructor(options: ArtifactLoaderOptions) {\n\t\tif (options.roots.length > ARTIFACT_ROOTS || options.entries.length > ARTIFACT_FILES)\n\t\t\tthrow new ArtifactError('Artifact selection exceeds its limit')\n\t\tthis.#options = {\n\t\t\t...options,\n\t\t\tentries: [...options.entries],\n\t\t\troots: [...options.roots],\n\t\t\t...(options.source === undefined ? {} : { source: { ...options.source } }),\n\t\t\t...(options.excluded === undefined ? {} : { excluded: [...options.excluded] }),\n\t\t}\n\t}\n\n\t/** Reads and identifies admitted files without evaluating selected modules.\n\t * @returns Frozen evidence identifying all captured bytes and the native runtime.\n\t * @throws Thrown for invalid selections, unsupported TypeScript, limits, or drift.\n\t */\n\tinspect(): ArtifactInventory {\n\t\tif (this.#inventory !== undefined) {\n\t\t\tthis.verify()\n\t\t\treturn this.#inventory\n\t\t}\n\t\tif (\n\t\t\t(this.#options.entries.length === 0 && this.#options.source === undefined) ||\n\t\t\tthis.#options.roots.length > ARTIFACT_ROOTS ||\n\t\t\tthis.#options.entries.length > ARTIFACT_FILES\n\t\t)\n\t\t\tthrow new ArtifactError('Artifact selection is empty or exceeds its limit')\n\t\tif (\n\t\t\tthis.#options.instrument !== undefined &&\n\t\t\t!this.#options.roots.includes(this.#options.instrument)\n\t\t)\n\t\t\tthrow new ArtifactError('Artifact instrument must be an admitted package root')\n\t\tconst sources = this.#capture()\n\t\tconst packages = [...this.#options.roots].sort().map((root, index, sorted): ArtifactPackage => {\n\t\t\tconst manifest = sources.find((file) => file.path === join(root, 'package.json'))\n\t\t\tif (manifest === undefined) throw new ArtifactError(`Artifact manifest is missing: ${root}`)\n\t\t\tconst value: unknown = JSON.parse(Buffer.from(manifest.source).toString('utf8'))\n\t\t\tif (\n\t\t\t\t!isRecord(value) ||\n\t\t\t\tvalue.type !== 'module' ||\n\t\t\t\t!isNonEmptyString(value.name) ||\n\t\t\t\t!isNonEmptyString(value.version)\n\t\t\t)\n\t\t\t\tthrow new ArtifactError(`Artifact requires a named, versioned ESM package: ${root}`)\n\t\t\tif (sorted.indexOf(root) !== index)\n\t\t\t\tthrow new ArtifactError(`Artifact package identity is duplicated: ${value.name}`)\n\t\t\treturn Object.freeze({ root, name: value.name, version: value.version })\n\t\t})\n\t\tfor (const entry of this.#options.entries) {\n\t\t\tif (\n\t\t\t\t!['.js', '.mjs'].includes(extname(entry)) ||\n\t\t\t\t!sources.some((file) => file.path === entry) ||\n\t\t\t\t!packages.some((item) => containsArtifact(join(item.root, 'dist'), entry))\n\t\t\t)\n\t\t\t\tthrow new ArtifactError(`Artifact entry must be admitted built ESM: ${entry}`)\n\t\t}\n\t\tconst source = this.#options.source\n\t\tif (source !== undefined) {\n\t\t\tif (\n\t\t\t\t!['.ts', '.mts', '.js', '.mjs'].includes(extname(source.entry)) ||\n\t\t\t\t!containsArtifact(source.root, source.entry) ||\n\t\t\t\t!sources.some((file) => file.path === source.entry)\n\t\t\t)\n\t\t\t\tthrow new ArtifactError('Artifact source entry must be an admitted module')\n\t\t\tfor (const file of sources.filter((candidate) =>\n\t\t\t\tcontainsArtifact(source.root, candidate.path),\n\t\t\t)) {\n\t\t\t\tif (file.path.endsWith('.ts') || file.path.endsWith('.mts')) {\n\t\t\t\t\tconst counterpart = file.path.endsWith('.mts')\n\t\t\t\t\t\t? `${file.path.slice(0, -4)}.mjs`\n\t\t\t\t\t\t: `${file.path.slice(0, -3)}.js`\n\t\t\t\t\tif (sources.some((candidate) => candidate.path === counterpart))\n\t\t\t\t\t\tthrow new ArtifactError(`Artifact source target is ambiguous: ${file.path}`)\n\t\t\t\t\tstripTypeScriptTypes(Buffer.from(file.source).toString('utf8'), { mode: 'strip' })\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsources.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))\n\t\tconst settings = process.env.NODE_OPTIONS\n\t\tconst evidence = {\n\t\t\tnode: process.version,\n\t\t\truntime: Object.freeze({\n\t\t\t\targuments: Object.freeze([...process.execArgv]),\n\t\t\t\tplatform: process.platform,\n\t\t\t\tarchitecture: process.arch,\n\t\t\t\t...(settings === undefined ? {} : { options: settings }),\n\t\t\t}),\n\t\t\tentries: Object.freeze(\n\t\t\t\t[\n\t\t\t\t\t...new Set([...this.#options.entries, ...(source === undefined ? [] : [source.entry])]),\n\t\t\t\t].sort(),\n\t\t\t),\n\t\t\tpackages: Object.freeze(packages),\n\t\t\t...(source === undefined ? {} : { source: Object.freeze({ ...source }) }),\n\t\t\t...(this.#options.instrument === undefined ? {} : { instrument: this.#options.instrument }),\n\t\t\tfiles: Object.freeze(\n\t\t\t\tsources.map(({ path, digest, size }) => Object.freeze({ path, digest, size })),\n\t\t\t),\n\t\t}\n\t\tthis.#sources = sources\n\t\tthis.#inventory = Object.freeze({\n\t\t\tdigest: hashStudyBytes(JSON.stringify(evidence)),\n\t\t\t...evidence,\n\t\t})\n\t\tthis.verify()\n\t\treturn this.#inventory\n\t}\n\n\t/** Refuses byte and population drift since inspection.\n\t * @throws Thrown when any admitted file or the admitted population changes.\n\t */\n\tverify(): void {\n\t\tif (this.#inventory === undefined) throw new ArtifactError('Artifact inspection is required')\n\t\tconst current = this.#capture()\n\t\tconst captured = new Map(this.#sources.map((file) => [file.path, file.digest]))\n\t\tif (\n\t\t\tcurrent.length !== this.#sources.length ||\n\t\t\tcurrent.some((file) => captured.get(file.path) !== file.digest)\n\t\t)\n\t\t\tthrow new ArtifactError('Artifact inventory drifted')\n\t}\n\n\t/** Imports one selected entry through synchronous captured-byte hooks.\n\t * @param entry - The exact canonical built entry or selected source adapter entry.\n\t * @returns The actual module namespace for the caller to narrow.\n\t * @throws Thrown for drift, unsupported edges, evaluation failures, or a reused worker.\n\t */\n\tasync load(entry: string): Promise<unknown> {\n\t\tconst inventory = this.inspect()\n\t\tif (!inventory.entries.includes(entry))\n\t\t\tthrow new ArtifactError('Artifact entry was not selected')\n\t\tif (this.#token === undefined) {\n\t\t\tif (ArtifactLoader.#active)\n\t\t\t\tthrow new ArtifactError('Artifact loading requires a fresh process')\n\t\t\tconst token = randomUUID()\n\t\t\tconst resolution = new Resolution({\n\t\t\t\ttoken,\n\t\t\t\tfiles: this.#sources,\n\t\t\t\t...(inventory.source === undefined ? {} : { source: inventory.source }),\n\t\t\t\t...(inventory.instrument === undefined ? {} : { instrument: inventory.instrument }),\n\t\t\t\t...(this.#options.excluded === undefined ? {} : { excluded: this.#options.excluded }),\n\t\t\t})\n\t\t\tregisterHooks({\n\t\t\t\tresolve: (specifier, context, next) => resolution.resolve(specifier, context, next),\n\t\t\t\tload: (href, context, next) => resolution.load(href, context, next),\n\t\t\t})\n\t\t\tthis.#token = token\n\t\t\tArtifactLoader.#active = true\n\t\t}\n\t\tconst url = pathToFileURL(entry)\n\t\turl.searchParams.set('artifact', this.#token)\n\t\tconst namespace: unknown = await import(url.href)\n\t\tthis.verify()\n\t\treturn namespace\n\t}\n\n\t// Captures every root's manifest and built files, then the optional source graph, threading the visit and byte tally through each step.\n\t#capture(): ArtifactSource[] {\n\t\tconst sources: ArtifactSource[] = []\n\t\tconst tally = this.#options.roots.reduce<ArtifactTally>(\n\t\t\t(counted, root) => {\n\t\t\t\tif (\n\t\t\t\t\t!isAbsolute(root) ||\n\t\t\t\t\tresolve(root) !== root ||\n\t\t\t\t\trealpathSync(root) !== root ||\n\t\t\t\t\t!lstatSync(root).isDirectory()\n\t\t\t\t)\n\t\t\t\t\tthrow new ArtifactError(`Artifact requires a canonical package root: ${root}`)\n\t\t\t\treturn this.#walk(\n\t\t\t\t\tjoin(root, 'dist'),\n\t\t\t\t\tsources,\n\t\t\t\t\tfalse,\n\t\t\t\t\t0,\n\t\t\t\t\tthis.#append(join(root, 'package.json'), sources, counted),\n\t\t\t\t)\n\t\t\t},\n\t\t\tObject.freeze({ visits: 0, bytes: 0 }),\n\t\t)\n\t\tconst source = this.#options.source\n\t\tif (source !== undefined) {\n\t\t\tif (\n\t\t\t\tthis.#options.roots.some(\n\t\t\t\t\t(root) =>\n\t\t\t\t\t\tjoin(root, 'dist') === source.root ||\n\t\t\t\t\t\tcontainsArtifact(join(root, 'dist'), source.root) ||\n\t\t\t\t\t\tcontainsArtifact(source.root, join(root, 'dist')),\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow new ArtifactError('Artifact source and built inventories must not overlap')\n\t\t\tthis.#walk(source.root, sources, true, 0, tally)\n\t\t}\n\t\treturn sources\n\t}\n\n\t// Reads one admitted file under the bytes that remain and returns the tally including it.\n\t#append(path: string, sources: ArtifactSource[], tally: ArtifactTally): ArtifactTally {\n\t\tif (sources.length >= ARTIFACT_FILES)\n\t\t\tthrow new ArtifactError('Artifact file count limit exceeded')\n\t\tconst file = readArtifact(path, ARTIFACT_BYTES - tally.bytes)\n\t\tsources.push(file)\n\t\treturn Object.freeze({ visits: tally.visits, bytes: tally.bytes + file.size })\n\t}\n\n\t// Visits a directory's entries lazily, so a limit refusal stops reading it, and returns the tally including its subtree.\n\t#walk(\n\t\tdirectory: string,\n\t\tsources: ArtifactSource[],\n\t\tsource: boolean,\n\t\tdepth: number,\n\t\ttally: ArtifactTally,\n\t): ArtifactTally {\n\t\tif (depth > ARTIFACT_DEPTH) throw new ArtifactError('Artifact directory depth limit exceeded')\n\t\tif (\n\t\t\t!isAbsolute(directory) ||\n\t\t\tresolve(directory) !== directory ||\n\t\t\trealpathSync(directory) !== directory ||\n\t\t\t!lstatSync(directory).isDirectory()\n\t\t)\n\t\t\tthrow new ArtifactError(`Artifact directory must be canonical and not linked: ${directory}`)\n\t\tconst handle = opendirSync(directory)\n\t\ttry {\n\t\t\treturn iterateArtifactEntries(handle).reduce<ArtifactTally>((counted, entry) => {\n\t\t\t\tconst visited = Object.freeze({ visits: counted.visits + 1, bytes: counted.bytes })\n\t\t\t\tif (visited.visits > ARTIFACT_VISITS)\n\t\t\t\t\tthrow new ArtifactError('Artifact traversal limit exceeded')\n\t\t\t\tconst path = join(directory, entry.name)\n\t\t\t\tif (entry.isSymbolicLink())\n\t\t\t\t\tthrow new ArtifactError(`Artifact links are unsupported: ${path}`)\n\t\t\t\tif (entry.isDirectory()) return this.#walk(path, sources, source, depth + 1, visited)\n\t\t\t\treturn (source\n\t\t\t\t\t? ['.ts', '.mts', '.js', '.mjs']\n\t\t\t\t\t: ['.js', '.mjs', '.cjs', '.json']\n\t\t\t\t).includes(extname(path)) &&\n\t\t\t\t\t!path.endsWith('.d.ts') &&\n\t\t\t\t\t!path.endsWith('.d.mts')\n\t\t\t\t\t? this.#append(path, sources, visited)\n\t\t\t\t\t: visited\n\t\t\t}, tally)\n\t\t} finally {\n\t\t\thandle.closeSync()\n\t\t}\n\t}\n}\n","import type {\n\tStudyAttempt,\n\tStudyJudgment,\n\tStudyLabeling,\n\tStudyManifest,\n\tStudyRubric,\n} from '../../core/types.js'\nimport type {\n\tStudyFile,\n\tStudyPacketBundle,\n\tStudyPacketEntry,\n\tStudyPacketLink,\n\tStudyResultReading,\n\tStudySealedResult,\n} from './types.js'\nimport type { FileHandle } from 'node:fs/promises'\nimport { attempt, canonicalStringify, parseJSON } from '@orkestrel/contract'\nimport { constants } from 'node:fs'\nimport { lstat, open, readdir } from 'node:fs/promises'\nimport { dirname, join, parse, relative, resolve, sep } from 'node:path'\nimport { StudyError } from '../../core/errors.js'\nimport { decodeStudyJSON, encodeStudyJSON, hashStudyBytes } from '../helpers.js'\nimport { STUDY_CUSTODY_BYTES, STUDY_PACKET_DISCLOSURE } from './constants.js'\nimport {\n\tisStudyCustodyAttempt,\n\tisStudyCustodyEvidence,\n\tisStudyCustodyManifest,\n\tisStudyCustodySeal,\n} from './validators.js'\n\n/**\n * Builds neutral semantic identities for the complete eligible sealed horizon.\n * @param result - The verified sealed execution\n * @param rubric - The compatible independently held rubric\n * @returns Deterministically sorted neutral mappings\n * @example\n * ```ts\n * buildStudyPacketLinks(result, rubric)\n * ```\n */\nexport function buildStudyPacketLinks(\n\tresult: StudySealedResult,\n\trubric: StudyRubric,\n): readonly StudyPacketLink[] {\n\t// The pairs are produced one at a time, and a hole is a position that reads as absent, so a hole\n\t// refuses after the links before it were counted, as visiting each position in turn does.\n\tconst pairs = result.manifest.schedule.values().flatMap((trial) =>\n\t\trubric.criteria\n\t\t\t.values()\n\t\t\t.filter(\n\t\t\t\t(criterion) => criterion.method === 'semantic' && criterion.scenario === trial.scenario,\n\t\t\t)\n\t\t\t.map((criterion) => ({ trial, criterion })),\n\t)\n\t// Each record carries the encoded bytes of every link up to and including its own.\n\tconst records: Array<{ readonly link: StudyPacketLink; readonly bytes: number }> = []\n\tfor (const { trial, criterion } of pairs) {\n\t\tconst link = {\n\t\t\ttrial: `t-${hashStudyBytes(encodeStudyJSON([result.seal.id, 'trial', trial.id]))}`,\n\t\t\tcriterion: `c-${hashStudyBytes(encodeStudyJSON([result.seal.id, 'criterion', criterion.id]))}`,\n\t\t\tsource: { trial: trial.id, criterion: criterion.id },\n\t\t}\n\t\tconst bytes = (records.at(-1)?.bytes ?? 256) + encodeStudyJSON(link).byteLength\n\t\tif (bytes > STUDY_CUSTODY_BYTES)\n\t\t\tthrow new StudyError('CAPACITY', 'Semantic packet mapping exceeds its custody allowance')\n\t\trecords.push({ link, bytes })\n\t}\n\tconst links = records.map(({ link }) => link)\n\treturn Object.freeze(\n\t\tlinks.sort((left, right) =>\n\t\t\t`${left.trial}/${left.criterion}` < `${right.trial}/${right.criterion}`\n\t\t\t\t? -1\n\t\t\t\t: `${left.trial}/${left.criterion}` > `${right.trial}/${right.criterion}`\n\t\t\t\t\t? 1\n\t\t\t\t\t: 0,\n\t\t),\n\t)\n}\n\n/**\n * Builds deterministic public semantic inputs and a separately retained private map.\n * @param result - The verified sealed execution\n * @param rubric - The compatible semantic criterion declaration\n * @param digest - The exact imported rubric-byte identity\n * @returns The packet bundle, or undefined for a purely mechanical rubric\n * @throws StudyError - Thrown when a semantic pair has no declared input or terminal record\n * @example\n * ```ts\n * buildStudyPacket(result, rubric, rubricDigest)\n * ```\n */\nexport function buildStudyPacket(\n\tresult: StudySealedResult,\n\trubric: StudyRubric,\n\tdigest: string,\n): StudyPacketBundle | undefined {\n\tconst links = buildStudyPacketLinks(result, rubric)\n\tif (links.length === 0) return undefined\n\tconst opening = encodeStudyJSON({ disclosure: STUDY_PACKET_DISCLOSURE, entries: [] }).byteLength\n\t// Each link is looked up, refused or counted before the next one is read; each record carries the\n\t// encoded bytes of every entry up to and including its own.\n\tconst records: Array<{ readonly entry: StudyPacketEntry; readonly length: number }> = []\n\tfor (const link of links) {\n\t\tconst trial = result.manifest.schedule.find((entry) => entry.id === link.source.trial)\n\t\tconst criterion = rubric.criteria.find((entry) => entry.id === link.source.criterion)\n\t\tconst scenario = result.manifest.scenarios.find((entry) => entry.id === trial?.scenario)\n\t\tconst goal = scenario?.goals.find((entry) => entry.id === criterion?.goal)\n\t\tconst observation = result.attempts\n\t\t\t.find((entry) => entry.trial.id === link.source.trial)\n\t\t\t?.observations.find((entry) => entry.goal === criterion?.goal)\n\t\tif (criterion === undefined || goal === undefined || observation === undefined)\n\t\t\tthrow new StudyError('EVIDENCE', 'Semantic packet refers to an absent sealed horizon')\n\t\tconst entry = {\n\t\t\ttrial: link.trial,\n\t\t\tcriterion: link.criterion,\n\t\t\tinput: goal.input,\n\t\t\tproduct: observation.product,\n\t\t\tassertion: criterion.assertion,\n\t\t}\n\t\tconst length = (records.at(-1)?.length ?? opening) + encodeStudyJSON(entry).byteLength\n\t\tif (length > STUDY_CUSTODY_BYTES)\n\t\t\tthrow new StudyError('CAPACITY', 'Semantic packet content exceeds its custody allowance')\n\t\trecords.push({ entry, length })\n\t}\n\tconst entries = records.map(({ entry }) => entry)\n\treturn Object.freeze({\n\t\tcontent: encodeStudyJSON({ disclosure: STUDY_PACKET_DISCLOSURE, entries }),\n\t\tmapping: encodeStudyJSON({\n\t\t\tresult: result.seal.id,\n\t\t\trubric: digest,\n\t\t\tentries: links,\n\t\t}),\n\t})\n}\n\n/**\n * Computes a bundle identity binding exact public packet and private map bytes.\n * @param packet - The immutable grading packet bundle\n * @returns The exact bundle digest\n * @example\n * ```ts\n * computeStudyPacketDigest(packet)\n * ```\n */\nexport function computeStudyPacketDigest(packet: StudyPacketBundle): string {\n\treturn hashStudyBytes(\n\t\tencodeStudyJSON({\n\t\t\tcontent: hashStudyBytes(packet.content),\n\t\t\tmapping: hashStudyBytes(packet.mapping),\n\t\t}),\n\t)\n}\n\n/**\n * Translates bound neutral imported labels through the sealed semantic horizon.\n * @param result - The verified sealed execution\n * @param rubric - The retained rubric\n * @param digest - The exact retained rubric-byte identity\n * @param labels - The original imported neutral labels\n * @returns Judgments translated to scheduled trial and criterion identities\n * @throws StudyError - Thrown when the packet or a label identity is foreign\n * @example\n * ```ts\n * translateStudyPacketLabeling(result, rubric, rubricDigest, labels)\n * ```\n */\nexport function translateStudyPacketLabeling(\n\tresult: StudySealedResult,\n\trubric: StudyRubric,\n\tdigest: string,\n\tlabels: StudyLabeling,\n): readonly StudyJudgment[] {\n\tconst packet = buildStudyPacket(result, rubric, digest)\n\tif (packet === undefined || labels.packet !== hashStudyBytes(packet.content))\n\t\tthrow new StudyError('EVIDENCE', 'Labels bind a different semantic packet')\n\tconst links = buildStudyPacketLinks(result, rubric)\n\treturn Object.freeze(\n\t\tlabels.judgments.map((judgment) => {\n\t\t\tconst link = links.find(\n\t\t\t\t(entry) => entry.trial === judgment.trial && entry.criterion === judgment.criterion,\n\t\t\t)\n\t\t\tif (link === undefined || (judgment.method !== 'human' && judgment.method !== 'model'))\n\t\t\t\tthrow new StudyError('EVIDENCE', 'Label refers to a foreign semantic packet identity')\n\t\t\treturn { ...judgment, trial: link.source.trial, criterion: link.source.criterion }\n\t\t}),\n\t)\n}\n\n/**\n * Refuses symbolic links and non-directory ancestors before custody operations.\n * @param directory - The absolute or relative directory\n * @returns The resolved checked directory\n * @throws StudyError - Thrown when any ancestor is linked or is not a directory\n * @example\n * ```ts\n * await checkStudyDirectory(directory)\n * ```\n */\nexport async function checkStudyDirectory(directory: string): Promise<string> {\n\tconst absolute = resolve(directory)\n\tconst root = parse(absolute).root\n\tconst names = relative(root, absolute).split(sep).filter(Boolean)\n\tfor (const [index] of names.entries()) {\n\t\tconst stat = await lstat(join(root, ...names.slice(0, index + 1)))\n\t\tif (!stat.isDirectory() || stat.isSymbolicLink())\n\t\t\tthrow new StudyError('CUSTODY', 'Linked or invalid custody directory')\n\t}\n\treturn absolute\n}\n\n/**\n * Reads from an open file handle into a buffer until the buffer is full or the file ends.\n * @param handle - The open file handle to read\n * @param target - The buffer to fill from the start of the file\n * @param offset - The position in the file and the buffer to continue from; Default: 0\n * @returns The bytes read, as the whole buffer when the file filled it or as its leading part when the file ended first\n */\nexport async function readStudyHandle(\n\thandle: FileHandle,\n\ttarget: Buffer,\n\toffset = 0,\n): Promise<Buffer> {\n\tif (offset >= target.length) return target\n\tconst reading = await handle.read(target, offset, target.length - offset, offset)\n\treturn reading.bytesRead === 0\n\t\t? target.subarray(0, offset)\n\t\t: readStudyHandle(handle, target, offset + reading.bytesRead)\n}\n\n/**\n * Reads bounded regular-file bytes without following a symbolic link.\n * @param path - The custody file path\n * @param limit - The byte allowance\n * @returns Exact retained bytes\n * @throws StudyError - Thrown when the file is linked, oversized, changed, or not regular\n * @example\n * ```ts\n * await readStudyBytes(path, 1024)\n * ```\n */\nexport async function readStudyBytes(path: string, limit: number): Promise<Uint8Array> {\n\tif (!Number.isSafeInteger(limit) || limit < 0)\n\t\tthrow new StudyError('CONFIG', 'Invalid custody byte allowance')\n\tawait checkStudyDirectory(dirname(path))\n\tconst prior = await lstat(path)\n\tif (prior.isSymbolicLink() || !prior.isFile() || prior.size > limit)\n\t\tthrow new StudyError('CUSTODY', 'Invalid or oversized custody file')\n\tconst handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))\n\ttry {\n\t\tconst stat = await handle.stat()\n\t\tif (!stat.isFile() || stat.size > limit || stat.dev !== prior.dev || stat.ino !== prior.ino)\n\t\t\tthrow new StudyError('CUSTODY', 'Custody file changed during admission')\n\t\tconst bytes = await readStudyHandle(handle, Buffer.alloc(stat.size + 1))\n\t\tif (bytes.length !== stat.size)\n\t\t\tthrow new StudyError('CUSTODY', 'Custody file changed while reading')\n\t\treturn bytes\n\t} finally {\n\t\tawait handle.close()\n\t}\n}\n\n/**\n * Writes an exclusive regular record and synchronizes it before reporting success.\n * @param path - The new custody path\n * @param bytes - The exact encoded record\n * @returns Nothing after the record is synchronized\n * @example\n * ```ts\n * await writeStudyBytes(path, bytes)\n * ```\n */\nexport async function writeStudyBytes(path: string, bytes: Uint8Array): Promise<void> {\n\tawait checkStudyDirectory(dirname(path))\n\tconst handle = await open(path, 'wx')\n\ttry {\n\t\tawait handle.writeFile(bytes)\n\t\tawait handle.sync()\n\t} finally {\n\t\tawait handle.close()\n\t}\n}\n\n/**\n * Scans regular execution files while refusing unknown directories and linked paths.\n * @param directory - The execution directory\n * @param manifest - The authoritative population\n * @returns Sorted exact inventory entries\n * @throws StudyError - Thrown when inventory escapes its declared tree\n * @example\n * ```ts\n * await scanStudyExecution(directory, manifest)\n * ```\n */\nexport async function scanStudyExecution(\n\tdirectory: string,\n\tmanifest: StudyManifest,\n): Promise<readonly StudyFile[]> {\n\tawait checkStudyDirectory(directory)\n\tconst known = new Set(manifest.schedule.map((trial) => trial.id))\n\tconst files = await scanStudyTree(directory, '', known, manifest.bounds.series.bytes)\n\treturn Object.freeze(\n\t\t[...files].sort((left, right) =>\n\t\t\tleft.path < right.path ? -1 : left.path > right.path ? 1 : 0,\n\t\t),\n\t)\n}\n\n/**\n * Scans one execution directory and the subdirectories it admits, reading each admitted file under the series bytes that remain.\n * @param directory - The execution directory\n * @param prefix - The slash-separated path of the scanned directory; the empty string names the execution root\n * @param known - The scheduled trial identities\n * @param allowance - The series bytes that remain before this directory\n * @returns The admitted files in read order: this directory's files, then each admitted subdirectory's, last listed first\n * @throws StudyError - Thrown when the tree holds a link, an unknown directory or file, or a file beyond the remaining allowance\n */\nexport async function scanStudyTree(\n\tdirectory: string,\n\tprefix: string,\n\tknown: ReadonlySet<string>,\n\tallowance: number,\n): Promise<readonly StudyFile[]> {\n\tconst files: StudyFile[] = []\n\tconst directories: string[] = []\n\tfor (const entry of await readdir(join(directory, ...prefix.split('/').filter(Boolean)), {\n\t\twithFileTypes: true,\n\t})) {\n\t\tconst path = prefix === '' ? entry.name : `${prefix}/${entry.name}`\n\t\tif (entry.isSymbolicLink())\n\t\t\tthrow new StudyError('CUSTODY', 'Execution contains a symbolic link')\n\t\tif (entry.isDirectory()) {\n\t\t\tif (path !== 'trials' && !(prefix === 'trials' && known.has(entry.name)))\n\t\t\t\tthrow new StudyError('CUSTODY', 'Execution contains an unknown directory')\n\t\t\tdirectories.push(path)\n\t\t\tcontinue\n\t\t}\n\t\tconst names = path.split('/')\n\t\tif (\n\t\t\t!entry.isFile() ||\n\t\t\t!(\n\t\t\t\tpath === 'manifest.json' ||\n\t\t\t\t(names.length === 3 &&\n\t\t\t\t\tnames[0] === 'trials' &&\n\t\t\t\t\tknown.has(names[1] ?? '') &&\n\t\t\t\t\t(names[2] === 'attempt.json' || names[2] === 'evidence.jsonl'))\n\t\t\t)\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Execution contains an unknown file')\n\t\t// A directory admits at most two file names, so the sum over its earlier files is constant work.\n\t\tconst bytes = await readStudyBytes(\n\t\t\tjoin(directory, ...names),\n\t\t\tfiles.reduce((left, file) => left - file.bytes, allowance),\n\t\t)\n\t\tfiles.push(Object.freeze({ path, bytes: bytes.byteLength, digest: hashStudyBytes(bytes) }))\n\t}\n\tconst remaining = files.reduce((left, file) => left - file.bytes, allowance)\n\t// Each step carries the allowance its subtree left, computed once from the step before it.\n\tconst steps: Array<{ readonly found: readonly StudyFile[]; readonly left: number }> = []\n\tfor (const child of [...directories].reverse()) {\n\t\tconst before = steps.at(-1)?.left ?? remaining\n\t\tconst found = await scanStudyTree(directory, child, known, before)\n\t\tsteps.push({ found, left: found.reduce((left, file) => left - file.bytes, before) })\n\t}\n\treturn [...files, ...steps.flatMap((step) => step.found)]\n}\n\n/**\n * Validates complete evidence lines and per-goal encoded evidence bounds.\n * @param bytes - The exact JSONL file\n * @param manifest - The bounds and scenario declarations\n * @param trial - The scheduled trial identity\n * @returns Nothing when evidence satisfies its custody contract\n * @throws StudyError - Thrown when evidence is partial, invalid, foreign, or oversized\n * @example\n * ```ts\n * validateStudyEvidenceBytes(bytes, manifest, trial)\n * ```\n */\nexport function validateStudyEvidenceBytes(\n\tbytes: Uint8Array,\n\tmanifest: StudyManifest,\n\ttrial: string,\n): void {\n\tconst scheduled = manifest.schedule.find((entry) => entry.id === trial)\n\tconst scenario = manifest.scenarios.find((entry) => entry.id === scheduled?.scenario)\n\tif (scenario === undefined || bytes.byteLength > manifest.bounds.trial.bytes)\n\t\tthrow new StudyError('CUSTODY', 'Evidence exceeds the declared trial')\n\tconst text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\tif (text !== '' && !text.endsWith('\\n'))\n\t\tthrow new StudyError('CUSTODY', 'Evidence ends with a partial record')\n\t// A line's goal is undefined where it is not valid evidence for a declared goal.\n\tconst records = text\n\t\t.split(/\\r\\n|\\n/)\n\t\t.slice(0, -1)\n\t\t.map((line) => {\n\t\t\tconst evidence = parseJSON(line)\n\t\t\treturn {\n\t\t\t\tgoal:\n\t\t\t\t\tisStudyCustodyEvidence(evidence) &&\n\t\t\t\t\tscenario.goals.some((goal) => goal.id === evidence.goal)\n\t\t\t\t\t\t? evidence.goal\n\t\t\t\t\t\t: undefined,\n\t\t\t\tsize: Buffer.byteLength(`${line}\\n`, 'utf8'),\n\t\t\t}\n\t\t})\n\t// Only the lines before the first invalid one count: an overflow among them is the earlier refusal.\n\tconst invalid = records.findIndex(({ goal }) => goal === undefined)\n\tconst admitted = invalid === -1 ? records : records.slice(0, invalid)\n\tif (\n\t\t[...Map.groupBy(admitted, ({ goal }) => goal).values()].some(\n\t\t\t(group) => group.reduce((total, { size }) => total + size, 0) > manifest.bounds.goal.bytes,\n\t\t)\n\t)\n\t\tthrow new StudyError('CUSTODY', 'Evidence exceeds a goal allowance')\n\tif (invalid !== -1) throw new StudyError('CUSTODY', 'Evidence refers to an invalid goal')\n}\n\n/**\n * Computes an execution seal identity from its exact sorted inventory.\n * @param result - The manifest result identity\n * @param files - The sorted inventory\n * @returns The deterministic seal digest\n * @example\n * ```ts\n * computeStudySealId('execution', files)\n * ```\n */\nexport function computeStudySealId(result: string, files: readonly StudyFile[]): string {\n\treturn hashStudyBytes(encodeStudyJSON({ result, files }))\n}\n\n/**\n * Inspects custody bytes offline and verifies complete execution before grading.\n * @param directory - The result directory\n * @returns A sealed result or explicitly interrupted safe metadata\n * @throws StudyError - Thrown when existing custody bytes are invalid or tampered\n * @example\n * ```ts\n * await readStudyResult(directory)\n * ```\n */\nexport async function readStudyResult(directory: string): Promise<StudyResultReading> {\n\tconst absolute = await checkStudyDirectory(directory)\n\tconst root = await readdir(absolute, { withFileTypes: true })\n\tfor (const entry of root) {\n\t\tif (entry.isSymbolicLink()) throw new StudyError('CUSTODY', 'Result contains a symbolic link')\n\t\tif (\n\t\t\tentry.name === 'execution' || entry.name === 'grades' || entry.name === 'reports'\n\t\t\t\t? !entry.isDirectory()\n\t\t\t\t: entry.name !== 'seal.json' || !entry.isFile()\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Result contains an unknown path')\n\t}\n\tconst sealed = root.some((entry) => entry.name === 'seal.json')\n\tif (!root.some((entry) => entry.name === 'execution')) {\n\t\tif (sealed) throw new StudyError('CUSTODY', 'Sealed result is missing execution')\n\t\treturn Object.freeze({\n\t\t\tstatus: 'interrupted',\n\t\t\tdirectory: absolute,\n\t\t\tmanifest: undefined,\n\t\t\tattempts: Object.freeze([]),\n\t\t})\n\t}\n\tconst execution = join(absolute, 'execution')\n\tconst entries = await readdir(execution, { withFileTypes: true })\n\tif (!entries.some((entry) => entry.name === 'manifest.json')) {\n\t\tif (entries.length !== 0 || sealed)\n\t\t\tthrow new StudyError('CUSTODY', 'Execution is missing its manifest')\n\t\treturn Object.freeze({\n\t\t\tstatus: 'interrupted',\n\t\t\tdirectory: absolute,\n\t\t\tmanifest: undefined,\n\t\t\tattempts: Object.freeze([]),\n\t\t})\n\t}\n\tconst manifestBytes = await readStudyBytes(join(execution, 'manifest.json'), STUDY_CUSTODY_BYTES)\n\tconst decoded = attempt((): unknown => decodeStudyJSON(manifestBytes))\n\tif (!decoded.success && sealed) throw decoded.error\n\tconst manifest: unknown = decoded.success ? decoded.value : undefined\n\tif (!isStudyCustodyManifest(manifest)) {\n\t\tif (sealed) throw new StudyError('CUSTODY', 'Invalid execution manifest')\n\t\treturn Object.freeze({\n\t\t\tstatus: 'interrupted',\n\t\t\tdirectory: absolute,\n\t\t\tmanifest: undefined,\n\t\t\tattempts: Object.freeze([]),\n\t\t})\n\t}\n\tconst files = await scanStudyExecution(execution, manifest)\n\tif (\n\t\tfiles.find((entry) => entry.path === 'manifest.json')?.digest !== hashStudyBytes(manifestBytes)\n\t)\n\t\tthrow new StudyError('CUSTODY', 'Manifest changed during inventory reading')\n\tconst attempts: StudyAttempt[] = []\n\tfor (const trial of manifest.schedule) {\n\t\tconst evidence = files.find((entry) => entry.path === `trials/${trial.id}/evidence.jsonl`)\n\t\tif (evidence !== undefined && sealed) {\n\t\t\tconst bytes = await readStudyBytes(\n\t\t\t\tjoin(execution, 'trials', trial.id, 'evidence.jsonl'),\n\t\t\t\tmanifest.bounds.trial.bytes,\n\t\t\t)\n\t\t\tif (hashStudyBytes(bytes) !== evidence.digest)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Evidence changed during inventory reading')\n\t\t\tvalidateStudyEvidenceBytes(bytes, manifest, trial.id)\n\t\t}\n\t\tconst terminal = files.find((entry) => entry.path === `trials/${trial.id}/attempt.json`)\n\t\tif (terminal === undefined) continue\n\t\tif (evidence === undefined)\n\t\t\tthrow new StudyError('CUSTODY', 'Terminal attempt is missing its evidence file')\n\t\tconst bytes = await readStudyBytes(\n\t\t\tjoin(execution, 'trials', trial.id, 'attempt.json'),\n\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t)\n\t\tif (hashStudyBytes(bytes) !== terminal.digest)\n\t\t\tthrow new StudyError('CUSTODY', 'Attempt changed during inventory reading')\n\t\tconst reading = attempt((): unknown => decodeStudyJSON(bytes))\n\t\tif (!reading.success && sealed) throw reading.error\n\t\tconst record: unknown = reading.success ? reading.value : undefined\n\t\tif (!isStudyCustodyAttempt(record, manifest) || record.trial.id !== trial.id) {\n\t\t\tif (sealed) throw new StudyError('CUSTODY', 'Invalid or foreign terminal attempt')\n\t\t\tcontinue\n\t\t}\n\t\tattempts.push(record)\n\t}\n\tif (!sealed)\n\t\treturn Object.freeze({\n\t\t\tstatus: 'interrupted',\n\t\t\tdirectory: absolute,\n\t\t\tmanifest,\n\t\t\tattempts: Object.freeze(attempts),\n\t\t})\n\tconst sealBytes = await readStudyBytes(join(absolute, 'seal.json'), STUDY_CUSTODY_BYTES)\n\tif (\n\t\tfiles.reduce((total, file) => total + file.bytes, sealBytes.byteLength) >\n\t\tmanifest.bounds.series.bytes\n\t)\n\t\tthrow new StudyError('CUSTODY', 'Seal and execution exceed the series allowance')\n\tconst seal = decodeStudyJSON(sealBytes)\n\tif (\n\t\t!isStudyCustodySeal(seal) ||\n\t\tseal.result !== manifest.id ||\n\t\tseal.id !== computeStudySealId(manifest.id, files) ||\n\t\tcanonicalStringify(seal.files) !== canonicalStringify(files) ||\n\t\tattempts.length !== manifest.schedule.length ||\n\t\tfiles.length !== 1 + manifest.schedule.length * 2\n\t)\n\t\tthrow new StudyError('CUSTODY', 'Execution seal does not match the complete byte inventory')\n\treturn Object.freeze({\n\t\tstatus: 'sealed',\n\t\tdirectory: absolute,\n\t\tmanifest,\n\t\tattempts: Object.freeze(attempts),\n\t\tseal,\n\t})\n}\n","import type { StudyEvidence } from '../../core/types.js'\nimport type { StudyCustodySinkInterface, StudyEvidenceSinkOptions } from './types.js'\nimport { StudyError } from '../../core/errors.js'\nimport { encodeStudyJSON } from '../helpers.js'\nimport { isStudyCustodyEvidence } from './validators.js'\n\n/** Retains admitted evidence in order and closes admission before terminal records. */\nexport class StudyEvidenceSink implements StudyCustodySinkInterface {\n\treadonly #options: StudyEvidenceSinkOptions\n\treadonly #goals = new Map<string, number>()\n\t// The admitted writes not yet settled; a write joins when admitted and leaves when it settles, and each waits for every earlier one.\n\treadonly #writes = new Set<Promise<void>>()\n\t#bytes = 0\n\t// Wraps the first failed write so every later append and the close refuse with that failure.\n\t#fault: { readonly error: unknown } | undefined\n\t#closing: Promise<void> | undefined\n\n\t/**\n\t * Owns the descriptor selection and constraints while retaining the live file and budget.\n\t * @param options - The owned descriptor, goal names, and byte admission bounds\n\t */\n\tconstructor(options: StudyEvidenceSinkOptions) {\n\t\tthis.#options = { ...options, goals: [...options.goals] }\n\t}\n\n\t/**\n\t * Admits exact encoded bytes before queuing an append in call order.\n\t * @param evidence - The validated domain record\n\t * @returns Nothing after the admitted append completes\n\t * @throws StudyError - Thrown when admission is closed or a byte limit is exceeded\n\t */\n\tappend(evidence: StudyEvidence): Promise<void> {\n\t\ttry {\n\t\t\tif (this.#closing !== undefined)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Evidence admission is closed')\n\t\t\tif (!isStudyCustodyEvidence(evidence) || !this.#options.goals.includes(evidence.goal))\n\t\t\t\tthrow new StudyError('EVIDENCE', 'Evidence refers to an undeclared goal')\n\t\t\tconst bytes = encodeStudyJSON(evidence)\n\t\t\tconst used = (this.#goals.get(evidence.goal) ?? 0) + bytes.byteLength\n\t\t\tconst trial = this.#bytes + bytes.byteLength\n\t\t\tif (used > this.#options.goal || trial > this.#options.trial) {\n\t\t\t\tconst message = 'Encoded evidence exceeds its allowance'\n\t\t\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\t\t\tcause: 'capacity',\n\t\t\t\t\tmessage,\n\t\t\t\t\trole: undefined,\n\t\t\t\t\tstop:\n\t\t\t\t\t\tused > this.#options.goal\n\t\t\t\t\t\t\t? { layer: 'custody', id: 'Goal evidence', max: this.#options.goal, consumed: used }\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tlayer: 'custody',\n\t\t\t\t\t\t\t\t\tid: 'Trial evidence',\n\t\t\t\t\t\t\t\t\tmax: this.#options.trial,\n\t\t\t\t\t\t\t\t\tconsumed: trial,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\tthis.#options.budget.reserve(bytes.byteLength)\n\t\t\tthis.#goals.set(evidence.goal, used)\n\t\t\tthis.#bytes += bytes.byteLength\n\t\t\tconst previous = Promise.allSettled([...this.#writes])\n\t\t\tconst write = previous.then(() => this.#write(bytes))\n\t\t\tthis.#writes.add(write)\n\t\t\tvoid write.then(\n\t\t\t\t() => this.#writes.delete(write),\n\t\t\t\t() => this.#writes.delete(write),\n\t\t\t)\n\t\t\treturn write\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error)\n\t\t}\n\t}\n\n\t/**\n\t * Closes admission immediately and synchronizes all previously admitted writes.\n\t * @returns Nothing when the evidence descriptor has closed\n\t */\n\tclose(): Promise<void> {\n\t\tthis.#closing ??= Promise.allSettled([...this.#writes])\n\t\t\t.then(async () => {\n\t\t\t\tif (this.#fault !== undefined) throw this.#fault.error\n\t\t\t\tawait this.#options.file.sync()\n\t\t\t})\n\t\t\t.finally(async () => {\n\t\t\t\tawait this.#options.file.close()\n\t\t\t})\n\t\treturn this.#closing\n\t}\n\n\t// Writes after every earlier write settled, and refuses once any earlier write failed.\n\tasync #write(bytes: Uint8Array): Promise<void> {\n\t\tif (this.#fault !== undefined) throw this.#fault.error\n\t\ttry {\n\t\t\tawait this.#options.file.writeFile(bytes)\n\t\t} catch (error) {\n\t\t\tthis.#fault ??= { error }\n\t\t\tthrow error\n\t\t}\n\t}\n}\n","import type {\n\tStudyAttempt,\n\tStudyManifest,\n\tStudySinkInterface,\n\tStudyTrial,\n} from '../../core/types.js'\nimport type {\n\tStudyCustodyPhase,\n\tStudyResultStoreOptions,\n\tStudyResultStoreInterface,\n\tStudySeal,\n\tStudyTrialCustody,\n} from './types.js'\nimport { canonicalStringify } from '@orkestrel/contract'\nimport { mkdir, open } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\nimport { StudyError } from '../../core/errors.js'\nimport { decodeStudyJSON, encodeStudyJSON } from '../helpers.js'\nimport { STUDY_CUSTODY_BYTES } from './constants.js'\nimport {\n\tcheckStudyDirectory,\n\tcomputeStudySealId,\n\treadStudyBytes,\n\treadStudyResult,\n\tscanStudyExecution,\n\tvalidateStudyEvidenceBytes,\n\twriteStudyBytes,\n} from './helpers.js'\nimport { StudyEvidenceSink } from './StudyEvidenceSink.js'\nimport { isStudyCustodyAttempt, isStudyCustodyManifest, isStudyCustodyTrial } from './validators.js'\n\n/** Owns append-only execution bytes and seals only a complete terminal population. */\nexport class StudyResultStore implements StudyResultStoreInterface {\n\treadonly #directory: string\n\treadonly #manifest: StudyManifest\n\treadonly #trials = new Map<string, StudyTrialCustody>()\n\treadonly #starting = new Set<string>()\n\t#phase: StudyCustodyPhase = 'new'\n\t#bytes = 0\n\n\t/**\n\t * Owns a validated manifest snapshot without creating any files.\n\t * @param options - The new result directory and execution declaration\n\t * @throws StudyError - Thrown when the manifest is invalid\n\t */\n\tconstructor(options: StudyResultStoreOptions) {\n\t\tif (!isStudyCustodyManifest(options.manifest))\n\t\t\tthrow new StudyError('CONFIG', 'Invalid execution manifest')\n\t\tconst snapshot = decodeStudyJSON(encodeStudyJSON(options.manifest))\n\t\tif (!isStudyCustodyManifest(snapshot))\n\t\t\tthrow new StudyError('CONFIG', 'Invalid manifest snapshot')\n\t\tthis.#manifest = snapshot\n\t\tthis.#directory = resolve(options.directory)\n\t}\n\n\t/**\n\t * Exclusively creates the result directory and initial manifest bytes.\n\t * @returns Nothing after the manifest is synchronized\n\t * @throws StudyError - Thrown when creation repeats or custody bounds are exceeded\n\t */\n\tasync create(): Promise<void> {\n\t\tif (this.#phase !== 'new') throw new StudyError('CUSTODY', 'Result creation has already begun')\n\t\tthis.#phase = 'creating'\n\t\ttry {\n\t\t\tconst bytes = encodeStudyJSON(this.#manifest)\n\t\t\tif (bytes.byteLength > STUDY_CUSTODY_BYTES)\n\t\t\t\tthrow new StudyError('CAPACITY', 'Manifest exceeds the metadata allowance')\n\t\t\tthis.#reserve(bytes.byteLength)\n\t\t\tawait checkStudyDirectory(dirname(this.#directory))\n\t\t\tawait mkdir(this.#directory)\n\t\t\tawait mkdir(join(this.#directory, 'execution'))\n\t\t\tawait mkdir(join(this.#directory, 'execution', 'trials'))\n\t\t\tawait writeStudyBytes(join(this.#directory, 'execution', 'manifest.json'), bytes)\n\t\t\tthis.#phase = 'ready'\n\t\t} catch (error) {\n\t\t\tthis.#phase = 'failed'\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/**\n\t * Exclusively creates the evidence sink for an exact scheduled trial.\n\t * @param trial - The scheduled trajectory\n\t * @returns The bounded append-only sink\n\t * @throws StudyError - Thrown when the trial is foreign, repeated, or late\n\t */\n\tasync start(trial: StudyTrial): Promise<StudySinkInterface> {\n\t\tif (\n\t\t\tthis.#phase !== 'ready' ||\n\t\t\t!isStudyCustodyTrial(trial) ||\n\t\t\tthis.#trials.has(trial.id) ||\n\t\t\tthis.#starting.has(trial.id)\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Trial cannot start in the current state')\n\t\tconst scheduled = this.#manifest.schedule.find((entry) => entry.id === trial.id)\n\t\tconst scenario = this.#manifest.scenarios.find((entry) => entry.id === trial.scenario)\n\t\tif (\n\t\t\tscheduled === undefined ||\n\t\t\tscenario === undefined ||\n\t\t\tcanonicalStringify(scheduled) !== canonicalStringify(trial)\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Trial differs from the execution schedule')\n\t\tthis.#starting.add(scheduled.id)\n\t\ttry {\n\t\t\tconst directory = join(this.#directory, 'execution', 'trials', scheduled.id)\n\t\t\tawait checkStudyDirectory(dirname(directory))\n\t\t\tawait mkdir(directory)\n\t\t\tconst file = await open(join(directory, 'evidence.jsonl'), 'wx')\n\t\t\tconst sink = new StudyEvidenceSink({\n\t\t\t\tfile,\n\t\t\t\tgoals: scenario.goals.map((goal) => goal.id),\n\t\t\t\tgoal: this.#manifest.bounds.goal.bytes,\n\t\t\t\ttrial: this.#manifest.bounds.trial.bytes,\n\t\t\t\tbudget: { reserve: (bytes) => this.#reserve(bytes) },\n\t\t\t})\n\t\t\tthis.#trials.set(scheduled.id, { sink, terminal: undefined })\n\t\t\treturn sink\n\t\t} catch (error) {\n\t\t\tthis.#phase = 'failed'\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tthis.#starting.delete(scheduled.id)\n\t\t}\n\t}\n\n\t/**\n\t * Closes evidence admission, drains admitted appends, and writes a terminal record.\n\t * @param attempt - The complete scheduled goal horizon\n\t * @returns Nothing after the terminal record is synchronized\n\t * @throws StudyError - Thrown when the terminal record is invalid, repeated, or late\n\t */\n\tfinish(attempt: StudyAttempt): Promise<void> {\n\t\ttry {\n\t\t\tif (this.#phase !== 'ready' || !isStudyCustodyAttempt(attempt, this.#manifest))\n\t\t\t\tthrow new StudyError('CUSTODY', 'Attempt differs from the declared horizon')\n\t\t\tconst custody = this.#trials.get(attempt.trial.id)\n\t\t\tif (custody === undefined || custody.terminal !== undefined)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Trial is unknown or already terminal')\n\t\t\tconst bytes = encodeStudyJSON(attempt)\n\t\t\tif (bytes.byteLength > STUDY_CUSTODY_BYTES)\n\t\t\t\tthrow new StudyError('CAPACITY', 'Attempt exceeds the metadata allowance')\n\t\t\tconst drained = custody.sink.close()\n\t\t\tconst terminal = this.#finish(attempt.trial.id, bytes, drained)\n\t\t\tthis.#trials.set(attempt.trial.id, { ...custody, terminal })\n\t\t\treturn terminal\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error)\n\t\t}\n\t}\n\n\t/**\n\t * Seals exact execution inventory after every scheduled trial has terminated.\n\t * @returns The immutable deterministic execution seal\n\t * @throws StudyError - Thrown when custody is incomplete, invalid, or already sealed\n\t */\n\tasync seal(): Promise<StudySeal> {\n\t\tif (\n\t\t\tthis.#phase !== 'ready' ||\n\t\t\tthis.#starting.size !== 0 ||\n\t\t\tthis.#trials.size !== this.#manifest.schedule.length ||\n\t\t\t[...this.#trials.values()].some((trial) => trial.terminal === undefined)\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Execution is not terminally accounted')\n\t\tthis.#phase = 'sealing'\n\t\ttry {\n\t\t\tawait Promise.all([...this.#trials.values()].map((trial) => trial.terminal))\n\t\t\tconst reading = await readStudyResult(this.#directory)\n\t\t\tif (\n\t\t\t\treading.status !== 'interrupted' ||\n\t\t\t\treading.manifest === undefined ||\n\t\t\t\treading.attempts.length !== this.#manifest.schedule.length ||\n\t\t\t\tcanonicalStringify(reading.manifest) !== canonicalStringify(this.#manifest)\n\t\t\t)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Execution changed before sealing')\n\t\t\tconst files = await scanStudyExecution(join(this.#directory, 'execution'), this.#manifest)\n\t\t\tif (files.length !== 1 + this.#manifest.schedule.length * 2)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Execution inventory is incomplete')\n\t\t\tfor (const trial of this.#manifest.schedule) {\n\t\t\t\tvalidateStudyEvidenceBytes(\n\t\t\t\t\tawait readStudyBytes(\n\t\t\t\t\t\tjoin(this.#directory, 'execution', 'trials', trial.id, 'evidence.jsonl'),\n\t\t\t\t\t\tthis.#manifest.bounds.trial.bytes,\n\t\t\t\t\t),\n\t\t\t\t\tthis.#manifest,\n\t\t\t\t\ttrial.id,\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst seal: StudySeal = Object.freeze({\n\t\t\t\tresult: this.#manifest.id,\n\t\t\t\tid: computeStudySealId(this.#manifest.id, files),\n\t\t\t\tfiles,\n\t\t\t})\n\t\t\tconst bytes = encodeStudyJSON(seal)\n\t\t\tif (bytes.byteLength > STUDY_CUSTODY_BYTES)\n\t\t\t\tthrow new StudyError('CAPACITY', 'Seal exceeds the metadata allowance')\n\t\t\tif (\n\t\t\t\tfiles.reduce((total, file) => total + file.bytes, bytes.byteLength) >\n\t\t\t\tthis.#manifest.bounds.series.bytes\n\t\t\t)\n\t\t\t\tthrow new StudyError('CAPACITY', 'Seal and execution exceed the series allowance')\n\t\t\tthis.#reserve(bytes.byteLength)\n\t\t\tawait writeStudyBytes(join(this.#directory, 'seal.json'), bytes)\n\t\t\tconst verified = await readStudyResult(this.#directory)\n\t\t\tif (verified.status !== 'sealed' || verified.seal.id !== seal.id)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Execution changed while sealing')\n\t\t\tthis.#phase = 'sealed'\n\t\t\treturn seal\n\t\t} catch (error) {\n\t\t\tthis.#phase = 'failed'\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t#reserve(bytes: number): void {\n\t\tif (this.#bytes + bytes > this.#manifest.bounds.series.bytes)\n\t\t\tthrow new StudyError('CAPACITY', 'Execution bytes exceed the series allowance')\n\t\tthis.#bytes += bytes\n\t}\n\n\tasync #finish(trial: string, bytes: Uint8Array, drained: Promise<void>): Promise<void> {\n\t\ttry {\n\t\t\tawait drained\n\t\t\tthis.#reserve(bytes.byteLength)\n\t\t\tawait writeStudyBytes(\n\t\t\t\tjoin(this.#directory, 'execution', 'trials', trial, 'attempt.json'),\n\t\t\t\tbytes,\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tthis.#phase = 'failed'\n\t\t\tthrow error\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 { StudyGrading, StudyLabeling, StudyRubric } from '../../core/types.js'\nimport type { StudyGradingStoreOptions, StudyPacketBundle, StudySealedResult } from './types.js'\nimport { canonicalStringify } from '@orkestrel/contract'\nimport { lstat, mkdir, readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { StudyError } from '../../core/errors.js'\nimport { computeStudyScores } from '../../core/helpers.js'\nimport { parseStudyGrading, parseStudyLabeling, parseStudyRubric } from '../../core/parsers.js'\nimport { isStudyDigest } from '../../core/validators.js'\nimport { decodeStudyJSON, encodeStudyJSON, hashStudyBytes } from '../helpers.js'\nimport { STUDY_CUSTODY_BYTES } from './constants.js'\nimport {\n\tcheckStudyDirectory,\n\tbuildStudyPacket,\n\tcomputeStudyPacketDigest,\n\treadStudyBytes,\n\treadStudyResult,\n\ttranslateStudyPacketLabeling,\n\twriteStudyBytes,\n} from './helpers.js'\n\n/** Retains immutable deterministic grading versions independently of execution bytes. */\nexport class StudyGradingStore {\n\treadonly #directory: string\n\treadonly #seal: string\n\treadonly #rubric: StudyRubric\n\treadonly #rubricBytes: Uint8Array\n\treadonly #rubricDigest: string\n\treadonly #labels: StudyLabeling | undefined\n\treadonly #labelsBytes: Uint8Array | undefined\n\treadonly #labelsDigest: string | undefined\n\treadonly #packet: StudyPacketBundle | undefined\n\t// The writes not yet settled; a write joins when called and leaves when it settles, and each waits for every earlier one.\n\treadonly #writes = new Set<Promise<string>>()\n\n\t/**\n\t * Owns exact imported grading bytes without writing any custody files.\n\t * @param options - The verified execution and exact rubric and optional labels bytes\n\t * @throws StudyError - Thrown when imported bytes exceed bounds or fail validation\n\t */\n\tconstructor(options: StudyGradingStoreOptions) {\n\t\tif (options.result.status !== 'sealed')\n\t\t\tthrow new StudyError('CUSTODY', 'Grading requires a sealed execution')\n\t\tif (\n\t\t\toptions.rubric.byteLength > STUDY_CUSTODY_BYTES ||\n\t\t\t(options.labels !== undefined && options.labels.byteLength > STUDY_CUSTODY_BYTES)\n\t\t)\n\t\t\tthrow new StudyError('CAPACITY', 'Imported grading bytes exceed the metadata allowance')\n\t\tthis.#directory = options.result.directory\n\t\tthis.#seal = options.result.seal.id\n\t\tthis.#rubricBytes = new Uint8Array(options.rubric)\n\t\tthis.#rubricDigest = hashStudyBytes(this.#rubricBytes)\n\t\tthis.#rubric = parseStudyRubric(decodeStudyJSON(this.#rubricBytes))\n\t\tthis.#labelsBytes = options.labels === undefined ? undefined : new Uint8Array(options.labels)\n\t\tthis.#labelsDigest =\n\t\t\tthis.#labelsBytes === undefined ? undefined : hashStudyBytes(this.#labelsBytes)\n\t\tthis.#labels =\n\t\t\tthis.#labelsBytes === undefined\n\t\t\t\t? undefined\n\t\t\t\t: parseStudyLabeling(decodeStudyJSON(this.#labelsBytes))\n\t\tif (\n\t\t\toptions.packet !== undefined &&\n\t\t\t(options.packet.content.byteLength > STUDY_CUSTODY_BYTES ||\n\t\t\t\toptions.packet.mapping.byteLength > STUDY_CUSTODY_BYTES)\n\t\t)\n\t\t\tthrow new StudyError('CAPACITY', 'Packet exceeds the grading metadata allowance')\n\t\tthis.#packet =\n\t\t\toptions.packet === undefined\n\t\t\t\t? undefined\n\t\t\t\t: {\n\t\t\t\t\t\tcontent: new Uint8Array(options.packet.content),\n\t\t\t\t\t\tmapping: new Uint8Array(options.packet.mapping),\n\t\t\t\t\t}\n\t}\n\n\t/**\n\t * Retains a deterministic grading version or verifies identical existing bytes.\n\t * @param grading - The complete evidence-backed judgments and artifact bindings\n\t * @returns The exact grading-byte SHA-256 identity\n\t * @throws StudyError - Thrown when coverage, bindings, or existing bytes are invalid\n\t */\n\twrite(grading: StudyGrading): Promise<string> {\n\t\ttry {\n\t\t\tconst snapshot = parseStudyGrading(grading)\n\t\t\tconst bytes = encodeStudyJSON(snapshot)\n\t\t\tif (bytes.byteLength > STUDY_CUSTODY_BYTES)\n\t\t\t\tthrow new StudyError('CAPACITY', 'Grading exceeds the metadata allowance')\n\t\t\tconst previous = Promise.allSettled([...this.#writes])\n\t\t\tconst operation = previous.then(() => this.#write(snapshot, bytes))\n\t\t\tthis.#writes.add(operation)\n\t\t\tvoid operation.then(\n\t\t\t\t() => this.#writes.delete(operation),\n\t\t\t\t() => this.#writes.delete(operation),\n\t\t\t)\n\t\t\treturn operation\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error)\n\t\t}\n\t}\n\n\t/**\n\t * Reads an immutable grading version and verifies every bound artifact byte.\n\t * @param id - The grading-byte SHA-256 identity\n\t * @returns The verified grading, or undefined when the version does not exist\n\t * @throws StudyError - Thrown when an existing version is partial or tampered\n\t */\n\tasync read(id: string): Promise<StudyGrading | undefined> {\n\t\tif (!isStudyDigest(id)) throw new StudyError('EVIDENCE', 'Invalid grading identity')\n\t\tconst result = await this.#verifyResult()\n\t\tconst directory = join(result.directory, 'grades', id)\n\t\ttry {\n\t\t\tawait lstat(directory)\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined\n\t\t\tthrow error\n\t\t}\n\t\tawait checkStudyDirectory(directory)\n\t\tconst bytes = await readStudyBytes(join(directory, 'grading.json'), STUDY_CUSTODY_BYTES)\n\t\tif (hashStudyBytes(bytes) !== id)\n\t\t\tthrow new StudyError('CUSTODY', 'Grading identity differs from its exact bytes')\n\t\tconst grading = parseStudyGrading(decodeStudyJSON(bytes))\n\t\tconst expected = [\n\t\t\t'grading.json',\n\t\t\t`${grading.rubric}.rubric.json`,\n\t\t\t...(grading.labels === undefined ? [] : [`${grading.labels}.labels.json`]),\n\t\t\t...(grading.packet === undefined\n\t\t\t\t? []\n\t\t\t\t: [`${grading.packet}.packet.json`, `${grading.packet}.mapping.json`]),\n\t\t]\n\t\tconst entries = await readdir(directory, { withFileTypes: true })\n\t\tif (\n\t\t\tentries.length !== expected.length ||\n\t\t\tentries.some(\n\t\t\t\t(entry) => !entry.isFile() || entry.isSymbolicLink() || !expected.includes(entry.name),\n\t\t\t)\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Grading inventory differs from its bound artifacts')\n\t\tconst rubricBytes = await readStudyBytes(\n\t\t\tjoin(directory, `${grading.rubric}.rubric.json`),\n\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t)\n\t\tif (hashStudyBytes(rubricBytes) !== grading.rubric)\n\t\t\tthrow new StudyError('CUSTODY', 'Rubric bytes differ from the grading identity')\n\t\tconst rubric = parseStudyRubric(decodeStudyJSON(rubricBytes))\n\t\tconst labels =\n\t\t\tgrading.labels === undefined ? undefined : await this.#retrieve(directory, grading.labels)\n\t\tconst packet: StudyPacketBundle | undefined =\n\t\t\tgrading.packet === undefined\n\t\t\t\t? undefined\n\t\t\t\t: {\n\t\t\t\t\t\tcontent: await readStudyBytes(\n\t\t\t\t\t\t\tjoin(directory, `${grading.packet}.packet.json`),\n\t\t\t\t\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tmapping: await readStudyBytes(\n\t\t\t\t\t\t\tjoin(directory, `${grading.packet}.mapping.json`),\n\t\t\t\t\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t\t\t\t\t),\n\t\t\t\t\t}\n\t\tthis.#validate(grading, result, rubric, labels, packet)\n\t\tawait this.#verifyResult()\n\t\treturn grading\n\t}\n\n\tasync #retrieve(directory: string, digest: string): Promise<StudyLabeling> {\n\t\tconst bytes = await readStudyBytes(\n\t\t\tjoin(directory, `${digest}.labels.json`),\n\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t)\n\t\tif (hashStudyBytes(bytes) !== digest)\n\t\t\tthrow new StudyError('CUSTODY', 'Labels bytes differ from the grading identity')\n\t\treturn parseStudyLabeling(decodeStudyJSON(bytes))\n\t}\n\n\tasync #write(grading: StudyGrading, bytes: Uint8Array): Promise<string> {\n\t\tconst result = await this.#verifyResult()\n\t\tif (grading.rubric !== this.#rubricDigest || grading.labels !== this.#labelsDigest)\n\t\t\tthrow new StudyError('EVIDENCE', 'Grading does not bind the imported artifact bytes')\n\t\tthis.#validate(grading, result, this.#rubric, this.#labels, this.#packet)\n\t\tconst id = hashStudyBytes(bytes)\n\t\tconst root = join(result.directory, 'grades')\n\t\ttry {\n\t\t\tawait mkdir(root)\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error && 'code' in error && error.code === 'EEXIST')) throw error\n\t\t}\n\t\tawait checkStudyDirectory(root)\n\t\tconst directory = join(root, id)\n\t\ttry {\n\t\t\tawait mkdir(directory)\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error && 'code' in error && error.code === 'EEXIST')) throw error\n\t\t\tconst existing = await this.read(id)\n\t\t\tif (\n\t\t\t\texisting === undefined ||\n\t\t\t\tcanonicalStringify(existing) !== canonicalStringify(grading) ||\n\t\t\t\thashStudyBytes(\n\t\t\t\t\tawait readStudyBytes(join(directory, 'grading.json'), STUDY_CUSTODY_BYTES),\n\t\t\t\t) !== id\n\t\t\t)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Existing grading version is incompatible')\n\t\t\treturn id\n\t\t}\n\t\tawait writeStudyBytes(join(directory, `${this.#rubricDigest}.rubric.json`), this.#rubricBytes)\n\t\tif (this.#packet !== undefined && grading.packet !== undefined) {\n\t\t\tawait writeStudyBytes(join(directory, `${grading.packet}.packet.json`), this.#packet.content)\n\t\t\tawait writeStudyBytes(join(directory, `${grading.packet}.mapping.json`), this.#packet.mapping)\n\t\t}\n\t\tif (this.#labelsBytes !== undefined && this.#labelsDigest !== undefined)\n\t\t\tawait writeStudyBytes(join(directory, `${this.#labelsDigest}.labels.json`), this.#labelsBytes)\n\t\tawait writeStudyBytes(join(directory, 'grading.json'), bytes)\n\t\tawait this.read(id)\n\t\treturn id\n\t}\n\n\tasync #verifyResult(): Promise<StudySealedResult> {\n\t\tconst result = await readStudyResult(this.#directory)\n\t\tif (result.status !== 'sealed' || result.seal.id !== this.#seal)\n\t\t\tthrow new StudyError('CUSTODY', 'Execution no longer matches the verified seal')\n\t\treturn result\n\t}\n\n\t#validate(\n\t\tgrading: StudyGrading,\n\t\tresult: StudySealedResult,\n\t\trubric: StudyRubric,\n\t\tlabels: StudyLabeling | undefined,\n\t\tpacket: StudyPacketBundle | undefined,\n\t): void {\n\t\tif (grading.result !== result.seal.id)\n\t\t\tthrow new StudyError('EVIDENCE', 'Grading binds a different execution seal')\n\t\tcomputeStudyScores(result.manifest, rubric, grading)\n\t\tif (grading.packet !== (packet === undefined ? undefined : computeStudyPacketDigest(packet)))\n\t\t\tthrow new StudyError('CUSTODY', 'Grading packet bytes do not match their bundle identity')\n\t\tif (packet !== undefined) {\n\t\t\tconst expected = buildStudyPacket(result, rubric, grading.rubric)\n\t\t\tif (\n\t\t\t\texpected === undefined ||\n\t\t\t\thashStudyBytes(expected.content) !== hashStudyBytes(packet.content) ||\n\t\t\t\thashStudyBytes(expected.mapping) !== hashStudyBytes(packet.mapping)\n\t\t\t)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Grading packet differs from the sealed semantic horizon')\n\t\t}\n\t\tif (labels !== undefined && packet === undefined)\n\t\t\tthrow new StudyError('EVIDENCE', 'Imported labels require a retained semantic packet')\n\t\tconst translated =\n\t\t\tlabels === undefined\n\t\t\t\t? []\n\t\t\t\t: translateStudyPacketLabeling(result, rubric, grading.rubric, labels)\n\t\tfor (const trial of result.manifest.schedule) {\n\t\t\tfor (const criterion of rubric.criteria) {\n\t\t\t\tif (criterion.scenario !== trial.scenario) continue\n\t\t\t\tconst judgment = grading.judgments.find(\n\t\t\t\t\t(entry) => entry.trial === trial.id && entry.criterion === criterion.id,\n\t\t\t\t)\n\t\t\t\tif (judgment === undefined)\n\t\t\t\t\tthrow new StudyError('EVIDENCE', 'Grading must record every scheduled criterion judgment')\n\t\t\t\tif (\n\t\t\t\t\tcriterion.method === 'semantic' &&\n\t\t\t\t\tjudgment.verdict !== 'unknown' &&\n\t\t\t\t\t!translated.some((entry) => canonicalStringify(entry) === canonicalStringify(judgment))\n\t\t\t\t)\n\t\t\t\t\tthrow new StudyError('EVIDENCE', 'Semantic verdict has no bound imported label')\n\t\t\t}\n\t\t}\n\t\tfor (const judgment of translated) {\n\t\t\tif (\n\t\t\t\t!grading.judgments.some(\n\t\t\t\t\t(entry) => canonicalStringify(entry) === canonicalStringify(judgment),\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow new StudyError(\n\t\t\t\t\t'EVIDENCE',\n\t\t\t\t\t'Imported label is absent or differs from its recorded judgment',\n\t\t\t\t)\n\t\t}\n\t}\n}\n","/** Caps declared execution duration at the native supervisor's host ceiling. */\nexport const STUDY_COMMAND_DURATION = 86400000\n\n/** Names the trusted command's independent offline predicate. */\nexport const STUDY_COMMAND_GRADER = 'consumer-adapter'\n\n/** Defines the complete public CLI reference shared by help and grammar diagnostics. */\nexport const STUDY_COMMAND_HELP = `study check <study> [--profile <name>]\nstudy execute <study> [--profile <name>] [--out <path>] [--expected <sha256>]\nstudy grade <result> --rubric <path>\nstudy label <result> --grading <sha256> --labels <path>\nstudy report <result> --grading <sha256>\nstudy --help\n\nProfiles default to local. Flags require values and may appear only once.\nResults default to tmp/studies/<result>; scratch also uses tmp/studies.\nA result is its id under tmp/studies, a root-relative path, or an absolute path.\nRelative paths, including --out, must stay inside the consumer working directory.\nOutput directories must be new; existing results are never overwritten.\n--expected pins the fingerprint returned by check. --grading selects an exact grading.\n--rubric selects independent criteria. --labels imports caller-supplied semantic labels.\nSuccess writes one JSON document; next contains suggested argv, never executed automatically.\ncheck, grade, label and report have a fixed allowance of 60 seconds.\nexecute checks first, then uses the declared series duration plus 15 seconds for cleanup.\nExit codes: 0 success, 64 invalid input, 124 deadline, 130 interruption, 1 operational failure.\n`\n","import type {\n\tStudyAttempt,\n\tStudyBounds,\n\tStudyDefinition,\n\tStudyEvidence,\n\tStudyGrading,\n\tStudyIdentity,\n\tStudyObservation,\n\tStudyProfile,\n\tStudyRubric,\n} from '../../core/types.js'\nimport type { StudyAttributionSource, StudyCommandArtifact } from './types.js'\nimport type { StudySealedResult } from '../stores/types.js'\nimport type { JSONValue } from '@orkestrel/contract'\nimport { parseJSON } from '@orkestrel/contract'\nimport { isAbsolute, join, resolve } from 'node:path'\nimport { STUDY_CAUSES, STUDY_LAYERS, STUDY_ROLES } from '../../core/constants.js'\nimport { StudyError } from '../../core/errors.js'\nimport { computeStudyScores, studyStopToJSON } from '../../core/helpers.js'\nimport { containsArtifact, encodeStudyJSON, hashStudyBytes } from '../helpers.js'\nimport { readStudyBytes } from '../stores/helpers.js'\nimport { isStudyCustodyEvidence } from '../stores/validators.js'\nimport { STUDY_RESERVED_NAME } from '../stores/constants.js'\n\n/**\n * Resolves a portable relative artifact path strictly inside its selected directory.\n * @param directory - The selected custody or study directory\n * @param path - The slash-separated relative artifact path\n * @returns The contained absolute host path\n * @throws StudyError - Thrown when a path is malformed, reserved, absolute, or escaping\n * @example\n * ```ts\n * resolveStudyPath(directory, 'profiles/local.json')\n * ```\n */\nexport function resolveStudyPath(directory: string, path: string): string {\n\tconst names = path.split('/')\n\tif (\n\t\tpath === '' ||\n\t\tisAbsolute(path) ||\n\t\t/[\\\\<>:\"|?*]/.test(path) ||\n\t\tArray.from(path).some(\n\t\t\t(character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127,\n\t\t) ||\n\t\tnames.some(\n\t\t\t(name) =>\n\t\t\t\tname === '' ||\n\t\t\t\tname === '.' ||\n\t\t\t\tname === '..' ||\n\t\t\t\tname.endsWith('.') ||\n\t\t\t\tname.endsWith(' ') ||\n\t\t\t\tSTUDY_RESERVED_NAME.test(name.split('.')[0] ?? ''),\n\t\t)\n\t)\n\t\tthrow new StudyError('CONFIG', 'Artifact path must be a portable contained relative path')\n\tconst absolute = resolve(directory, ...names)\n\tif (!containsArtifact(resolve(directory), absolute))\n\t\tthrow new StudyError('CONFIG', 'Artifact path escapes its selected directory')\n\treturn absolute\n}\n\n/**\n * Resolves the execution profile's caller-selected built artifact paths.\n * @param root - The repository root\n * @param profile - The validated source profile\n * @returns The reproducible resolved execution profile\n * @example\n * ```ts\n * resolveStudyProfile(root, profile)\n * ```\n */\nexport function resolveStudyProfile(root: string, profile: StudyProfile): StudyProfile {\n\treturn {\n\t\t...profile,\n\t\tqualification:\n\t\t\tprofile.qualification === undefined ? undefined : resolve(root, profile.qualification),\n\t\tagent: resolve(root, profile.agent),\n\t\tsubject: resolve(root, profile.subject),\n\t\troots: profile.roots.map((path) => resolve(root, path)),\n\t\tprovider:\n\t\t\tprofile.provider === undefined\n\t\t\t\t? undefined\n\t\t\t\t: { ...profile.provider, entry: resolve(root, profile.provider.entry) },\n\t}\n}\n\n/**\n * Computes the native supervisor's exact validated execution fingerprint.\n * @param identity - The reproducible executable identities\n * @param bounds - The validated nested execution limits\n * @param definition - The optional full declaration binding supervisor check to execute\n * @returns The fingerprint that execute must compare before any writes or child work\n * @example\n * ```ts\n * computeStudyCommandFingerprint(identity, bounds)\n * ```\n */\nexport function computeStudyCommandFingerprint(\n\tidentity: StudyIdentity,\n\tbounds: StudyBounds,\n\tdefinition?: StudyDefinition,\n): string {\n\treturn hashStudyBytes(\n\t\tencodeStudyJSON({ identity, bounds, ...(definition === undefined ? {} : { definition }) }),\n\t)\n}\n\n/**\n * Computes public fixture identity from execution policy and exact scenario bytes.\n * @param definition - The complete retained study declaration\n * @param scenarios - The exact public scenario artifact identities\n * @returns The digest shared by compatible capacity and memory executions\n * @example\n * ```ts\n * computeStudyFixtureDigest(definition, scenarios)\n * ```\n */\nexport function computeStudyFixtureDigest(\n\tdefinition: StudyDefinition,\n\tscenarios: readonly StudyCommandArtifact[],\n): string {\n\treturn hashStudyBytes(\n\t\tencodeStudyJSON({\n\t\t\tdriver: definition.driver,\n\t\t\tarms: definition.arms,\n\t\t\torder: definition.order,\n\t\t\tretries: definition.retries,\n\t\t\tscenarios,\n\t\t}),\n\t)\n}\n\n/**\n * Reads sealed evidence bytes through custody checks without loading executable code.\n * @param result - The independently verified sealed execution\n * @returns Evidence records keyed by scheduled trial identity\n * @throws StudyError - Thrown when evidence drifts, becomes partial, or fails validation\n * @example\n * ```ts\n * await collectStudyEvidence(result)\n * ```\n */\nexport async function collectStudyEvidence(\n\tresult: StudySealedResult,\n): Promise<Readonly<Record<string, readonly StudyEvidence[]>>> {\n\tconst retained: Array<readonly [string, readonly StudyEvidence[]]> = []\n\tfor (const trial of result.manifest.schedule) {\n\t\tconst path = `trials/${trial.id}/evidence.jsonl`\n\t\tconst file = result.seal.files.find((entry) => entry.path === path)\n\t\tconst bytes = await readStudyBytes(\n\t\t\tjoin(result.directory, 'execution', 'trials', trial.id, 'evidence.jsonl'),\n\t\t\tresult.manifest.bounds.trial.bytes,\n\t\t)\n\t\tif (file === undefined || hashStudyBytes(bytes) !== file.digest)\n\t\t\tthrow new StudyError('CUSTODY', 'Evidence changed after execution verification')\n\t\tconst text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\t\tif (text !== '' && !text.endsWith('\\n'))\n\t\t\tthrow new StudyError('CUSTODY', 'Evidence is incomplete')\n\t\tconst rows = text\n\t\t\t.split(/\\r\\n|\\n/)\n\t\t\t.slice(0, -1)\n\t\t\t.map((line): StudyEvidence => {\n\t\t\t\tconst row = parseJSON(line)\n\t\t\t\tif (!isStudyCustodyEvidence(row)) throw new StudyError('CUSTODY', 'Evidence row is invalid')\n\t\t\t\treturn row\n\t\t\t})\n\t\tretained.push([trial.id, Object.freeze(rows)])\n\t}\n\treturn Object.freeze(Object.fromEntries(retained))\n}\n\n/**\n * Partitions records by their explicit execution fact without inferring any.\n * @param records - The attempts, observations, or attribution sources to partition\n * @returns Counts of executed and unexecuted records, which sum to the record count\n * @example\n * ```ts\n * computeStudyPartition(attempts) // { executed: 2, unexecuted: 1 }\n * ```\n */\nexport function computeStudyPartition(\n\trecords: ReadonlyArray<StudyAttempt | StudyObservation | StudyAttributionSource>,\n): Readonly<Record<'executed' | 'unexecuted', number>> {\n\treturn {\n\t\texecuted: records.filter((record) => record.executed).length,\n\t\tunexecuted: records.filter((record) => !record.executed).length,\n\t}\n}\n\n/**\n * Groups failed records by cause, role, and layer, each group carrying its source readings.\n * @remarks\n * A group exists for each cause, role, and layer that holds at least one record. Groups follow\n * `STUDY_CAUSES`, then `STUDY_ROLES` with an absent role last, then `STUDY_LAYERS` with an absent\n * layer last. `role` and `layer` are null when absent. `executed` and `unexecuted` partition the\n * group by each record's own execution fact. `readings` lists every record of the group that carries\n * a stop, in source order, with `trial`, `goal` at the goal level only, `id`, `max`, and `consumed`\n * (null when the source reported none). A failure sealed before the `stop` member existed groups with\n * a null layer and no reading; the helper infers no layer from a message.\n * @param sources - The failed records, in source order\n * @returns The JSON groups\n * @example\n * ```ts\n * computeStudyAttributions([{ trial: 'r1-s1-a1', goal: undefined, failure, executed: true }])\n * ```\n */\nexport function computeStudyAttributions(sources: readonly StudyAttributionSource[]): JSONValue {\n\treturn STUDY_CAUSES.flatMap((cause) =>\n\t\t[...STUDY_ROLES, undefined].flatMap((role) =>\n\t\t\t[...STUDY_LAYERS, undefined].flatMap((layer) => {\n\t\t\t\tconst group = sources.filter(\n\t\t\t\t\t(source) =>\n\t\t\t\t\t\tsource.failure.cause === cause &&\n\t\t\t\t\t\tsource.failure.role === role &&\n\t\t\t\t\t\tsource.failure.stop?.layer === layer,\n\t\t\t\t)\n\t\t\t\tif (group.length === 0) return []\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tcause,\n\t\t\t\t\t\trole: role ?? null,\n\t\t\t\t\t\tlayer: layer ?? null,\n\t\t\t\t\t\t...computeStudyPartition(group),\n\t\t\t\t\t\treadings: group.flatMap((source) => {\n\t\t\t\t\t\t\tconst stop = source.failure.stop\n\t\t\t\t\t\t\treturn stop === undefined\n\t\t\t\t\t\t\t\t? []\n\t\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\ttrial: source.trial,\n\t\t\t\t\t\t\t\t\t\t\t...(source.goal === undefined ? {} : { goal: source.goal }),\n\t\t\t\t\t\t\t\t\t\t\t...Object.fromEntries(\n\t\t\t\t\t\t\t\t\t\t\t\tObject.entries(studyStopToJSON(stop) ?? {}).filter(\n\t\t\t\t\t\t\t\t\t\t\t\t\t([key]) => key !== 'layer',\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t}),\n\t\t),\n\t)\n}\n\n/**\n * Computes whole-horizon results with operational costs and repetitions kept distinct.\n * @param result - The verified complete execution\n * @param rubric - The retained compatible rubric\n * @param grading - The independently verified selected grading\n * @returns The JSON report without pooling identities or inventing absent measurements\n * @remarks\n * Operations count affected trial and goal records, not independent failure events, and the\n * trial and goal counts overlap and are never added. Completion is operational: a goal is\n * completed when it holds a non-partial product and no failure, and a trial when it holds no\n * failure and every goal completed. It is neither task success nor a qualification gate.\n * @example\n * ```ts\n * computeStudyReport(result, rubric, grading)\n * ```\n */\nexport function computeStudyReport(\n\tresult: StudySealedResult,\n\trubric: StudyRubric,\n\tgrading: StudyGrading,\n): JSONValue {\n\tconst scores = computeStudyScores(result.manifest, rubric, grading)\n\tconst observations = result.attempts.flatMap((attempt) => attempt.observations)\n\tconst usage = observations.flatMap((observation) => observation.usage)\n\tconst completed = new Set(\n\t\tobservations.filter(\n\t\t\t(observation) =>\n\t\t\t\tobservation.product !== undefined &&\n\t\t\t\t!observation.product.partial &&\n\t\t\t\tobservation.failure === undefined,\n\t\t),\n\t)\n\tconst repetitions = result.manifest.definition.order.map((order, repetition) => ({\n\t\trepetition,\n\t\torder: [...order],\n\t\tarms: result.manifest.definition.arms.map((arm) => {\n\t\t\tconst trials = new Set(\n\t\t\t\tresult.manifest.schedule\n\t\t\t\t\t.filter((trial) => trial.repetition === repetition && trial.arm === arm)\n\t\t\t\t\t.map((trial) => trial.id),\n\t\t\t)\n\t\t\tconst applicable = result.manifest.schedule\n\t\t\t\t.filter((trial) => trials.has(trial.id))\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) => ({ trial: trial.id, criterion })),\n\t\t\t\t)\n\t\t\tconst judgments = applicable.map((pair) => ({\n\t\t\t\tcriterion: pair.criterion,\n\t\t\t\tjudgment: grading.judgments.find(\n\t\t\t\t\t(entry) => entry.trial === pair.trial && entry.criterion === pair.criterion.id,\n\t\t\t\t),\n\t\t\t}))\n\t\t\tconst achieved = judgments.filter((entry) => entry.judgment?.verdict === 'achieved').length\n\t\t\tconst unsuccessful = judgments.filter(\n\t\t\t\t(entry) => entry.judgment?.verdict === 'unsuccessful',\n\t\t\t).length\n\t\t\tconst unknown = applicable.length - achieved - unsuccessful\n\t\t\treturn {\n\t\t\t\tarm,\n\t\t\t\ttotal: applicable.length,\n\t\t\t\tachieved,\n\t\t\t\tunsuccessful,\n\t\t\t\tunknown,\n\t\t\t\tcritical: judgments.filter(\n\t\t\t\t\t(entry) => entry.criterion.critical && entry.judgment?.verdict === 'unsuccessful',\n\t\t\t\t).length,\n\t\t\t\tlower: achieved / applicable.length,\n\t\t\t\tupper: (achieved + unknown) / applicable.length,\n\t\t\t\tcoverage: (achieved + unsuccessful) / applicable.length,\n\t\t\t}\n\t\t}),\n\t}))\n\tconst identity = result.manifest.identity\n\treturn {\n\t\tcommand: 'report',\n\t\tresult: result.manifest.id,\n\t\tseal: result.seal.id,\n\t\tidentity: {\n\t\t\tagent: identity.agent,\n\t\t\tsubject: identity.subject,\n\t\t\tinstrument: identity.instrument,\n\t\t\tfixtures: identity.fixtures,\n\t\t\tprofile: identity.profile,\n\t\t\t...(identity.provider === undefined ? {} : { provider: identity.provider }),\n\t\t},\n\t\tpurpose: result.manifest.definition.purpose,\n\t\tpopulation: 'Complete declared trial and criterion horizon',\n\t\tuncertainty:\n\t\t\trepetitions.length === 1\n\t\t\t\t? 'One repetition is descriptive and does not establish replicated capacity or quality.'\n\t\t\t\t: 'Repetitions are retained separately; intervals represent unresolved grading, not statistical confidence.',\n\t\tscores: scores.map((score) => ({ ...score })),\n\t\trepetitions,\n\t\toperations: {\n\t\t\ttrials: {\n\t\t\t\tscheduled: result.manifest.schedule.length,\n\t\t\t\tterminal: result.attempts.length,\n\t\t\t\t...computeStudyPartition(result.attempts),\n\t\t\t\tcompleted: result.attempts.filter(\n\t\t\t\t\t(attempt) =>\n\t\t\t\t\t\tattempt.failure === undefined &&\n\t\t\t\t\t\tattempt.observations.every((observation) => completed.has(observation)),\n\t\t\t\t).length,\n\t\t\t\tfaults: STUDY_CAUSES.map((cause) => ({\n\t\t\t\t\tcause,\n\t\t\t\t\t...computeStudyPartition(\n\t\t\t\t\t\tresult.attempts.filter((attempt) => attempt.failure?.cause === cause),\n\t\t\t\t\t),\n\t\t\t\t})),\n\t\t\t\tattributions: computeStudyAttributions(\n\t\t\t\t\tresult.attempts.flatMap((attempt) =>\n\t\t\t\t\t\tattempt.failure === undefined\n\t\t\t\t\t\t\t? []\n\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttrial: attempt.trial.id,\n\t\t\t\t\t\t\t\t\t\tgoal: undefined,\n\t\t\t\t\t\t\t\t\t\tfailure: attempt.failure,\n\t\t\t\t\t\t\t\t\t\texecuted: attempt.executed,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t},\n\t\t\tgoals: {\n\t\t\t\tscheduled: observations.length,\n\t\t\t\t...computeStudyPartition(observations),\n\t\t\t\tproducts: observations.filter((observation) => observation.product !== undefined).length,\n\t\t\t\tpartial: observations.filter((observation) => observation.product?.partial === true).length,\n\t\t\t\tcompleted: observations.filter((observation) => completed.has(observation)).length,\n\t\t\t\tfaults: STUDY_CAUSES.map((cause) => ({\n\t\t\t\t\tcause,\n\t\t\t\t\t...computeStudyPartition(\n\t\t\t\t\t\tobservations.filter((observation) => observation.failure?.cause === cause),\n\t\t\t\t\t),\n\t\t\t\t})),\n\t\t\t\tattributions: computeStudyAttributions(\n\t\t\t\t\tresult.attempts.flatMap((attempt) =>\n\t\t\t\t\t\tattempt.observations.flatMap((observation) =>\n\t\t\t\t\t\t\tobservation.failure === undefined\n\t\t\t\t\t\t\t\t? []\n\t\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\ttrial: attempt.trial.id,\n\t\t\t\t\t\t\t\t\t\t\tgoal: observation.goal,\n\t\t\t\t\t\t\t\t\t\t\tfailure: observation.failure,\n\t\t\t\t\t\t\t\t\t\t\texecuted: observation.executed,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\tcosts: {\n\t\t\tduration: result.attempts.reduce((total, attempt) => total + attempt.duration, 0),\n\t\t\troles: STUDY_ROLES.map((role) => {\n\t\t\t\tconst charges = usage.filter((entry) => entry.role === role)\n\t\t\t\treturn {\n\t\t\t\t\trole,\n\t\t\t\t\tmeasurements: charges.length,\n\t\t\t\t\tcalls: charges.reduce((total, entry) => total + entry.calls, 0),\n\t\t\t\t\tduration: charges.reduce((total, entry) => total + entry.duration, 0),\n\t\t\t\t\ttokens: {\n\t\t\t\t\t\tknown: charges.reduce((total, entry) => total + (entry.tokens ?? 0), 0),\n\t\t\t\t\t\tunknown: charges.filter((entry) => entry.tokens === undefined).length,\n\t\t\t\t\t},\n\t\t\t\t\tbytes: {\n\t\t\t\t\t\tknown: charges.reduce((total, entry) => total + (entry.bytes ?? 0), 0),\n\t\t\t\t\t\tunknown: charges.filter((entry) => entry.bytes === undefined).length,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}),\n\t\t},\n\t}\n}\n","import type { StudyCommandRequest } from './types.js'\nimport { isAbsolute, resolve } from 'node:path'\nimport { StudyError } from '../../core/errors.js'\nimport { isStudyDigest } from '../../core/validators.js'\nimport { isStudyCustodyName } from '../stores/validators.js'\nimport { STUDY_COMMAND_HELP } from './constants.js'\nimport { resolveStudyPath } from './helpers.js'\n\n/** Parses public command tokens with operation-specific grammar diagnostics.\n * @param arguments_ - Exact command tokens, after the CLI help boundary.\n * @returns The independent operation request.\n * @throws StudyError when a token, required flag, or portable path is invalid.\n * @example Parse a study command\n * ```ts\n * import { parseStudyArguments } from '@orkestrel/study/server'\n *\n * parseStudyArguments(['check', 'files', '--profile', 'local'])\n * ```\n */\nexport function parseStudyArguments(arguments_: readonly string[]): StudyCommandRequest {\n\tconst command = arguments_[0]\n\tconst target = arguments_[1]\n\tconst usage =\n\t\tSTUDY_COMMAND_HELP.split('\\n').find((line) => line.startsWith('study ' + command + ' ')) ??\n\t\t'Expected study check, execute, grade, label, or report; use study --help.'\n\tif (!['check', 'execute', 'grade', 'label', 'report'].includes(command ?? ''))\n\t\tthrow new StudyError(\n\t\t\t'CONFIG',\n\t\t\t'Unknown or missing command ' + JSON.stringify(command ?? '<command>') + '. ' + usage,\n\t\t)\n\tif (target === undefined || target === '' || target.startsWith('-'))\n\t\tthrow new StudyError(\n\t\t\t'CONFIG',\n\t\t\t'Missing <' +\n\t\t\t\t(command === 'check' || command === 'execute' ? 'study' : 'result') +\n\t\t\t\t'> before ' +\n\t\t\t\tJSON.stringify(target ?? '<end>') +\n\t\t\t\t'. ' +\n\t\t\t\tusage,\n\t\t)\n\tconst allowed =\n\t\tcommand === 'check'\n\t\t\t? ['--profile']\n\t\t\t: command === 'execute'\n\t\t\t\t? ['--profile', '--out', '--expected']\n\t\t\t\t: command === 'grade'\n\t\t\t\t\t? ['--rubric']\n\t\t\t\t\t: command === 'label'\n\t\t\t\t\t\t? ['--grading', '--labels']\n\t\t\t\t\t\t: ['--grading']\n\tconst tokens: ReadonlyArray<string | undefined> = arguments_.slice(2)\n\t// Positions, not present elements: a sparse token array keeps each hole as an absent flag or value.\n\tconst pairs = [...tokens.entries()].flatMap(([index, flag]) =>\n\t\tindex % 2 === 0 ? [{ flag, value: tokens[index + 1] }] : [],\n\t)\n\t// Reversed so the earliest index of each flag is the one the lookup retains.\n\tconst firsts = new Map(pairs.map(({ flag }, index) => [flag, index] as const).reverse())\n\tfor (const [index, { flag, value }] of pairs.entries()) {\n\t\tif (flag === undefined || !allowed.includes(flag))\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\tJSON.stringify(flag ?? '<end>') +\n\t\t\t\t\t' is not a ' +\n\t\t\t\t\tcommand +\n\t\t\t\t\t' flag; accepts ' +\n\t\t\t\t\tallowed.join(', ') +\n\t\t\t\t\t'. ' +\n\t\t\t\t\tusage,\n\t\t\t)\n\t\tif (firsts.get(flag) !== index) throw new StudyError('CONFIG', flag + ' is duplicate. ' + usage)\n\t\tif (value === undefined || value === '' || value.startsWith('-'))\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\tflag + ' requires a value before ' + JSON.stringify(value ?? '<end>') + '. ' + usage,\n\t\t\t)\n\t}\n\tconst flags = new Map(\n\t\tpairs.flatMap(({ flag, value }) =>\n\t\t\tflag === undefined || value === undefined ? [] : [[flag, value] as const],\n\t\t),\n\t)\n\tif (command === 'check' || command === 'execute') {\n\t\tif (!isStudyCustodyName(target))\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'Invalid study token ' + JSON.stringify(target) + '; use a portable study name. ' + usage,\n\t\t\t)\n\t\tconst profile = flags.get('--profile') ?? 'local'\n\t\tconst out = flags.get('--out')\n\t\tconst expected = flags.get('--expected')\n\t\tif (!isStudyCustodyName(profile))\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'--profile ' + JSON.stringify(profile) + ' must be a portable name. ' + usage,\n\t\t\t)\n\t\tif (out !== undefined && !isAbsolute(out)) {\n\t\t\ttry {\n\t\t\t\tresolveStudyPath(resolve('.'), out)\n\t\t\t} catch {\n\t\t\t\tthrow new StudyError(\n\t\t\t\t\t'CONFIG',\n\t\t\t\t\t'--out ' +\n\t\t\t\t\t\tJSON.stringify(out) +\n\t\t\t\t\t\t' must be a portable contained path and cannot escape the consumer root. ' +\n\t\t\t\t\t\tusage,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tif (expected !== undefined && !isStudyDigest(expected))\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'--expected ' + JSON.stringify(expected) + ' must be a SHA-256 fingerprint. ' + usage,\n\t\t\t)\n\t\treturn { command, target, profile, out, expected }\n\t}\n\tif (command === 'grade') {\n\t\tconst rubric = flags.get('--rubric')\n\t\tif (rubric === undefined) throw new StudyError('CONFIG', 'Missing --rubric. ' + usage)\n\t\treturn { command, target, rubric }\n\t}\n\tconst grading = flags.get('--grading')\n\tif (!isStudyDigest(grading))\n\t\tthrow new StudyError(\n\t\t\t'CONFIG',\n\t\t\t'--grading ' +\n\t\t\t\tJSON.stringify(grading ?? '<missing>') +\n\t\t\t\t' must be an exact SHA-256 grading identity. ' +\n\t\t\t\tusage,\n\t\t)\n\tif (command === 'label') {\n\t\tconst labels = flags.get('--labels')\n\t\tif (labels === undefined) throw new StudyError('CONFIG', 'Missing --labels. ' + usage)\n\t\treturn { command, target, grading, labels }\n\t}\n\treturn { command: 'report', target, grading }\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","/** Limits each serialized IPC envelope, including its JSON framing. */\nexport const STUDY_FRAME_BYTES = 16 * 1024 * 1024\n\n/** Limits outstanding bidirectional protocol work per process. */\nexport const STUDY_PENDING_LIMIT = 64\n\n/** Limits combined worker stdout and stderr before termination. */\nexport const STUDY_LOG_BYTES = 64 * 1024\n\n/** Bounds how long inherited output handles stay open after native exit, in milliseconds. */\nexport const STUDY_DRAIN_DURATION = 1000\n\n/** Attributes an expired process handshake or cleanup deadline. */\nexport const STUDY_PROCESS_LABEL = 'Process lifecycle'\n\n/** Names the worker operation routed by the built application entry. */\nexport const STUDY_WORKER_OPERATION = 'study-worker'\n\n/** Names the private bounded validation and grading route. */\nexport const STUDY_TASK_OPERATION = 'study-adapter'\n\n/** Names the command route beneath the native supervisor. */\nexport const STUDY_COMMAND_OPERATION = 'study-command'\n\n/** Caps pure domain work independently of its event loop. */\nexport const STUDY_TASK_DURATION = 60000\n","import type { StudyFailure, StudyProfile } from '../../core/types.js'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type { ChildProcess } from 'node:child_process'\nimport { canonicalStringify, isJSONValue, isRecord } from '@orkestrel/contract'\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, readFileSync, realpathSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, join } from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { StudyError } from '../../core/errors.js'\nimport { hashStudyBytes } from '../helpers.js'\nimport { STUDY_DRAIN_DURATION } from './constants.js'\n\n/** Projects optional domain fields into the JSON wire representation.\n * @param value - An owned domain value with optional undefined fields.\n * @returns A JSON-compatible snapshot.\n * @example Project a wire value\n * ```ts\n * import { valueToWire } from '@orkestrel/study/server'\n *\n * valueToWire({ state: 'ready', failure: undefined }) // { state: 'ready' }\n * ```\n */\nexport function valueToWire(value: unknown): JSONValue {\n\tconst parsed: unknown = JSON.parse(JSON.stringify(value))\n\tif (!isJSONValue(parsed)) throw new StudyError('FAULT', 'Invalid study wire value')\n\treturn parsed\n}\n\n/** Creates attributable protocol infrastructure failure.\n * @param message - The refused operation or broken boundary.\n * @returns A domain failure that never awards task credit.\n */\nexport function createStudyProcessFailure(message: string): StudyFailure {\n\treturn { cause: 'infrastructure', message, role: undefined, stop: undefined }\n}\n\n/** Binds the canonical fully resolved execution profile carried over IPC.\n * @param profile - The resolved execution settings, with optional absent leaves.\n * @returns The SHA256 digest of the canonical JSON wire representation.\n */\nexport function computeStudyProfileDigest(profile: StudyProfile): string {\n\tconst encoded = canonicalStringify(valueToWire(profile))\n\tif (encoded === undefined) throw new StudyError('CONFIG', 'Study profile is not JSON-compatible')\n\treturn hashStudyBytes(encoded)\n}\n\n/** Collects the executable entries a profile selects, each canonical path once.\n * @param profile - The resolved execution profile.\n * @returns The agent, subject, and provider entries without repeating a shared entry.\n * @remarks The declared roles stay separate in the profile; only capture and loading deduplicate.\n */\nexport function collectStudyEntries(profile: StudyProfile): readonly string[] {\n\treturn [\n\t\t...new Set([\n\t\t\tprofile.agent,\n\t\t\tprofile.subject,\n\t\t\t...(profile.provider === undefined ? [] : [profile.provider.entry]),\n\t\t]),\n\t]\n}\n\n/** Computes the instrument identity binding trusted runtime bytes to the adapter inventory.\n * @param entry - The SHA-256 identity of the trusted runtime entry bytes.\n * @param inventory - The captured adapter inventory digest.\n * @returns The identity that validation, grading, and trial children must share.\n */\nexport function computeStudyInstrumentDigest(entry: string, inventory: string): string {\n\treturn hashStudyBytes(JSON.stringify([entry, inventory]))\n}\n\n/** Resolves the actual host package from its trusted executable entry.\n * @param entry - The runtime's own executable, never a consumer-supplied module.\n * @returns The canonical study package root.\n */\nexport function resolveStudyInstrument(entry: string): string {\n\tconst root = collectStudyAncestors(dirname(realpathSync(entry))).find((directory) => {\n\t\tconst manifest = join(directory, 'package.json')\n\t\tif (!existsSync(manifest)) return false\n\t\tconst value: unknown = JSON.parse(readFileSync(manifest, 'utf8'))\n\t\treturn isRecord(value) && value.name === '@orkestrel/study'\n\t})\n\tif (root === undefined) throw new StudyError('CONFIG', 'Cannot locate the study runtime package')\n\treturn root\n}\n\n/** Collects a directory and each of its ancestors up to the filesystem root, nearest first.\n * @param directory - The absolute directory to start from.\n * @returns The directory followed by every parent directory, ending at the root.\n */\nexport function collectStudyAncestors(directory: string): readonly string[] {\n\tconst parent = dirname(directory)\n\treturn parent === directory ? [directory] : [directory, ...collectStudyAncestors(parent)]\n}\n\n/** Refuses a profile that omits the actual host runtime's declared dependency bytes.\n * @param instrument - The canonical package owning the trusted runtime entry.\n * @param roots - Explicitly admitted package roots, including the instrument.\n */\nexport function validateStudyRuntime(instrument: string, roots: readonly string[]): void {\n\tconst pending = [instrument]\n\tconst visited = new Set<string>()\n\twhile (pending.length > 0) {\n\t\tconst root = pending.pop()\n\t\tif (root === undefined || visited.has(root)) continue\n\t\tvisited.add(root)\n\t\tif (!roots.includes(root))\n\t\t\tthrow new StudyError('CONFIG', `Profile roots omit a runtime dependency: ${root}`)\n\t\tconst manifest = join(root, 'package.json')\n\t\tconst value: unknown = JSON.parse(readFileSync(manifest, 'utf8'))\n\t\tif (!isRecord(value) || value.dependencies === undefined) continue\n\t\tif (!isRecord(value.dependencies))\n\t\t\tthrow new StudyError('CONFIG', 'Runtime dependency declarations are invalid')\n\t\tconst resolver = createRequire(manifest)\n\t\tfor (const dependency of Object.keys(value.dependencies))\n\t\t\tpending.push(dirname(realpathSync(resolver.resolve(`${dependency}/package.json`))))\n\t}\n}\n\n/** Releases inherited output handles a bounded time after native exit.\n * @param child - A newly spawned child, subscribed before native exit.\n * @remarks A descendant that outlives an exited root is outside discoverable-tree cleanup; this only stops the parent from waiting on its pipes.\n */\nexport function drainStudyChild(child: ChildProcess): void {\n\tconst closed = new AbortController()\n\tchild.once('exit', () => {\n\t\t// A close before the allowance ends aborts the wait, which is the only rejection it can have.\n\t\tvoid delay(STUDY_DRAIN_DURATION, undefined, { signal: closed.signal }).then(\n\t\t\t() => {\n\t\t\t\tchild.stdout?.destroy()\n\t\t\t\tchild.stderr?.destroy()\n\t\t\t},\n\t\t\t() => undefined,\n\t\t)\n\t})\n\tchild.once('close', () => closed.abort())\n}\n\n/** Terminates the recorded native process tree under a finite cleanup allowance.\n * @param child - The exclusively owned child process.\n */\nexport function terminateStudyChild(child: ChildProcess): void {\n\tif (child.pid === undefined || child.exitCode !== null || child.signalCode !== null) return\n\ttry {\n\t\tif (process.platform === 'win32')\n\t\t\texecFileSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], {\n\t\t\t\twindowsHide: true,\n\t\t\t\ttimeout: 2000,\n\t\t\t\tstdio: 'ignore',\n\t\t\t})\n\t\telse {\n\t\t\tconst rows = execFileSync('ps', ['-eo', 'pid=,ppid='], {\n\t\t\t\ttimeout: 2000,\n\t\t\t\tencoding: 'utf8',\n\t\t\t\tmaxBuffer: 1024 * 1024,\n\t\t\t})\n\t\t\t\t.trim()\n\t\t\t\t.split(/\\r\\n|\\n/)\n\t\t\t\t.map((row) => row.trim().split(/\\s+/).map(Number))\n\t\t\tconst descendants = new Set([child.pid])\n\t\t\t// One pass per row bounds the depth of any parent chain the table can hold.\n\t\t\trows.forEach(() => {\n\t\t\t\tfor (const [pid, parent] of rows)\n\t\t\t\t\tif (pid !== undefined && parent !== undefined && descendants.has(parent))\n\t\t\t\t\t\tdescendants.add(pid)\n\t\t\t})\n\t\t\tfor (const pid of [...descendants].reverse()) {\n\t\t\t\ttry {\n\t\t\t\t\tprocess.kill(pid, 'SIGKILL')\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!(error instanceof Error && 'code' in error && error.code === 'ESRCH')) throw error\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\ttry {\n\t\t\tprocess.kill(child.pid, 0)\n\t\t} catch (status) {\n\t\t\tif (status instanceof Error && 'code' in status && status.code === 'ESRCH') return\n\t\t\tthrow status\n\t\t}\n\t\tif (child.exitCode === null && child.signalCode === null) {\n\t\t\tchild.kill('SIGKILL')\n\t\t\tthrow error\n\t\t}\n\t}\n}\n","import type {\n\tStudyArtifactIdentity,\n\tStudyArtifactModule,\n\tStudyArtifactLoaderOptions,\n} from './types.js'\nimport type { StudyAdapterInterface } from '../adapters/types.js'\nimport { dirname, isAbsolute } from 'node:path'\nimport { readFileSync } from 'node:fs'\nimport { StudyError } from '../../core/errors.js'\nimport { ArtifactLoader } from '../artifacts/ArtifactLoader.js'\nimport { readStudyAdapter } from '../adapters/helpers.js'\nimport { hashStudyBytes } from '../helpers.js'\nimport { readStudyBytes } from '../stores/helpers.js'\nimport { STUDY_CUSTODY_BYTES } from '../stores/constants.js'\nimport {\n\tcollectStudyEntries,\n\tcomputeStudyInstrumentDigest,\n\tresolveStudyInstrument,\n\tvalidateStudyRuntime,\n} from './helpers.js'\n\n/** Binds consumer instrumentation separately from selected executable identities. */\nexport class StudyArtifactLoader {\n\t#options: StudyArtifactLoaderOptions\n\t#loader: ArtifactLoader | undefined\n\t#instrument: ArtifactLoader | undefined\n\t#identity: StudyArtifactIdentity | undefined\n\t#entry: string | undefined\n\t/** Owns resolved built and consumer source selections.\n\t * @param options - The trusted host, adapter, and profile.\n\t */\n\tconstructor(options: StudyArtifactLoaderOptions) {\n\t\tthis.#options = structuredClone(options)\n\t\tif (\n\t\t\t![\n\t\t\t\toptions.entry,\n\t\t\t\toptions.root,\n\t\t\t\toptions.adapter,\n\t\t\t\t...collectStudyEntries(options.profile),\n\t\t\t\t...options.profile.roots,\n\t\t\t].every(isAbsolute)\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Study artifact paths must be absolute')\n\t}\n\t/** Inventories bytes without importing selected code.\n\t * @returns Bound executable and instrumentation identities.\n\t */\n\tasync inspect(): Promise<StudyArtifactIdentity> {\n\t\tif (this.#identity !== undefined) {\n\t\t\tthis.verify()\n\t\t\treturn this.#identity\n\t\t}\n\t\tconst profile = this.#options.profile\n\t\tconst instrument = resolveStudyInstrument(this.#options.entry)\n\t\tconst roots = [...new Set([...profile.roots, instrument])]\n\t\tvalidateStudyRuntime(instrument, roots)\n\t\tconst source = { root: dirname(this.#options.adapter), entry: this.#options.adapter }\n\t\tthis.#instrument = new ArtifactLoader({ entries: [], roots, source, instrument })\n\t\tconst entry = hashStudyBytes(await readStudyBytes(this.#options.entry, STUDY_CUSTODY_BYTES))\n\t\tthis.#entry = entry\n\t\tthis.#loader = new ArtifactLoader({\n\t\t\tentries: collectStudyEntries(profile),\n\t\t\troots,\n\t\t\tsource,\n\t\t\tinstrument,\n\t\t})\n\t\tconst inventory = this.#loader.inspect()\n\t\tthis.#identity = Object.freeze({\n\t\t\tagent: inventory.digest,\n\t\t\tsubject: inventory.digest,\n\t\t\tprovider: profile.provider === undefined ? undefined : inventory.digest,\n\t\t\tinstrument: computeStudyInstrumentDigest(entry, this.#instrument.inspect().digest),\n\t\t})\n\t\tthis.verify()\n\t\treturn this.#identity\n\t}\n\t/** Loads the adapter from the trial inventory.\n\t * @returns The complete consumer adapter.\n\t */\n\tasync adapter(): Promise<StudyAdapterInterface> {\n\t\tawait this.inspect()\n\t\tif (this.#loader === undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Artifact inspection is required')\n\t\treturn readStudyAdapter(await this.#loader.load(this.#options.adapter))\n\t}\n\t/** Loads admitted built namespaces inside the trial child.\n\t * @returns The agent, subject and optional provider; a shared entry loads once and keeps each role.\n\t */\n\tasync load(): Promise<StudyArtifactModule> {\n\t\tawait this.inspect()\n\t\tif (this.#loader === undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Artifact inspection is required')\n\t\tconst profile = this.#options.profile\n\t\tconst loaded: Array<readonly [string, unknown]> = []\n\t\tfor (const entry of collectStudyEntries(profile))\n\t\t\tloaded.push([entry, await this.#loader.load(entry)])\n\t\tconst namespaces = new Map(loaded)\n\t\tthis.verify()\n\t\tconst provider = profile.provider\n\t\treturn Object.freeze({\n\t\t\tagent: namespaces.get(profile.agent),\n\t\t\tsubject: namespaces.get(profile.subject),\n\t\t\tprovider: provider === undefined ? undefined : namespaces.get(provider.entry),\n\t\t})\n\t}\n\t/** Refuses instrument and inventory drift after inspection. */\n\tverify(): void {\n\t\tif (this.#loader === undefined || this.#instrument === undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Artifact inspection is required')\n\t\tif (hashStudyBytes(readFileSync(this.#options.entry)) !== this.#entry)\n\t\t\tthrow new StudyError('FAULT', 'Study instrument bytes drifted')\n\t\tthis.#loader.verify()\n\t\tthis.#instrument.verify()\n\t}\n}\n","import type { StudyFrame } from './types.js'\nimport type {\n\tStudyCharge,\n\tStudyEvidence,\n\tStudyFailure,\n\tStudyTrial,\n\tStudyIdentity,\n} from '../../core/types.js'\nimport {\n\tisStudyCause,\n\tisStudyDigest,\n\tisStudyName,\n\tisStudyRole,\n\tisStudyStop,\n} from '../../core/validators.js'\nimport { holds, isJSONValue, isRecord } from '@orkestrel/contract'\n\n/** Checks the complete transport envelope before domain handling.\n * @param value - Native IPC decoded value.\n * @returns True if the envelope is bounded in shape and JSON-compatible; false otherwise.\n */\nexport function isStudyFrame(value: unknown): value is StudyFrame {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tObject.keys(value).length === 3 &&\n\t\t\tObject.hasOwn(value, 'id') &&\n\t\t\tObject.hasOwn(value, 'operation') &&\n\t\t\tObject.hasOwn(value, 'value') &&\n\t\t\ttypeof value.id === 'number' &&\n\t\t\tNumber.isSafeInteger(value.id) &&\n\t\t\tvalue.id >= 0 &&\n\t\t\ttypeof value.operation === 'string' &&\n\t\t\t[\n\t\t\t\t'open',\n\t\t\t\t'goal',\n\t\t\t\t'close',\n\t\t\t\t'admit',\n\t\t\t\t'finish',\n\t\t\t\t'fail',\n\t\t\t\t'evidence',\n\t\t\t\t'reply',\n\t\t\t\t'error',\n\t\t\t\t'abort',\n\t\t\t].includes(value.operation) &&\n\t\t\tisJSONValue(value.value),\n\t)\n}\n\n/** Checks operational failure attribution arriving over IPC.\n * @param value - Decoded failure value.\n * @returns True if the failure carries a known cause, an optional role, and an optional stop that satisfies `isStudyStop` on a `capacity` or `deadline` cause; false otherwise.\n */\nexport function isStudyProcessFailure(value: unknown): value is StudyFailure {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\ttypeof value.message === 'string' &&\n\t\t\tisStudyCause(value.cause) &&\n\t\t\t(value.role === undefined || isStudyRole(value.role)) &&\n\t\t\t(value.stop === undefined ||\n\t\t\t\t((value.cause === 'capacity' || value.cause === 'deadline') && isStudyStop(value.stop))),\n\t)\n}\n\n/** Checks a request's declared role and finite cost ceilings.\n * @param value - Decoded charge.\n * @returns True if all charge leaves are valid; false otherwise.\n */\nexport function isStudyCharge(value: unknown): value is StudyCharge {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tisStudyRole(value.role) &&\n\t\t\ttypeof value.tokens === 'number' &&\n\t\t\tNumber.isSafeInteger(value.tokens) &&\n\t\t\tvalue.tokens >= 0 &&\n\t\t\ttypeof value.bytes === 'number' &&\n\t\t\tNumber.isSafeInteger(value.bytes) &&\n\t\t\tvalue.bytes >= 0,\n\t)\n}\n\n/** Checks append-only public evidence.\n * @param value - Decoded evidence.\n * @returns True if event, goal and payload are valid; false otherwise.\n */\nexport function isStudyEvidence(value: unknown): value is StudyEvidence {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tisStudyName(value.event) &&\n\t\t\tisStudyName(value.goal) &&\n\t\t\tisJSONValue(value.value),\n\t)\n}\n\n/** Checks a fresh trial's declared identifiers.\n * @param value - Decoded trial.\n * @returns True if every identifier and repetition is valid; false otherwise.\n */\nexport function isStudyTrial(value: unknown): value is StudyTrial {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tisStudyName(value.id) &&\n\t\t\tisStudyName(value.scenario) &&\n\t\t\tisStudyName(value.arm) &&\n\t\t\ttypeof value.repetition === 'number' &&\n\t\t\tNumber.isSafeInteger(value.repetition) &&\n\t\t\tvalue.repetition >= 0,\n\t)\n}\n\n/** Checks the exact digest fields carried by the execution declaration.\n * @param value - Decoded identity.\n * @returns True if all required identities are digests; false otherwise.\n */\nexport function isStudyIdentity(value: unknown): value is StudyIdentity {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tisStudyDigest(value.agent) &&\n\t\t\tisStudyDigest(value.subject) &&\n\t\t\t(value.provider === undefined || isStudyDigest(value.provider)) &&\n\t\t\tisStudyDigest(value.instrument) &&\n\t\t\tisStudyDigest(value.fixtures) &&\n\t\t\tisStudyDigest(value.profile),\n\t)\n}\n","import type { StudyChannelOptions, StudyFrame, StudyOperation, StudyResponse } from './types.js'\nimport type { JSONValue } from '@orkestrel/contract'\nimport { StudyControl, failureToStudyError, readStudyFailure } from '../../core/engines/index.js'\nimport { STUDY_FRAME_BYTES, STUDY_PENDING_LIMIT } from './constants.js'\nimport { createStudyProcessFailure, valueToWire } from './helpers.js'\nimport { isStudyFrame, isStudyProcessFailure } from './validators.js'\n\n/** Correlates bounded IPC work and rejects every outstanding request on transport failure. */\nexport class StudyChannel {\n\t#options: StudyChannelOptions\n\t#control = new StudyControl()\n\treadonly #pending = new Map<number, StudyResponse>()\n\t#next = 0\n\t#received = 0\n\treadonly #working = new Set<symbol>()\n\t#message: (value: unknown) => void\n\t#disconnect: () => void\n\t#error: (error: Error) => void\n\n\t/** Subscribes to one native IPC endpoint.\n\t * @param options - Native endpoint and owning domain handlers; the bag is snapshotted while selected collaborators keep their identity.\n\t */\n\tconstructor(options: StudyChannelOptions) {\n\t\tthis.#options = { ...options }\n\t\tthis.#message = this.#onMessage.bind(this)\n\t\tthis.#disconnect = this.#onDisconnect.bind(this)\n\t\tthis.#error = this.close.bind(this)\n\t\tthis.#options.endpoint.on('message', this.#message)\n\t\tthis.#options.endpoint.on('disconnect', this.#disconnect)\n\t\tthis.#options.endpoint.on('error', this.#error)\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.#control.signal\n\t}\n\n\t#onMessage(value: unknown): void {\n\t\tvoid this.#receive(value).catch((error: unknown) => this.close(error))\n\t}\n\n\t#onDisconnect(): void {\n\t\tthis.close(failureToStudyError(createStudyProcessFailure('Study process disconnected')))\n\t}\n\n\t/** Sends one correlated domain request.\n\t * @param operation - The domain operation expected by the peer.\n\t * @param value - Public JSON payload.\n\t * @returns The peer's acknowledged result.\n\t */\n\trequest(operation: StudyOperation, value: JSONValue): Promise<JSONValue> {\n\t\tif (this.#control.failure !== undefined)\n\t\t\treturn Promise.reject(failureToStudyError(this.#control.failure))\n\t\tif (this.#pending.size >= STUDY_PENDING_LIMIT)\n\t\t\treturn Promise.reject(\n\t\t\t\tfailureToStudyError(createStudyProcessFailure('Study IPC pending limit exceeded')),\n\t\t\t)\n\t\tconst id = ++this.#next\n\t\treturn new Promise<JSONValue>((resolve, reject) => {\n\t\t\tthis.#pending.set(id, { resolve, reject })\n\t\t\tthis.#send({ id, operation, value }).catch((error: unknown) => this.close(error))\n\t\t})\n\t}\n\n\t/** Forwards cancellation without closing the cleanup transport.\n\t * @param value - Validated goal, trial or ticket cancellation attribution.\n\t */\n\tabort(value: JSONValue): void {\n\t\tvoid this.#send({ id: 0, operation: 'abort', value }).catch((error: unknown) =>\n\t\t\tthis.close(error),\n\t\t)\n\t}\n\n\t/** Removes endpoint handlers and rejects all unresolved calls.\n\t * @param error - The first transport or owning lifecycle failure.\n\t */\n\tclose(\n\t\terror: unknown = failureToStudyError(createStudyProcessFailure('Study channel closed')),\n\t): void {\n\t\tthis.#control.fail(readStudyFailure(error))\n\t\tthis.#options.endpoint.removeListener('message', this.#message)\n\t\tthis.#options.endpoint.removeListener('disconnect', this.#disconnect)\n\t\tthis.#options.endpoint.removeListener('error', this.#error)\n\t\tfor (const pending of this.#pending.values())\n\t\t\tpending.reject(failureToStudyError(this.#control.failure ?? readStudyFailure(error)))\n\t\tthis.#pending.clear()\n\t\tthis.#control.close()\n\t}\n\n\tasync #send(frame: StudyFrame): Promise<void> {\n\t\tif (Buffer.byteLength(JSON.stringify(frame)) > STUDY_FRAME_BYTES)\n\t\t\tthrow failureToStudyError(createStudyProcessFailure('Study IPC frame limit exceeded'))\n\t\tif (!this.#options.endpoint.connected || this.#options.endpoint.send === undefined)\n\t\t\tthrow failureToStudyError(createStudyProcessFailure('Study IPC is unavailable'))\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tthis.#options.endpoint.send?.(frame, undefined, {}, (error: Error | null) =>\n\t\t\t\terror === null ? resolve() : reject(error),\n\t\t\t)\n\t\t})\n\t}\n\n\tasync #receive(value: unknown): Promise<void> {\n\t\tif (!isStudyFrame(value) || Buffer.byteLength(JSON.stringify(value)) > STUDY_FRAME_BYTES)\n\t\t\tthrow failureToStudyError(createStudyProcessFailure('Malformed study IPC frame'))\n\t\tif (value.operation === 'abort') {\n\t\t\tif (value.id !== 0)\n\t\t\t\tthrow failureToStudyError(createStudyProcessFailure('Foreign study cancellation'))\n\t\t\tthis.#options.abort(value.value)\n\t\t\treturn\n\t\t}\n\t\tif (value.operation === 'reply' || value.operation === 'error') {\n\t\t\tconst pending = this.#pending.get(value.id)\n\t\t\tif (pending === undefined)\n\t\t\t\tthrow failureToStudyError(createStudyProcessFailure('Unknown study IPC reply'))\n\t\t\tif (value.operation === 'reply') pending.resolve(value.value)\n\t\t\telse {\n\t\t\t\tif (!isStudyProcessFailure(value.value))\n\t\t\t\t\tthrow failureToStudyError(createStudyProcessFailure('Invalid study IPC failure'))\n\t\t\t\tpending.reject(failureToStudyError(value.value))\n\t\t\t}\n\t\t\tthis.#pending.delete(value.id)\n\t\t\treturn\n\t\t}\n\t\tif (value.id !== this.#received + 1 || this.#working.size >= STUDY_PENDING_LIMIT)\n\t\t\tthrow failureToStudyError(\n\t\t\t\tcreateStudyProcessFailure('Out-of-order or excessive study IPC request'),\n\t\t\t)\n\t\tconst id = value.id\n\t\tthis.#received = id\n\t\t// The request joins the registry before its handler can run, so a request the handler admits\n\t\t// on its synchronous path meets the limit.\n\t\tconst working = Symbol('request')\n\t\tthis.#working.add(working)\n\t\ttry {\n\t\t\tconst result = await this.#options.handle(value.operation, value.value)\n\t\t\t// The admitted id answers both outcomes: another listener on the shared endpoint may edit\n\t\t\t// the borrowed frame while the handler is pending.\n\t\t\tawait this.#send({ id, operation: 'reply', value: result })\n\t\t} catch (error) {\n\t\t\tawait this.#send({\n\t\t\t\tid,\n\t\t\t\toperation: 'error',\n\t\t\t\tvalue: valueToWire(readStudyFailure(error)),\n\t\t\t})\n\t\t} finally {\n\t\t\tthis.#working.delete(working)\n\t\t}\n\t}\n}\n","import type { StudyContext } from '../../core/types.js'\n\n/** Holds one goal's parent context and the worker admission sequence it issues while the goal runs.\n * @example Issue worker admissions in sequence\n * ```ts\n * import type { StudyContext } from '@orkestrel/study'\n * import { StudyProcessGoal } from '@orkestrel/study/server'\n *\n * declare const context: StudyContext\n *\n * const goal = new StudyProcessGoal(context)\n * goal.issue(2) // undefined\n * goal.issue(1) // 1\n * goal.issue(1) // undefined\n * goal.issue(2) // 2\n * ```\n */\nexport class StudyProcessGoal {\n\treadonly #context: StudyContext\n\t#issued = 0\n\n\t/** Binds one goal to the parent meter and evidence sink it runs under.\n\t * @param context - The actual parent meter, evidence sink and cancellation of the goal.\n\t */\n\tconstructor(context: StudyContext) {\n\t\tthis.#context = context\n\t}\n\n\t/** Reports the parent meter and evidence sink the goal runs under. */\n\tget context(): StudyContext {\n\t\treturn this.#context\n\t}\n\n\t/** Issues the identifier of the next worker admission when the worker asked for exactly that one.\n\t * @param requested - The identifier the worker supplied.\n\t * @returns The issued identifier, or undefined when the requested one is not the next in sequence.\n\t */\n\tissue(requested: unknown): number | undefined {\n\t\tif (requested !== this.#issued + 1) return undefined\n\t\tthis.#issued++\n\t\treturn this.#issued\n\t}\n}\n","import type {\n\tStudyContext,\n\tStudyGoal,\n\tStudyProduct,\n\tStudySessionInterface,\n} from '../../core/types.js'\nimport type { StudyOperation, StudyParentTicket, StudyProcessSessionOptions } from './types.js'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type { ChildProcess } from 'node:child_process'\nimport { isRecord } from '@orkestrel/contract'\nimport { execFile, fork } from 'node:child_process'\nimport { mkdtemp } from 'node:fs/promises'\nimport { isAbsolute, join } from 'node:path'\nimport {\n\tStudyControl,\n\tStudyDeadline,\n\tfailureToStudyError,\n\treadStudyFailure,\n} from '../../core/engines/index.js'\nimport { StudyError } from '../../core/errors.js'\nimport { isStudyProduct, isStudyUsage } from '../../core/validators.js'\nimport { STUDY_LOG_BYTES, STUDY_PROCESS_LABEL, STUDY_WORKER_OPERATION } from './constants.js'\nimport { createStudyProcessFailure, drainStudyChild, valueToWire } from './helpers.js'\nimport { StudyChannel } from './StudyChannel.js'\nimport { StudyProcessGoal } from './StudyProcessGoal.js'\nimport { isStudyCharge, isStudyEvidence, isStudyProcessFailure } from './validators.js'\n\n/** Keeps admission and evidence custody in the parent of one fresh trial process. */\nexport class StudyProcessSession implements StudySessionInterface {\n\t#options: StudyProcessSessionOptions\n\t#control: StudyControl\n\t#listeners = new AbortController()\n\t#child: ChildProcess | undefined\n\t#channel: StudyChannel | undefined\n\t#exit: Promise<void> | undefined\n\t#closing: Promise<void> | undefined\n\treadonly #goals = new Set<StudyProcessGoal>()\n\treadonly #tickets = new Map<number, StudyParentTicket>()\n\treadonly #appends = new Set<Promise<void>>()\n\t#logs = 0\n\t#started = false\n\t#deadline: ReturnType<typeof setTimeout> | undefined\n\n\t/** Owns one trial's process lifecycle without starting host work.\n\t * @param options - Public trial and process configuration; the configuration is snapshotted while the borrowed signal keeps its identity.\n\t */\n\tconstructor(options: StudyProcessSessionOptions) {\n\t\tconst { signal, ...configuration } = options\n\t\tthis.#options = { ...structuredClone(configuration), signal }\n\t\tthis.#control = new StudyControl(signal)\n\t}\n\n\t/** Starts the child and verifies its artifact-bound readiness. */\n\tasync start(): Promise<void> {\n\t\tif (this.#started || this.#closing !== undefined)\n\t\t\tthrow new StudyError('FAULT', 'Study process start is single use')\n\t\tthis.#started = true\n\t\tif (this.#control.failure !== undefined) throw failureToStudyError(this.#control.failure)\n\t\tif (![this.#options.entry, this.#options.root, this.#options.directory].every(isAbsolute))\n\t\t\tthrow new StudyError('CONFIG', 'Study process paths must be absolute')\n\t\tconst directory = await mkdtemp(join(this.#options.directory, 'trial-'))\n\t\tif (this.#control.failure !== undefined) throw failureToStudyError(this.#control.failure)\n\t\tconst child = fork(this.#options.entry, [STUDY_WORKER_OPERATION], {\n\t\t\tcwd: this.#options.root,\n\t\t\texecArgv: [...process.execArgv],\n\t\t\tsilent: true,\n\t\t\tserialization: 'json',\n\t\t\twindowsHide: true,\n\t\t\tdetached: process.platform !== 'win32',\n\t\t})\n\t\tdrainStudyChild(child)\n\t\tthis.#child = child\n\t\tthis.#deadline = setTimeout(() => {\n\t\t\tthis.#control.fail({\n\t\t\t\tcause: 'deadline',\n\t\t\t\tmessage: 'Trial native deadline exceeded',\n\t\t\t\trole: undefined,\n\t\t\t\t// The session holds no start time, so the timer firing proves only that the elapsed time reached the limit.\n\t\t\t\tstop: {\n\t\t\t\t\tlayer: 'scope',\n\t\t\t\t\tid: 'Trial duration',\n\t\t\t\t\tmax: this.#options.profile.bounds.trial.duration,\n\t\t\t\t\tconsumed: undefined,\n\t\t\t\t},\n\t\t\t})\n\t\t\tvoid this.#terminate().catch((error: unknown) => this.#control.fail(readStudyFailure(error)))\n\t\t}, this.#options.profile.bounds.trial.duration)\n\t\tthis.#exit = new Promise<void>((resolve) => child.once('close', () => resolve()))\n\t\tthis.#channel = new StudyChannel({\n\t\t\tendpoint: child,\n\t\t\thandle: (operation, value) =>\n\t\t\t\tthis.#handle(operation, value).catch((error: unknown) => {\n\t\t\t\t\tthis.#control.fail(readStudyFailure(error))\n\t\t\t\t\tthrow error\n\t\t\t\t}),\n\t\t\tabort: () => {\n\t\t\t\tthrow new StudyError('FAULT', 'Worker cannot cancel parent authority')\n\t\t\t},\n\t\t})\n\t\tthis.#channel.signal.addEventListener(\n\t\t\t'abort',\n\t\t\t() => this.#control.fail(readStudyFailure(this.#channel?.signal.reason)),\n\t\t\t{ once: true, signal: this.#listeners.signal },\n\t\t)\n\t\tthis.#control.signal.addEventListener(\n\t\t\t'abort',\n\t\t\t() => this.#channel?.abort(valueToWire({ failure: this.#control.failure })),\n\t\t\t{ once: true, signal: this.#listeners.signal },\n\t\t)\n\t\tchild.stdout?.on('data', (value: Buffer) => this.#readLog(value))\n\t\tchild.stderr?.on('data', (value: Buffer) => this.#readLog(value))\n\t\tconst ready = await this.#control.wait(\n\t\t\tnew StudyDeadline({\n\t\t\t\tduration: this.#options.profile.bounds.trial.duration,\n\t\t\t\tlabel: STUDY_PROCESS_LABEL,\n\t\t\t}).wait(\n\t\t\t\tthis.#channel.request(\n\t\t\t\t\t'open',\n\t\t\t\t\tvalueToWire({ ...this.#options, signal: undefined, directory }),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t\tif (\n\t\t\t!isRecord(ready) ||\n\t\t\tready.pid !== child.pid ||\n\t\t\tready.agent !== this.#options.identity.agent ||\n\t\t\tready.subject !== this.#options.identity.subject ||\n\t\t\tready.instrument !== this.#options.identity.instrument\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Worker readiness identity differs')\n\t}\n\n\t/** Runs one ordered goal through parent-authorized requests and acknowledged evidence.\n\t * @param goal - Public goal without grading truth.\n\t * @param context - Actual parent meter and evidence sink.\n\t * @returns The retained child product after every admitted operation settles.\n\t */\n\tasync execute(goal: StudyGoal, context: StudyContext): Promise<StudyProduct> {\n\t\tif (this.#goals.size !== 0 || this.#closing !== undefined || this.#channel === undefined)\n\t\t\tthrow new StudyError('FAULT', 'Study process cannot execute in its current state')\n\t\tif (this.#control.failure !== undefined) throw failureToStudyError(this.#control.failure)\n\t\tconst running = new StudyProcessGoal(context)\n\t\tthis.#goals.add(running)\n\t\tconst listeners = new AbortController()\n\t\tconst control = new StudyControl(context.signal)\n\t\tthis.#control.signal.addEventListener(\n\t\t\t'abort',\n\t\t\t() =>\n\t\t\t\tcontrol.fail(this.#control.failure ?? createStudyProcessFailure('Study process failed')),\n\t\t\t{ once: true, signal: listeners.signal },\n\t\t)\n\t\tcontrol.signal.addEventListener(\n\t\t\t'abort',\n\t\t\t() => this.#channel?.abort(valueToWire({ failure: control.failure })),\n\t\t\t{ once: true, signal: listeners.signal },\n\t\t)\n\t\ttry {\n\t\t\tconst product = await control.wait(this.#channel.request('goal', valueToWire(goal)))\n\t\t\tif (this.#tickets.size !== 0 || this.#appends.size !== 0)\n\t\t\t\tthrow new StudyError('FAULT', 'Worker goal ended with unsettled admission or evidence')\n\t\t\tif (!isStudyProduct(product)) throw new StudyError('FAULT', 'Worker product is invalid')\n\t\t\treturn product\n\t\t} catch (error) {\n\t\t\tthis.#control.fail(readStudyFailure(error))\n\t\t\tthrow failureToStudyError(this.#control.failure ?? readStudyFailure(error))\n\t\t} finally {\n\t\t\tlisteners.abort()\n\t\t\tcontrol.close()\n\t\t\tthis.#goals.delete(running)\n\t\t}\n\t}\n\n\t/** Requests verified cleanup, then terminates only this recorded process tree. */\n\tclose(): Promise<void> {\n\t\tthis.#closing ??= this.#close()\n\t\treturn this.#closing\n\t}\n\n\tasync #handle(operation: StudyOperation, value: JSONValue): Promise<JSONValue> {\n\t\tconst [running] = this.#goals\n\t\tif (running === undefined) throw new StudyError('FAULT', 'Worker requested work outside a goal')\n\t\tconst context = running.context\n\t\tif (operation === 'admit') {\n\t\t\tif (!isRecord(value) || !isStudyCharge(value.charge))\n\t\t\t\tthrow new StudyError('FAULT', 'Invalid worker admission')\n\t\t\tconst id = running.issue(value.id)\n\t\t\tif (id === undefined) throw new StudyError('FAULT', 'Invalid worker admission')\n\t\t\tconst ticket = await context.meter.admit(value.charge)\n\t\t\tconst listeners = new AbortController()\n\t\t\tthis.#tickets.set(id, { ticket, listeners })\n\t\t\tticket.signal.addEventListener(\n\t\t\t\t'abort',\n\t\t\t\t() =>\n\t\t\t\t\tthis.#channel?.abort(\n\t\t\t\t\t\tvalueToWire({ id, failure: readStudyFailure(ticket.signal.reason) }),\n\t\t\t\t\t),\n\t\t\t\t{ once: true, signal: listeners.signal },\n\t\t\t)\n\t\t\tif (ticket.signal.aborted) throw ticket.signal.reason\n\t\t\treturn { id }\n\t\t}\n\t\tif (operation === 'finish' || operation === 'fail') {\n\t\t\tif (!isRecord(value) || typeof value.id !== 'number')\n\t\t\t\tthrow new StudyError('FAULT', 'Invalid worker settlement')\n\t\t\tconst entry = this.#tickets.get(value.id)\n\t\t\tif (entry === undefined)\n\t\t\t\tthrow new StudyError('FAULT', 'Foreign or repeated worker settlement')\n\t\t\tif (\n\t\t\t\t(operation === 'finish' && !isStudyUsage(value.usage)) ||\n\t\t\t\t(operation === 'fail' && !isStudyProcessFailure(value.failure))\n\t\t\t)\n\t\t\t\tthrow new StudyError('FAULT', 'Invalid worker settlement payload')\n\t\t\tthis.#tickets.delete(value.id)\n\t\t\tentry.listeners.abort()\n\t\t\tif (operation === 'finish' && isStudyUsage(value.usage)) entry.ticket.finish(value.usage)\n\t\t\telse if (isStudyProcessFailure(value.failure)) entry.ticket.fail(value.failure)\n\t\t\treturn true\n\t\t}\n\t\tif (operation === 'evidence') {\n\t\t\tif (!isStudyEvidence(value)) throw new StudyError('FAULT', 'Invalid worker evidence')\n\t\t\tconst appending = context.evidence.append(value)\n\t\t\tthis.#appends.add(appending)\n\t\t\ttry {\n\t\t\t\tawait appending\n\t\t\t\treturn true\n\t\t\t} finally {\n\t\t\t\tthis.#appends.delete(appending)\n\t\t\t}\n\t\t}\n\t\tthrow new StudyError('FAULT', 'Worker requested a forbidden operation')\n\t}\n\n\t#readLog(value: Buffer): void {\n\t\tthis.#logs += value.byteLength\n\t\tif (this.#logs > STUDY_LOG_BYTES) {\n\t\t\tthis.#control.fail(createStudyProcessFailure('Worker output limit exceeded'))\n\t\t\tvoid this.close().catch(() => undefined)\n\t\t}\n\t}\n\n\tasync #close(): Promise<void> {\n\t\tconst failure = await this.#acknowledge()\n\t\tfor (const entry of this.#tickets.values()) {\n\t\t\tentry.listeners.abort()\n\t\t\tif (!entry.ticket.signal.aborted) {\n\t\t\t\ttry {\n\t\t\t\t\tentry.ticket.fail(\n\t\t\t\t\t\tthis.#control.failure ??\n\t\t\t\t\t\t\tcreateStudyProcessFailure('Worker closed with an unfinished request'),\n\t\t\t\t\t)\n\t\t\t\t} catch {\n\t\t\t\t\t/* First parent failure is already retained. */\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.#tickets.clear()\n\t\tthis.#listeners.abort()\n\t\tthis.#channel?.close(failure)\n\t\tawait this.#terminate()\n\t\tthis.#control.close()\n\t\tif (failure !== undefined) throw failure\n\t}\n\n\t// Asks the worker to clean up and returns the failure that stopped it, or undefined when it acknowledged.\n\tasync #acknowledge(): Promise<unknown> {\n\t\ttry {\n\t\t\tif (this.#channel !== undefined && !this.#channel.signal.aborted) {\n\t\t\t\tconst closed = await new StudyDeadline({\n\t\t\t\t\tduration: this.#options.profile.bounds.request.duration,\n\t\t\t\t\tlabel: STUDY_PROCESS_LABEL,\n\t\t\t\t}).wait(this.#channel.request('close', true))\n\t\t\t\tif (closed !== true)\n\t\t\t\t\tthrow new StudyError('FAULT', 'Worker cleanup acknowledgment is invalid')\n\t\t\t}\n\t\t\treturn undefined\n\t\t} catch (error) {\n\t\t\treturn error\n\t\t}\n\t}\n\n\tasync #terminate(): Promise<void> {\n\t\tclearTimeout(this.#deadline)\n\t\tconst child = this.#child\n\t\tif (child === undefined) return\n\t\tif (child.exitCode === null && child.signalCode === null && child.pid !== undefined) {\n\t\t\tif (process.platform === 'win32') {\n\t\t\t\tawait new Promise<void>((resolve, reject) =>\n\t\t\t\t\texecFile(\n\t\t\t\t\t\t'taskkill',\n\t\t\t\t\t\t['/PID', String(child.pid), '/T', '/F'],\n\t\t\t\t\t\t{ windowsHide: true, timeout: 2000 },\n\t\t\t\t\t\t(error) =>\n\t\t\t\t\t\t\terror === null || child.exitCode !== null || child.signalCode !== null\n\t\t\t\t\t\t\t\t? resolve()\n\t\t\t\t\t\t\t\t: reject(error),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t} else process.kill(-child.pid, 'SIGKILL')\n\t\t}\n\t\tif (this.#exit !== undefined)\n\t\t\tawait new StudyDeadline({ duration: 2000, label: STUDY_PROCESS_LABEL }).wait(this.#exit)\n\t}\n}\n","import type { StudyDriverInterface, StudySessionInterface, StudyTrial } from '../../core/types.js'\nimport type { StudyProcessOptions } from './types.js'\nimport { StudyProcessSession } from './StudyProcessSession.js'\n\n/** Opens one fresh native child for each scheduled trial. */\nexport class StudyProcessDriver implements StudyDriverInterface {\n\t#options: StudyProcessOptions\n\n\t/** Owns immutable resolved launch settings.\n\t * @param options - Built entry, admitted identities and exclusive scratch parent.\n\t */\n\tconstructor(options: StudyProcessOptions) {\n\t\tthis.#options = structuredClone(options)\n\t}\n\n\t/** Opens isolated child state and waits for its verified readiness.\n\t * @param trial - The public scheduled trial.\n\t * @param signal - Authoritative parent cancellation.\n\t * @returns A ready process-backed session.\n\t */\n\tasync open(trial: StudyTrial, signal: AbortSignal): Promise<StudySessionInterface> {\n\t\tconst session = new StudyProcessSession({ ...this.#options, trial, signal })\n\t\ttry {\n\t\t\tawait session.start()\n\t\t\treturn session\n\t\t} catch (error) {\n\t\t\tawait session.close().catch(() => undefined)\n\t\t\tthrow error\n\t\t}\n\t}\n}\n","import type { ChildProcess } from 'node:child_process'\nimport type { StudyTaskOptions, StudyTaskResult } from './types.js'\nimport { isJSONValue, isRecord } from '@orkestrel/contract'\nimport { fork } from 'node:child_process'\nimport { StudyError } from '../../core/errors.js'\nimport { isStudyDigest } from '../../core/validators.js'\nimport { STUDY_FRAME_BYTES, STUDY_LOG_BYTES, STUDY_TASK_OPERATION } from './constants.js'\nimport { drainStudyChild, terminateStudyChild } from './helpers.js'\n\n/** Supervises one forked adapter child until it closes with one verified response. */\nexport class StudyTaskChild {\n\treadonly #options: StudyTaskOptions\n\treadonly #duration: number\n\treadonly #signal: AbortSignal\n\t#failure: unknown\n\t#result: StudyTaskResult | undefined\n\t#logs = 0\n\t#executed = false\n\n\t/** Binds one adapter evaluation to its owned route, validated deadline and caller cancellation.\n\t * @param options - The owning task's snapshotted entry, root and selection.\n\t * @param duration - The validated deadline in milliseconds.\n\t * @param signal - Caller cancellation.\n\t */\n\tconstructor(options: StudyTaskOptions, duration: number, signal: AbortSignal) {\n\t\tthis.#options = options\n\t\tthis.#duration = duration\n\t\tthis.#signal = signal\n\t}\n\n\t/** Forks the adapter child, sends one request frame and settles with its single verified response.\n\t * @param input - The validated request frame.\n\t * @returns The verified adapter output and instrumentation identity.\n\t * @throws StudyError - Thrown with code `CONFIG` when this child is already supervised.\n\t */\n\texecute(input: Readonly<Record<string, unknown>>): Promise<StudyTaskResult> {\n\t\tif (this.#executed) throw new StudyError('CONFIG', 'Study task child can execute only once')\n\t\tthis.#executed = true\n\t\tconst signal = this.#signal\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst child = fork(this.#options.entry, [STUDY_TASK_OPERATION], {\n\t\t\t\tcwd: this.#options.root,\n\t\t\t\texecArgv: [...process.execArgv],\n\t\t\t\tsilent: true,\n\t\t\t\twindowsHide: true,\n\t\t\t\tdetached: process.platform !== 'win32',\n\t\t\t\tserialization: 'json',\n\t\t\t})\n\t\t\tdrainStudyChild(child)\n\t\t\tconst listeners = new AbortController()\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.#failure = new StudyError('FAULT', 'Adapter deadline exceeded', {\n\t\t\t\t\tcause: 'deadline',\n\t\t\t\t\tmessage: 'Adapter deadline exceeded',\n\t\t\t\t\trole: undefined,\n\t\t\t\t\tstop: {\n\t\t\t\t\t\tlayer: 'scope',\n\t\t\t\t\t\tid: 'Adapter duration',\n\t\t\t\t\t\tmax: this.#duration,\n\t\t\t\t\t\tconsumed: undefined,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tthis.#terminate(child)\n\t\t\t}, this.#duration)\n\t\t\tsignal.addEventListener(\n\t\t\t\t'abort',\n\t\t\t\t() => {\n\t\t\t\t\tthis.#failure = signal.reason\n\t\t\t\t\tthis.#terminate(child)\n\t\t\t\t},\n\t\t\t\t{ once: true, signal: listeners.signal },\n\t\t\t)\n\t\t\tchild.on('message', (value: unknown) => {\n\t\t\t\ttry {\n\t\t\t\t\tif (\n\t\t\t\t\t\tthis.#result !== undefined ||\n\t\t\t\t\t\t!isRecord(value) ||\n\t\t\t\t\t\tBuffer.byteLength(JSON.stringify(value)) > STUDY_FRAME_BYTES\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new StudyError('FAULT', 'Adapter response is oversized or repeated')\n\t\t\t\t\tif (typeof value.error === 'string')\n\t\t\t\t\t\tthrow new StudyError(value.code === 'CONFIG' ? 'CONFIG' : 'FAULT', value.error)\n\t\t\t\t\tif (!isStudyDigest(value.instrument) || !isJSONValue(value.value))\n\t\t\t\t\t\tthrow new StudyError('FAULT', 'Adapter response is malformed')\n\t\t\t\t\tthis.#result = { instrument: value.instrument, value: value.value }\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.#failure = error\n\t\t\t\t}\n\t\t\t\tthis.#terminate(child)\n\t\t\t})\n\t\t\tfor (const stream of [child.stdout, child.stderr])\n\t\t\t\tstream?.on('data', (chunk: Buffer) => {\n\t\t\t\t\tthis.#logs += chunk.byteLength\n\t\t\t\t\tif (this.#logs <= STUDY_LOG_BYTES) return\n\t\t\t\t\tthis.#failure = new StudyError('FAULT', 'Adapter output exceeds the log allowance')\n\t\t\t\t\tthis.#terminate(child)\n\t\t\t\t})\n\t\t\tchild.once('error', (error) => {\n\t\t\t\tthis.#failure = error\n\t\t\t})\n\t\t\tchild.once('close', () => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tlisteners.abort()\n\t\t\t\tconst result = this.#result\n\t\t\t\tif (this.#failure !== undefined) reject(this.#failure)\n\t\t\t\telse if (result === undefined)\n\t\t\t\t\treject(new StudyError('FAULT', 'Adapter exited without a complete response'))\n\t\t\t\telse resolve(result)\n\t\t\t})\n\t\t\tchild.send(input, (error: Error | null) => {\n\t\t\t\tif (error === null) return\n\t\t\t\tthis.#failure = error\n\t\t\t\tthis.#terminate(child)\n\t\t\t})\n\t\t\tif (signal.aborted) {\n\t\t\t\tthis.#failure = signal.reason\n\t\t\t\tthis.#terminate(child)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Terminates the child tree; a termination failure replaces the failure that requested it.\n\t#terminate(child: ChildProcess): void {\n\t\ttry {\n\t\t\tterminateStudyChild(child)\n\t\t} catch (error) {\n\t\t\tthis.#failure = error\n\t\t}\n\t}\n}\n","import type { StudyTaskOptions, StudyTaskRequest, StudyTaskResult } from './types.js'\nimport { isRecord } from '@orkestrel/contract'\nimport { StudyError } from '../../core/errors.js'\nimport { STUDY_FRAME_BYTES, STUDY_TASK_DURATION } from './constants.js'\nimport { valueToWire } from './helpers.js'\nimport { StudyTaskChild } from './StudyTaskChild.js'\n\n/** Bounds adapter evaluation by an independent native parent timer. */\nexport class StudyTask {\n\t#options: StudyTaskOptions\n\t/** Owns the built child route and captured source selection.\n\t * @param options - Consumer root, runtime entry, adapter, and admitted dependencies.\n\t */\n\tconstructor(options: StudyTaskOptions) {\n\t\tthis.#options = structuredClone(options)\n\t}\n\t/** Executes one validation or grading operation in a fresh child.\n\t * @param request - Declarations or retained evidence, never a trial payload.\n\t * @param signal - Caller cancellation.\n\t * @returns Verified adapter output and active instrumentation identity.\n\t */\n\texecute(request: StudyTaskRequest, signal: AbortSignal): Promise<StudyTaskResult> {\n\t\tsignal.throwIfAborted()\n\t\tconst duration = this.#options.duration ?? STUDY_TASK_DURATION\n\t\tif (!Number.isSafeInteger(duration) || duration <= 0 || duration > STUDY_TASK_DURATION)\n\t\t\tthrow new StudyError('CONFIG', 'Adapter deadline must be finite and at most 60 seconds')\n\t\tconst input = valueToWire({ ...this.#options, ...request })\n\t\tif (!isRecord(input)) throw new StudyError('CONFIG', 'Adapter input must be an object')\n\t\tif (Buffer.byteLength(JSON.stringify(input)) > STUDY_FRAME_BYTES)\n\t\t\tthrow new StudyError('CONFIG', 'Adapter input exceeds the frame allowance')\n\t\t// Each call supervises its own child, so concurrent calls never share event state.\n\t\treturn new StudyTaskChild(this.#options, duration, signal).execute(input)\n\t}\n}\n","import type { JSONValue } from '@orkestrel/contract'\nimport type { StudyGrading, StudyManifest, StudyScenario } from '../../core/types.js'\nimport type { StudySealedResult } from '../stores/types.js'\nimport type {\n\tStudyCommandArtifact,\n\tStudyCommandOptions,\n\tStudyExecutionRequest,\n\tStudyGradeRequest,\n\tStudyGradingContext,\n\tStudyLabelRequest,\n\tStudyPreparation,\n\tStudyReportRequest,\n} from './types.js'\nimport { arrayOf, isArray, isString, parseJSON } from '@orkestrel/contract'\nimport { randomUUID } from 'node:crypto'\nimport { mkdir, mkdtemp, rm } from 'node:fs/promises'\nimport { isAbsolute, join, resolve } from 'node:path'\nimport { StudyError } from '../../core/errors.js'\nimport { buildStudySchedule, validateStudyInputs } from '../../core/helpers.js'\nimport {\n\tparseStudyDefinition,\n\tparseStudyGrading,\n\tparseStudyLabeling,\n\tparseStudyProfile,\n\tparseStudyRubric,\n\tparseStudyScenario,\n} from '../../core/parsers.js'\nimport { StudySeries } from '../../core/engines/StudySeries.js'\nimport { StudyArtifactLoader } from '../processes/StudyArtifactLoader.js'\nimport { StudyProcessDriver } from '../processes/StudyProcessDriver.js'\nimport { computeStudyProfileDigest, valueToWire } from '../processes/helpers.js'\nimport { decodeStudyJSON, encodeStudyJSON, hashStudyBytes } from '../helpers.js'\nimport { STUDY_CUSTODY_BYTES, STUDY_PACKET_DISCLOSURE } from '../stores/constants.js'\nimport {\n\tbuildStudyPacket,\n\tcheckStudyDirectory,\n\tcomputeStudyPacketDigest,\n\treadStudyBytes,\n\treadStudyResult,\n\ttranslateStudyPacketLabeling,\n} from '../stores/helpers.js'\nimport { StudyGradingStore } from '../stores/StudyGradingStore.js'\nimport { StudyResultStore } from '../stores/StudyResultStore.js'\nimport { StudyTask } from '../processes/StudyTask.js'\nimport { isStudyJudgment } from '../../core/validators.js'\nimport { STUDY_COMMAND_DURATION, STUDY_COMMAND_GRADER } from './constants.js'\nimport {\n\tcollectStudyEvidence,\n\tcomputeStudyCommandFingerprint,\n\tcomputeStudyFixtureDigest,\n\tcomputeStudyReport,\n\tresolveStudyPath,\n\tresolveStudyProfile,\n} from './helpers.js'\nimport { parseStudyArguments } from './parsers.js'\n\n/** Executes validated study operations with execution and grading custody kept independent. */\nexport class StudyCommand {\n\treadonly #root: string\n\treadonly #entry: string\n\n\t/**\n\t * Owns the trusted host entry and repository location without reading or writing files.\n\t * @param options - The repository root and built trusted application entry\n\t */\n\tconstructor(options: StudyCommandOptions) {\n\t\tthis.#root = resolve(options.root)\n\t\tthis.#entry = resolve(this.#root, options.entry)\n\t}\n\n\t/**\n\t * Parses command tokens once and executes their independent operation.\n\t * @param arguments_ - The exact command tokens\n\t * @param signal - The caller's execution cancellation\n\t * @returns Truthful operation metadata or a verified whole-horizon report\n\t * @throws StudyError - Thrown when arguments, declarations, identities, or custody fail\n\t */\n\tasync execute(arguments_: readonly string[], signal: AbortSignal): Promise<JSONValue> {\n\t\tconst request = parseStudyArguments(arguments_)\n\t\tsignal.throwIfAborted()\n\t\tif (request.command === 'check') return this.#check(await this.#prepare(request, signal))\n\t\tif (request.command === 'execute') return this.#execution(request, signal)\n\t\tif (request.command === 'grade') return this.#grade(request, signal)\n\t\tif (request.command === 'label') return this.#label(request, signal)\n\t\tif (request.command === 'report') return this.#report(request, signal)\n\t\tthrow new StudyError('CONFIG', 'Unsupported study operation')\n\t}\n\n\tasync #prepare(request: StudyExecutionRequest, signal: AbortSignal): Promise<StudyPreparation> {\n\t\tconst directory = resolveStudyPath(join(this.#root, 'studies'), request.target)\n\t\tconst definitionBytes = await readStudyBytes(\n\t\t\tresolveStudyPath(directory, 'study.json'),\n\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t)\n\t\tconst definition = parseStudyDefinition(decodeStudyJSON(definitionBytes))\n\t\tif (definition.name !== request.target)\n\t\t\tthrow new StudyError('CONFIG', 'Study name differs from its selected directory')\n\t\tconst bundle = resolveStudyPath(join(this.#root, 'studies'), definition.driver)\n\t\tconst steps: Array<{\n\t\t\treadonly scenario: StudyScenario\n\t\t\treadonly fixture: StudyCommandArtifact\n\t\t}> = []\n\t\tfor (const id of definition.scenarios) {\n\t\t\tsignal.throwIfAborted()\n\t\t\tconst path = `scenarios/${id}.json`\n\t\t\tconst bytes = await readStudyBytes(resolveStudyPath(bundle, path), STUDY_CUSTODY_BYTES)\n\t\t\tconst scenario = parseStudyScenario(decodeStudyJSON(bytes))\n\t\t\tif (scenario.id !== id) throw new StudyError('CONFIG', 'Scenario identity is incompatible')\n\t\t\tsteps.push({ scenario, fixture: { path, digest: hashStudyBytes(bytes) } })\n\t\t}\n\t\tconst scenarios = steps.map((step) => step.scenario)\n\t\tconst fixtures = steps.map((step) => step.fixture)\n\t\tconst profileBytes = await readStudyBytes(\n\t\t\tresolveStudyPath(bundle, `profiles/${request.profile}.json`),\n\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t)\n\t\tconst source = parseStudyProfile(decodeStudyJSON(profileBytes))\n\t\tif (source.name !== request.profile)\n\t\t\tthrow new StudyError('CONFIG', 'Profile name differs from its selected file')\n\t\tif (source.bounds.series.duration > STUDY_COMMAND_DURATION)\n\t\t\tthrow new StudyError('CONFIG', 'Series duration exceeds the 24-hour host ceiling')\n\t\tconst profile = resolveStudyProfile(this.#root, source)\n\t\tconst rubricBytes = await readStudyBytes(\n\t\t\tresolveStudyPath(directory, definition.rubric),\n\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t)\n\t\tconst rubric = parseStudyRubric(decodeStudyJSON(rubricBytes))\n\t\tvalidateStudyInputs(definition, scenarios, rubric, profile)\n\t\tif (definition.purpose === 'quality' && profile.qualification === undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Quality studies require a capacity qualification')\n\t\tsignal.throwIfAborted()\n\t\tconst artifacts = new StudyArtifactLoader({\n\t\t\troot: this.#root,\n\t\t\tentry: this.#entry,\n\t\t\tprofile,\n\t\t\tadapter: join(bundle, 'index.ts'),\n\t\t})\n\t\tconst selected = await artifacts.inspect()\n\t\tconst validation = await new StudyTask({\n\t\t\troot: this.#root,\n\t\t\tentry: this.#entry,\n\t\t\tadapter: join(bundle, 'index.ts'),\n\t\t\troots: profile.roots,\n\t\t}).execute({ operation: 'validate', input: { definition, scenarios, rubric, profile } }, signal)\n\t\tif (validation.value !== true || validation.instrument !== selected.instrument)\n\t\t\tthrow new StudyError('FAULT', 'Adapter validation identity differs')\n\t\tartifacts.verify()\n\t\treturn {\n\t\t\tdirectory: bundle,\n\t\t\tdefinition,\n\t\t\tscenarios: Object.freeze(scenarios),\n\t\t\trubric,\n\t\t\tprofile,\n\t\t\tidentity: {\n\t\t\t\t...selected,\n\t\t\t\tfixtures: computeStudyFixtureDigest(definition, fixtures),\n\t\t\t\tprofile: computeStudyProfileDigest(profile),\n\t\t\t},\n\t\t\tartifacts,\n\t\t\tsource: hashStudyBytes(profileBytes),\n\t\t}\n\t}\n\n\t#check(preparation: StudyPreparation): JSONValue {\n\t\tconst fingerprint = computeStudyCommandFingerprint(\n\t\t\tpreparation.identity,\n\t\t\tpreparation.profile.bounds,\n\t\t\tpreparation.definition,\n\t\t)\n\t\treturn valueToWire({\n\t\t\tcommand: 'check',\n\t\t\tstudy: preparation.definition.name,\n\t\t\tpurpose: preparation.definition.purpose,\n\t\t\tdriver: preparation.definition.driver,\n\t\t\tprofile: preparation.profile.name,\n\t\t\tbounds: preparation.profile.bounds,\n\t\t\tidentity: preparation.identity,\n\t\t\tprovenance: { profile: preparation.source },\n\t\t\tfingerprint,\n\t\t\tnext: [\n\t\t\t\t'execute',\n\t\t\t\tpreparation.definition.name,\n\t\t\t\t'--profile',\n\t\t\t\tpreparation.profile.name,\n\t\t\t\t'--expected',\n\t\t\t\tfingerprint,\n\t\t\t],\n\t\t\tschedule: buildStudySchedule(preparation.definition, preparation.scenarios),\n\t\t})\n\t}\n\n\tasync #execution(request: StudyExecutionRequest, signal: AbortSignal): Promise<JSONValue> {\n\t\tconst preparation = await this.#prepare(request, signal)\n\t\tconst fingerprint = computeStudyCommandFingerprint(\n\t\t\tpreparation.identity,\n\t\t\tpreparation.profile.bounds,\n\t\t\tpreparation.definition,\n\t\t)\n\t\tif (request.expected !== undefined && request.expected !== fingerprint)\n\t\t\tthrow new StudyError('CONFIG', 'Validated execution changed after the supervisor check')\n\t\tsignal.throwIfAborted()\n\t\tconst id = randomUUID()\n\t\tconst qualification = await this.#qualification(preparation)\n\t\tsignal.throwIfAborted()\n\t\tconst parent = await this.#temporary()\n\t\tsignal.throwIfAborted()\n\t\tconst directory = request.out === undefined ? join(parent, id) : this.#file(request.out)\n\t\tconst manifest: StudyManifest = {\n\t\t\tid,\n\t\t\tcreated: new Date().toISOString(),\n\t\t\tdefinition: preparation.definition,\n\t\t\tscenarios: preparation.scenarios,\n\t\t\tidentity: preparation.identity,\n\t\t\tschedule: buildStudySchedule(preparation.definition, preparation.scenarios),\n\t\t\tbounds: preparation.profile.bounds,\n\t\t\tqualification,\n\t\t\thost: {\n\t\t\t\tnode: process.version,\n\t\t\t\tplatform: process.platform,\n\t\t\t\tarchitecture: process.arch,\n\t\t\t\tprofile: preparation.source,\n\t\t\t\troots: JSON.stringify(preparation.profile.roots),\n\t\t\t},\n\t\t}\n\t\tconst store = new StudyResultStore({ directory, manifest })\n\t\tawait store.create()\n\t\tconst scratch = await mkdtemp(join(parent, 'scratch-'))\n\t\ttry {\n\t\t\tconst driver = new StudyProcessDriver({\n\t\t\t\troot: this.#root,\n\t\t\t\tentry: this.#entry,\n\t\t\t\tprofile: preparation.profile,\n\t\t\t\tidentity: preparation.identity,\n\t\t\t\tdriver: preparation.definition.driver,\n\t\t\t\tadapter: join(preparation.directory, 'index.ts'),\n\t\t\t\tdirectory: scratch,\n\t\t\t})\n\t\t\tconst attempts = await new StudySeries({ manifest, driver, store, signal }).execute()\n\t\t\tpreparation.artifacts.verify()\n\t\t\tconst seal = await store.seal()\n\t\t\treturn valueToWire({\n\t\t\t\tcommand: 'execute',\n\t\t\t\tstatus: attempts.some((attempt) => attempt.failure !== undefined)\n\t\t\t\t\t? 'operational-failure'\n\t\t\t\t\t: 'completed',\n\t\t\t\tresult: id,\n\t\t\t\tpath: directory,\n\t\t\t\tseal: seal.id,\n\t\t\t\tfingerprint,\n\t\t\t\tnext: [\n\t\t\t\t\t'grade',\n\t\t\t\t\tdirectory,\n\t\t\t\t\t'--rubric',\n\t\t\t\t\tresolveStudyPath(\n\t\t\t\t\t\tresolveStudyPath(join(this.#root, 'studies'), preparation.definition.name),\n\t\t\t\t\t\tpreparation.definition.rubric,\n\t\t\t\t\t),\n\t\t\t\t],\n\t\t\t})\n\t\t} finally {\n\t\t\tawait rm(scratch, { recursive: true, force: true, maxRetries: 3 })\n\t\t}\n\t}\n\n\tasync #grade(request: StudyGradeRequest, signal: AbortSignal): Promise<JSONValue> {\n\t\tconst result = await this.#result(request.target)\n\t\tconst bytes = await readStudyBytes(this.#file(request.rubric), STUDY_CUSTODY_BYTES)\n\t\tconst rubric = parseStudyRubric(decodeStudyJSON(bytes))\n\t\tconst evidence = await collectStudyEvidence(result)\n\t\tsignal.throwIfAborted()\n\t\tconst roots = parseJSON(result.manifest.host.roots ?? '')\n\t\tif (!arrayOf(isString)(roots))\n\t\t\tthrow new StudyError('CONFIG', 'Execution does not retain adapter dependency roots')\n\t\tconst evaluated = await new StudyTask({\n\t\t\troot: this.#root,\n\t\t\tentry: this.#entry,\n\t\t\tadapter: join(\n\t\t\t\tresolveStudyPath(join(this.#root, 'studies'), result.manifest.definition.driver),\n\t\t\t\t'index.ts',\n\t\t\t),\n\t\t\troots,\n\t\t}).execute(\n\t\t\t{\n\t\t\t\toperation: 'grade',\n\t\t\t\tinput: { manifest: result.manifest, rubric, attempts: result.attempts, evidence },\n\t\t\t},\n\t\t\tsignal,\n\t\t)\n\t\tconst judgments: unknown = evaluated.value\n\t\tif (!isArray(judgments) || !judgments.every(isStudyJudgment))\n\t\t\tthrow new StudyError('FAULT', 'Grader returned invalid judgments')\n\t\tconst digest = hashStudyBytes(bytes)\n\t\tconst packet = buildStudyPacket(result, rubric, digest)\n\t\tconst grading: StudyGrading = {\n\t\t\tresult: result.seal.id,\n\t\t\trubric: digest,\n\t\t\tgrader: STUDY_COMMAND_GRADER,\n\t\t\tinstrument: evaluated.instrument,\n\t\t\tattempts: result.manifest.schedule.map((trial) => trial.id),\n\t\t\tlabels: undefined,\n\t\t\tjudgments,\n\t\t\t...(packet === undefined ? {} : { packet: computeStudyPacketDigest(packet) }),\n\t\t}\n\t\tconst store = new StudyGradingStore({\n\t\t\tresult,\n\t\t\trubric: bytes,\n\t\t\t...(packet === undefined ? {} : { packet }),\n\t\t})\n\t\tconst id = await store.write(grading)\n\t\treturn valueToWire({\n\t\t\tcommand: 'grade',\n\t\t\tresult: result.manifest.id,\n\t\t\tgrading: id,\n\t\t\tnext: ['report', result.directory, '--grading', id],\n\t\t\t...(packet === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tpacket: {\n\t\t\t\t\t\t\tid: hashStudyBytes(packet.content),\n\t\t\t\t\t\t\tpath: join(result.directory, 'grades', id, `${grading.packet}.packet.json`),\n\t\t\t\t\t\t\tdisclosure: STUDY_PACKET_DISCLOSURE,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t})\n\t}\n\n\tasync #label(request: StudyLabelRequest, signal: AbortSignal): Promise<JSONValue> {\n\t\tconst result = await this.#result(request.target)\n\t\tconst previous = await this.#grading(result, request.grading)\n\t\tif (previous.packet === undefined || previous.grading.packet === undefined)\n\t\t\tthrow new StudyError('EVIDENCE', 'Selected grading has no semantic packet')\n\t\tconst bytes = await readStudyBytes(this.#file(request.labels), STUDY_CUSTODY_BYTES)\n\t\tconst labels = parseStudyLabeling(decodeStudyJSON(bytes))\n\t\tconst translated = translateStudyPacketLabeling(\n\t\t\tresult,\n\t\t\tprevious.rubric,\n\t\t\tprevious.grading.rubric,\n\t\t\tlabels,\n\t\t)\n\t\tsignal.throwIfAborted()\n\t\tconst grading: StudyGrading = {\n\t\t\t...previous.grading,\n\t\t\t// Binds the preceding grader so equal labels over distinct gradings stay distinct.\n\t\t\tinstrument: hashStudyBytes(\n\t\t\t\tJSON.stringify([previous.grading.instrument, await this.#instrument()]),\n\t\t\t),\n\t\t\tlabels: hashStudyBytes(bytes),\n\t\t\tjudgments: previous.grading.judgments.map((judgment) => {\n\t\t\t\tconst imported = translated.find(\n\t\t\t\t\t(entry) => entry.trial === judgment.trial && entry.criterion === judgment.criterion,\n\t\t\t\t)\n\t\t\t\tif (imported !== undefined) return imported\n\t\t\t\tif (\n\t\t\t\t\tprevious.rubric.criteria.find((criterion) => criterion.id === judgment.criterion)\n\t\t\t\t\t\t?.method !== 'semantic'\n\t\t\t\t)\n\t\t\t\t\treturn judgment\n\t\t\t\treturn {\n\t\t\t\t\t...judgment,\n\t\t\t\t\tverdict: 'unknown',\n\t\t\t\t\tmethod: 'human',\n\t\t\t\t\treason: 'No label in the selected imported packet',\n\t\t\t\t\treferences: [],\n\t\t\t\t}\n\t\t\t}),\n\t\t}\n\t\tconst store = new StudyGradingStore({\n\t\t\tresult,\n\t\t\trubric: previous.bytes,\n\t\t\tlabels: bytes,\n\t\t\tpacket: previous.packet,\n\t\t})\n\t\tconst id = await store.write(grading)\n\t\treturn valueToWire({\n\t\t\tcommand: 'label',\n\t\t\tresult: result.manifest.id,\n\t\t\tprevious: request.grading,\n\t\t\tgrading: id,\n\t\t\tpacket: labels.packet,\n\t\t\tnext: ['report', result.directory, '--grading', id],\n\t\t})\n\t}\n\n\tasync #report(request: StudyReportRequest, signal: AbortSignal): Promise<JSONValue> {\n\t\tconst result = await this.#result(request.target)\n\t\tconst context = await this.#grading(result, request.grading)\n\t\tsignal.throwIfAborted()\n\t\tconst labels =\n\t\t\tcontext.labels === undefined ? undefined : parseStudyLabeling(decodeStudyJSON(context.labels))\n\t\treturn valueToWire({\n\t\t\tcommand: 'report',\n\t\t\tgrading: request.grading,\n\t\t\treport: computeStudyReport(result, context.rubric, context.grading),\n\t\t\tlabeling:\n\t\t\t\tlabels === undefined\n\t\t\t\t\t? { status: 'absent' }\n\t\t\t\t\t: { labeler: labels.labeler, version: labels.version, usage: labels.usage },\n\t\t})\n\t}\n\n\tasync #result(target: string): Promise<StudySealedResult> {\n\t\tconst path = isAbsolute(target)\n\t\t\t? resolve(target)\n\t\t\t: target.includes('/')\n\t\t\t\t? resolveStudyPath(this.#root, target)\n\t\t\t\t: resolveStudyPath(join(this.#root, 'tmp', 'studies'), target)\n\t\tconst result = await readStudyResult(path)\n\t\tif (result.status !== 'sealed')\n\t\t\tthrow new StudyError('CUSTODY', 'Interrupted execution cannot be graded or reported')\n\t\treturn result\n\t}\n\n\tasync #grading(result: StudySealedResult, id: string): Promise<StudyGradingContext> {\n\t\tconst directory = join(result.directory, 'grades', id)\n\t\tconst raw = await readStudyBytes(join(directory, 'grading.json'), STUDY_CUSTODY_BYTES).catch(\n\t\t\t(error: unknown) => {\n\t\t\t\tif (error instanceof Error && 'code' in error && error.code === 'ENOENT')\n\t\t\t\t\tthrow new StudyError(\n\t\t\t\t\t\t'CUSTODY',\n\t\t\t\t\t\t`Selected grading is missing: ${join(directory, 'grading.json')}`,\n\t\t\t\t\t)\n\t\t\t\tthrow error\n\t\t\t},\n\t\t)\n\t\tif (hashStudyBytes(raw) !== id)\n\t\t\tthrow new StudyError('CUSTODY', 'Selected grading differs from its byte identity')\n\t\tconst declared = parseStudyGrading(decodeStudyJSON(raw))\n\t\tconst bytes = await readStudyBytes(\n\t\t\tjoin(directory, `${declared.rubric}.rubric.json`),\n\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t)\n\t\tconst rubric = parseStudyRubric(decodeStudyJSON(bytes))\n\t\tconst grading = await new StudyGradingStore({ result, rubric: bytes }).read(id)\n\t\tif (grading === undefined)\n\t\t\tthrow new StudyError('CUSTODY', `Selected grading is missing: ${directory}`)\n\t\tconst packet =\n\t\t\tgrading.packet === undefined\n\t\t\t\t? undefined\n\t\t\t\t: {\n\t\t\t\t\t\tcontent: await readStudyBytes(\n\t\t\t\t\t\t\tjoin(directory, `${grading.packet}.packet.json`),\n\t\t\t\t\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tmapping: await readStudyBytes(\n\t\t\t\t\t\t\tjoin(directory, `${grading.packet}.mapping.json`),\n\t\t\t\t\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t\t\t\t\t),\n\t\t\t\t\t}\n\t\tconst labels =\n\t\t\tgrading.labels === undefined\n\t\t\t\t? undefined\n\t\t\t\t: await readStudyBytes(\n\t\t\t\t\t\tjoin(directory, `${grading.labels}.labels.json`),\n\t\t\t\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t\t\t\t)\n\t\tif (\n\t\t\thashStudyBytes(bytes) !== grading.rubric ||\n\t\t\t(packet !== undefined && computeStudyPacketDigest(packet) !== grading.packet) ||\n\t\t\t(labels !== undefined && hashStudyBytes(labels) !== grading.labels)\n\t\t)\n\t\t\tthrow new StudyError(\n\t\t\t\t'CUSTODY',\n\t\t\t\t'Grading artifacts changed while reading their verified context',\n\t\t\t)\n\t\treturn { grading, rubric, bytes, packet, labels }\n\t}\n\n\t#file(path: string): string {\n\t\treturn isAbsolute(path) ? resolve(path) : resolveStudyPath(this.#root, path)\n\t}\n\n\t#temporary(): Promise<string> {\n\t\treturn ['tmp', 'studies'].reduce(async (previous, name) => {\n\t\t\tconst directory = join(await previous, name)\n\t\t\ttry {\n\t\t\t\tawait mkdir(directory)\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof Error && 'code' in error && error.code === 'EEXIST')) throw error\n\t\t\t}\n\t\t\treturn checkStudyDirectory(directory)\n\t\t}, checkStudyDirectory(this.#root))\n\t}\n\n\tasync #qualification(preparation: StudyPreparation): Promise<string | undefined> {\n\t\tif (\n\t\t\tpreparation.profile.qualification === undefined ||\n\t\t\tpreparation.definition.purpose === 'capacity'\n\t\t)\n\t\t\treturn undefined\n\t\tconst result = await this.#result(preparation.profile.qualification)\n\t\tif (\n\t\t\tresult.manifest.definition.purpose !== 'capacity' ||\n\t\t\thashStudyBytes(encodeStudyJSON(result.manifest.identity)) !==\n\t\t\t\thashStudyBytes(encodeStudyJSON(preparation.identity)) ||\n\t\t\thashStudyBytes(encodeStudyJSON(result.manifest.bounds)) !==\n\t\t\t\thashStudyBytes(encodeStudyJSON(preparation.profile.bounds)) ||\n\t\t\thashStudyBytes(encodeStudyJSON(result.manifest.schedule)) !==\n\t\t\t\thashStudyBytes(\n\t\t\t\t\tencodeStudyJSON(buildStudySchedule(preparation.definition, preparation.scenarios)),\n\t\t\t\t) ||\n\t\t\thashStudyBytes(encodeStudyJSON(result.manifest.scenarios)) !==\n\t\t\t\thashStudyBytes(encodeStudyJSON(preparation.scenarios)) ||\n\t\t\tresult.attempts.some(\n\t\t\t\t(attempt) =>\n\t\t\t\t\tattempt.failure !== undefined ||\n\t\t\t\t\tattempt.observations.some(\n\t\t\t\t\t\t(observation) => observation.failure !== undefined || observation.product === undefined,\n\t\t\t\t\t),\n\t\t\t)\n\t\t)\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'Qualification requires a compatible complete capacity result with no operational failures',\n\t\t\t)\n\t\treturn result.seal.id\n\t}\n\n\tasync #instrument(): Promise<string> {\n\t\treturn hashStudyBytes(await readStudyBytes(this.#entry, STUDY_CUSTODY_BYTES))\n\t}\n}\n","import type { StudyFailure, StudyTicket, StudyUsage } from '../../core/types.js'\nimport type { StudyRemoteTicketOptions } from './types.js'\nimport { StudyError } from '../../core/errors.js'\n\n/** Transmits one settlement without inventing local admission authority. */\nexport class StudyRemoteTicket implements StudyTicket {\n\t#options: StudyRemoteTicketOptions\n\t#settled = false\n\n\t/** Owns the parent's ticket identity and composed cancellation.\n\t * @param options - Transported ticket state and settlement callback, snapshotted at construction.\n\t */\n\tconstructor(options: StudyRemoteTicketOptions) {\n\t\tthis.#options = { ...options }\n\t}\n\tget signal(): AbortSignal {\n\t\treturn this.#options.signal\n\t}\n\tget settled(): boolean {\n\t\treturn this.#settled\n\t}\n\n\t/** Sends actual usage for authoritative parent settlement.\n\t * @param usage - Actual measured request usage.\n\t */\n\tfinish(usage: StudyUsage): void {\n\t\tthis.#settle('finish', usage)\n\t}\n\n\t/** Sends operational failure while preserving unknown actual cost.\n\t * @param failure - The first observed request failure.\n\t */\n\tfail(failure: StudyFailure): void {\n\t\tthis.#settle('fail', failure)\n\t}\n\n\t#settle(operation: 'finish' | 'fail', value: StudyUsage | StudyFailure): void {\n\t\tif (this.#settled) {\n\t\t\tthis.#options.settle('fail', {\n\t\t\t\tcause: 'infrastructure',\n\t\t\t\tmessage: 'Worker ticket settled more than once',\n\t\t\t\trole: undefined,\n\t\t\t\tstop: undefined,\n\t\t\t})\n\t\t\tthrow new StudyError('FAULT', 'Worker ticket settled more than once')\n\t\t}\n\t\tthis.#settled = true\n\t\tthis.#options.settle(operation, value)\n\t}\n}\n","import type { StudyCharge, StudyFailure, StudyTicket, StudyUsage } from '../../core/types.js'\nimport type { StudyRemoteMeterInterface, StudyRemoteMeterOptions } from './types.js'\nimport { isRecord } from '@orkestrel/contract'\nimport { failureToStudyError, readStudyFailure } from '../../core/engines/index.js'\nimport { StudyError } from '../../core/errors.js'\nimport { isStudyUsage } from '../../core/validators.js'\nimport { createStudyProcessFailure, valueToWire } from './helpers.js'\nimport { StudyRemoteTicket } from './StudyRemoteTicket.js'\nimport { isStudyProcessFailure } from './validators.js'\n\n/** Waits for authoritative parent admission and drains acknowledged settlements. */\nexport class StudyRemoteMeter implements StudyRemoteMeterInterface {\n\t#options: StudyRemoteMeterOptions\n\t#next = 0\n\t#admissions = 0\n\treadonly #tickets = new Map<number, AbortController>()\n\treadonly #pending = new Set<Promise<void>>()\n\t#usage: StudyUsage[] = []\n\t#closed = false\n\n\t/** Owns one goal's transported tickets without local budget decisions.\n\t * @param options - Parent transport and shared worker failure control, snapshotted at construction.\n\t */\n\tconstructor(options: StudyRemoteMeterOptions) {\n\t\tthis.#options = { ...options }\n\t}\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/** Requests and awaits the parent's dispatch grant.\n\t * @param charge - Upper bounds that the parent reserves before replying.\n\t * @returns A ticket only after authoritative admission succeeds.\n\t */\n\tasync admit(charge: StudyCharge): Promise<StudyTicket> {\n\t\tif (this.#closed || this.#options.control.failure !== undefined)\n\t\t\tthrow failureToStudyError(\n\t\t\t\tthis.#options.control.failure ?? createStudyProcessFailure('Worker meter is closed'),\n\t\t\t)\n\t\tconst id = ++this.#next\n\t\tthis.#admissions++\n\t\ttry {\n\t\t\tconst response = await this.#options.control.wait(\n\t\t\t\tthis.#options.channel.request('admit', valueToWire({ id, charge })),\n\t\t\t)\n\t\t\tif (!isRecord(response) || response.id !== id)\n\t\t\t\tthrow new StudyError('FAULT', 'Worker admission grant is invalid')\n\t\t\tif (this.#closed) throw new StudyError('FAULT', 'Worker goal ended during admission')\n\t\t\tconst controller = new AbortController()\n\t\t\tthis.#tickets.set(id, controller)\n\t\t\treturn new StudyRemoteTicket({\n\t\t\t\tid,\n\t\t\t\tsignal: AbortSignal.any([controller.signal, this.signal]),\n\t\t\t\tsettle: (operation, value) => this.#settle(id, operation, value),\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthis.#options.control.fail(readStudyFailure(error))\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tthis.#admissions--\n\t\t}\n\t}\n\n\t/** Propagates the parent's ticket cancellation without changing its cause.\n\t * @param id - Parent-issued ticket identity.\n\t * @param failure - Authoritative parent attribution.\n\t */\n\tabort(id: number, failure: StudyFailure): void {\n\t\tconst ticket = this.#tickets.get(id)\n\t\tif (ticket === undefined)\n\t\t\tthrow new StudyError('FAULT', 'Cancellation names an unknown worker ticket')\n\t\tticket.abort(failureToStudyError(failure))\n\t\tthis.#options.control.fail(failure)\n\t}\n\n\t/** Closes admission and requires every ticket and acknowledgment to finish. */\n\tasync close(): Promise<void> {\n\t\tthis.#closed = true\n\t\tif (this.#tickets.size !== 0 || this.#admissions !== 0)\n\t\t\tthis.#options.control.fail(\n\t\t\t\tcreateStudyProcessFailure('Worker goal ended with unfinished requests'),\n\t\t\t)\n\t\tawait Promise.all(this.#pending)\n\t\tif (this.#options.control.failure !== undefined)\n\t\t\tthrow failureToStudyError(this.#options.control.failure)\n\t}\n\n\t#settle(id: number, operation: 'finish' | 'fail', value: StudyUsage | StudyFailure): void {\n\t\tif (!this.#tickets.delete(id)) {\n\t\t\tthis.#options.control.fail(\n\t\t\t\tcreateStudyProcessFailure('Worker ticket settlement is repeated or foreign'),\n\t\t\t)\n\t\t\tthrow failureToStudyError(\n\t\t\t\tthis.#options.control.failure ?? createStudyProcessFailure('Worker settlement failed'),\n\t\t\t)\n\t\t}\n\t\tconst accepted = Object.freeze({ ...value })\n\t\tconst work = this.#options.channel\n\t\t\t.request(\n\t\t\t\toperation,\n\t\t\t\tvalueToWire(operation === 'finish' ? { id, usage: accepted } : { id, failure: accepted }),\n\t\t\t)\n\t\t\t.then(\n\t\t\t\t() => {\n\t\t\t\t\tif (operation === 'finish' && isStudyUsage(accepted)) this.#usage.push(accepted)\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tthis.#options.control.fail(readStudyFailure(error))\n\t\t\t\t},\n\t\t\t)\n\t\tthis.#pending.add(work)\n\t\tvoid work.finally(() => this.#pending.delete(work))\n\t\tif (operation === 'fail' && isStudyProcessFailure(accepted))\n\t\t\tthis.#options.control.fail(accepted)\n\t}\n}\n","import type { StudySessionInterface } from '../../core/types.js'\nimport type { StudyOperation } from './types.js'\nimport type { JSONValue } from '@orkestrel/contract'\nimport { isRecord } from '@orkestrel/contract'\nimport {\n\tStudyControl,\n\tStudyDeadline,\n\tfailureToStudyError,\n\treadStudyFailure,\n} from '../../core/engines/index.js'\nimport { StudyError } from '../../core/errors.js'\nimport { isStudyGoal, isStudyProduct, isStudyProfile } from '../../core/validators.js'\nimport { STUDY_PROCESS_LABEL } from './constants.js'\nimport { computeStudyProfileDigest, createStudyProcessFailure, valueToWire } from './helpers.js'\nimport { StudyArtifactLoader } from './StudyArtifactLoader.js'\nimport { StudyChannel } from './StudyChannel.js'\nimport { StudyRemoteMeter } from './StudyRemoteMeter.js'\nimport { isStudyIdentity, isStudyProcessFailure, isStudyTrial } from './validators.js'\n\n/** Executes one verified trial behind parent-authorized admission and custody. */\nexport class StudyWorker {\n\t#control = new StudyControl()\n\t#channel: StudyChannel | undefined\n\t#artifacts: StudyArtifactLoader | undefined\n\t#session: StudySessionInterface | undefined\n\treadonly #meters = new Set<StudyRemoteMeter>()\n\t#opening = false\n\t#closing = false\n\t#duration = 1000\n\t#executed = false\n\treadonly #evidence = new Set<Promise<void>>()\n\n\t/** Serves the inherited IPC channel until its parent disconnects.\n\t * @returns Completion after channel and acquired session cleanup.\n\t */\n\tasync execute(): Promise<void> {\n\t\tif (this.#executed || process.send === undefined || !process.connected)\n\t\t\tthrow new StudyError('CONFIG', 'Study worker requires one inherited IPC channel')\n\t\tthis.#executed = true\n\t\tthis.#channel = new StudyChannel({\n\t\t\tendpoint: process,\n\t\t\thandle: (operation, value) => this.#handle(operation, value),\n\t\t\tabort: (value) => this.#abort(value),\n\t\t})\n\t\ttry {\n\t\t\tawait new Promise<void>((resolve) =>\n\t\t\t\tthis.#channel?.signal.addEventListener('abort', () => resolve(), { once: true }),\n\t\t\t)\n\t\t} finally {\n\t\t\tthis.#control.fail(createStudyProcessFailure('Study worker disconnected'))\n\t\t\tif (this.#session !== undefined)\n\t\t\t\tawait new StudyDeadline({ duration: this.#duration, label: STUDY_PROCESS_LABEL })\n\t\t\t\t\t.wait(this.#session.close())\n\t\t\t\t\t.catch(() => undefined)\n\t\t\tthis.#session = undefined\n\t\t\tthis.#channel.close()\n\t\t\tthis.#control.close()\n\t\t}\n\t}\n\n\tasync #handle(operation: StudyOperation, value: JSONValue): Promise<JSONValue> {\n\t\ttry {\n\t\t\tif (operation === 'open') return await this.#open(value)\n\t\t\tif (operation === 'goal') return await this.#goal(value)\n\t\t\tif (operation === 'close') {\n\t\t\t\tif (this.#closing) throw new StudyError('FAULT', 'Worker cleanup repeated')\n\t\t\t\tthis.#closing = true\n\t\t\t\tthis.#control.fail({\n\t\t\t\t\tcause: 'interrupted',\n\t\t\t\t\tmessage: 'Worker cleanup requested',\n\t\t\t\t\trole: undefined,\n\t\t\t\t\tstop: undefined,\n\t\t\t\t})\n\t\t\t\tif (this.#session !== undefined)\n\t\t\t\t\tawait new StudyDeadline({ duration: this.#duration, label: STUDY_PROCESS_LABEL }).wait(\n\t\t\t\t\t\tthis.#session.close(),\n\t\t\t\t\t)\n\t\t\t\tthis.#session = undefined\n\t\t\t\tthis.#artifacts?.verify()\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tthrow new StudyError('FAULT', 'Parent requested a forbidden worker operation')\n\t\t} catch (error) {\n\t\t\tthis.#control.fail(readStudyFailure(error))\n\t\t\tthrow error\n\t\t}\n\t}\n\n\tasync #open(value: JSONValue): Promise<JSONValue> {\n\t\tif (this.#opening || this.#closing || this.#control.failure !== undefined)\n\t\t\tthrow new StudyError('FAULT', 'Worker trial can open only once')\n\t\tthis.#opening = true\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\ttypeof value.entry !== 'string' ||\n\t\t\ttypeof value.root !== 'string' ||\n\t\t\ttypeof value.directory !== 'string' ||\n\t\t\ttypeof value.driver !== 'string' ||\n\t\t\ttypeof value.adapter !== 'string' ||\n\t\t\t!isStudyProfile(value.profile) ||\n\t\t\t!isStudyIdentity(value.identity) ||\n\t\t\t!isStudyTrial(value.trial)\n\t\t)\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'Worker opening declaration is invalid or driver is unsupported',\n\t\t\t)\n\t\tthis.#duration = value.profile.bounds.request.duration\n\t\tthis.#artifacts = new StudyArtifactLoader({\n\t\t\tentry: value.entry,\n\t\t\troot: value.root,\n\t\t\tprofile: value.profile,\n\t\t\tadapter: value.adapter,\n\t\t})\n\t\tconst identity = await this.#artifacts.inspect()\n\t\tif (\n\t\t\tidentity.agent !== value.identity.agent ||\n\t\t\tidentity.subject !== value.identity.subject ||\n\t\t\tidentity.provider !== value.identity.provider ||\n\t\t\tidentity.instrument !== value.identity.instrument ||\n\t\t\tcomputeStudyProfileDigest(value.profile) !== value.identity.profile\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Worker artifact identity differs from parent declaration')\n\t\tconst modules = await this.#artifacts.load()\n\t\tconst adapter = await this.#artifacts.adapter()\n\t\tconst driver = adapter.driver({\n\t\t\t...modules,\n\t\t\tprofile: value.profile,\n\t\t\tdirectory: value.directory,\n\t\t})\n\t\tthis.#session = await driver.open(value.trial, this.#control.signal)\n\t\tif (this.#control.failure !== undefined) throw failureToStudyError(this.#control.failure)\n\t\treturn valueToWire({ ...identity, pid: process.pid })\n\t}\n\n\tasync #goal(value: JSONValue): Promise<JSONValue> {\n\t\tif (\n\t\t\tthis.#session === undefined ||\n\t\t\tthis.#channel === undefined ||\n\t\t\tthis.#meters.size !== 0 ||\n\t\t\tthis.#closing ||\n\t\t\tthis.#control.failure !== undefined ||\n\t\t\t!isStudyGoal(value)\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Worker goal is invalid or out of order')\n\t\tconst meter = new StudyRemoteMeter({ channel: this.#channel, control: this.#control })\n\t\tthis.#meters.add(meter)\n\t\ttry {\n\t\t\tconst product = await this.#control.wait(\n\t\t\t\tthis.#session.execute(value, {\n\t\t\t\t\tsignal: this.#control.signal,\n\t\t\t\t\tmeter,\n\t\t\t\t\tevidence: { append: (evidence) => this.#append(valueToWire(evidence)) },\n\t\t\t\t}),\n\t\t\t)\n\t\t\tawait meter.close()\n\t\t\tawait Promise.all(this.#evidence)\n\t\t\tif (this.#control.failure !== undefined) throw failureToStudyError(this.#control.failure)\n\t\t\tif (!isStudyProduct(product))\n\t\t\t\tthrow new StudyError('FAULT', 'Worker driver returned an invalid product')\n\t\t\treturn valueToWire(product)\n\t\t} finally {\n\t\t\tthis.#meters.delete(meter)\n\t\t}\n\t}\n\n\t#append(value: JSONValue): Promise<void> {\n\t\tif (\n\t\t\tthis.#channel === undefined ||\n\t\t\tthis.#meters.size === 0 ||\n\t\t\tthis.#control.failure !== undefined\n\t\t)\n\t\t\treturn Promise.reject(new StudyError('FAULT', 'Worker evidence is outside an active goal'))\n\t\tconst pending = this.#channel\n\t\t\t.request('evidence', value)\n\t\t\t.then((acknowledged) => {\n\t\t\t\tif (acknowledged !== true)\n\t\t\t\t\tthrow new StudyError('FAULT', 'Worker evidence was not acknowledged')\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tthis.#control.fail(readStudyFailure(error))\n\t\t\t\tthrow error\n\t\t\t})\n\t\tthis.#evidence.add(pending)\n\t\tvoid pending.then(\n\t\t\t() => this.#evidence.delete(pending),\n\t\t\t() => this.#evidence.delete(pending),\n\t\t)\n\t\treturn pending\n\t}\n\n\t#abort(value: JSONValue): void {\n\t\tif (!isRecord(value) || !isStudyProcessFailure(value.failure))\n\t\t\tthrow new StudyError('FAULT', 'Worker cancellation is malformed')\n\t\tif (value.id === undefined) this.#control.fail(value.failure)\n\t\telse {\n\t\t\tconst [meter] = this.#meters\n\t\t\tif (typeof value.id !== 'number' || meter === undefined)\n\t\t\t\tthrow new StudyError('FAULT', 'Worker ticket cancellation is foreign')\n\t\t\tmeter.abort(value.id, value.failure)\n\t\t}\n\t}\n}\n","import type { JSONValue } from '@orkestrel/contract'\nimport type { StudyEvidence, StudyAttempt, StudyProfile } from '../../core/types.js'\nimport type { StudyAdapterInterface } from '../adapters/types.js'\nimport { arrayOf, isArray, isRecord, isString } from '@orkestrel/contract'\nimport { dirname } from 'node:path'\nimport { isStudyError, StudyError } from '../../core/errors.js'\nimport {\n\tparseStudyDefinition,\n\tparseStudyProfile,\n\tparseStudyRubric,\n\tparseStudyScenario,\n} from '../../core/parsers.js'\nimport { isStudyJudgment } from '../../core/validators.js'\nimport { ArtifactLoader } from '../artifacts/ArtifactLoader.js'\nimport { readStudyAdapter } from '../adapters/helpers.js'\nimport { hashStudyBytes } from '../helpers.js'\nimport { STUDY_CUSTODY_BYTES } from '../stores/constants.js'\nimport { readStudyBytes } from '../stores/helpers.js'\nimport {\n\tisStudyCustodyAttempt,\n\tisStudyCustodyEvidence,\n\tisStudyCustodyManifest,\n} from '../stores/validators.js'\nimport { STUDY_FRAME_BYTES } from './constants.js'\nimport {\n\tcollectStudyEntries,\n\tcomputeStudyInstrumentDigest,\n\tresolveStudyInstrument,\n\tvalidateStudyRuntime,\n\tvalueToWire,\n} from './helpers.js'\n\n/** Evaluates only admitted instrumentation in a disposable native child. */\nexport class StudyTaskWorker {\n\t/** Processes exactly one inherited request and returns a bounded response. */\n\tasync execute(): Promise<void> {\n\t\tif (process.send === undefined || !process.connected)\n\t\t\tthrow new StudyError('CONFIG', 'Adapter worker requires inherited IPC')\n\t\tprocess.channel?.ref()\n\t\tconst value: unknown = await new Promise((resolve) => process.once('message', resolve))\n\t\tconst outcome = await this.#execute(value).catch((error: unknown): JSONValue => ({\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\tcode: isStudyError(error) ? error.code : 'FAULT',\n\t\t}))\n\t\tconst response: JSONValue =\n\t\t\tBuffer.byteLength(JSON.stringify(outcome)) > STUDY_FRAME_BYTES\n\t\t\t\t? { error: 'Adapter result exceeds the frame allowance', code: 'FAULT' }\n\t\t\t\t: outcome\n\t\tawait new Promise<void>((resolve, reject) =>\n\t\t\tprocess.send?.(response, (error: Error | null) =>\n\t\t\t\terror === null ? resolve() : reject(error),\n\t\t\t),\n\t\t)\n\t}\n\tasync #execute(value: unknown): Promise<JSONValue> {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\tBuffer.byteLength(JSON.stringify(value)) > STUDY_FRAME_BYTES ||\n\t\t\ttypeof value.adapter !== 'string' ||\n\t\t\ttypeof value.entry !== 'string' ||\n\t\t\t!arrayOf(isString)(value.roots) ||\n\t\t\t!isRecord(value.input)\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Adapter request is malformed')\n\t\tconst runtime = resolveStudyInstrument(value.entry)\n\t\tconst roots = [...new Set([...value.roots, runtime])]\n\t\tvalidateStudyRuntime(runtime, roots)\n\t\t// Validation precedes agent, subject and provider evaluation, so their selected entries stay\n\t\t// unreachable from every adapter import edge while shared admitted packages still load.\n\t\tconst profile =\n\t\t\tvalue.operation === 'validate' ? parseStudyProfile(value.input.profile) : undefined\n\t\tconst loader = new ArtifactLoader({\n\t\t\tentries: [],\n\t\t\troots,\n\t\t\tinstrument: runtime,\n\t\t\tsource: { root: dirname(value.adapter), entry: value.adapter },\n\t\t\t...(profile === undefined ? {} : { excluded: collectStudyEntries(profile) }),\n\t\t})\n\t\tconst instrument = computeStudyInstrumentDigest(\n\t\t\thashStudyBytes(await readStudyBytes(value.entry, STUDY_CUSTODY_BYTES)),\n\t\t\tloader.inspect().digest,\n\t\t)\n\t\tconst adapter = readStudyAdapter(await loader.load(value.adapter))\n\t\tif (profile === undefined && value.operation !== 'grade')\n\t\t\tthrow new StudyError('CONFIG', 'Unknown adapter operation')\n\t\tconst output: unknown =\n\t\t\tprofile === undefined\n\t\t\t\t? this.#grade(adapter, value.input)\n\t\t\t\t: this.#validate(adapter, value.input, profile)\n\t\tloader.verify()\n\t\treturn valueToWire({ instrument, value: output })\n\t}\n\n\t#validate(\n\t\tadapter: StudyAdapterInterface,\n\t\tinput: Readonly<Record<string, unknown>>,\n\t\tprofile: StudyProfile,\n\t): true {\n\t\tif (!isArray(input.scenarios)) throw new StudyError('CONFIG', 'Adapter scenarios are invalid')\n\t\tadapter.validate({\n\t\t\tdefinition: parseStudyDefinition(input.definition),\n\t\t\tscenarios: input.scenarios.map(parseStudyScenario),\n\t\t\trubric: parseStudyRubric(input.rubric),\n\t\t\tprofile,\n\t\t})\n\t\treturn true\n\t}\n\n\t#grade(adapter: StudyAdapterInterface, input: Readonly<Record<string, unknown>>): unknown {\n\t\tif (\n\t\t\t!isStudyCustodyManifest(input.manifest) ||\n\t\t\t!isArray(input.attempts) ||\n\t\t\t!isRecord(input.evidence)\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Adapter grading input is invalid')\n\t\tconst manifest = input.manifest\n\t\tconst attempts: readonly unknown[] = input.attempts\n\t\tif (\n\t\t\t!attempts.every((retained): retained is StudyAttempt =>\n\t\t\t\tisStudyCustodyAttempt(retained, manifest),\n\t\t\t)\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Adapter attempts are invalid')\n\t\tconst evidence: Record<string, readonly StudyEvidence[]> = Object.fromEntries(\n\t\t\tObject.entries(input.evidence).map(([trial, records]) => {\n\t\t\t\tif (!isArray(records) || !records.every(isStudyCustodyEvidence))\n\t\t\t\t\tthrow new StudyError('CONFIG', 'Adapter evidence is invalid')\n\t\t\t\treturn [trial, records]\n\t\t\t}),\n\t\t)\n\t\tconst output = adapter.grade({\n\t\t\tmanifest,\n\t\t\tattempts,\n\t\t\trubric: parseStudyRubric(input.rubric),\n\t\t\tevidence,\n\t\t})\n\t\tif (!isArray(output) || !output.every(isStudyJudgment))\n\t\t\tthrow new StudyError('FAULT', 'Adapter returned invalid judgments')\n\t\treturn output\n\t}\n}\n","/** Bounds each supervised operation other than execution to 60 seconds. */\nexport const STUDY_LAUNCH_DURATION = 60000\n\n/** Extends supervised execution beyond its declared series duration for cleanup. */\nexport const STUDY_LAUNCH_CLEANUP = 15000\n\n/** Bounds combined supervised command output to 16 MiB before terminating the tree. */\nexport const STUDY_LAUNCH_BYTES = 16 * 1024 * 1024\n","import type { ChildProcess } from 'node:child_process'\nimport type { StudyLaunchResult } from './types.js'\nimport { StudyError } from '../../core/errors.js'\nimport { terminateStudyChild } from '../processes/helpers.js'\nimport { STUDY_LAUNCH_BYTES } from './constants.js'\n\n/** Supervises one launched command child until it closes under its output allowance and deadline. */\nexport class StudyLaunchChild {\n\treadonly #child: ChildProcess\n\treadonly #duration: number\n\treadonly #forward: boolean\n\treadonly #signal: AbortSignal\n\treadonly #chunks: Buffer[] = []\n\t#bytes = 0\n\t#failure: Error | undefined\n\t#expired = false\n\t#executed = false\n\n\t/** Binds one spawned child to its deadline, output route and the launcher's interruption.\n\t * @param child - The spawned child; `execute` subscribes before any of its events can fire.\n\t * @param duration - The deadline in milliseconds.\n\t * @param forward - If `true`, stdout is forwarded to this process; if `false`, it is captured as the result output.\n\t * @param signal - The launcher's interruption; an abort terminates the child and reports 130.\n\t */\n\tconstructor(child: ChildProcess, duration: number, forward: boolean, signal: AbortSignal) {\n\t\tthis.#child = child\n\t\tthis.#duration = duration\n\t\tthis.#forward = forward\n\t\tthis.#signal = signal\n\t}\n\n\t/** Waits for the child to close and reports its exit code and captured output.\n\t * @returns The child's code, 130 after interruption or 124 after the deadline, with captured stdout.\n\t * @throws StudyError - Thrown with code `CONFIG` when this child is already supervised.\n\t */\n\texecute(): Promise<StudyLaunchResult> {\n\t\tif (this.#executed) throw new StudyError('CONFIG', 'Study launch can execute only once')\n\t\tthis.#executed = true\n\t\tconst child = this.#child\n\t\tconst signal = this.#signal\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst listeners = new AbortController()\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.#expired = true\n\t\t\t\tterminateStudyChild(child)\n\t\t\t}, this.#duration)\n\t\t\tsignal.addEventListener('abort', () => terminateStudyChild(child), {\n\t\t\t\tonce: true,\n\t\t\t\tsignal: listeners.signal,\n\t\t\t})\n\t\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\t\tif (!this.#measure(chunk)) return\n\t\t\t\tif (this.#forward) process.stdout.write(chunk)\n\t\t\t\telse this.#chunks.push(chunk)\n\t\t\t})\n\t\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\t\tif (this.#measure(chunk)) process.stderr.write(chunk)\n\t\t\t})\n\t\t\tchild.once('error', (error) => {\n\t\t\t\tthis.#failure ??= error\n\t\t\t})\n\t\t\tchild.once('close', (code) => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tlisteners.abort()\n\t\t\t\tif (this.#failure !== undefined) {\n\t\t\t\t\treject(this.#failure)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (this.#expired)\n\t\t\t\t\tprocess.stderr.write(\n\t\t\t\t\t\t`study: DEADLINE: Process tree exceeded its ${this.#duration} ms deadline\\n`,\n\t\t\t\t\t)\n\t\t\t\tresolve({\n\t\t\t\t\tcode: signal.aborted ? 130 : this.#expired ? 124 : (code ?? 1),\n\t\t\t\t\toutput: Buffer.concat(this.#chunks).toString('utf8'),\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (signal.aborted) terminateStudyChild(child)\n\t\t})\n\t}\n\n\t// Counts a chunk against the shared stdout and stderr allowance; an overflow retains the failure and terminates the tree.\n\t#measure(chunk: Buffer): boolean {\n\t\tthis.#bytes += chunk.byteLength\n\t\tif (this.#bytes <= STUDY_LAUNCH_BYTES) return true\n\t\tthis.#failure ??= new Error('Study command output exceeds the 16 MiB host allowance')\n\t\tterminateStudyChild(this.#child)\n\t\treturn false\n\t}\n}\n","import type { StudyLaunchOptions, StudyLaunchResult } from './types.js'\nimport { isRecord } from '@orkestrel/contract'\nimport { spawn } from 'node:child_process'\nimport { StudyError } from '../../core/errors.js'\nimport { isStudyBounds, isStudyDigest } from '../../core/validators.js'\nimport { STUDY_COMMAND_DURATION } from '../commands/constants.js'\nimport { parseStudyArguments } from '../commands/parsers.js'\nimport { STUDY_COMMAND_OPERATION } from '../processes/constants.js'\nimport { STUDY_LAUNCH_CLEANUP, STUDY_LAUNCH_DURATION } from './constants.js'\nimport { StudyLaunchChild } from './StudyLaunchChild.js'\n\n/** Supervises finite command trees and binds offline check to execution. */\nexport class StudyLauncher {\n\treadonly #root: string\n\treadonly #entry: string\n\treadonly #interruption = new AbortController()\n\treadonly #signal: () => void\n\n\t/** Owns the trusted runtime entry and caller working directory.\n\t * @param options - Native entry and consumer root.\n\t */\n\tconstructor(options: StudyLaunchOptions) {\n\t\tthis.#root = options.root\n\t\tthis.#entry = options.entry\n\t\tthis.#signal = this.#interruption.abort.bind(this.#interruption)\n\t}\n\n\t/** Checks and supervises the requested command under its finite native allowance.\n\t * @param arguments_ - Public command tokens.\n\t * @returns The exact operational or supervisor exit code.\n\t */\n\tasync execute(arguments_: readonly string[]): Promise<number> {\n\t\tconst entry = this.#entry\n\t\tconst request = parseStudyArguments(arguments_)\n\t\tprocess.on('SIGINT', this.#signal)\n\t\tprocess.on('SIGTERM', this.#signal)\n\t\ttry {\n\t\t\tif (request.command !== 'execute') {\n\t\t\t\tif (this.#interruption.signal.aborted) return 130\n\t\t\t\treturn (await this.#launch(entry, arguments_, STUDY_LAUNCH_DURATION, true)).code\n\t\t\t}\n\t\t\tconst check = ['check', request.target, '--profile', request.profile]\n\t\t\tconst reading = await this.#launch(entry, check, STUDY_LAUNCH_DURATION, false)\n\t\t\tif (reading.code !== 0) {\n\t\t\t\tprocess.stdout.write(reading.output)\n\t\t\t\treturn reading.code\n\t\t\t}\n\t\t\tconst value: unknown = JSON.parse(reading.output)\n\t\t\tif (\n\t\t\t\t!isRecord(value) ||\n\t\t\t\t!isStudyBounds(value.bounds) ||\n\t\t\t\tvalue.bounds.series.duration > STUDY_COMMAND_DURATION\n\t\t\t)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Study execution requires a validated series duration within the 24-hour host ceiling',\n\t\t\t\t)\n\t\t\tif (!isStudyDigest(value.fingerprint))\n\t\t\t\tthrow new Error('Study check did not return an execution fingerprint')\n\t\t\tconst duration = value.bounds.series.duration + STUDY_LAUNCH_CLEANUP\n\t\t\tif (request.expected !== undefined && request.expected !== value.fingerprint)\n\t\t\t\tthrow new StudyError('CONFIG', 'Validated execution differs from the requested fingerprint')\n\t\t\tconst execution = [\n\t\t\t\t'execute',\n\t\t\t\trequest.target,\n\t\t\t\t'--profile',\n\t\t\t\trequest.profile,\n\t\t\t\t...(request.out === undefined ? [] : ['--out', request.out]),\n\t\t\t\t'--expected',\n\t\t\t\tvalue.fingerprint,\n\t\t\t]\n\t\t\tif (this.#interruption.signal.aborted) return 130\n\t\t\treturn (await this.#launch(entry, execution, duration, true)).code\n\t\t} finally {\n\t\t\tprocess.removeListener('SIGINT', this.#signal)\n\t\t\tprocess.removeListener('SIGTERM', this.#signal)\n\t\t}\n\t}\n\n\t// Spawns one command child; its own entity supervises the deadline, output allowance and interruption.\n\t#launch(\n\t\tentry: string,\n\t\targuments_: readonly string[],\n\t\tduration: number,\n\t\tforward: boolean,\n\t): Promise<StudyLaunchResult> {\n\t\tconst child = spawn(\n\t\t\tprocess.execPath,\n\t\t\t[...process.execArgv, entry, STUDY_COMMAND_OPERATION, ...arguments_],\n\t\t\t{\n\t\t\t\tcwd: this.#root,\n\t\t\t\tshell: false,\n\t\t\t\twindowsHide: true,\n\t\t\t\tdetached: process.platform !== 'win32',\n\t\t\t\tstdio: ['ignore', 'pipe', 'pipe', 'ipc'],\n\t\t\t},\n\t\t)\n\t\treturn new StudyLaunchChild(child, duration, forward, this.#interruption.signal).execute()\n\t}\n}\n","import type { StudyLaunchOptions } from './types.js'\nimport { isRecord } from '@orkestrel/contract'\nimport { StudyError } from '../../core/errors.js'\nimport { StudyCommand } from '../commands/StudyCommand.js'\nimport { STUDY_COMMAND_HELP } from '../commands/constants.js'\nimport {\n\tSTUDY_COMMAND_OPERATION,\n\tSTUDY_TASK_OPERATION,\n\tSTUDY_WORKER_OPERATION,\n} from '../processes/constants.js'\nimport { StudyTaskWorker } from '../processes/StudyTaskWorker.js'\nimport { StudyWorker } from '../processes/StudyWorker.js'\nimport { StudyLauncher } from './StudyLauncher.js'\n\n/** Dispatches private child routes before the public native supervisor. */\nexport class StudyCLI {\n\t#options: StudyLaunchOptions\n\t/** Owns the installed executable path and consumer working directory.\n\t * @param options - Exact runtime entry and consumer root, snapshotted at construction.\n\t */\n\tconstructor(options: StudyLaunchOptions) {\n\t\tthis.#options = { ...options }\n\t}\n\t/** Executes one route with truthful public exit semantics.\n\t * @param arguments_ - Native command arguments.\n\t * @returns The command, deadline, interruption, or invalid-input exit code.\n\t */\n\tasync execute(arguments_: readonly string[]): Promise<number> {\n\t\ttry {\n\t\t\tif (\n\t\t\t\t[STUDY_COMMAND_OPERATION, STUDY_WORKER_OPERATION, STUDY_TASK_OPERATION].includes(\n\t\t\t\t\targuments_[0] ?? '',\n\t\t\t\t) &&\n\t\t\t\t(process.send === undefined || !process.connected)\n\t\t\t)\n\t\t\t\tthrow new StudyError(\n\t\t\t\t\t'CONFIG',\n\t\t\t\t\t`Private route ${JSON.stringify(arguments_[0])} requires supervised native IPC; use study check, execute, grade, label, or report. Use study --help for grammar.`,\n\t\t\t\t)\n\t\t\tif (arguments_[0] === STUDY_WORKER_OPERATION) {\n\t\t\t\tawait new StudyWorker().execute()\n\t\t\t\treturn 0\n\t\t\t}\n\t\t\tif (arguments_[0] === STUDY_TASK_OPERATION) {\n\t\t\t\tawait new StudyTaskWorker().execute()\n\t\t\t\treturn 0\n\t\t\t}\n\t\t\tif (arguments_[0] !== STUDY_COMMAND_OPERATION) {\n\t\t\t\tif (arguments_.includes('--help')) {\n\t\t\t\t\tprocess.stdout.write(STUDY_COMMAND_HELP)\n\t\t\t\t\treturn 0\n\t\t\t\t}\n\t\t\t\tif (arguments_.length === 0) {\n\t\t\t\t\tprocess.stderr.write(STUDY_COMMAND_HELP)\n\t\t\t\t\treturn 64\n\t\t\t\t}\n\t\t\t\treturn await new StudyLauncher(this.#options).execute(arguments_)\n\t\t\t}\n\t\t\tconst controller = new AbortController()\n\t\t\tconst listener = controller.abort.bind(controller)\n\t\t\tprocess.once('SIGINT', listener)\n\t\t\tprocess.once('SIGTERM', listener)\n\t\t\ttry {\n\t\t\t\tconst result = await new StudyCommand(this.#options).execute(\n\t\t\t\t\targuments_.slice(1),\n\t\t\t\t\tcontroller.signal,\n\t\t\t\t)\n\t\t\t\tprocess.stdout.write(`${JSON.stringify(result)}\\n`)\n\t\t\t\treturn controller.signal.aborted\n\t\t\t\t\t? 130\n\t\t\t\t\t: isRecord(result) && result.status === 'operational-failure'\n\t\t\t\t\t\t? 1\n\t\t\t\t\t\t: 0\n\t\t\t} finally {\n\t\t\t\tprocess.removeListener('SIGINT', listener)\n\t\t\t\tprocess.removeListener('SIGTERM', listener)\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code =\n\t\t\t\terror instanceof Error && 'code' in error && typeof error.code === 'string'\n\t\t\t\t\t? error.code\n\t\t\t\t\t: 'FAULT'\n\t\t\tprocess.stderr.write(\n\t\t\t\t`study: ${code}: ${error instanceof Error ? error.message : String(error)}\\n`,\n\t\t\t)\n\t\t\treturn error instanceof StudyError\n\t\t\t\t? error.code === 'CONFIG'\n\t\t\t\t\t? 64\n\t\t\t\t\t: error.failure?.cause === 'deadline'\n\t\t\t\t\t\t? 124\n\t\t\t\t\t\t: error.failure?.cause === 'interrupted'\n\t\t\t\t\t\t\t? 130\n\t\t\t\t\t\t\t: 1\n\t\t\t\t: 1\n\t\t}\n\t}\n}\n","import type { ProviderDelta, ProviderRequest, ProviderResult } from '@orkestrel/agent'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type { StudyAgentResponse } from './types.js'\nimport { attempt, canonicalStringify, isArray, isObject, isRecord } from '@orkestrel/contract'\nimport { StudyError } from '../../core/errors.js'\nimport { hashStudyBytes } from '../helpers.js'\n\n/**\n * Builds a request revision by hashing its canonical rendering exactly as rendered.\n * @remarks\n * The request is rendered once with key-sorted canonical JSON and hashed as rendered; no\n * newline or JSON round trip is added. Any change to content, order, ids, tools, or options\n * changes the revision.\n * @param request - The exact pre-encoding request\n * @returns The lowercase SHA-256 digest, or undefined when the request cannot be canonically rendered; a rendering failure never throws\n */\nexport function buildStudyAgentRevision(request: ProviderRequest): string | undefined {\n\tconst rendered = attempt(() => canonicalStringify(request))\n\tif (!rendered.success || rendered.value === undefined) return undefined\n\treturn hashStudyBytes(rendered.value)\n}\n\n/**\n * Builds the JSON evidence form of a Ledger result's logical classifier readings.\n * @param result - Value returned by the Ledger\n * @returns Null when the result carries no readings array, else one entry per well-formed reading in asking order, each with its duration or null\n */\nexport function buildStudyAgentReadings(result: unknown): JSONValue {\n\tif (!isObject(result) || !('readings' in result) || !isArray(result.readings)) return null\n\treturn result.readings.flatMap((entry): JSONValue[] =>\n\t\t!isObject(entry) ||\n\t\t!('key' in entry) ||\n\t\ttypeof entry.key !== 'string' ||\n\t\t!('phase' in entry) ||\n\t\ttypeof entry.phase !== 'string' ||\n\t\t!('outcome' in entry) ||\n\t\ttypeof entry.outcome !== 'string'\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t{\n\t\t\t\t\t\tkey: entry.key,\n\t\t\t\t\t\tphase: entry.phase,\n\t\t\t\t\t\toutcome: entry.outcome,\n\t\t\t\t\t\tduration:\n\t\t\t\t\t\t\t'duration' in entry && typeof entry.duration === 'number' ? entry.duration : null,\n\t\t\t\t\t},\n\t\t\t\t],\n\t)\n}\n\n/**\n * Resolves the content a scripted response serves, from its declaration or from a prior tool message.\n * @param request - The projected actual request messages\n * @param response - The declared response being served\n * @returns The declared content, or the content of the actual tool message the response consumes\n * @throws StudyError - Thrown when a consuming response has no actual referenced tool result\n */\nexport function resolveStudyAgentContent(\n\trequest: readonly JSONValue[],\n\tresponse: StudyAgentResponse,\n): string {\n\tif (response.consume === undefined) return response.content\n\tconst prior = request.findLast(\n\t\t(message) => isRecord(message) && message.role === 'tool' && message.call === response.consume,\n\t)\n\tif (!isRecord(prior) || typeof prior.content !== 'string')\n\t\tthrow new StudyError('FAULT', 'Continuation has no actual referenced tool result')\n\treturn prior.content\n}\n\n/**\n * Drains a scripted provider stream into its assembled result.\n * @param stream - The provider stream to consume to its end\n * @returns The result the stream returns after its last delta\n */\nexport async function readStudyAgentResult(\n\tstream: AsyncGenerator<ProviderDelta, ProviderResult>,\n): Promise<ProviderResult> {\n\tfor (;;) {\n\t\tconst next = await stream.next()\n\t\tif (next.done) return next.value\n\t}\n}\n\n/**\n * Projects foreign provider messages onto the exact fields the workload reads.\n * @param value - The foreign provider message collection\n * @returns Owned JSON message readings in original order\n * @throws StudyError - Thrown when a dereferenced foreign member is malformed\n * @example\n * ```ts\n * readStudyAgentMessages([{ id: 'm1', role: 'user', content: 'Hi' }]) // [{ role: 'user', content: 'Hi' }]\n * ```\n */\nexport function readStudyAgentMessages(value: unknown): readonly JSONValue[] {\n\tif (!isArray(value)) throw new StudyError('FAULT', 'Provider messages are not an array')\n\treturn Object.freeze(\n\t\tArray.from(value).map((message): JSONValue => {\n\t\t\tif (!isObject(message)) throw new StudyError('FAULT', 'Provider message fields are invalid')\n\t\t\tconst role = 'role' in message ? message.role : undefined\n\t\t\tconst content = 'content' in message ? message.content : undefined\n\t\t\tconst call = 'call' in message ? message.call : undefined\n\t\t\tif (\n\t\t\t\ttypeof role !== 'string' ||\n\t\t\t\ttypeof content !== 'string' ||\n\t\t\t\t(call !== undefined && typeof call !== 'string')\n\t\t\t)\n\t\t\t\tthrow new StudyError('FAULT', 'Provider message fields are invalid')\n\t\t\treturn Object.freeze({\n\t\t\t\trole,\n\t\t\t\tcontent,\n\t\t\t\t...(call === undefined ? {} : { call }),\n\t\t\t})\n\t\t}),\n\t)\n}\n","import type { StudyAgentResponse } from './types.js'\nimport { holds, isArray, isJSONValue, isRecord } from '@orkestrel/contract'\nimport { isToolCall } from '@orkestrel/tool'\nimport { matchesStudyKeys } from '../../core/helpers.js'\n\n/**\n * Checks whether a scripted response has JSON calls and workload controls.\n * @remarks\n * The guard accepts exact own data keys: `content` and `calls` are required; `consume`, `abort`,\n * `tokens`, `bytes` and `truncated` are optional. Each call must satisfy the Tool package's call\n * guard and carry JSON arguments. The guard sets no size limit on content, calls or `consume`; a\n * consumer composes its own workload bounds. A throwing accessor returns false.\n * @param value - The candidate response\n * @returns True if every declared response member is valid; false otherwise\n * @example\n * ```ts\n * isStudyAgentResponse({ content: 'done', calls: [] }) // true\n * ```\n */\nexport function isStudyAgentResponse(value: unknown): value is StudyAgentResponse {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(\n\t\t\t\tvalue,\n\t\t\t\t['content', 'calls'],\n\t\t\t\t['consume', 'abort', 'tokens', 'bytes', 'truncated'],\n\t\t\t) &&\n\t\t\ttypeof value.content === 'string' &&\n\t\t\tisArray(value.calls) &&\n\t\t\tvalue.calls.every(isToolCall) &&\n\t\t\tisJSONValue(value.calls) &&\n\t\t\t(value.consume === undefined ||\n\t\t\t\t(typeof value.consume === 'string' && value.consume.length > 0)) &&\n\t\t\t(value.abort === undefined || typeof value.abort === 'boolean') &&\n\t\t\t(value.truncated === undefined || typeof value.truncated === 'boolean') &&\n\t\t\t['tokens', 'bytes'].every(\n\t\t\t\t(key) =>\n\t\t\t\t\tvalue[key] === undefined ||\n\t\t\t\t\t(typeof value[key] === 'number' && Number.isSafeInteger(value[key]) && value[key] >= 0),\n\t\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 { JSONValue } from '@orkestrel/contract'\nimport type { StudyEvidence } from '../../core/types.js'\nimport type { StudyAgentStamp } from './types.js'\n\n/** Holds one goal's retained trace rows, its latest admission and its last refused identity. */\nexport class StudyAgentTraceGoal {\n\treadonly #goal: string\n\treadonly #rows: StudyEvidence[] = []\n\t#admission: StudyAgentStamp | undefined\n\t#refused: unknown\n\n\t/** Binds the rows that follow to one goal.\n\t * @param goal - The goal whose rows follow.\n\t */\n\tconstructor(goal: string) {\n\t\tthis.#goal = goal\n\t}\n\n\t/** Reports the goal the rows belong to. */\n\tget goal(): string {\n\t\treturn this.#goal\n\t}\n\n\t/** Reports every row retained so far; the same live view for the goal's whole life, which sees each row retained later. */\n\tget rows(): readonly StudyEvidence[] {\n\t\treturn this.#rows\n\t}\n\n\t/** Reports the goal's latest admission stamp; undefined before one, or when the latest was not observed. */\n\tget admission(): StudyAgentStamp | undefined {\n\t\treturn this.#admission\n\t}\n\n\t/** Retains one row for the goal.\n\t * @param event - The evidence event name.\n\t * @param value - The JSON evidence value.\n\t */\n\tappend(event: string, value: JSONValue): void {\n\t\tthis.#rows.push({ event, goal: this.#goal, value })\n\t}\n\n\t/** Retains the goal's latest admission stamp.\n\t * @param stamp - The admission measurement's stamp; undefined when it was not observed.\n\t */\n\tadmit(stamp: StudyAgentStamp | undefined): void {\n\t\tthis.#admission = stamp\n\t}\n\n\t/** Latches a refused failure identity.\n\t * @param error - The refused value.\n\t * @returns True if it differs from the last refused identity; false otherwise.\n\t */\n\trefuse(error: unknown): boolean {\n\t\tif (this.#refused === error) return false\n\t\tthis.#refused = error\n\t\treturn true\n\t}\n}\n","import type { LedgerGauge, ProviderRequest } from '@orkestrel/agent'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type { StudySinkInterface } from '../../core/types.js'\nimport type { StudyAgentDispatch, StudyAgentReading } from '../../core/agents/types.js'\nimport type {\n\tStudyAgentRole,\n\tStudyAgentStage,\n\tStudyAgentStamp,\n\tStudyAgentTraceOptions,\n} from './types.js'\nimport {\n\tbuildStudyAgentParts,\n\tprojectStudyAgentRequest,\n\ttranslateStudyAgentError,\n} from '../../core/agents/helpers.js'\nimport { StudyError } from '../../core/errors.js'\nimport { buildStudyAgentRevision } from './helpers.js'\nimport { StudyAgentTraceGoal } from './StudyAgentTraceGoal.js'\n\n/** Correlates measured Agent requests and retains their evidence across a trial's goals. */\nexport class StudyAgentTrace {\n\treadonly #options: StudyAgentTraceOptions\n\t// Dispatch identities per role; one current dispatch cannot be overtaken by another of its role\n\t// because the consumer awaits each request before the next of that role.\n\t// Each dispatch replaces the map, so a reader never sees one change in place.\n\t#slots: ReadonlyMap<StudyAgentRole, StudyAgentDispatch> = new Map()\n\t// The goal in flight; `start` binds it and its flush releases it when it settles.\n\t#goal: StudyAgentTraceGoal | undefined\n\t// The goals being flushed; a goal joins when its flush starts and leaves when the flush settles.\n\treadonly #flushes = new Set<StudyAgentTraceGoal>()\n\t#ordinal = 0\n\t#dispatches = 0\n\n\t/** Binds the measuring runtime, the failure owner and the consumer origin join.\n\t * @param options - Runtime, latch, observation switch and origin handler.\n\t */\n\tconstructor(options: StudyAgentTraceOptions) {\n\t\tthis.#options = { ...options }\n\t}\n\n\t/** Reports the active goal; undefined between goals. */\n\tget goal(): string | undefined {\n\t\treturn this.#goal?.goal\n\t}\n\n\t/** Begins a goal's rows. Ordinals, dispatch numbers and role identities continue from earlier goals.\n\t * @param goal - The goal whose rows follow.\n\t * @throws StudyError - Thrown with code `CONFIG` when a goal is already active; the active goal and its rows stay unchanged.\n\t */\n\tstart(goal: string): void {\n\t\tif (this.#goal !== undefined) throw new StudyError('CONFIG', 'Trace goal is already active')\n\t\tthis.#goal = new StudyAgentTraceGoal(goal)\n\t}\n\n\t/** Retains one domain row for the active goal, whether or not observation is enabled; a row outside a goal is dropped.\n\t * @param event - The evidence event name.\n\t * @param value - The JSON evidence value.\n\t */\n\tappend(event: string, value: JSONValue): void {\n\t\tthis.#goal?.append(event, value)\n\t}\n\n\t/** Appends the retained rows in order, including rows added during the flush, and ends the goal even when custody refuses a row.\n\t * @param evidence - The sink that takes custody of each row.\n\t * @returns Completion after every row is appended; immediately when no goal is active.\n\t * @throws StudyError - Thrown with code `CONFIG` when another flush is pending; the pending flush is untouched.\n\t */\n\tasync flush(evidence: StudySinkInterface): Promise<void> {\n\t\tconst running = this.#goal\n\t\tif (running === undefined) return\n\t\tif (this.#flushes.size !== 0) throw new StudyError('CONFIG', 'Trace flush is already pending')\n\t\t// The goal joins the registry before the sink can run, so a sink that re-enters `flush` meets it.\n\t\tthis.#flushes.add(running)\n\t\ttry {\n\t\t\tfor (const row of running.rows) await evidence.append(row)\n\t\t} finally {\n\t\t\tthis.#goal = undefined\n\t\t\tthis.#flushes.delete(running)\n\t\t}\n\t}\n\n\t/** Prices a window measurement and, when observing, retains it as the goal's admission.\n\t * @param request - The measured request.\n\t * @param gauge - The explicit gauge pricing the estimate.\n\t * @returns The projected prompt tokens.\n\t */\n\tadmit(request: ProviderRequest, gauge: LedgerGauge): number {\n\t\tconst estimate = this.#options.runtime.estimateRequest(request)\n\t\tconst projected = projectStudyAgentRequest(gauge, estimate)\n\t\tconst stamp = this.measure('admission', 'agent', request, { estimate, projected }, undefined)\n\t\tthis.#goal?.admit(stamp)\n\t\treturn projected\n\t}\n\n\t/** Retains a dispatching agent request's reading, names it for the wire request that follows, and records its estimate.\n\t * @param reading - The explicit size reading.\n\t * @param request - The exact pre-encoding request.\n\t */\n\trecord(reading: StudyAgentReading, request: ProviderRequest): void {\n\t\tconst goal = this.#observed()\n\t\tif (goal === undefined) return\n\t\tconst dispatch = this.#number('agent', request, reading)\n\t\tgoal.append('estimate', {\n\t\t\testimate: reading.estimate,\n\t\t\tprojected: reading.projected ?? null,\n\t\t\trevision: dispatch.revision ?? null,\n\t\t\tdispatch: dispatch.id,\n\t\t})\n\t}\n\n\t/** Takes one synchronous measurement row; the goal's flush appends it, failure included.\n\t * @param stage - Where the measurement was taken.\n\t * @param role - The responsibility whose request was measured.\n\t * @param request - The exact pre-encoding request.\n\t * @param reading - The explicit size reading.\n\t * @param dispatch - The dispatch number the request received; undefined for an admission.\n\t * @returns The ordinal and revision; undefined when not observing.\n\t */\n\tmeasure(\n\t\tstage: StudyAgentStage,\n\t\trole: StudyAgentRole,\n\t\trequest: ProviderRequest,\n\t\treading: StudyAgentReading,\n\t\tdispatch: number | undefined,\n\t): StudyAgentStamp | undefined {\n\t\tconst goal = this.#observed()\n\t\tif (goal === undefined) return undefined\n\t\tconst ordinal = ++this.#ordinal\n\t\tconst revision = buildStudyAgentRevision(request) ?? null\n\t\tgoal.append('context', {\n\t\t\tstage,\n\t\t\trole,\n\t\t\tordinal,\n\t\t\trevision,\n\t\t\testimate: reading.estimate,\n\t\t\tprojected: reading.projected ?? null,\n\t\t\t...(dispatch === undefined ? {} : { dispatch }),\n\t\t\tparts: buildStudyAgentParts(this.#options.runtime.measureRequest(request)),\n\t\t\torigins: this.#options.origins(request.messages),\n\t\t})\n\t\treturn { ordinal, revision }\n\t}\n\n\t/** Numbers a request about to be dispatched and retains it as its role's current dispatch; does nothing unless observing.\n\t * @param role - The responsibility dispatching.\n\t * @param request - The exact pre-encoding request.\n\t * @param reading - The explicit size reading.\n\t */\n\tdispatch(role: StudyAgentRole, request: ProviderRequest, reading: StudyAgentReading): void {\n\t\tif (this.#observed() === undefined) return\n\t\tthis.#number(role, request, reading)\n\t}\n\n\t/** Reads the role's current dispatch identity for the wire request that follows it.\n\t * @param role - The responsibility dispatching.\n\t * @returns The dispatch id and revision; undefined before any observed dispatch of the role.\n\t */\n\tcanonical(role: StudyAgentRole): StudyAgentDispatch | undefined {\n\t\treturn this.#slots.get(role)\n\t}\n\n\t/** Latches the study-level reading of a failure before an enclosing runtime can swallow it and retains one refusal row per refused identity in a goal.\n\t * @param error - The caught or reported value.\n\t * @returns The translated failure, or the same value when it is not an Agent window refusal.\n\t */\n\ttranslate(error: unknown): unknown {\n\t\tconst translated = translateStudyAgentError(error, this.#options.runtime)\n\t\tthis.#refuse(error, translated)\n\t\tthis.#options.latch.fail(translated)\n\t\treturn translated\n\t}\n\n\t// Reads the active goal only while observation is enabled.\n\t#observed(): StudyAgentTraceGoal | undefined {\n\t\treturn this.#options.observe ? this.#goal : undefined\n\t}\n\n\t// Numbers the dispatch, retains its context row and makes it the role's current identity.\n\t#number(\n\t\trole: StudyAgentRole,\n\t\trequest: ProviderRequest,\n\t\treading: StudyAgentReading,\n\t): StudyAgentDispatch {\n\t\tconst id = ++this.#dispatches\n\t\tconst stamp = this.measure('dispatch', role, request, reading, id)\n\t\tconst dispatch = Object.freeze({ id, revision: stamp?.revision ?? undefined })\n\t\tthis.#slots = new Map([...this.#slots, [role, dispatch]])\n\t\treturn dispatch\n\t}\n\n\t// Retains one refusal row per refused error identity in a goal, however many callbacks it traverses.\n\t#refuse(error: unknown, translated: unknown): void {\n\t\tconst goal = this.#observed()\n\t\tif (translated === error || goal === undefined || !goal.refuse(error)) return\n\t\tconst context = this.#options.runtime.isAgentError(error) ? error.context : undefined\n\t\tgoal.append('refusal', {\n\t\t\tcause: 'capacity',\n\t\t\trole: 'agent',\n\t\t\tordinal: goal.admission?.ordinal ?? null,\n\t\t\trevision: goal.admission?.revision ?? null,\n\t\t\tconsumed: typeof context?.consumed === 'number' ? context.consumed : null,\n\t\t\tmax: typeof context?.max === 'number' ? context.max : null,\n\t\t})\n\t}\n}\n","import type { Message, ProviderRequest } from '@orkestrel/agent'\nimport type { StudyAgentSummaryOptions } from './types.js'\nimport { cloneJSONValue, isFiniteNumber, isJSONValue } from '@orkestrel/contract'\nimport { StudyError } from '../../core/errors.js'\nimport { projectStudyAgentRequest, validateStudyAgentUsage } from '../../core/agents/helpers.js'\n\n/** Folds a conversation through the real provider under an explicit gauge and prompt limit. */\nexport class StudyAgentSummary {\n\treadonly #options: StudyAgentSummaryOptions\n\n\t/** Binds the provider, the measuring trace, the gauge, the limit and the consumer's instruction.\n\t * @param options - Delegate, measurement seam, limits and cancellation.\n\t * @throws StudyError - Thrown with code `CONFIG` when the limit is not a positive safe integer, or the gauge scale is not finite and greater than 0 or its overhead is not finite and at least 0.\n\t */\n\tconstructor(options: StudyAgentSummaryOptions) {\n\t\t// The gauge is copied after validation, so later mutation of the caller's object cannot bypass the bound.\n\t\tconst { limit } = options\n\t\tconst { scale, overhead } = options.gauge\n\t\tif (!Number.isSafeInteger(limit) || limit <= 0)\n\t\t\tthrow new StudyError('CONFIG', 'Summary limit must be a positive safe integer')\n\t\tif (!isFiniteNumber(scale) || scale <= 0 || !isFiniteNumber(overhead) || overhead < 0)\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'Summary gauge scale must be finite and positive and its overhead finite and nonnegative',\n\t\t\t)\n\t\tthis.#options = { ...options, limit, gauge: { scale, overhead } }\n\t}\n\n\t/** Measures one canonical request, refuses it at the limit, and sends the very same array to the provider.\n\t * @param messages - The conversation to fold; the instruction follows as the final user turn.\n\t * @param signal - Bounds the request; the options' signal bounds it when omitted.\n\t * @returns The summary content, retained as evidence before a blank result is refused.\n\t * @throws StudyError - Thrown with code `CAPACITY` when the projection reaches the limit, and with code `FAULT` when usage is unusable, no goal is active, or the content is blank.\n\t */\n\tasync summarize(messages: readonly Message[], signal: AbortSignal | undefined): Promise<string> {\n\t\tconst { provider, runtime, trace, latch, gauge, limit, instruction } = this.#options\n\t\tconst bound = signal ?? this.#options.signal\n\t\tbound.throwIfAborted()\n\t\tlatch.check()\n\t\t// One canonical array: measured once, admitted or refused, then sent as the very same array. The\n\t\t// instruction is the final user turn, so the chat template opens a fresh reply instead of\n\t\t// continuing the last folded assistant message.\n\t\tconst canonical: readonly Message[] = [...messages, instruction]\n\t\tconst request: ProviderRequest = { messages: canonical }\n\t\tconst estimate = runtime.estimateRequest(request)\n\t\tconst projected = projectStudyAgentRequest(gauge, estimate)\n\t\tconst reading = { estimate, projected }\n\t\tif (projected >= limit) {\n\t\t\tconst message = 'Summary request projection reaches the summary room'\n\t\t\t// The refusal keeps its own admission, so the Agent's admission stays the one a later window refusal names.\n\t\t\tconst stamp = trace.measure('admission', 'summary', request, reading, undefined)\n\t\t\tif (stamp !== undefined)\n\t\t\t\ttrace.append('refusal', {\n\t\t\t\t\tcause: 'capacity',\n\t\t\t\t\trole: 'summary',\n\t\t\t\t\tordinal: stamp.ordinal,\n\t\t\t\t\trevision: stamp.revision,\n\t\t\t\t\tconsumed: projected,\n\t\t\t\t\tmax: limit,\n\t\t\t\t})\n\t\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\t\tcause: 'capacity',\n\t\t\t\tmessage,\n\t\t\t\trole: 'summary',\n\t\t\t\tstop: { layer: 'window', id: 'Summary room', max: limit, consumed: projected },\n\t\t\t})\n\t\t}\n\t\ttrace.dispatch('summary', request, reading)\n\t\tconst result = await provider.generate(canonical, bound)\n\t\tif (!bound.aborted) validateStudyAgentUsage(result.usage, 'summary')\n\t\tlatch.check()\n\t\tif (trace.goal === undefined || typeof result.content !== 'string')\n\t\t\tthrow new StudyError('FAULT', 'Summary outside an active goal or invalid content')\n\t\tconst value: unknown = {\n\t\t\tsources: messages.map((message) => message.id),\n\t\t\tcontent: result.content,\n\t\t}\n\t\tif (!isJSONValue(value)) throw new StudyError('FAULT', 'Summary evidence is not JSON')\n\t\ttrace.append('summary', cloneJSONValue(value))\n\t\tif (result.content.trim() === '') {\n\t\t\tconst message = 'Summary returned no usable content'\n\t\t\tthrow new StudyError('FAULT', message, {\n\t\t\t\tcause: 'content',\n\t\t\t\tmessage,\n\t\t\t\trole: 'summary',\n\t\t\t\tstop: undefined,\n\t\t\t})\n\t\t}\n\t\treturn result.content\n\t}\n}\n","import type { StudyAgentPlan, StudyAgentResponse } from './types.js'\n\n/** Serves one goal's owned response sequence in declared order. */\nexport class StudyAgentScriptGoal {\n\treadonly #plan: StudyAgentPlan\n\t#cursor = 0\n\n\t/** Binds one goal's owned plan.\n\t * @param plan - The validated plan whose response snapshot the provider owns.\n\t */\n\tconstructor(plan: StudyAgentPlan) {\n\t\tthis.#plan = plan\n\t}\n\n\t/** Reports the goal's owned plan. */\n\tget plan(): StudyAgentPlan {\n\t\treturn this.#plan\n\t}\n\n\t/** Takes the next declared response and advances past it.\n\t * @returns The response; undefined once the sequence is exhausted, which it then stays.\n\t */\n\ttake(): StudyAgentResponse | undefined {\n\t\tconst response = this.#plan.responses[this.#cursor]\n\t\tif (response !== undefined) this.#cursor++\n\t\treturn response\n\t}\n}\n","import type { Message, ProviderDelta, ProviderInterface, ProviderResult } from '@orkestrel/agent'\nimport type { StudyTicket } from '../../core/types.js'\nimport type { StudyAgentPlan, StudyAgentResponse, StudyAgentScriptOptions } from './types.js'\nimport { isBudgetError } from '@orkestrel/budget'\nimport { cloneJSONValue, isArray } from '@orkestrel/contract'\nimport { randomUUID } from 'node:crypto'\nimport { StudyError } from '../../core/errors.js'\nimport { failStudyTicket } from '../../core/engines/helpers.js'\nimport { encodeStudyJSON } from '../helpers.js'\nimport {\n\tresolveStudyAgentContent,\n\treadStudyAgentMessages,\n\treadStudyAgentResult,\n} from './helpers.js'\nimport { isStudyAgentResponse } from './validators.js'\nimport { StudyAgentScriptGoal } from './StudyAgentScriptGoal.js'\n\n/** Serves declared inert responses through the actual Agent provider boundary. */\nexport class StudyAgentScript implements ProviderInterface {\n\treadonly id = randomUUID()\n\treadonly name = 'scripted-study'\n\treadonly #bytes: number\n\t// The prepared goal; `prepare` binds it and `clear` releases it. A running stream keeps the goal it took its response from.\n\t#goal: StudyAgentScriptGoal | undefined\n\t// The responses being served; a response joins when its stream starts and leaves when the stream settles.\n\treadonly #serving = new Set<StudyAgentResponse>()\n\n\t/**\n\t * Binds the encoded byte bound every served request and response must fit.\n\t * @param options - The explicit encoded bound; it is also each response's default admitted bytes\n\t * @throws StudyError - Thrown when the bound is not a nonnegative safe integer\n\t */\n\tconstructor(options: StudyAgentScriptOptions) {\n\t\tif (!Number.isSafeInteger(options.bytes) || options.bytes < 0)\n\t\t\tthrow new StudyError('CONFIG', 'Scripted byte bound must be a nonnegative safe integer')\n\t\tthis.#bytes = options.bytes\n\t}\n\n\t/**\n\t * Prepares one goal's declared response sequence and metered operational boundary until `clear` ends the goal.\n\t * @param plan - The workload's responses and its operational context\n\t * @returns Nothing when the provider is ready\n\t * @throws StudyError - Thrown with code `CONFIG` when a response is still running, a goal is already prepared, or a declared response is invalid; a prepared goal stays prepared\n\t */\n\tprepare(plan: StudyAgentPlan): void {\n\t\tif (this.#serving.size !== 0)\n\t\t\tthrow new StudyError('CONFIG', 'Cannot replace a running scripted workload')\n\t\tif (this.#goal !== undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Scripted goal is already prepared')\n\t\tif (!isArray(plan.responses) || !plan.responses.every(isStudyAgentResponse))\n\t\t\tthrow new StudyError('CONFIG', 'Scripted response sequence is invalid')\n\t\t// Own the declared calls so later caller mutation cannot change a served response; the\n\t\t// clone is re-narrowed through the guard rather than asserted.\n\t\tconst owned: unknown = plan.responses.map((response) => ({\n\t\t\t...response,\n\t\t\tcalls: cloneJSONValue(response.calls),\n\t\t}))\n\t\tif (!isArray(owned) || !owned.every(isStudyAgentResponse))\n\t\t\tthrow new StudyError('CONFIG', 'Scripted response sequence is invalid')\n\t\tthis.#goal = new StudyAgentScriptGoal({ ...plan, responses: Object.freeze(owned) })\n\t}\n\n\t/**\n\t * Ends the prepared goal so another goal can be prepared; a stream already running keeps serving its own goal.\n\t * @returns Nothing; a provider with no prepared goal stays unprepared\n\t */\n\tclear(): void {\n\t\tthis.#goal = undefined\n\t}\n\n\t/**\n\t * Consumes the same streaming response into its assembled provider result.\n\t * @param messages - The actual Agent conversation\n\t * @param signal - The enclosing Agent run signal\n\t * @returns The assembled declared response\n\t */\n\tasync generate(messages: readonly Message[], signal: AbortSignal): Promise<ProviderResult> {\n\t\treturn readStudyAgentResult(this.stream(messages, signal))\n\t}\n\n\t/**\n\t * Streams a declared response after authoritative admission and retains actual request bytes.\n\t * @param messages - The actual Agent conversation\n\t * @param signal - The enclosing Agent run signal\n\t * @returns The declared response, optionally consuming an actual prior tool message\n\t * @remarks\n\t * A stream abandoned after admission accounts for an Agent budget cut without latching a failure.\n\t * Other abandoned streams fail the admitted request with the run signal's reason, or a `FAULT`\n\t * when the signal carries none.\n\t * @throws StudyError - Thrown with code `CONFIG` when no goal is prepared, another response is running, or the responses are exhausted; thrown with the meter's refusal when admission fails\n\t */\n\tasync *stream(\n\t\tmessages: readonly Message[],\n\t\tsignal: AbortSignal,\n\t): AsyncGenerator<ProviderDelta, ProviderResult> {\n\t\tconst goal = this.#goal\n\t\tif (goal === undefined || this.#serving.size !== 0)\n\t\t\tthrow new StudyError('CONFIG', 'Scripted provider is unavailable')\n\t\tconst response = goal.take()\n\t\tif (response === undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Scripted provider response sequence is exhausted')\n\t\tconst plan = goal.plan\n\t\tthis.#serving.add(response)\n\t\tconst started = performance.now()\n\t\ttry {\n\t\t\tconst request = readStudyAgentMessages(messages)\n\t\t\tconst content = resolveStudyAgentContent(request, response)\n\t\t\tconst result: ProviderResult = {\n\t\t\t\tcontent,\n\t\t\t\t...(response.calls.length === 0 ? {} : { tools: response.calls }),\n\t\t\t\t...(response.truncated === true ? { truncated: true } : {}),\n\t\t\t}\n\t\t\tconst bytes = encodeStudyJSON({ request, response: result }).byteLength\n\t\t\tif (bytes > this.#bytes) {\n\t\t\t\tconst message = 'Scripted request exceeds its encoded workload bound'\n\t\t\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\t\t\tcause: 'capacity',\n\t\t\t\t\tmessage,\n\t\t\t\t\trole: undefined,\n\t\t\t\t\tstop: { layer: 'scope', id: 'Scripted bytes', max: this.#bytes, consumed: bytes },\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst ticket = await this.#admit(plan, response)\n\t\t\ttry {\n\t\t\t\tconst bounded = AbortSignal.any([\n\t\t\t\t\tsignal,\n\t\t\t\t\tplan.context.signal,\n\t\t\t\t\tplan.context.meter.signal,\n\t\t\t\t\tticket.signal,\n\t\t\t\t])\n\t\t\t\tbounded.throwIfAborted()\n\t\t\t\tawait plan.context.evidence.append({\n\t\t\t\t\tevent: 'provider',\n\t\t\t\t\tgoal: plan.goal,\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\tcalls: response.calls.map((call) => ({\n\t\t\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\t\t\tname: call.name,\n\t\t\t\t\t\t\t\targuments: cloneJSONValue(call.arguments),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tif (content.length > 0) yield { channel: 'content', text: content }\n\t\t\t\tbounded.throwIfAborted()\n\t\t\t\tticket.finish({\n\t\t\t\t\trole: 'agent',\n\t\t\t\t\tcalls: 1,\n\t\t\t\t\ttokens: undefined,\n\t\t\t\t\tbytes,\n\t\t\t\t\tduration: Math.ceil(performance.now() - started),\n\t\t\t\t})\n\t\t\t\tif (response.abort === true) {\n\t\t\t\t\tawait plan.context.evidence.append({\n\t\t\t\t\t\tevent: 'workload',\n\t\t\t\t\t\tgoal: plan.goal,\n\t\t\t\t\t\tvalue: { aborted: true },\n\t\t\t\t\t})\n\t\t\t\t\tplan.workload.abort(new Error('Declared workload cancellation'))\n\t\t\t\t}\n\t\t\t\treturn result\n\t\t\t} catch (error) {\n\t\t\t\t// An Agent budget's cut is Agent's own stop, so the request is accounted and the layer stays in Agent's record.\n\t\t\t\tif (isBudgetError(error)) this.#cut(ticket, bytes, started)\n\t\t\t\telse failStudyTicket(ticket, error, 'agent')\n\t\t\t\tthrow error\n\t\t\t} finally {\n\t\t\t\t// Generator return bypasses the catch, before Agent publishes the stop's layer.\n\t\t\t\tif (isBudgetError(signal.reason)) this.#cut(ticket, bytes, started)\n\t\t\t\telse\n\t\t\t\t\tfailStudyTicket(\n\t\t\t\t\t\tticket,\n\t\t\t\t\t\tsignal.reason ??\n\t\t\t\t\t\t\tnew StudyError('FAULT', 'Scripted response was abandoned before completion'),\n\t\t\t\t\t\t'agent',\n\t\t\t\t\t)\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.#serving.delete(response)\n\t\t}\n\t}\n\n\t// Finishes an unsettled request that an Agent budget cut, with unknown tokens; a settled or aborted ticket is left untouched.\n\t#cut(ticket: StudyTicket, bytes: number, started: number): void {\n\t\tif (ticket.settled || ticket.signal.aborted) return\n\t\tticket.finish({\n\t\t\trole: 'agent',\n\t\t\tcalls: 1,\n\t\t\ttokens: undefined,\n\t\t\tbytes,\n\t\t\tduration: Math.ceil(performance.now() - started),\n\t\t})\n\t}\n\n\t// Admits the response's ceiling, retaining a refused admission as evidence before rethrowing it.\n\tasync #admit(plan: StudyAgentPlan, response: StudyAgentResponse): Promise<StudyTicket> {\n\t\ttry {\n\t\t\treturn await plan.context.meter.admit({\n\t\t\t\trole: 'agent',\n\t\t\t\ttokens: response.tokens ?? 1,\n\t\t\t\tbytes: response.bytes ?? this.#bytes,\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tawait plan.context.evidence.append({\n\t\t\t\tevent: 'admission',\n\t\t\t\tgoal: plan.goal,\n\t\t\t\tvalue: { role: 'agent', refused: true },\n\t\t\t})\n\t\t\tthrow error\n\t\t}\n\t}\n}\n","import type { JSONValue } from '@orkestrel/contract'\nimport type { OllamaTiming } from '@orkestrel/ollama'\nimport type { StudyProvider, StudyRole, StudyRoom, StudyStop } from '../../core/types.js'\nimport type {\n\tStudyOllamaPolicy,\n\tStudyOllamaRequest,\n\tStudyOllamaOptions,\n\tStudyOllamaTerminal,\n\tStudyOllamaTransportOptions,\n} from './types.js'\nimport {\n\tattempt,\n\tcanonicalStringify,\n\tisArray,\n\tisInteger,\n\tisObject,\n\tisRecord,\n\tparseJSON,\n} from '@orkestrel/contract'\nimport { StudyError } from '../../core/errors.js'\nimport { parseStudyReading } from '../../core/parsers.js'\n\n/**\n * Declares the pinned serving identities the Ollama transport verifies, keyed by the label their inventory evidence carries.\n * @param provider - Declared serving identities\n * @returns The model pin, plus the judge pin when the provider declares both the judge name and its digest\n */\nexport function buildStudyOllamaModels(\n\tprovider: StudyProvider,\n): StudyOllamaTransportOptions['models'] {\n\treturn {\n\t\tmodel: { name: provider.model, digest: provider.digest.model },\n\t\t...(provider.judge === undefined || provider.digest.judge === undefined\n\t\t\t? {}\n\t\t\t: { judge: { name: provider.judge, digest: provider.digest.judge } }),\n\t}\n}\n\n/**\n * Builds the provider options one role's declared wire policy determines.\n * @remarks\n * The policy's `options` object keeps its identity and key order. A strict policy adds `truncate`\n * and `shift` as `false`; any other policy omits both keys. The `length` allowance is read by the\n * transport and projects nothing.\n * @param policy - The role's declared wire policy\n * @returns The model, think flag, options object, and the strict native fields when declared\n */\nexport function buildStudyOllamaOptions(policy: StudyOllamaPolicy): StudyOllamaOptions {\n\treturn {\n\t\tmodel: policy.model,\n\t\toptions: policy.options,\n\t\tthink: policy.think,\n\t\t...(policy.strict ? { truncate: false, shift: false } : {}),\n\t}\n}\n\n/**\n * Validates declared role policies against the pinned inventory before any dispatch.\n * @param roles - The declared wire policy of each model role\n * @param models - The pinned served identities\n * @returns Nothing when every policy names a pinned model and a positive output allowance\n * @throws StudyError - Thrown with code `CONFIG` when a policy names an unpinned model, declares no positive safe-integer `num_predict`, or makes the raw judge wire strict\n */\nexport function validateStudyOllamaRoles(\n\troles: StudyOllamaTransportOptions['roles'],\n\tmodels: StudyOllamaTransportOptions['models'],\n): void {\n\tconst names = Object.values(models).map((model) => model.name)\n\tfor (const [role, policy] of Object.entries(roles)) {\n\t\tif (policy === undefined) continue\n\t\tif (!names.includes(policy.model))\n\t\t\tthrow new StudyError('CONFIG', 'Ollama role policy names a model the inventory does not pin')\n\t\tconst output = policy.options.num_predict\n\t\tif (output === undefined || !Number.isSafeInteger(output) || output <= 0)\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'Ollama role policy declares no positive num_predict allowance',\n\t\t\t)\n\t\tif (role === 'judge' && policy.strict)\n\t\t\tthrow new StudyError('CONFIG', 'Ollama strict fields apply only to chat roles')\n\t}\n}\n\n/**\n * Reads exact outbound Ollama facts and refuses a request outside its declared policy.\n * @remarks\n * The refusal happens before admission, so a refused request is never accounted.\n * @param options - The admitted origin, pinned inventory, and declared role policies\n * @param role - The responsible request role\n * @param input - The requested URL\n * @param init - The native fetch settings\n * @returns The validated dispatch facts\n * @throws StudyError - Thrown with code `CONFIG` when the endpoint, model, options, flags, or strict fields differ from the declaration, or the role declares no policy\n */\nexport function readStudyOllamaRequest(\n\toptions: Pick<StudyOllamaTransportOptions, 'url' | 'models' | 'roles'>,\n\trole: StudyRole,\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n): StudyOllamaRequest {\n\tif (input instanceof Request)\n\t\tthrow new StudyError('CONFIG', 'Ollama transport requires explicit URL requests')\n\tconst url = new URL(input)\n\tconst path =\n\t\trole === 'metadata'\n\t\t\t? init?.method === 'POST'\n\t\t\t\t? '/api/show'\n\t\t\t\t: '/api/tags'\n\t\t\t: role === 'judge'\n\t\t\t\t? '/api/generate'\n\t\t\t\t: '/api/chat'\n\tif (\n\t\turl.origin !== new URL(options.url).origin ||\n\t\turl.pathname !== path ||\n\t\turl.search !== '' ||\n\t\turl.hash !== '' ||\n\t\turl.username !== '' ||\n\t\turl.password !== ''\n\t)\n\t\tthrow new StudyError(\n\t\t\t'CONFIG',\n\t\t\t'Ollama transport endpoint differs from the admitted origin and path',\n\t\t)\n\tif (role === 'metadata') {\n\t\tif (path === '/api/show') {\n\t\t\tif (typeof init?.body !== 'string')\n\t\t\t\tthrow new StudyError('CONFIG', 'Invalid model metadata request')\n\t\t\tconst body: unknown = JSON.parse(init.body)\n\t\t\tif (\n\t\t\t\t!isRecord(body) ||\n\t\t\t\tObject.keys(body).length !== 1 ||\n\t\t\t\ttypeof body.model !== 'string' ||\n\t\t\t\t!Object.values(options.models).some((model) => model.name === body.model)\n\t\t\t)\n\t\t\t\tthrow new StudyError('CONFIG', 'Invalid model metadata identity')\n\t\t\treturn {\n\t\t\t\trole,\n\t\t\t\tpath,\n\t\t\t\tmodel: body.model,\n\t\t\t\toutput: 0,\n\t\t\t\tbytes: new TextEncoder().encode(init.body).byteLength,\n\t\t\t\toptions: {},\n\t\t\t\tstrict: false,\n\t\t\t\tlength: false,\n\t\t\t}\n\t\t}\n\t\tif (init?.method !== 'GET' || init.body !== undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Invalid inventory request')\n\t\treturn {\n\t\t\trole,\n\t\t\tpath,\n\t\t\tmodel: undefined,\n\t\t\toutput: 0,\n\t\t\tbytes: 0,\n\t\t\toptions: {},\n\t\t\tstrict: false,\n\t\t\tlength: false,\n\t\t}\n\t}\n\tif (init?.method !== 'POST' || typeof init.body !== 'string')\n\t\tthrow new StudyError('CONFIG', 'Ollama transport requires an encoded JSON POST')\n\tconst policy = role === 'tool' ? undefined : options.roles[role]\n\tif (policy === undefined)\n\t\tthrow new StudyError('CONFIG', 'Ollama transport role has no declared wire policy')\n\tconst output = policy.options.num_predict\n\tif (output === undefined || !Number.isSafeInteger(output) || output <= 0)\n\t\tthrow new StudyError('CONFIG', 'Ollama role policy declares no positive num_predict allowance')\n\tconst body: unknown = JSON.parse(init.body)\n\tif (\n\t\t!isRecord(body) ||\n\t\tbody.model !== policy.model ||\n\t\t!isRecord(body.options) ||\n\t\tcanonicalStringify(body.options) !== canonicalStringify(policy.options) ||\n\t\tbody.stream !== (role !== 'judge')\n\t)\n\t\tthrow new StudyError(\n\t\t\t'CONFIG',\n\t\t\t'Ollama transport model or effective options differ from the declared policy',\n\t\t)\n\tif (\n\t\trole === 'judge'\n\t\t\t? body.raw !== true || body.logprobs !== true\n\t\t\t: typeof body.think !== 'boolean' || (body.think === true && !policy.think)\n\t)\n\t\tthrow new StudyError('CONFIG', 'Ollama transport flags differ from the declared policy')\n\t// The strict fields govern chat requests only; the judge's raw generate wire is outside them.\n\tconst strict = policy.strict && role !== 'judge'\n\tif (strict && (body.truncate !== false || body.shift !== false))\n\t\tthrow new StudyError('CONFIG', 'Ollama transport must disable native truncation and shifting')\n\treturn {\n\t\trole,\n\t\tpath,\n\t\tmodel: policy.model,\n\t\toutput,\n\t\tbytes: new TextEncoder().encode(init.body).byteLength,\n\t\toptions: { ...policy.options },\n\t\tstrict,\n\t\tlength: policy.length,\n\t}\n}\n\n/**\n * Reads the declared model context ceiling without claiming daemon allocation.\n * @param value - The parsed Ollama show response\n * @param context - The requested total context\n * @returns The unambiguous model context ceiling\n * @throws StudyError - Thrown with code `FAULT` when context metadata is missing, or `CAPACITY` when it is ambiguous or below the requested context\n */\nexport function readStudyOllamaSupport(value: unknown, context: number): number {\n\tif (\n\t\t!isRecord(value) ||\n\t\t!isRecord(value.model_info) ||\n\t\ttypeof value.model_info['general.architecture'] !== 'string'\n\t)\n\t\tthrow new StudyError('FAULT', 'Missing model context metadata')\n\tconst architecture = value.model_info['general.architecture']\n\tconst keys = Object.keys(value.model_info).filter((key) => key.endsWith('.context_length'))\n\tconst ceiling = value.model_info[`${architecture}.context_length`]\n\tif (\n\t\tkeys.length !== 1 ||\n\t\ttypeof ceiling !== 'number' ||\n\t\t!Number.isSafeInteger(ceiling) ||\n\t\tceiling < context\n\t) {\n\t\tconst message = 'Model context metadata does not support the requested context'\n\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\tcause: 'capacity',\n\t\t\tmessage,\n\t\t\trole: undefined,\n\t\t\tstop: {\n\t\t\t\tlayer: 'model',\n\t\t\t\tid: 'context_length',\n\t\t\t\tmax:\n\t\t\t\t\tkeys.length === 1 && Number.isSafeInteger(ceiling)\n\t\t\t\t\t\t? parseStudyReading(ceiling)\n\t\t\t\t\t\t: undefined,\n\t\t\t\tconsumed: context,\n\t\t\t},\n\t\t})\n\t}\n\treturn ceiling\n}\n\n/**\n * Reads a native Ollama error member as the attributable failure it names, without usage.\n * @remarks\n * No token usage is read from the member.\n * The failure is `CAPACITY` when the member, a string or an object, names the exact structured\n * type `exceed_context_size_error` with a finite positive integer `n_prompt_tokens` above `n_ctx`,\n * a `code` of 400 if supplied, and a status of 400 if supplied. Every other member, a malformed\n * one included, is `FAULT` with its readable reason.\n * @param value - The parsed HTTP error body or wire row\n * @param role - The responsibility whose request was dispatched; the failure retains it\n * @param status - The HTTP status of the carrying response; undefined for a row of a stream that answered 200\n * @returns Undefined when the value carries no `error` member; otherwise the attributable failure\n */\nexport function readStudyOllamaFailure(\n\tvalue: unknown,\n\trole: StudyRole,\n\tstatus?: number,\n): StudyError | undefined {\n\tif (!isRecord(value) || !('error' in value)) return undefined\n\tconst field = value.error\n\t// The live daemon sends structured JSON inside a string; decode it once and unwrap one error object.\n\tconst decoded = typeof field === 'string' ? parseJSON(field) : field\n\tconst structured = isRecord(decoded)\n\t\t? isRecord(decoded.error)\n\t\t\t? decoded.error\n\t\t\t: decoded\n\t\t: undefined\n\tconst native = structured?.message\n\tconst text =\n\t\ttypeof native === 'string' && native.trim() !== ''\n\t\t\t? native\n\t\t\t: typeof field === 'string'\n\t\t\t\t? field\n\t\t\t\t: ''\n\tconst label = structured?.type\n\tconst type = typeof label === 'string' && label !== '' ? label : undefined\n\tconst origin = status === undefined ? 'Ollama error' : `Ollama HTTP ${status} error`\n\tconst prompt = structured?.n_prompt_tokens\n\tconst limit = structured?.n_ctx\n\tconst capacity =\n\t\ttype === 'exceed_context_size_error' &&\n\t\tisInteger(prompt) &&\n\t\tprompt > 0 &&\n\t\tisInteger(limit) &&\n\t\tlimit > 0 &&\n\t\tprompt > limit &&\n\t\t(structured?.code === undefined || structured?.code === 400) &&\n\t\t(status === undefined || status === 400)\n\tconst reason =\n\t\ttext.trim() === '' && type === undefined\n\t\t\t? `Malformed ${origin}`\n\t\t\t: `${origin}${type === undefined ? '' : ` (${type})`}${text.trim() === '' ? '' : `: ${text}`}`\n\treturn new StudyError(capacity ? 'CAPACITY' : 'FAULT', reason, {\n\t\tcause: capacity ? 'capacity' : 'infrastructure',\n\t\tmessage: reason,\n\t\trole,\n\t\tstop: capacity\n\t\t\t? {\n\t\t\t\t\tlayer: 'model',\n\t\t\t\t\tid: 'num_ctx',\n\t\t\t\t\tmax: parseStudyReading(limit),\n\t\t\t\t\tconsumed: parseStudyReading(prompt),\n\t\t\t\t}\n\t\t\t: undefined,\n\t})\n}\n\n/**\n * Reads one Ollama response row without inventing absent usage.\n * @param value - The parsed wire row\n * @param request - The admitted dispatch\n * @returns The terminal facts, or undefined for a nonterminal row\n * @throws StudyError - Thrown with the recognized provider failure when the row carries an `error` member, before any other row check; `FAULT` for a malformed row, model, message, finish reason, or usage\n */\nexport function readStudyOllamaTerminal(\n\tvalue: unknown,\n\trequest: StudyOllamaRequest,\n): StudyOllamaTerminal | undefined {\n\tconst failure = readStudyOllamaFailure(value, request.role)\n\tif (failure !== undefined) throw failure\n\tif (!isRecord(value) || typeof value.done !== 'boolean')\n\t\tthrow new StudyError('FAULT', 'Malformed Ollama response row')\n\tif (value.model !== request.model)\n\t\tthrow new StudyError('FAULT', 'Ollama response model differs from the dispatched model')\n\tif (request.role !== 'judge') {\n\t\tif (\n\t\t\t!isRecord(value.message) ||\n\t\t\ttypeof value.message.content !== 'string' ||\n\t\t\t(value.message.thinking !== undefined && typeof value.message.thinking !== 'string')\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Malformed Ollama message')\n\t\tif (value.message.tool_calls !== undefined) {\n\t\t\tif (!isArray(value.message.tool_calls))\n\t\t\t\tthrow new StudyError('FAULT', 'Malformed Ollama tool calls')\n\t\t\tfor (const call of value.message.tool_calls)\n\t\t\t\tif (\n\t\t\t\t\t!isRecord(call) ||\n\t\t\t\t\t!isRecord(call.function) ||\n\t\t\t\t\ttypeof call.function.name !== 'string' ||\n\t\t\t\t\t!isRecord(call.function.arguments)\n\t\t\t\t)\n\t\t\t\t\tthrow new StudyError('FAULT', 'Malformed Ollama tool call')\n\t\t}\n\t}\n\tif (!value.done) return undefined\n\tif (typeof value.done_reason !== 'string' || value.done_reason.length === 0)\n\t\tthrow new StudyError('FAULT', 'Missing Ollama finish reason')\n\tfor (const key of ['prompt_eval_count', 'eval_count'])\n\t\tif (\n\t\t\tvalue[key] !== undefined &&\n\t\t\t(typeof value[key] !== 'number' || !Number.isSafeInteger(value[key]) || value[key] < 0)\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Malformed Ollama usage', {\n\t\t\t\tcause: 'infrastructure',\n\t\t\t\tmessage: 'Malformed Ollama usage',\n\t\t\t\trole: request.role,\n\t\t\t\tstop: undefined,\n\t\t\t})\n\tconst prompt = typeof value.prompt_eval_count === 'number' ? value.prompt_eval_count : undefined\n\tconst completion = typeof value.eval_count === 'number' ? value.eval_count : undefined\n\treturn { prompt, completion, reason: value.done_reason }\n}\n\n/**\n * Checks terminal policy after the actual wire cost has been retained.\n * @param terminal - The valid terminal facts\n * @param room - The reserved context and safety margin\n * @param request - The admitted dispatch and its declared finish policy; every refusal retains its role\n * @returns Nothing when the completion satisfies the declared policy\n * @throws StudyError - Thrown with code `CAPACITY` when the actual prompt exceeds its room, generation exceeds its allowance, or an undeclared `length` finish or capped generation occurs; `FAULT` for another unsupported finish reason\n */\nexport function validateStudyOllamaCompletion(\n\tterminal: StudyOllamaTerminal,\n\troom: Pick<StudyRoom, 'context' | 'safety'>,\n\trequest: StudyOllamaRequest,\n): void {\n\tconst { prompt, completion, reason } = terminal\n\tconst { role } = request\n\tconst capped: StudyStop = {\n\t\tlayer: 'model',\n\t\tid: 'num_predict',\n\t\tmax: request.output,\n\t\tconsumed: completion,\n\t}\n\tconst ceiling = room.context - request.output - room.safety\n\tif (prompt !== undefined && prompt > ceiling) {\n\t\tconst message = 'Actual prompt exceeded reserved context capacity'\n\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\tcause: 'capacity',\n\t\t\tmessage,\n\t\t\trole,\n\t\t\tstop: { layer: 'window', id: 'Context room', max: ceiling, consumed: prompt },\n\t\t})\n\t}\n\tif (completion !== undefined && completion > request.output) {\n\t\tconst message = 'Actual generation exceeded the output allowance'\n\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\tcause: 'capacity',\n\t\t\tmessage,\n\t\t\trole,\n\t\t\tstop: capped,\n\t\t})\n\t}\n\tif (\n\t\t!request.length &&\n\t\t(reason === 'length' || (completion !== undefined && completion >= request.output))\n\t) {\n\t\tconst message = 'Substantive generation reached its output cap'\n\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\tcause: 'capacity',\n\t\t\tmessage,\n\t\t\trole,\n\t\t\tstop: capped,\n\t\t})\n\t}\n\tif (reason !== 'stop' && !(request.length && reason === 'length')) {\n\t\tconst message = 'Unsupported Ollama finish reason'\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 * Verifies that each pinned name resolves to one inventory entry with its pinned digest.\n * @param value - The parsed inventory response\n * @param models - The pinned served identities\n * @returns Nothing for a matching inventory\n * @throws StudyError - Thrown with code `FAULT` when the inventory is unsupported or a pinned identity does not match\n */\nexport function validateStudyOllamaInventory(\n\tvalue: unknown,\n\tmodels: StudyOllamaTransportOptions['models'],\n): void {\n\tif (!isObject(value) || !('models' in value) || !isArray(value.models))\n\t\tthrow new StudyError('FAULT', 'Unsupported Ollama inventory')\n\tconst served = value.models\n\tfor (const { name, digest } of Object.values(models)) {\n\t\tconst matches = served.filter((model) => isRecord(model) && model.name === name)\n\t\tconst model = matches[0]\n\t\tif (\n\t\t\tmatches.length !== 1 ||\n\t\t\t!isRecord(model) ||\n\t\t\ttypeof model.digest !== 'string' ||\n\t\t\tmodel.digest.replace(/^sha256:/, '') !== digest.replace(/^sha256:/, '')\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Serving inventory does not match the required model digest')\n\t}\n}\n\n/**\n * Reads the pinned serving digest of an admitted request's model.\n * @param models - The pinned served identities\n * @param request - The admitted dispatch\n * @returns The pinned digest, or undefined for an inventory request or an unpinned model\n */\nexport function readStudyOllamaDigest(\n\tmodels: StudyOllamaTransportOptions['models'],\n\trequest: StudyOllamaRequest,\n): string | undefined {\n\tif (request.model === undefined) return undefined\n\treturn Object.values(models).find((model) => model.name === request.model)?.digest\n}\n\n/**\n * Reads daemon timing from a terminal row without letting an observation fail the request.\n * @param extract - The admitted extractor\n * @param record - The validated terminal row\n * @returns The raw timing, or undefined when absent or the extractor throws\n */\nexport function readStudyOllamaTiming(\n\textract: StudyOllamaTransportOptions['timing'],\n\trecord: Readonly<Record<string, unknown>>,\n): OllamaTiming | undefined {\n\ttry {\n\t\treturn extract(record)\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Builds the JSON evidence form of a timing observation with raw nanoseconds and counts.\n * @param timing - The extracted timing\n * @returns Null when no terminal timing was observed; otherwise every unreported member as null\n */\nexport function buildStudyOllamaTiming(timing: OllamaTiming | undefined): JSONValue {\n\tif (timing === undefined) return null\n\treturn {\n\t\tdurations: {\n\t\t\ttotal: timing.durations.total ?? null,\n\t\t\tload: timing.durations.load ?? null,\n\t\t\tprompt: timing.durations.prompt ?? null,\n\t\t\tdecode: timing.durations.decode ?? null,\n\t\t},\n\t\tcounts: {\n\t\t\tprompt: timing.counts.prompt ?? null,\n\t\t\tdecode: timing.counts.decode ?? null,\n\t\t\tcached: timing.counts.cached ?? null,\n\t\t},\n\t\tinvalid: [...timing.invalid],\n\t}\n}\n\n/**\n * Builds a reading of the raw prompt text an encoded request body carries, as sent.\n * @param body - The encoded request body\n * @returns The prompt's UTF-16 code units and UTF-8 bytes, labeled with its encoding, or undefined when there is no string prompt; these are readings of the actual text, not token allocations\n */\nexport function buildStudyOllamaRaw(body: unknown): JSONValue | undefined {\n\tif (typeof body !== 'string') return undefined\n\tconst parsed = attempt((): unknown => JSON.parse(body))\n\tif (!parsed.success || !isRecord(parsed.value) || typeof parsed.value.prompt !== 'string')\n\t\treturn undefined\n\treturn {\n\t\tencoding: 'utf-8',\n\t\tunits: parsed.value.prompt.length,\n\t\tbytes: new TextEncoder().encode(parsed.value.prompt).byteLength,\n\t}\n}\n","import type { StudyAgentDispatch } from '../../core/agents/types.js'\nimport type {\n\tStudyOllamaModel,\n\tStudyOllamaPolicy,\n\tStudyOllamaRole,\n\tStudyOllamaSnapshot,\n\tStudyOllamaTransportOptions,\n} from './types.js'\nimport { StudyError } from '../../core/errors.js'\n\n/**\n * Builds a frozen owned copy of transport configuration that later caller mutation cannot reach.\n * @remarks\n * Every caller member is read once, outer fields before nested data. Every nested data object is\n * copied and frozen; the caller's objects are never frozen. The cancellation signal and timing\n * extractor keep their live identity.\n * @param options - The caller's transport configuration\n * @returns The owned configuration, not yet validated\n */\nexport function buildStudyOllamaTransportOptions(\n\toptions: StudyOllamaTransportOptions,\n): StudyOllamaTransportOptions {\n\tconst { url, room, limit, models, roles, signal, observe, timing } = options\n\tconst owned: Record<string, StudyOllamaModel> = Object.fromEntries(\n\t\tObject.entries(models).map(([label, { name, digest }]) => [\n\t\t\tlabel,\n\t\t\tObject.freeze({ name, digest }),\n\t\t]),\n\t)\n\tconst policies: Partial<Record<StudyOllamaRole, StudyOllamaPolicy>> = Object.fromEntries(\n\t\t(['agent', 'summary', 'judge'] as const).flatMap((role) => {\n\t\t\tconst policy = roles[role]\n\t\t\tif (policy === undefined) return []\n\t\t\tconst { model, options: wire, think, strict, length } = policy\n\t\t\treturn [\n\t\t\t\t[\n\t\t\t\t\trole,\n\t\t\t\t\tObject.freeze({ model, options: Object.freeze({ ...wire }), think, strict, length }),\n\t\t\t\t] as const,\n\t\t\t]\n\t\t}),\n\t)\n\tconst { context, safety } = room\n\tconst { duration, bytes } = limit\n\treturn Object.freeze({\n\t\turl,\n\t\troom: Object.freeze({ context, safety }),\n\t\tlimit: Object.freeze({ duration, bytes }),\n\t\tmodels: Object.freeze(owned),\n\t\troles: Object.freeze(policies),\n\t\tsignal,\n\t\tobserve,\n\t\ttiming,\n\t})\n}\n\n/**\n * Builds an owned snapshot of one outbound request before anything is awaited.\n * @remarks\n * The URL spelling, accepted settings, headers, and dispatch are copied at the call, each caller\n * member read once; headers are cloned from the copied settings. The settings' `signal` keeps its\n * live identity so caller cancellation still reaches the request.\n * @param input - The requested URL\n * @param init - The native fetch settings\n * @param dispatch - The canonical dispatch the caller measured\n * @returns The owned request facts\n * @throws StudyError - Thrown with code `CONFIG` when the input is a `Request`\n */\nexport function buildStudyOllamaSnapshot(\n\tinput: string | URL | Request,\n\tinit: RequestInit | undefined,\n\tdispatch: StudyAgentDispatch | undefined,\n): StudyOllamaSnapshot {\n\tif (input instanceof Request)\n\t\tthrow new StudyError('CONFIG', 'Ollama transport requires explicit URL requests')\n\tconst copy = init === undefined ? undefined : { ...init }\n\treturn {\n\t\turl: typeof input === 'string' ? input : input.href,\n\t\tinit:\n\t\t\tcopy === undefined || copy.headers === undefined\n\t\t\t\t? copy\n\t\t\t\t: { ...copy, headers: new Headers(copy.headers) },\n\t\tdispatch: dispatch === undefined ? undefined : { id: dispatch.id, revision: dispatch.revision },\n\t}\n}\n","import type { OllamaTiming } from '@orkestrel/ollama'\nimport type { StudyOllamaTerminal, StudyOllamaWire } from './types.js'\nimport { StudyError } from '../../core/errors.js'\n\n/** Tracks one owned HTTP response through its counted bytes, decoded rows, terminal and settlement. */\nexport class StudyOllamaExchange implements StudyOllamaWire {\n\treadonly activity: StudyOllamaWire['activity']\n\treadonly request: StudyOllamaWire['request']\n\treadonly ticket: StudyOllamaWire['ticket']\n\treadonly signal: StudyOllamaWire['signal']\n\treadonly reader: StudyOllamaWire['reader']\n\treadonly decoder: StudyOllamaWire['decoder']\n\treadonly status: StudyOllamaWire['status']\n\treadonly started: StudyOllamaWire['started']\n\treadonly id: StudyOllamaWire['id']\n\treadonly sent: StudyOllamaWire['sent']\n\treadonly dispatch: StudyOllamaWire['dispatch']\n\t#bytes: number\n\t#text = ''\n\t#terminal: StudyOllamaTerminal | undefined\n\t#timing: OllamaTiming | undefined\n\t#settled = false\n\n\t/** Binds the facts of one dispatched request and its open response.\n\t * @param wire - The request, accounting boundary, reader and identities; its byte count starts the tally.\n\t */\n\tconstructor(\n\t\twire: Pick<\n\t\t\tStudyOllamaWire,\n\t\t\t| 'activity'\n\t\t\t| 'request'\n\t\t\t| 'ticket'\n\t\t\t| 'signal'\n\t\t\t| 'reader'\n\t\t\t| 'decoder'\n\t\t\t| 'status'\n\t\t\t| 'started'\n\t\t\t| 'id'\n\t\t\t| 'sent'\n\t\t\t| 'dispatch'\n\t\t\t| 'bytes'\n\t\t>,\n\t) {\n\t\tthis.activity = wire.activity\n\t\tthis.request = wire.request\n\t\tthis.ticket = wire.ticket\n\t\tthis.signal = wire.signal\n\t\tthis.reader = wire.reader\n\t\tthis.decoder = wire.decoder\n\t\tthis.status = wire.status\n\t\tthis.started = wire.started\n\t\tthis.id = wire.id\n\t\tthis.sent = wire.sent\n\t\tthis.dispatch = wire.dispatch\n\t\tthis.#bytes = wire.bytes\n\t}\n\n\t/** Holds the encoded request bytes plus every response byte counted so far. */\n\tget bytes(): number {\n\t\treturn this.#bytes\n\t}\n\n\t/** Holds the decoded response text not yet consumed as complete rows. */\n\tget text(): string {\n\t\treturn this.#text\n\t}\n\n\t/** Holds the validated terminal row once observed. */\n\tget terminal(): StudyOllamaTerminal | undefined {\n\t\treturn this.#terminal\n\t}\n\n\t/** Holds the daemon timing of the terminal row once observed. */\n\tget timing(): OllamaTiming | undefined {\n\t\treturn this.#timing\n\t}\n\n\t/** Reports whether the request was accounted, finished or failed. */\n\tget settled(): boolean {\n\t\treturn this.#settled\n\t}\n\n\t/** Adds a response chunk's bytes to the tally and refuses a tally beyond the allowance.\n\t * @param length - The chunk's byte length.\n\t * @param limit - The response byte allowance.\n\t * @throws StudyError - Thrown with code `CAPACITY` and the request's role when the tally exceeds the allowance.\n\t */\n\tcount(length: number, limit: number): void {\n\t\tthis.#bytes += length\n\t\tif (this.#bytes <= limit) return\n\t\tconst message = 'Ollama wire byte allowance exceeded'\n\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\tcause: 'capacity',\n\t\t\tmessage,\n\t\t\trole: this.request.role,\n\t\t\tstop: { layer: 'scope', id: 'Wire bytes', max: limit, consumed: this.#bytes },\n\t\t})\n\t}\n\n\t/** Appends a chunk to the retained text through the strict decoder.\n\t * @param chunk - The next response bytes.\n\t * @throws TypeError - Thrown when the bytes are not valid UTF-8.\n\t */\n\tdecode(chunk: Uint8Array): void {\n\t\tthis.#text += this.decoder.decode(chunk, { stream: true })\n\t}\n\n\t/** Appends what the strict decoder still holds after the last chunk.\n\t * @throws TypeError - Thrown when the bytes ended inside a UTF-8 sequence.\n\t */\n\tflush(): void {\n\t\tthis.#text += this.decoder.decode()\n\t}\n\n\t/** Takes the complete lines of the retained text and keeps the unfinished tail.\n\t * @param final - If `true`, the whole text is consumed and nothing is kept; if `false`, the last line is kept as an unfinished tail.\n\t * @returns The lines in arrival order.\n\t */\n\ttake(final: boolean): readonly string[] {\n\t\tconst lines = this.#text.split(/\\r\\n|\\n/)\n\t\tthis.#text = final ? '' : (lines.at(-1) ?? '')\n\t\treturn final ? lines : lines.slice(0, -1)\n\t}\n\n\t/** Retains what a row read as its terminal and its daemon timing.\n\t * @param terminal - The terminal the row validated as, or undefined when the row is not terminal.\n\t * @param timing - The daemon timing of that row, or undefined when it is not observed.\n\t */\n\tobserve(terminal: StudyOllamaTerminal | undefined, timing: OllamaTiming | undefined): void {\n\t\tthis.#terminal = terminal\n\t\tthis.#timing = timing\n\t}\n\n\t/** Marks the request accounted, finished or failed. */\n\tsettle(): void {\n\t\tthis.#settled = true\n\t}\n}\n","import type { JSONValue } from '@orkestrel/contract'\nimport type { StudyOllamaActivity } from './types.js'\n\n/** Holds one goal's accounting boundary and whether its checkpoint has joined a dispatch row. */\nexport class StudyOllamaGoal {\n\treadonly #activity: StudyOllamaActivity\n\t#attached = false\n\n\t/** Binds one goal's accounting boundary.\n\t * @param activity - The goal's admitted activity; it is held by reference.\n\t */\n\tconstructor(activity: StudyOllamaActivity) {\n\t\tthis.#activity = activity\n\t}\n\n\t/** Reports the goal's accounting boundary. */\n\tget activity(): StudyOllamaActivity {\n\t\treturn this.#activity\n\t}\n\n\t/** Hands out the goal's checkpoint for its first observed dispatch.\n\t * @returns The checkpoint the first time it is asked for; undefined afterwards and whenever the goal has none.\n\t */\n\tattach(): JSONValue | undefined {\n\t\tconst checkpoint = this.#activity.checkpoint\n\t\tif (checkpoint === undefined || this.#attached) return undefined\n\t\tthis.#attached = true\n\t\treturn checkpoint\n\t}\n}\n","import type { BudgetError } from '@orkestrel/budget'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type { OllamaTiming } from '@orkestrel/ollama'\nimport type { StudyRole, StudyTicket } from '../../core/types.js'\nimport type { StudyAgentDispatch, StudyLatchInterface } from '../../core/agents/types.js'\nimport type {\n\tStudyOllamaActivity,\n\tStudyOllamaRequest,\n\tStudyOllamaSnapshot,\n\tStudyOllamaTerminal,\n\tStudyOllamaTransportOptions,\n} from './types.js'\nimport { isBudgetError } from '@orkestrel/budget'\nimport { isRecord, parseJSON } from '@orkestrel/contract'\nimport { StudyError } from '../../core/errors.js'\nimport { readStudyFailure } from '../../core/engines/helpers.js'\nimport { buildStudyAgentDispatch } from '../../core/agents/helpers.js'\nimport { studyStopToJSON } from '../../core/helpers.js'\nimport { buildStudyOllamaSnapshot, buildStudyOllamaTransportOptions } from './cloners.js'\nimport { StudyOllamaExchange } from './StudyOllamaExchange.js'\nimport { StudyOllamaGoal } from './StudyOllamaGoal.js'\nimport {\n\tbuildStudyOllamaRaw,\n\tbuildStudyOllamaTiming,\n\treadStudyOllamaDigest,\n\treadStudyOllamaFailure,\n\treadStudyOllamaRequest,\n\treadStudyOllamaSupport,\n\treadStudyOllamaTerminal,\n\treadStudyOllamaTiming,\n\tvalidateStudyOllamaCompletion,\n\tvalidateStudyOllamaInventory,\n\tvalidateStudyOllamaRoles,\n} from './helpers.js'\n\n/** Admits and accounts Ollama wire requests under declared policies and latches failure. */\nexport class StudyOllamaTransport implements StudyLatchInterface {\n\treadonly #options: StudyOllamaTransportOptions\n\treadonly #abort = new AbortController()\n\treadonly #wires = new Set<StudyOllamaExchange>()\n\t// The bound goal; `prepare` binds it and `clear` or `close` releases it. An admitted request keeps the goal it was admitted under.\n\t#goal: StudyOllamaGoal | undefined\n\t// Wraps the first retained failure so a thrown undefined or null is still a presence.\n\t#fault: { readonly error: unknown } | undefined\n\t#count = 0\n\t// The model of the latest model dispatch; it spans goals, so the next goal's first dispatch reports a switch.\n\t#previous: string | undefined\n\n\t/** Records immutable transport bounds and refuses a role policy the inventory cannot serve.\n\t * @param options - Origin, room, request limit, pinned inventory, role policies, and cancellation.\n\t */\n\tconstructor(options: StudyOllamaTransportOptions) {\n\t\tconst owned = buildStudyOllamaTransportOptions(options)\n\t\tvalidateStudyOllamaRoles(owned.roles, owned.models)\n\t\tthis.#options = owned\n\t}\n\n\t/** Binds subsequent wire requests to one live goal until `clear` or `close` ends it.\n\t * @param activity - The goal's accounting boundary.\n\t * @throws StudyError - Thrown with code `FAULT` when a model response is still open or a goal is still bound; the bound goal stays bound.\n\t * @throws unknown - Thrown with the retained failure or the cancellation reason, as `check` throws it.\n\t */\n\tprepare(activity: StudyOllamaActivity): void {\n\t\tthis.check()\n\t\tif (this.#wires.size !== 0)\n\t\t\tthrow new StudyError('FAULT', 'Previous model response is still open')\n\t\tif (this.#goal !== undefined) throw new StudyError('FAULT', 'Previous goal is still bound')\n\t\tthis.#goal = new StudyOllamaGoal(activity)\n\t}\n\n\t/** Ends the bound goal so another goal can be prepared; a request already admitted keeps its own goal.\n\t * @returns Nothing; a transport with no bound goal stays unbound, and a closed transport stays closed.\n\t */\n\tclear(): void {\n\t\tthis.#goal = undefined\n\t}\n\n\t/** Refuses work after any retained failure or cancellation.\n\t * @returns Nothing when work may continue.\n\t */\n\tcheck(): void {\n\t\tif (this.#fault !== undefined) throw this.#fault.error\n\t\tthis.#options.signal.throwIfAborted()\n\t\tthis.#abort.signal.throwIfAborted()\n\t}\n\n\t/** Retains an operational failure even when an inner runtime catches it.\n\t * @param error - The observed failure; the first retained failure keeps its identity, and a branded `BudgetError` retains nothing because Agent reports that stop in its own result.\n\t */\n\tfail(error: unknown): void {\n\t\t// An Agent budget's cut is reported by Agent's own result, so nothing is retained to re-raise.\n\t\tif (!isBudgetError(error)) this.#fault ??= { error }\n\t}\n\n\t/** Checks every pinned serving identity through admitted inventory and metadata requests.\n\t * @returns Completion after inventory validation and support evidence.\n\t * @throws StudyError - Thrown with code `FAULT` when no goal is bound; the transport retains this refusal as its failure, as it retains every verification failure.\n\t */\n\tasync verify(): Promise<void> {\n\t\ttry {\n\t\t\tconst response = await this.fetch('metadata', new URL('/api/tags', this.#options.url), {\n\t\t\t\tmethod: 'GET',\n\t\t\t})\n\t\t\tconst value: unknown = await response.json()\n\t\t\tvalidateStudyOllamaInventory(value, this.#options.models)\n\t\t\tconst goal = this.#goal\n\t\t\tif (goal === undefined) throw new StudyError('FAULT', 'Inventory has no goal attribution')\n\t\t\tconst activity = goal.activity\n\t\t\tconst models = Object.values(this.#options.models)\n\t\t\tfor (const model of new Set(models.map((entry) => entry.name))) {\n\t\t\t\tconst support = await this.fetch('metadata', new URL('/api/show', this.#options.url), {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tbody: JSON.stringify({ model }),\n\t\t\t\t\theaders: { 'content-type': 'application/json' },\n\t\t\t\t})\n\t\t\t\tconst metadata: unknown = await support.json()\n\t\t\t\tconst ceiling = readStudyOllamaSupport(metadata, this.#options.room.context)\n\t\t\t\tawait activity.context.evidence.append({\n\t\t\t\t\tevent: 'support',\n\t\t\t\t\tgoal: activity.goal,\n\t\t\t\t\tvalue: { model, ceiling, requested: this.#options.room.context },\n\t\t\t\t})\n\t\t\t}\n\t\t\tawait activity.context.evidence.append({\n\t\t\t\tevent: 'inventory',\n\t\t\t\tgoal: activity.goal,\n\t\t\t\tvalue: Object.fromEntries(\n\t\t\t\t\tObject.entries(this.#options.models).map(([label, model]) => [label, model.digest]),\n\t\t\t\t),\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthis.fail(error)\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/** Dispatches exactly one admitted request with bounded streaming reads.\n\t * @param role - The accountable responsibility.\n\t * @param input - The exact configured URL.\n\t * @param init - The native fetch settings.\n\t * @param original - The immutable canonical dispatch the caller measured for this request; it joins the observation rows and never changes the request.\n\t * @returns A validated streaming response.\n\t * @throws StudyError - Thrown with code `FAULT` when no goal is bound, before admission and without retaining a failure.\n\t * @throws StudyError - Thrown with the recognized provider failure or a role-attributed `FAULT` for a non-2xx response, after its bounded body was read and its request accounted once.\n\t */\n\tasync fetch(\n\t\trole: StudyRole,\n\t\tinput: string | URL | Request,\n\t\tinit?: RequestInit,\n\t\toriginal?: StudyAgentDispatch,\n\t): Promise<Response> {\n\t\tthis.check()\n\t\tconst goal = this.#goal\n\t\tif (goal === undefined) throw new StudyError('FAULT', 'Model dispatch outside an active goal')\n\t\tconst activity = goal.activity\n\t\ttry {\n\t\t\t// Everything the request depends on is owned before the first await; the caller's originals are never read again.\n\t\t\tconst snapshot = buildStudyOllamaSnapshot(input, init, original)\n\t\t\tconst settings = snapshot.init\n\t\t\tconst request = readStudyOllamaRequest(this.#options, role, snapshot.url, settings)\n\t\t\tconst limit = this.#options.limit\n\t\t\tif (request.bytes >= limit.bytes) {\n\t\t\t\tconst message = 'Encoded request consumes the response byte allowance'\n\t\t\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\t\t\tcause: 'capacity',\n\t\t\t\t\tmessage,\n\t\t\t\t\trole: undefined,\n\t\t\t\t\tstop: { layer: 'scope', id: 'Wire bytes', max: limit.bytes, consumed: request.bytes },\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst ticket = await activity.context.meter.admit({\n\t\t\t\trole,\n\t\t\t\ttokens: role === 'metadata' ? 0 : this.#options.room.context - this.#options.room.safety,\n\t\t\t\tbytes: limit.bytes,\n\t\t\t})\n\t\t\tconst id = ++this.#count\n\t\t\tconst started = performance.now()\n\t\t\tconst signal = AbortSignal.any([\n\t\t\t\tthis.#options.signal,\n\t\t\t\tthis.#abort.signal,\n\t\t\t\tactivity.context.signal,\n\t\t\t\tactivity.context.meter.signal,\n\t\t\t\tticket.signal,\n\t\t\t\tAbortSignal.timeout(limit.duration),\n\t\t\t\t...(settings?.signal === undefined || settings.signal === null ? [] : [settings.signal]),\n\t\t\t])\n\t\t\tconst wire = await this.#send(role, goal, ticket, request, snapshot, signal, id, started)\n\t\t\tthis.#wires.add(wire)\n\t\t\tif (wire.status < 200 || wire.status > 299) return await this.#refuse(wire)\n\t\t\treturn new Response(\n\t\t\t\tnew ReadableStream<Uint8Array>({\n\t\t\t\t\tpull: (controller) => this.#pull(wire, controller),\n\t\t\t\t\t// A consumer cancel without a reason is the only absence; any thrown value keeps its identity.\n\t\t\t\t\tcancel: (reason: unknown) =>\n\t\t\t\t\t\tisBudgetError(reason)\n\t\t\t\t\t\t\t? this.#cut(wire, reason)\n\t\t\t\t\t\t\t: this.#failWire(\n\t\t\t\t\t\t\t\t\twire,\n\t\t\t\t\t\t\t\t\treason === undefined\n\t\t\t\t\t\t\t\t\t\t? new StudyError('FAULT', 'Ollama response cancelled before its end')\n\t\t\t\t\t\t\t\t\t\t: reason,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\tstatus: wire.status,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'content-type':\n\t\t\t\t\t\t\trole === 'judge' || role === 'metadata' ? 'application/json' : 'application/x-ndjson',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tthis.fail(error)\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/** Cancels every outstanding native reader and permanently closes the transport.\n\t * @returns Completion after finite native cancellation.\n\t */\n\tasync close(): Promise<void> {\n\t\tthis.#abort.abort(new StudyError('FAULT', 'Ollama transport closed'))\n\t\tawait Promise.all(\n\t\t\t[...this.#wires].map((wire) => this.#failWire(wire, this.#abort.signal.reason)),\n\t\t)\n\t\tthis.#goal = undefined\n\t}\n\n\t// Buffers a non-2xx body under the wire bounds and parses it once at its end, because an error body is one JSON document, not rows.\n\tasync #refuse(wire: StudyOllamaExchange): Promise<never> {\n\t\tconst failure = await this.#diagnose(wire)\n\t\tawait this.#failWire(wire, failure)\n\t\tthrow failure\n\t}\n\n\t// Reads the refusal body to its end and returns the failure it names, or the error that stopped the read.\n\tasync #diagnose(wire: StudyOllamaExchange): Promise<unknown> {\n\t\t// A lenient decoder: undecodable bytes make the body invalid JSON, which is a generic refusal rather than a decode crash.\n\t\tconst decoder = new TextDecoder()\n\t\tconst parts: string[] = []\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\twire.signal.throwIfAborted()\n\t\t\t\tconst chunk = await wire.reader.read()\n\t\t\t\twire.signal.throwIfAborted()\n\t\t\t\tif (chunk.done) break\n\t\t\t\twire.count(chunk.value.byteLength, this.#options.limit.bytes)\n\t\t\t\tparts.push(decoder.decode(chunk.value, { stream: true }))\n\t\t\t}\n\t\t\tconst body: unknown = parseJSON(parts.join('') + decoder.decode())\n\t\t\tconst message = `Ollama HTTP response refused: ${wire.status}`\n\t\t\treturn (\n\t\t\t\treadStudyOllamaFailure(body, wire.request.role, wire.status) ??\n\t\t\t\tnew StudyError('FAULT', message, {\n\t\t\t\t\tcause: 'infrastructure',\n\t\t\t\t\tmessage,\n\t\t\t\t\trole: wire.request.role,\n\t\t\t\t\tstop: undefined,\n\t\t\t\t})\n\t\t\t)\n\t\t} catch (error) {\n\t\t\treturn error\n\t\t}\n\t}\n\n\tasync #pull(\n\t\twire: StudyOllamaExchange,\n\t\tcontroller: ReadableStreamDefaultController<Uint8Array>,\n\t): Promise<void> {\n\t\ttry {\n\t\t\twire.signal.throwIfAborted()\n\t\t\tconst chunk = await wire.reader.read()\n\t\t\twire.signal.throwIfAborted()\n\t\t\tif (!chunk.done) {\n\t\t\t\twire.count(chunk.value.byteLength, this.#options.limit.bytes)\n\t\t\t\twire.decode(chunk.value)\n\t\t\t\tif (wire.request.role !== 'metadata' && wire.request.role !== 'judge')\n\t\t\t\t\tthis.#rows(wire, false)\n\t\t\t\tcontroller.enqueue(chunk.value)\n\t\t\t\treturn\n\t\t\t}\n\t\t\twire.flush()\n\t\t\tif (wire.request.role === 'metadata') {\n\t\t\t\tconst value: unknown = JSON.parse(wire.text)\n\t\t\t\tif (wire.request.path === '/api/tags')\n\t\t\t\t\tvalidateStudyOllamaInventory(value, this.#options.models)\n\t\t\t\telse readStudyOllamaSupport(value, this.#options.room.context)\n\t\t\t} else if (wire.request.role === 'judge') {\n\t\t\t\tthis.#observe(wire, JSON.parse(wire.text))\n\t\t\t} else this.#rows(wire, true)\n\t\t\tif (wire.request.role !== 'metadata' && wire.terminal === undefined)\n\t\t\t\tthrow new StudyError('FAULT', 'Ollama response has no terminal row')\n\t\t\tawait this.#finish(wire)\n\t\t\tif (wire.terminal !== undefined) await this.#judge(wire, wire.terminal)\n\t\t\tcontroller.close()\n\t\t} catch (error) {\n\t\t\tthis.fail(error)\n\t\t\ttry {\n\t\t\t\tif (isBudgetError(error)) await this.#cut(wire, error)\n\t\t\t\telse await this.#failWire(wire, error)\n\t\t\t} finally {\n\t\t\t\tcontroller.error(error)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Checks the terminal against the wire's declared policy; a refusal that names a stop is retained as one `stop` row before it propagates.\n\tasync #judge(wire: StudyOllamaExchange, terminal: StudyOllamaTerminal): Promise<void> {\n\t\ttry {\n\t\t\tvalidateStudyOllamaCompletion(terminal, this.#options.room, wire.request)\n\t\t} catch (error) {\n\t\t\tconst stop = readStudyFailure(error).stop\n\t\t\tif (stop !== undefined)\n\t\t\t\tawait wire.activity.context.evidence.append({\n\t\t\t\t\tevent: 'stop',\n\t\t\t\t\tgoal: wire.activity.goal,\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\trole: wire.request.role,\n\t\t\t\t\t\tpath: wire.request.path,\n\t\t\t\t\t\tfinish: terminal.reason,\n\t\t\t\t\t\tprompt: terminal.prompt ?? null,\n\t\t\t\t\t\tcompletion: terminal.completion ?? null,\n\t\t\t\t\t\tstop: studyStopToJSON(stop),\n\t\t\t\t\t\t...(this.#options.observe ? this.#timeline(wire) : {}),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t// Consumes the complete rows of the wire's text; each row after the terminal is refused.\n\t#rows(wire: StudyOllamaExchange, final: boolean): void {\n\t\tfor (const line of wire.take(final)) {\n\t\t\tif (line.trim() === '') continue\n\t\t\tif (wire.terminal !== undefined)\n\t\t\t\tthrow new StudyError('FAULT', 'Ollama emitted a row after its terminal')\n\t\t\tthis.#observe(wire, JSON.parse(line))\n\t\t}\n\t}\n\n\t// Validates a row against the wire's request and retains it; the timing extractor runs only on a terminal row.\n\t#observe(wire: StudyOllamaExchange, row: unknown): void {\n\t\tconst terminal = readStudyOllamaTerminal(row, wire.request)\n\t\twire.observe(terminal, terminal === undefined ? undefined : this.#time(row))\n\t}\n\n\t// Reads the daemon timing of a terminal row when timing is observed.\n\t#time(row: unknown): OllamaTiming | undefined {\n\t\treturn this.#options.observe && isRecord(row)\n\t\t\t? readStudyOllamaTiming(this.#options.timing, row)\n\t\t\t: undefined\n\t}\n\n\t// Dispatches one admitted request and owns the wire it opens; a failure before the wire exists fails the request's ticket here.\n\tasync #send(\n\t\trole: StudyRole,\n\t\tgoal: StudyOllamaGoal,\n\t\tticket: StudyTicket,\n\t\trequest: StudyOllamaRequest,\n\t\tsnapshot: StudyOllamaSnapshot,\n\t\tsignal: AbortSignal,\n\t\tid: number,\n\t\tstarted: number,\n\t): Promise<StudyOllamaExchange> {\n\t\tconst { url, init: settings, dispatch } = snapshot\n\t\ttry {\n\t\t\tsignal.throwIfAborted()\n\t\t\tawait goal.activity.context.evidence.append({\n\t\t\t\tevent: 'dispatch',\n\t\t\t\tgoal: goal.activity.goal,\n\t\t\t\tvalue: {\n\t\t\t\t\trole,\n\t\t\t\t\tpath: request.path,\n\t\t\t\t\tmodel: request.model ?? null,\n\t\t\t\t\toptions: { ...request.options },\n\t\t\t\t\tbytes: request.bytes,\n\t\t\t\t\t...(this.#options.observe ? this.#dispatch(goal, request, id, settings, dispatch) : {}),\n\t\t\t\t},\n\t\t\t})\n\t\t\tsignal.throwIfAborted()\n\t\t\tconst sent = performance.now()\n\t\t\tconst response = await globalThis.fetch(url, { ...settings, signal, redirect: 'error' })\n\t\t\tif (response.body === null)\n\t\t\t\tthrow new StudyError('FAULT', `Ollama HTTP response refused: ${response.status}`)\n\t\t\treturn new StudyOllamaExchange({\n\t\t\t\tactivity: goal.activity,\n\t\t\t\trequest,\n\t\t\t\tticket,\n\t\t\t\tsignal,\n\t\t\t\treader: response.body.getReader(),\n\t\t\t\tdecoder: new TextDecoder('utf-8', { fatal: true }),\n\t\t\t\tstatus: response.status,\n\t\t\t\tstarted,\n\t\t\t\tid,\n\t\t\t\tsent,\n\t\t\t\tdispatch,\n\t\t\t\tbytes: request.bytes,\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tif (!ticket.signal.aborted) {\n\t\t\t\t// An Agent budget's cut before the wire exists is Agent's own stop: the request is accounted with unknown cost.\n\t\t\t\tif (isBudgetError(error))\n\t\t\t\t\tticket.finish({\n\t\t\t\t\t\trole,\n\t\t\t\t\t\tcalls: 1,\n\t\t\t\t\t\ttokens: undefined,\n\t\t\t\t\t\tbytes: undefined,\n\t\t\t\t\t\tduration: Math.ceil(performance.now() - started),\n\t\t\t\t\t})\n\t\t\t\telse ticket.fail({ ...readStudyFailure(error), role })\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t#dispatch(\n\t\tgoal: StudyOllamaGoal,\n\t\trequest: StudyOllamaRequest,\n\t\tid: number,\n\t\tinit: RequestInit | undefined,\n\t\tdispatch: StudyAgentDispatch | undefined,\n\t): Readonly<Record<string, JSONValue>> {\n\t\tconst previous = this.#previous\n\t\tconst model = request.role !== 'metadata'\n\t\tif (model) this.#previous = request.model\n\t\tconst checkpoint = goal.activity.checkpoint\n\t\tconst snapshot = goal.attach()\n\t\tconst raw = buildStudyOllamaRaw(init?.body)\n\t\treturn {\n\t\t\tid,\n\t\t\t...buildStudyAgentDispatch(dispatch),\n\t\t\t...(raw === undefined ? {} : { raw }),\n\t\t\tdigest: readStudyOllamaDigest(this.#options.models, request) ?? null,\n\t\t\tprevious: previous ?? null,\n\t\t\tchanged: model && previous !== undefined && previous !== request.model,\n\t\t\t...(request.strict ? { strict: true } : {}),\n\t\t\t...(checkpoint === undefined\n\t\t\t\t? {}\n\t\t\t\t: { body: typeof init?.body === 'string' ? init.body : null }),\n\t\t\t...(snapshot === undefined ? {} : { snapshot }),\n\t\t}\n\t}\n\n\t#timeline(wire: StudyOllamaExchange): Readonly<Record<string, JSONValue>> {\n\t\treturn {\n\t\t\tid: wire.id,\n\t\t\t...buildStudyAgentDispatch(wire.dispatch),\n\t\t\tstarted: wire.started,\n\t\t\tsent: wire.sent,\n\t\t\telapsed: performance.now() - wire.sent,\n\t\t}\n\t}\n\n\tasync #finish(wire: StudyOllamaExchange): Promise<void> {\n\t\tif (wire.settled) throw new StudyError('FAULT', 'Duplicate wire accounting')\n\t\tconst terminal = wire.terminal\n\t\tconst observation = this.#options.observe\n\t\t\t? { ...this.#timeline(wire), timing: buildStudyOllamaTiming(wire.timing) }\n\t\t\t: {}\n\t\tawait wire.activity.context.evidence.append({\n\t\t\tevent: 'wire',\n\t\t\tgoal: wire.activity.goal,\n\t\t\tvalue: {\n\t\t\t\trole: wire.request.role,\n\t\t\t\tpath: wire.request.path,\n\t\t\t\tmodel: wire.request.model ?? null,\n\t\t\t\toptions: { ...wire.request.options },\n\t\t\t\tfinish: terminal?.reason ?? null,\n\t\t\t\tprompt: terminal?.prompt ?? null,\n\t\t\t\tcompletion: terminal?.completion ?? null,\n\t\t\t\tbytes: wire.bytes,\n\t\t\t\t...observation,\n\t\t\t},\n\t\t})\n\t\twire.settle()\n\t\ttry {\n\t\t\twire.ticket.finish({\n\t\t\t\trole: wire.request.role,\n\t\t\t\tcalls: 1,\n\t\t\t\ttokens:\n\t\t\t\t\twire.request.role === 'metadata'\n\t\t\t\t\t\t? 0\n\t\t\t\t\t\t: terminal?.prompt !== undefined && terminal.completion !== undefined\n\t\t\t\t\t\t\t? terminal.prompt + terminal.completion\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\tbytes: wire.bytes,\n\t\t\t\tduration: Math.ceil(performance.now() - wire.started),\n\t\t\t})\n\t\t} finally {\n\t\t\tthis.#wires.delete(wire)\n\t\t\twire.reader.releaseLock()\n\t\t}\n\t}\n\n\t// Accounts a request an Agent budget cut: the wire settles, the cut is retained as one `cut` row, and the request finishes with unknown tokens.\n\tasync #cut(wire: StudyOllamaExchange, error: BudgetError): Promise<void> {\n\t\tif (wire.settled) return\n\t\twire.settle()\n\t\tconst observation = this.#options.observe ? this.#timeline(wire) : {}\n\t\tconst stop = readStudyFailure(error).stop\n\t\ttry {\n\t\t\tawait wire.activity.context.evidence.append({\n\t\t\t\tevent: 'cut',\n\t\t\t\tgoal: wire.activity.goal,\n\t\t\t\tvalue: {\n\t\t\t\t\trole: wire.request.role,\n\t\t\t\t\tpath: wire.request.path,\n\t\t\t\t\tbytes: wire.bytes,\n\t\t\t\t\tstatus: wire.status,\n\t\t\t\t\tbudget:\n\t\t\t\t\t\tstop === undefined\n\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t: { id: stop.id, max: stop.max ?? null, consumed: stop.consumed ?? null },\n\t\t\t\t\t...observation,\n\t\t\t\t},\n\t\t\t})\n\t\t\tif (!wire.ticket.signal.aborted)\n\t\t\t\twire.ticket.finish({\n\t\t\t\t\trole: wire.request.role,\n\t\t\t\t\tcalls: 1,\n\t\t\t\t\ttokens: undefined,\n\t\t\t\t\tbytes: wire.bytes,\n\t\t\t\t\tduration: Math.ceil(performance.now() - wire.started),\n\t\t\t\t})\n\t\t} catch (failure) {\n\t\t\tthis.fail(failure)\n\t\t\tif (!wire.ticket.settled && !wire.ticket.signal.aborted)\n\t\t\t\twire.ticket.fail({ ...readStudyFailure(failure), role: wire.request.role })\n\t\t\tthrow failure\n\t\t} finally {\n\t\t\tthis.#wires.delete(wire)\n\t\t\tawait wire.reader.cancel(error).catch(() => undefined)\n\t\t\twire.reader.releaseLock()\n\t\t}\n\t}\n\n\tasync #failWire(wire: StudyOllamaExchange, error: unknown): Promise<void> {\n\t\tif (wire.settled) return\n\t\tthis.fail(error)\n\t\twire.settle()\n\t\tconst observation = this.#options.observe ? this.#timeline(wire) : {}\n\t\tconst failure = readStudyFailure(this.#fault?.error)\n\t\ttry {\n\t\t\tif (!wire.ticket.signal.aborted) wire.ticket.fail({ ...failure, role: wire.request.role })\n\t\t\tawait wire.activity.context.evidence.append({\n\t\t\t\tevent: 'failure',\n\t\t\t\tgoal: wire.activity.goal,\n\t\t\t\tvalue: {\n\t\t\t\t\trole: wire.request.role,\n\t\t\t\t\tpath: wire.request.path,\n\t\t\t\t\tbytes: wire.bytes,\n\t\t\t\t\tstatus: wire.status,\n\t\t\t\t\t// Bounded so a daemon-supplied message cannot grow the retained row.\n\t\t\t\t\treason: failure.message.slice(0, 256),\n\t\t\t\t\t...observation,\n\t\t\t\t},\n\t\t\t})\n\t\t} finally {\n\t\t\tthis.#wires.delete(wire)\n\t\t\tawait wire.reader.cancel(error).catch(() => undefined)\n\t\t\twire.reader.releaseLock()\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AASA,IAAa,oBAAoB,OAAO,IAAI,wBAAwB;;AASpE,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,eAAsC,OAAO,OAAO;CAChE;CACA;CACA;CACA;CACA;AACD,CAAC;;;;;;;;;;;;ACfD,SAAgB,gBAAgB,OAAkD;CACjF,OAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,CAAC,CAAC,QAAQ,GAAG,WAAW,UAAU,KAAA,CAAS,CA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AK,KAAK;EACf,KAAK,OAAO;EACZ,MAAM,cAAc,KAAK,SAAS,UAAU,KAAK,UAAU,IAAI,IAAI,CAAC;EACpE,MAAM,UAAU,iBAAiB,KAAK,QAAQ,KAAK;EACnD,IAAI;GACH,IAAI,CAAC,KAAK,OAAO,OAAO,SAAS,KAAK,OAAO,KAAK;IAAE,GAAG;IAAS,MAAM,KAAK,QAAQ;GAAK,CAAC;GACzF,MAAM,KAAK,SAAS,QAAQ,SAAS,OAAO;IAC3C,OAAO;IACP,MAAM,KAAK,SAAS;IACpB,OAAO;KACN,MAAM,KAAK,QAAQ;KACnB,MAAM,KAAK,QAAQ;KACnB,OAAO,KAAK;KACZ,QAAQ,KAAK;KAEb,QAAQ,QAAQ,QAAQ,MAAM,GAAG,GAAG;KACpC,GAAG;IACJ;GACD,CAAC;EACF,UAAU;GACT,KAAK,OAAO,OAAO,IAAI;GACvB,MAAM,KAAK,OAAO,OAAO,KAAK,CAAC,CAAC,YAAY,KAAA,CAAS;GACrD,KAAK,OAAO,YAAY;EACzB;CACD;AACD"}
1
+ {"version":3,"file":"index.cjs","names":["holds","isError","relative","sep","isAbsolute","createHash","canonicalStringify","parseJSON","StudyError","holds","isRecord","STUDY_NAME","isStudyName","holds","isRecord","matchesStudyKeys","isStudyTimestamp","isStudyDefinition","isArray","isStudyScenario","isStudyBounds","isStudyRecord","isStudyDigest","buildStudySchedule","canonicalStringify","isJSONValue","isStudyCause","isNonEmptyString","isStudyRole","isStudyStop","isStudyUsage","holds","isRecord","StudyError","isStudyRubric","isArray","isStudyJudgment","holds","INTRINSICS","isString","holds","isRecord","arrayOf","isString","isStudyDigest","isArray","isAbsolute","resolve","parse","relative","sep","join","lstatSync","realpathSync","dirname","opendirSync","parseJSON","isRecord","readSync","openSync","fstatSync","isBuiltin","join","fileURLToPath","basename","extname","stripTypeScriptTypes","pathToFileURL","join","isRecord","isNonEmptyString","extname","randomUUID","pathToFileURL","isAbsolute","resolve","parse","dirname","relative","sep","writeFile","realpathSync","lstatSync","opendirSync","StudyError","resolve","parse","relative","sep","lstat","join","dirname","open","constants","readdir","parseJSON","attempt","canonicalStringify","isRecord","StudyError","StudyError","parseJSON","StudyError","resolve","dirname","mkdir","join","canonicalStringify","open","StudyError","parseStudyRubric","parseStudyLabeling","parseStudyGrading","isStudyDigest","join","lstat","readdir","mkdir","canonicalStringify","holds","isRecord","matchesStudyKeys","isAbsolute","basename","isStudyRecord","isJSONValue","isStudyCause","isStudyRole","isStudyStop","isStudyName","isStudyDigest","holds","isRecord","isString","isStudyName","isStudyDigest","join","StudyError","resolve","parse","relative","sep","lstat","parseStudyDefinition","parseStudyScenario","parseStudyRubric","isAbsolute","realpathSync","parseJSON","STUDY_CAUSES","STUDY_ROLES","STUDY_LAYERS","studyStopToJSON","computeStudyScores","StudyError","isAbsolute","resolve","isStudyDigest","parseJSON","isRecord","StudyError","canonicalStringify","isRecord","parseStudyReading","parseJSON","isInteger","isArray","isObject","attempt","StudyError","canonicalStringify","isJSONValue","dirname","realpathSync","join","existsSync","readFileSync","isRecord","createRequire","delay","execFileSync","isAbsolute","StudyError","dirname","readFileSync","StudyControl","failureToStudyError","readStudyFailure","StudyControl","StudyError","failureToStudyError","isAbsolute","mkdtemp","join","fork","readStudyFailure","StudyDeadline","isRecord","isStudyProduct","isStudyUsage","execFile","StudyError","StudyError","open","StudyError","StudyError","fork","isRecord","isStudyDigest","isJSONValue","StudyError","isRecord","resolve","StudyError","join","writeFile","parseStudyProfile","buildStudySchedule","randomUUID","mkdtemp","StudySeries","rm","canonicalStringify","parseStudyRubric","parseJSON","arrayOf","isString","isArray","isStudyJudgment","parseStudyLabeling","isAbsolute","parseStudyGrading","mkdir","StudyError","failureToStudyError","isRecord","StudyError","readStudyFailure","isStudyUsage","StudyError","StudyControl","StudyError","StudyDeadline","readStudyFailure","isRecord","isStudyProfile","canonicalStringify","open","failureToStudyError","isStudyGoal","isStudyProduct","StudyError","isStudyError","isRecord","arrayOf","isString","parseStudyProfile","dirname","isArray","parseStudyDefinition","parseStudyScenario","parseStudyRubric","isStudyJudgment","StudyError","isRecord","isStudyBounds","isStudyDigest","StudyError","spawn","StudyError","isRecord","attempt","isRecord","isToolCall","StudyError","isObject","cloneJSONValue","canonicalStringify","isArray","holds","isRecord","matchesStudyKeys","isArray","isToolCall","isJSONValue","StudyError","projectStudyAgentRequest","buildStudyAgentParts","translateStudyAgentError","StudyError","isStudyAgentGauge","projectStudyAgentRequest","isJSONValue","cloneJSONValue","randomUUID","StudyError","isArray","cloneJSONValue","isBudgetError","StudyError","StudyError","isFunction","StudyError","StudyControl","MAX_TIMEOUT_MS","StudyScope","StudyMeter","isBudgetError","parseJSON","isRecord","readStudyFailure","studyStopToJSON","Abort","isStudyError","buildStudyAgentDispatch"],"sources":["../../../src/server/helpers.ts","../../../src/server/stores/constants.ts","../../../src/server/ollama/validators.ts","../../../src/server/stores/validators.ts","../../../src/server/adapters/validators.ts","../../../src/server/adapters/helpers.ts","../../../src/server/artifacts/constants.ts","../../../src/server/artifacts/errors.ts","../../../src/server/artifacts/validators.ts","../../../src/server/artifacts/helpers.ts","../../../src/server/artifacts/Resolution.ts","../../../src/server/artifacts/ArtifactLoader.ts","../../../src/server/stores/helpers.ts","../../../src/server/stores/StudyEvidenceSink.ts","../../../src/server/stores/StudyExchangeSink.ts","../../../src/server/stores/StudyResultStore.ts","../../../src/server/stores/StudyGradingStore.ts","../../../src/server/commands/constants.ts","../../../src/server/processes/validators.ts","../../../src/server/commands/validators.ts","../../../src/server/commands/helpers.ts","../../../src/server/commands/parsers.ts","../../../src/server/processes/constants.ts","../../../src/server/ollama/helpers.ts","../../../src/server/processes/helpers.ts","../../../src/server/processes/StudyArtifactLoader.ts","../../../src/server/processes/StudyChannel.ts","../../../src/server/processes/StudyProcessGoal.ts","../../../src/server/processes/StudyProcessSession.ts","../../../src/server/processes/StudyProcessDriver.ts","../../../src/server/commands/StudyDaemonTrial.ts","../../../src/server/commands/StudyDaemonSession.ts","../../../src/server/processes/StudyTaskChild.ts","../../../src/server/processes/StudyTask.ts","../../../src/server/commands/StudyCommand.ts","../../../src/server/processes/StudyRemoteTicket.ts","../../../src/server/processes/StudyRemoteMeter.ts","../../../src/server/ollama/StudyOllamaReplay.ts","../../../src/server/processes/StudyWorker.ts","../../../src/server/processes/StudyTaskWorker.ts","../../../src/server/launchers/constants.ts","../../../src/server/launchers/StudyLaunchChild.ts","../../../src/server/launchers/StudyLauncher.ts","../../../src/server/launchers/StudyCLI.ts","../../../src/server/agents/helpers.ts","../../../src/server/agents/validators.ts","../../../src/server/agents/StudyAgentTraceGoal.ts","../../../src/server/agents/StudyAgentTrace.ts","../../../src/server/agents/StudyAgentSummary.ts","../../../src/server/agents/StudyAgentScriptGoal.ts","../../../src/server/agents/StudyAgentScript.ts","../../../src/server/ollama/cloners.ts","../../../src/server/ollama/StudyOllamaExchange.ts","../../../src/server/ollama/StudyOllamaGoal.ts","../../../src/server/ollama/StudyOllamaTransport.ts"],"sourcesContent":["import { StudyError } from '@src/core'\nimport { canonicalStringify, holds, isError, parseJSON } from '@orkestrel/contract'\nimport { createHash } from 'node:crypto'\nimport { isAbsolute, relative, sep } from 'node:path'\n\n/** Reports whether a caught value is a Node error carrying the given system code.\n * @remarks Requires an `Error` from this realm. Structured cloning, such as a worker's `postMessage`,\n * drops a Node error's system code, so the cloned error does not match.\n * @param value - The caught value.\n * @param code - The system error code to match.\n * @returns True if the value is an Error from this realm carrying the code; false otherwise.\n * @example Match a system error\n * ```ts\n * import { matchesSystemError } from '@orkestrel/study/server'\n *\n * const error = Object.assign(new Error('Missing declaration'), { code: 'ENOENT' })\n * matchesSystemError(error, 'ENOENT') // true\n * matchesSystemError({ code: 'ENOENT' }, 'ENOENT') // false\n * ```\n */\nexport function matchesSystemError(value: unknown, code: string): boolean {\n\treturn holds(() => isError(value) && 'code' in value && value.code === code)\n}\n\n/** Checks strict lexical containment under a selected directory.\n * @param root - The canonical directory.\n * @param path - The candidate absolute file.\n * @returns True if the file is below the directory; false otherwise.\n */\nexport function containsArtifact(root: string, path: string): boolean {\n\tconst location = relative(root, path)\n\treturn (\n\t\tlocation !== '' &&\n\t\tlocation !== '..' &&\n\t\t!location.startsWith(`..${sep}`) &&\n\t\t!isAbsolute(location)\n\t)\n}\n\n/**\n * Computes the lowercase SHA-256 identity of exact bytes or UTF-8 text.\n * @param input - The retained bytes, or text identified by its UTF-8 bytes\n * @returns The lowercase hexadecimal digest\n * @example Identify captured bytes\n * ```ts\n * import { hashStudyBytes } from '@orkestrel/study/server'\n *\n * hashStudyBytes('retained evidence')\n * ```\n */\nexport function hashStudyBytes(input: string | Uint8Array): string {\n\treturn createHash('sha256').update(input).digest('hex')\n}\n\n/**\n * Encodes deterministic JSON bytes without synthesizing execution metadata.\n * @param value - The validated record\n * @returns The exact canonical UTF-8 bytes\n * @throws StudyError - Thrown when the record cannot be serialized\n * @example Encode custody bytes\n * ```ts\n * import { encodeStudyJSON } from '@orkestrel/study/server'\n *\n * encodeStudyJSON({ id: 1 })\n * ```\n */\nexport function encodeStudyJSON(value: unknown): Uint8Array {\n\tconst wire = JSON.stringify(value)\n\tconst text = wire === undefined ? undefined : canonicalStringify(parseJSON(wire))\n\tif (text === undefined) throw new StudyError('EVIDENCE', 'Record cannot be encoded')\n\treturn Buffer.from(`${text}\\n`, 'utf8')\n}\n\n/**\n * Decodes strict UTF-8 custody bytes and parses their JSON text.\n * @param bytes - The exact retained bytes\n * @returns The parsed value, or undefined when the text is not JSON\n * @throws TypeError - Thrown when the bytes are not valid UTF-8\n * @example\n * ```ts\n * decodeStudyJSON(new TextEncoder().encode('{\"id\":1}')) // { id: 1 }\n * ```\n */\nexport function decodeStudyJSON(bytes: Uint8Array): unknown {\n\treturn parseJSON(new TextDecoder('utf-8', { fatal: true }).decode(bytes))\n}\n","/** Limits untrusted metadata before JSON parsing or file allocation. */\nexport const STUDY_CUSTODY_BYTES = 16 * 1024 * 1024\n\n/** Rejects names that Windows reserves even on other hosts. */\nexport const STUDY_RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i\n\n/** Discloses the limits of neutral identifiers when public text remains visible. */\nexport const STUDY_PACKET_DISCLOSURE =\n\t'Identifiers omit treatment and model names. Input and product text may still reveal design details.'\n","import type {\n\tStudyOllamaMetadata,\n\tStudyOllamaModel,\n\tStudyOllamaPolicy,\n\tStudyOllamaStep,\n} from './types.js'\nimport { holds, isRecord } from '@orkestrel/contract'\nimport { STUDY_NAME } from '@src/core'\nimport { hashStudyBytes } from '../helpers.js'\n\n/** Checks whether a value declares independent positive metadata allowances.\n * @param value - The untrusted metadata declaration.\n * @returns True if the declaration has positive safe calls and bytes and finite duration; false otherwise.\n */\nexport function isStudyOllamaMetadata(value: unknown): value is StudyOllamaMetadata {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\ttypeof value.calls === 'number' &&\n\t\t\tNumber.isSafeInteger(value.calls) &&\n\t\t\tvalue.calls > 0 &&\n\t\t\ttypeof value.bytes === 'number' &&\n\t\t\tNumber.isSafeInteger(value.bytes) &&\n\t\t\tvalue.bytes > 0 &&\n\t\t\ttypeof value.duration === 'number' &&\n\t\t\tNumber.isFinite(value.duration) &&\n\t\t\tvalue.duration > 0,\n\t)\n}\n\n/** Checks whether a value pins a served model name and SHA-256 digest.\n * @param value - The untrusted model pin.\n * @returns True if the value declares a nonempty name and lowercase SHA-256 digest; false otherwise.\n */\nexport function isStudyOllamaModel(value: unknown): value is StudyOllamaModel {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\ttypeof value.name === 'string' &&\n\t\t\tvalue.name.length > 0 &&\n\t\t\ttypeof value.digest === 'string' &&\n\t\t\t/^[a-f0-9]{64}$/.test(value.digest),\n\t)\n}\n\n/** Checks whether a value declares a complete finite model-generation policy.\n * @param value - The untrusted role policy.\n * @returns True if every policy member and output allowance is valid; false otherwise.\n */\nexport function isStudyOllamaPolicy(value: unknown): value is StudyOllamaPolicy {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\ttypeof value.model === 'string' &&\n\t\t\tvalue.model.length > 0 &&\n\t\t\ttypeof value.think === 'boolean' &&\n\t\t\ttypeof value.strict === 'boolean' &&\n\t\t\ttypeof value.length === 'boolean' &&\n\t\t\tisRecord(value.options) &&\n\t\t\tObject.values(value.options).every(\n\t\t\t\t(entry) => typeof entry === 'number' && Number.isFinite(entry),\n\t\t\t) &&\n\t\t\ttypeof value.options.num_predict === 'number' &&\n\t\t\tNumber.isSafeInteger(value.options.num_predict) &&\n\t\t\tvalue.options.num_predict > 0,\n\t)\n}\n\n/** Checks whether a value declares exclusive exact or capture admission with a valid receipt.\n * @param value - The untrusted ordered step.\n * @returns True if identity, policy, admission shape and exact receipt are valid; false otherwise.\n */\nexport function isStudyOllamaStep(value: unknown): value is StudyOllamaStep {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\ttypeof value.ordinal !== 'number' ||\n\t\t\t!Number.isSafeInteger(value.ordinal) ||\n\t\t\tvalue.ordinal <= 0 ||\n\t\t\ttypeof value.goal !== 'string' ||\n\t\t\t!STUDY_NAME.test(value.goal) ||\n\t\t\t(value.role !== 'agent' && value.role !== 'summary' && value.role !== 'judge') ||\n\t\t\tvalue.path !== (value.role === 'judge' ? '/api/generate' : '/api/chat') ||\n\t\t\t!isStudyOllamaPolicy(value.policy) ||\n\t\t\t(value.role === 'judge' && value.policy.strict)\n\t\t)\n\t\t\treturn false\n\t\tif (value.admission === 'capture')\n\t\t\treturn (\n\t\t\t\ttypeof value.bytes === 'number' &&\n\t\t\t\tNumber.isSafeInteger(value.bytes) &&\n\t\t\t\tvalue.bytes > 0 &&\n\t\t\t\t!Object.hasOwn(value, 'body') &&\n\t\t\t\t!Object.hasOwn(value, 'input')\n\t\t\t)\n\t\treturn (\n\t\t\tvalue.admission === 'exact' &&\n\t\t\ttypeof value.body === 'string' &&\n\t\t\tvalue.body.length > 0 &&\n\t\t\ttypeof value.input === 'string' &&\n\t\t\tvalue.input === hashStudyBytes(value.body) &&\n\t\t\t!Object.hasOwn(value, 'bytes')\n\t\t)\n\t})\n}\n","import type {\n\tStudyAttempt,\n\tStudyEvidence,\n\tStudyFailure,\n\tStudyManifest,\n\tStudyObservation,\n\tStudyTrial,\n} from '@src/core'\nimport type {\n\tStudyExchangeBytes,\n\tStudyExchangeDeclaration,\n\tStudyExchangeHistory,\n\tStudyExchangeIdentity,\n\tStudyExchangeReply,\n\tStudyExchangeRow,\n\tStudyFile,\n\tStudySeal,\n} from './types.js'\nimport {\n\tbuildStudySchedule,\n\tmatchesStudyKeys,\n\tisStudyBounds,\n\tisStudyCause,\n\tisStudyDefinition,\n\tisStudyDigest,\n\tisStudyName,\n\tisStudyRole,\n\tisStudyRecord,\n\tisStudyScenario,\n\tisStudyStop,\n\tisStudyTimestamp,\n\tisStudyUsage,\n} from '@src/core'\nimport {\n\tholds,\n\tcanonicalStringify,\n\tisArray,\n\tisJSONValue,\n\tisNonEmptyString,\n\tisRecord,\n} from '@orkestrel/contract'\nimport { STUDY_RESERVED_NAME } from './constants.js'\nimport { hashStudyBytes } from '../helpers.js'\nimport {\n\tisStudyOllamaMetadata,\n\tisStudyOllamaModel,\n\tisStudyOllamaStep,\n} from '../ollama/validators.js'\n\n/**\n * Checks whether a trial name is portable on all supported hosts.\n * @param value - The candidate name\n * @returns True if the name is portable; false otherwise\n * @example\n * ```ts\n * isStudyCustodyName('r1-s1-a1') // true\n * ```\n */\nexport function isStudyCustodyName(value: unknown): value is string {\n\treturn isStudyName(value) && !STUDY_RESERVED_NAME.test(value)\n}\n\n/**\n * Checks whether a manifest exactly binds its declared population and identities.\n * @param value - The candidate manifest\n * @returns True if the manifest is valid; false otherwise\n * @example\n * ```ts\n * isStudyCustodyManifest({}) // false\n * ```\n */\nexport function isStudyCustodyManifest(value: unknown): value is StudyManifest {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(\n\t\t\t\tvalue,\n\t\t\t\t['id', 'created', 'definition', 'scenarios', 'identity', 'schedule', 'bounds', 'host'],\n\t\t\t\t['qualification', 'record'],\n\t\t\t) ||\n\t\t\t!isStudyCustodyName(value.id) ||\n\t\t\t!isStudyTimestamp(value.created) ||\n\t\t\t!isStudyDefinition(value.definition) ||\n\t\t\t!isArray(value.scenarios) ||\n\t\t\t!value.scenarios.every(isStudyScenario) ||\n\t\t\t!isStudyBounds(value.bounds) ||\n\t\t\t(value.record !== undefined && !isStudyRecord(value.record)) ||\n\t\t\t!isRecord(value.identity) ||\n\t\t\t!matchesStudyKeys(\n\t\t\t\tvalue.identity,\n\t\t\t\t['agent', 'subject', 'instrument', 'fixtures', 'profile'],\n\t\t\t\t['provider'],\n\t\t\t) ||\n\t\t\t(value.identity.provider !== undefined && !isStudyDigest(value.identity.provider)) ||\n\t\t\t(value.qualification !== undefined && !isStudyDigest(value.qualification)) ||\n\t\t\t!isRecord(value.host) ||\n\t\t\t!Object.values(value.host).every((entry) => typeof entry === 'string') ||\n\t\t\t!isArray(value.schedule)\n\t\t)\n\t\t\treturn false\n\t\tconst identity = value.identity\n\t\tif (\n\t\t\t!['agent', 'subject', 'instrument', 'fixtures', 'profile'].every((key) =>\n\t\t\t\tisStudyDigest(identity[key]),\n\t\t\t)\n\t\t)\n\t\t\treturn false\n\t\tconst schedule = buildStudySchedule(value.definition, value.scenarios)\n\t\treturn (\n\t\t\tvalue.schedule.every(isStudyCustodyTrial) &&\n\t\t\tcanonicalStringify(schedule) === canonicalStringify(value.schedule)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a scheduled trial has exact valid identity fields.\n * @param value - The candidate trial\n * @returns True if its identity is valid; false otherwise\n * @example\n * ```ts\n * isStudyCustodyTrial({}) // false\n * ```\n */\nexport function isStudyCustodyTrial(value: unknown): value is StudyTrial {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['id', 'scenario', 'arm', 'repetition']) &&\n\t\t\tisStudyCustodyName(value.id) &&\n\t\t\tisStudyName(value.scenario) &&\n\t\t\tisStudyName(value.arm) &&\n\t\t\ttypeof value.repetition === 'number' &&\n\t\t\tNumber.isSafeInteger(value.repetition) &&\n\t\t\tvalue.repetition >= 0\n\t\t)\n\t})\n}\n\n/**\n * Checks whether evidence is exact JSON with a declared event and goal name.\n * @param value - The candidate evidence\n * @returns True if evidence is valid; false otherwise\n * @example\n * ```ts\n * isStudyCustodyEvidence({ event: 'saved', goal: 'write', value: true }) // true\n * ```\n */\nexport function isStudyCustodyEvidence(value: unknown): value is StudyEvidence {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['event', 'goal', 'value']) &&\n\t\t\tisStudyName(value.event) &&\n\t\t\tisStudyName(value.goal) &&\n\t\t\tisJSONValue(value.value)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a failure carries exact attributable operational fields.\n * @remarks\n * `role` and `stop` are optional keys. A `stop` is valid only on a `capacity` or `deadline` failure,\n * and it must satisfy `isStudyStop`; a failure sealed before the `stop` member existed has no key.\n * @param value - The candidate failure\n * @returns True if the failure is valid; false otherwise\n * @example\n * ```ts\n * isStudyCustodyFailure({}) // false\n * ```\n */\nexport function isStudyCustodyFailure(value: unknown): value is StudyFailure {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['cause', 'message'], ['role', 'stop']) &&\n\t\t\tisStudyCause(value.cause) &&\n\t\t\tisNonEmptyString(value.message) &&\n\t\t\t(value.role === undefined || isStudyRole(value.role)) &&\n\t\t\t(value.stop === undefined ||\n\t\t\t\t((value.cause === 'capacity' || value.cause === 'deadline') && isStudyStop(value.stop)))\n\t\t)\n\t})\n}\n\n/**\n * Checks whether an observation preserves output or an explicit unexecuted failure.\n * @param value - The candidate observation\n * @returns True if the observation is valid, with an executed fact or an unexecuted fact that holds a failure and no product, usage or duration; false otherwise\n * @example\n * ```ts\n * isStudyCustodyObservation({}) // false\n * ```\n */\nexport function isStudyCustodyObservation(value: unknown): value is StudyObservation {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(value, ['goal', 'usage', 'duration', 'executed'], ['product', 'failure']) ||\n\t\t\t!isStudyName(value.goal) ||\n\t\t\t!isArray(value.usage) ||\n\t\t\t!value.usage.every(isStudyUsage) ||\n\t\t\ttypeof value.duration !== 'number' ||\n\t\t\t!Number.isSafeInteger(value.duration) ||\n\t\t\tvalue.duration < 0 ||\n\t\t\t(value.failure !== undefined && !isStudyCustodyFailure(value.failure)) ||\n\t\t\ttypeof value.executed !== 'boolean' ||\n\t\t\t(value.executed === false &&\n\t\t\t\t(value.product !== undefined ||\n\t\t\t\t\tvalue.failure === undefined ||\n\t\t\t\t\tvalue.usage.length !== 0 ||\n\t\t\t\t\tvalue.duration !== 0))\n\t\t)\n\t\t\treturn false\n\t\tif (value.product === undefined) return value.failure !== undefined\n\t\treturn (\n\t\t\tisRecord(value.product) &&\n\t\t\tmatchesStudyKeys(value.product, ['value', 'partial']) &&\n\t\t\tisJSONValue(value.product.value) &&\n\t\t\ttypeof value.product.partial === 'boolean'\n\t\t)\n\t})\n}\n\n/**\n * Checks whether an attempt terminally accounts for the exact scheduled goal horizon.\n * @param value - The candidate attempt\n * @param manifest - The authoritative declaration\n * @returns True if the terminal record is compatible and its execution facts are consistent; false otherwise\n * @remarks\n * Executed goals form a prefix of the horizon and an executed goal with a failure ends it.\n * An unexecuted attempt holds only unexecuted goals, and an attempt without a failure holds only\n * executed goals that did not fail.\n * @example\n * ```ts\n * isStudyCustodyAttempt({}, manifest) // false\n * ```\n */\nexport function isStudyCustodyAttempt(\n\tvalue: unknown,\n\tmanifest: StudyManifest,\n): value is StudyAttempt {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(value, ['trial', 'observations', 'duration', 'executed'], ['failure']) ||\n\t\t\t!isStudyCustodyTrial(value.trial) ||\n\t\t\t!isArray(value.observations) ||\n\t\t\t!value.observations.every(isStudyCustodyObservation) ||\n\t\t\ttypeof value.duration !== 'number' ||\n\t\t\t!Number.isSafeInteger(value.duration) ||\n\t\t\tvalue.duration < 0 ||\n\t\t\t(value.failure !== undefined && !isStudyCustodyFailure(value.failure))\n\t\t)\n\t\t\treturn false\n\t\tconst identity = value.trial\n\t\tconst trial = manifest.schedule.find((entry) => entry.id === identity.id)\n\t\tconst scenario = manifest.scenarios.find((entry) => entry.id === identity.scenario)\n\t\tif (\n\t\t\ttrial === undefined ||\n\t\t\tscenario === undefined ||\n\t\t\tcanonicalStringify(trial) !== canonicalStringify(value.trial) ||\n\t\t\tvalue.observations.length !== scenario.goals.length ||\n\t\t\t!value.observations.every(\n\t\t\t\t(observation, index) => observation.goal === scenario.goals[index]?.id,\n\t\t\t)\n\t\t)\n\t\t\treturn false\n\t\tconst executed = value.executed\n\t\tif (typeof executed !== 'boolean') return false\n\t\t// A terminal record without a failure holds only executed goals that did not fail.\n\t\tif (\n\t\t\tvalue.failure === undefined &&\n\t\t\t!value.observations.every((entry) => entry.executed && entry.failure === undefined)\n\t\t)\n\t\t\treturn false\n\t\t// An executed goal needs an executed attempt and no earlier goal that was unexecuted or failed,\n\t\t// so it lies at or before the first goal that was unexecuted or failed. A hole reads as an\n\t\t// absent observation, which refuses the record, as visiting every position does.\n\t\tconst observations = Array.from(value.observations)\n\t\tconst stop = observations.findIndex(\n\t\t\t(observation) => !observation.executed || observation.failure !== undefined,\n\t\t)\n\t\treturn observations.every(\n\t\t\t(observation, index) => !observation.executed || (executed && (stop === -1 || index <= stop)),\n\t\t)\n\t})\n}\n\n/**\n * Checks whether an execution file inventory entry is path-safe and bounded.\n * @param value - The candidate entry\n * @returns True if the entry is valid; false otherwise\n * @example\n * ```ts\n * isStudyCustodyFile({}) // false\n * ```\n */\nexport function isStudyCustodyFile(value: unknown): value is StudyFile {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['path', 'bytes', 'digest']) &&\n\t\t\ttypeof value.path === 'string' &&\n\t\t\t(value.path === 'manifest.json' ||\n\t\t\t\t/^trials\\/[a-z0-9]+(?:-[a-z0-9]+)*\\/(?:evidence.jsonl|attempt.json|exchanges.jsonl)$/.test(\n\t\t\t\t\tvalue.path,\n\t\t\t\t)) &&\n\t\t\tvalue.path.split('/').every((name) => !STUDY_RESERVED_NAME.test(name)) &&\n\t\t\ttypeof value.bytes === 'number' &&\n\t\t\tNumber.isSafeInteger(value.bytes) &&\n\t\t\tvalue.bytes >= 0 &&\n\t\t\tisStudyDigest(value.digest)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a seal has an exact unique execution inventory.\n * @param value - The candidate seal\n * @returns True if the seal is structurally valid; false otherwise\n * @example\n * ```ts\n * isStudyCustodySeal({}) // false\n * ```\n */\nexport function isStudyCustodySeal(value: unknown): value is StudySeal {\n\treturn holds(() => {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['result', 'id', 'files']) &&\n\t\t\tisStudyCustodyName(value.result) &&\n\t\t\tisStudyDigest(value.id) &&\n\t\t\tisArray(value.files) &&\n\t\t\tvalue.files.length > 0 &&\n\t\t\tvalue.files.every(isStudyCustodyFile) &&\n\t\t\tnew Set(value.files.map((entry) => entry.path)).size === value.files.length\n\t\t)\n\t})\n}\n\n/** Checks whether encoded body bytes have their exact canonical base64 and SHA-256 identity.\n * @param value - The candidate byte envelope.\n * @returns True if decoded length and digest match; false otherwise.\n */\nexport function isStudyExchangeBytes(value: unknown): value is StudyExchangeBytes {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\ttypeof value.body !== 'string' ||\n\t\t\ttypeof value.size !== 'number' ||\n\t\t\t!Number.isSafeInteger(value.size) ||\n\t\t\tvalue.size < 0 ||\n\t\t\t!isStudyDigest(value.digest)\n\t\t)\n\t\t\treturn false\n\t\tconst bytes = Buffer.from(value.body, 'base64')\n\t\treturn (\n\t\t\tbytes.length === value.size &&\n\t\t\tbytes.toString('base64') === value.body &&\n\t\t\thashStudyBytes(bytes) === value.digest\n\t\t)\n\t})\n}\n\n/** Checks whether an exchange carries an admissible ordered HTTP identity.\n * @param value - The candidate identity.\n * @returns True if identity and stage fields are valid; false otherwise.\n */\nexport function isStudyExchangeIdentity(value: unknown): value is StudyExchangeIdentity {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\ttypeof value.ordinal !== 'number' ||\n\t\t\t!Number.isSafeInteger(value.ordinal) ||\n\t\t\tvalue.ordinal <= 0 ||\n\t\t\t!isStudyName(value.goal) ||\n\t\t\t!isStudyRole(value.role) ||\n\t\t\t(value.method !== 'GET' && value.method !== 'POST')\n\t\t)\n\t\t\treturn false\n\t\tif (value.stage === 'execution')\n\t\t\treturn (\n\t\t\t\t(value.role === 'agent' || value.role === 'summary' || value.role === 'judge') &&\n\t\t\t\tvalue.method === 'POST' &&\n\t\t\t\tvalue.path === (value.role === 'judge' ? '/api/generate' : '/api/chat') &&\n\t\t\t\ttypeof value.step === 'number' &&\n\t\t\t\tNumber.isSafeInteger(value.step) &&\n\t\t\t\tvalue.step > 0\n\t\t\t)\n\t\tif (Object.hasOwn(value, 'step')) return false\n\t\tif (value.stage === 'maintenance')\n\t\t\treturn (\n\t\t\t\tvalue.role === 'maintenance' && value.method === 'POST' && value.path === '/api/generate'\n\t\t\t)\n\t\treturn (\n\t\t\t(value.stage === 'preflight' || value.stage === 'postflight') &&\n\t\t\tvalue.role === 'metadata' &&\n\t\t\t(value.path === '/api/version' || value.path === '/api/tags'\n\t\t\t\t? value.method === 'GET'\n\t\t\t\t: value.path === '/api/show' && value.method === 'POST')\n\t\t)\n\t})\n}\n\n/** Checks whether a retained reply describes bounded successful application bytes and chunks.\n * @param value - The candidate reply.\n * @returns True if status, selected headers and chunk lengths are valid; false otherwise.\n */\nexport function isStudyExchangeReply(value: unknown): value is StudyExchangeReply {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tisStudyExchangeBytes(value) &&\n\t\t\t'status' in value &&\n\t\t\ttypeof value.status === 'number' &&\n\t\t\tNumber.isSafeInteger(value.status) &&\n\t\t\tvalue.status >= 200 &&\n\t\t\tvalue.status <= 599 &&\n\t\t\t'headers' in value &&\n\t\t\tisArray(value.headers) &&\n\t\t\tvalue.headers.every(\n\t\t\t\t(header) =>\n\t\t\t\t\tisArray(header) &&\n\t\t\t\t\theader.length === 2 &&\n\t\t\t\t\t(header[0] === 'content-type' || header[0] === 'content-encoding') &&\n\t\t\t\t\ttypeof header[1] === 'string' &&\n\t\t\t\t\t!/[\\r\\n]/.test(header[1]),\n\t\t\t) &&\n\t\t\t'chunks' in value &&\n\t\t\tisArray(value.chunks) &&\n\t\t\tvalue.chunks.every(\n\t\t\t\t(size) => typeof size === 'number' && Number.isSafeInteger(size) && size > 0,\n\t\t\t) &&\n\t\t\tvalue.chunks.reduce<number>(\n\t\t\t\t(total, size) => total + (typeof size === 'number' ? size : 0),\n\t\t\t\t0,\n\t\t\t) === value.size,\n\t)\n}\n\n/** Checks whether the opening row declares a finite ordered procedure and serving identities.\n * @param value - The candidate declaration.\n * @returns True if all declared populations are valid; false otherwise.\n */\nexport function isStudyExchangeDeclaration(value: unknown): value is StudyExchangeDeclaration {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!matchesStudyKeys(value, [\n\t\t\t\t'phase',\n\t\t\t\t'trial',\n\t\t\t\t'version',\n\t\t\t\t'models',\n\t\t\t\t'metadata',\n\t\t\t\t'procedure',\n\t\t\t\t'maintenance',\n\t\t\t]) ||\n\t\t\tvalue.phase !== 'declaration' ||\n\t\t\t!isStudyCustodyName(value.trial) ||\n\t\t\t!isNonEmptyString(value.version) ||\n\t\t\t!isRecord(value.models) ||\n\t\t\tObject.keys(value.models).length === 0 ||\n\t\t\t!Object.values(value.models).every(isStudyOllamaModel) ||\n\t\t\t!isStudyOllamaMetadata(value.metadata) ||\n\t\t\t!isArray(value.procedure) ||\n\t\t\tvalue.procedure.length === 0 ||\n\t\t\t!value.procedure.every(isStudyOllamaStep) ||\n\t\t\t!isArray(value.maintenance) ||\n\t\t\t!value.maintenance.every(isStudyOllamaModel)\n\t\t)\n\t\t\treturn false\n\t\tconst models = Object.values(value.models).filter(isStudyOllamaModel)\n\t\treturn (\n\t\t\tvalue.procedure.every(\n\t\t\t\t(step, index) =>\n\t\t\t\t\tstep.ordinal === index + 1 && models.some((model) => model.name === step.policy.model),\n\t\t\t) &&\n\t\t\tvalue.maintenance.every(\n\t\t\t\t(model, index, entries) =>\n\t\t\t\t\tentries.findIndex((entry) => entry.name === model.name) === index &&\n\t\t\t\t\tmodels.some((entry) => entry.name === model.name && entry.digest === model.digest),\n\t\t\t) &&\n\t\t\tmodels.every((model) =>\n\t\t\t\tmodels.every((other) => model.name !== other.name || model.digest === other.digest),\n\t\t\t)\n\t\t)\n\t})\n}\n\n/** Checks whether a sidecar row has exactly its declared fields and verified byte identities.\n * @param value - The candidate row.\n * @returns True if the row belongs to the closed sidecar grammar; false otherwise.\n */\nexport function isStudyExchangeRow(value: unknown): value is StudyExchangeRow {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tif (value.phase === 'declaration') return isStudyExchangeDeclaration(value)\n\t\tif (value.phase === 'complete')\n\t\t\treturn (\n\t\t\t\tmatchesStudyKeys(value, ['phase', 'count']) &&\n\t\t\t\ttypeof value.count === 'number' &&\n\t\t\t\tNumber.isSafeInteger(value.count) &&\n\t\t\t\tvalue.count > 0\n\t\t\t)\n\t\tconst identity = ['phase', 'ordinal', 'goal', 'role', 'path', 'method', 'stage']\n\t\tif (!isStudyExchangeIdentity(value)) return false\n\t\tif (value.phase === 'attempt')\n\t\t\treturn (\n\t\t\t\tmatchesStudyKeys(value, [...identity, 'body', 'size', 'digest'], ['step']) &&\n\t\t\t\tisStudyExchangeBytes(value)\n\t\t\t)\n\t\tif (value.phase === 'response')\n\t\t\treturn (\n\t\t\t\tmatchesStudyKeys(\n\t\t\t\t\tvalue,\n\t\t\t\t\t[...identity, 'body', 'size', 'digest', 'status', 'headers', 'chunks'],\n\t\t\t\t\t['step'],\n\t\t\t\t) &&\n\t\t\t\tisStudyExchangeReply(value) &&\n\t\t\t\tvalue.status < 300\n\t\t\t)\n\t\treturn (\n\t\t\tvalue.phase === 'failure' &&\n\t\t\tmatchesStudyKeys(value, [...identity, 'reason'], ['step', 'response']) &&\n\t\t\ttypeof value.reason === 'string' &&\n\t\t\t(value.response === undefined || isStudyExchangeReply(value.response))\n\t\t)\n\t})\n}\n\n/** Checks whether a history has verified row shapes before its complete relational validation.\n * @param value - The candidate history.\n * @returns True if its envelopes and rows have valid types; false otherwise.\n */\nexport function isStudyExchangeHistory(value: unknown): value is StudyExchangeHistory {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['seal', 'file', 'declaration', 'exchanges', 'completion']) &&\n\t\t\tisStudyDigest(value.seal) &&\n\t\t\tisStudyCustodyFile(value.file) &&\n\t\t\tisStudyExchangeDeclaration(value.declaration) &&\n\t\t\tisArray(value.exchanges) &&\n\t\t\tvalue.exchanges.every(\n\t\t\t\t(pair) =>\n\t\t\t\t\tisRecord(pair) &&\n\t\t\t\t\tmatchesStudyKeys(pair, ['attempt', 'response']) &&\n\t\t\t\t\tisStudyExchangeRow(pair.attempt) &&\n\t\t\t\t\tpair.attempt.phase === 'attempt' &&\n\t\t\t\t\tisStudyExchangeRow(pair.response) &&\n\t\t\t\t\tpair.response.phase === 'response',\n\t\t\t) &&\n\t\t\tisStudyExchangeRow(value.completion) &&\n\t\t\tvalue.completion.phase === 'complete',\n\t)\n}\n","import type { StudyAdapterInterface } from './types.js'\nimport { holds } from '@orkestrel/contract'\n\n/** Checks whether a factory returned the complete consumer adapter contract.\n * @param value - The unknown factory result.\n * @returns True if validation, construction, and grading are callable; false otherwise.\n * @example Refuse an incomplete adapter\n * ```ts\n * import { isStudyAdapter } from '@orkestrel/study/server'\n *\n * isStudyAdapter({}) // false\n * ```\n */\nexport function isStudyAdapter(value: unknown): value is StudyAdapterInterface {\n\treturn holds(() => {\n\t\treturn (\n\t\t\ttypeof value === 'object' &&\n\t\t\tvalue !== null &&\n\t\t\t'validate' in value &&\n\t\t\ttypeof value.validate === 'function' &&\n\t\t\t'driver' in value &&\n\t\t\ttypeof value.driver === 'function' &&\n\t\t\t'grade' in value &&\n\t\t\ttypeof value.grade === 'function'\n\t\t)\n\t})\n}\n","import type { StudyEvidence, StudyJudgment } from '@src/core'\nimport type {\n\tStudyAdapterInterface,\n\tStudyAdjudication,\n\tStudyGradeFunction,\n\tStudyGradeTarget,\n\tStudyReference,\n} from './types.js'\nimport { StudyError, isStudyJudgment, isStudyRubric } from '@src/core'\nimport { isArray, isRecord } from '@orkestrel/contract'\nimport {\n\tisStudyCustodyAttempt,\n\tisStudyCustodyEvidence,\n\tisStudyCustodyManifest,\n} from '../stores/validators.js'\nimport { isStudyAdapter } from './validators.js'\n\n/** Reads a complete adapter from an admitted module namespace.\n * @param namespace - The captured consumer module.\n * @returns The validated adapter instance.\n */\nexport function readStudyAdapter(namespace: unknown): StudyAdapterInterface {\n\tif (!isRecord(namespace) || typeof namespace.createStudyAdapter !== 'function')\n\t\tthrow new StudyError('CONFIG', 'Consumer module must export createStudyAdapter')\n\tconst adapter: unknown = namespace.createStudyAdapter()\n\tif (!isStudyAdapter(adapter))\n\t\tthrow new StudyError('CONFIG', 'Consumer factory returned an incomplete study adapter')\n\treturn adapter\n}\n\n/**\n * Renders a citation of one retained trial file or evidence row.\n * @param target - The declared pair whose retained observations the citation must name\n * @param reference - The attempt file, the evidence file, or one zero-based evidence row\n * @returns The retained path, with a one-based row position for an evidence row\n * @throws StudyError - Thrown when the trial was not retained, or the citation names a row that does not exist or a row of the attempt file\n * @example Cite a retained evidence row\n * ```ts\n * import type { StudyGradeTarget } from '@orkestrel/study/server'\n * import { buildStudyReference } from '@orkestrel/study/server'\n *\n * declare const target: StudyGradeTarget\n *\n * buildStudyReference(target, { file: 'evidence', row: 0 }) // 'trials/r1-s1-a1/evidence.jsonl#1'\n * ```\n */\nexport function buildStudyReference(target: StudyGradeTarget, reference: StudyReference): string {\n\tif (!isRecord(reference)) throw new StudyError('EVIDENCE', 'Grading reference must be a record')\n\tif (target.attempt === undefined)\n\t\tthrow new StudyError('EVIDENCE', 'Grading reference names a trial that was not retained')\n\tif (reference.file !== 'attempt' && reference.file !== 'evidence')\n\t\tthrow new StudyError('EVIDENCE', 'Grading reference names an unknown retained file')\n\tconst file = reference.file === 'attempt' ? 'attempt.json' : 'evidence.jsonl'\n\tconst path = `trials/${target.trial.id}/${file}`\n\tif (reference.row === undefined) return path\n\tif (\n\t\treference.file !== 'evidence' ||\n\t\t!Number.isSafeInteger(reference.row) ||\n\t\treference.row < 0 ||\n\t\treference.row >= target.evidence.length ||\n\t\t!isStudyCustodyEvidence(target.evidence[reference.row])\n\t)\n\t\tthrow new StudyError('EVIDENCE', 'Grading reference names a retained row that does not exist')\n\treturn `${path}#${reference.row + 1}`\n}\n\n/**\n * Grades every declared trial and criterion pair through the consumer's predicate.\n * @param input - The sealed declaration, retained attempts, retained evidence, and independent rubric\n * @param grade - The consumer's domain predicate; it supplies each verdict, method, reason, and citation\n * @returns One judgment for each declared pair, in schedule then rubric order, with one-based evidence references\n * @remarks\n * The traversal validates its input at this boundary, so a direct call retains the checks the\n * host also makes. A trial without a retained attempt still receives a judgment: the predicate\n * sees no attempt and no evidence, and missing evidence stays whatever verdict the consumer\n * reads from it. The traversal never decides success, and it cites nothing the retained\n * evidence cannot back.\n * @throws StudyError - Thrown when the rubric, declaration, attempts, or evidence are invalid or foreign, when a criterion names an undeclared goal, or when a reading is not a valid judgment\n * @example Grade retained evidence with a consumer predicate\n * ```ts\n * import type { StudyAdjudication, StudyGradeFunction } from '@orkestrel/study/server'\n * import { gradeStudyEvidence } from '@orkestrel/study/server'\n *\n * declare const input: StudyAdjudication\n * declare const grade: StudyGradeFunction\n *\n * gradeStudyEvidence(input, grade)\n * ```\n */\nexport function gradeStudyEvidence(\n\tinput: StudyAdjudication,\n\tgrade: StudyGradeFunction,\n): readonly StudyJudgment[] {\n\tif (!isRecord(input)) throw new StudyError('CONFIG', 'Invalid grading input')\n\tconst { manifest, rubric, attempts, evidence } = input\n\tif (!isStudyRubric(rubric)) throw new StudyError('CONFIG', 'Invalid grading rubric')\n\tif (!isStudyCustodyManifest(manifest))\n\t\tthrow new StudyError('CONFIG', 'Invalid grading manifest or schedule')\n\tconst schedule = manifest.schedule\n\tif (!isArray(attempts) || !attempts.every((attempt) => isStudyCustodyAttempt(attempt, manifest)))\n\t\tthrow new StudyError('EVIDENCE', 'Invalid or duplicate grading attempts')\n\tconst retained = new Map(attempts.map((attempt) => [attempt.trial.id, attempt]))\n\tif (retained.size !== attempts.length)\n\t\tthrow new StudyError('EVIDENCE', 'Invalid or duplicate grading attempts')\n\tconst known = new Set(schedule.map((trial) => trial.id))\n\tif (\n\t\t!isRecord(evidence) ||\n\t\t!Object.entries(evidence).every(\n\t\t\t([id, rows]) =>\n\t\t\t\tknown.has(id) && isArray(rows) && Array.from(rows).every(isStudyCustodyEvidence),\n\t\t)\n\t)\n\t\tthrow new StudyError('EVIDENCE', 'Invalid or foreign grading evidence')\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)\n\t\t\tthrow new StudyError('CONFIG', 'Grading criterion references an undeclared goal')\n\t}\n\t// Iterators pull each trial and criterion only after the preceding predicate returned, so a\n\t// predicate that edits the caller's live arrays changes what the next judgment names.\n\treturn Object.freeze(\n\t\tschedule\n\t\t\t.values()\n\t\t\t.flatMap((trial) => {\n\t\t\t\tconst attempt = retained.get(trial.id)\n\t\t\t\tconst rows: readonly StudyEvidence[] =\n\t\t\t\t\tattempt === undefined ? Object.freeze([]) : (evidence[trial.id] ?? Object.freeze([]))\n\t\t\t\treturn rubric.criteria\n\t\t\t\t\t.values()\n\t\t\t\t\t.filter((criterion) => criterion.scenario === trial.scenario)\n\t\t\t\t\t.map((criterion): StudyJudgment => {\n\t\t\t\t\t\tconst target: StudyGradeTarget = Object.freeze({\n\t\t\t\t\t\t\ttrial,\n\t\t\t\t\t\t\tcriterion,\n\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\tevidence: rows,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tconst reading = grade(target)\n\t\t\t\t\t\tif (!isRecord(reading) || !isArray(reading.references))\n\t\t\t\t\t\t\tthrow new StudyError('EVIDENCE', 'Grading predicate returned an invalid reading')\n\t\t\t\t\t\tconst judgment = {\n\t\t\t\t\t\t\ttrial: trial.id,\n\t\t\t\t\t\t\tcriterion: criterion.id,\n\t\t\t\t\t\t\tverdict: reading.verdict,\n\t\t\t\t\t\t\tmethod: reading.method,\n\t\t\t\t\t\t\treason: reading.reason,\n\t\t\t\t\t\t\treferences: Object.freeze(\n\t\t\t\t\t\t\t\treading.references.map((reference) => buildStudyReference(target, reference)),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!isStudyJudgment(judgment))\n\t\t\t\t\t\t\tthrow new StudyError('EVIDENCE', 'Grading predicate returned an invalid judgment')\n\t\t\t\t\t\treturn Object.freeze(judgment)\n\t\t\t\t\t})\n\t\t\t})\n\t\t\t.toArray(),\n\t)\n}\n","/** Bounds admitted files before another capture is allocated. */\nexport const ARTIFACT_FILES = 8192\n\n/** Bounds all captured input bytes to 128 MiB. */\nexport const ARTIFACT_BYTES = 128 * 1024 * 1024\n\n/** Bounds one captured input file to 16 MiB. */\nexport const ARTIFACT_FILE_BYTES = 16 * 1024 * 1024\n\n/** Bounds all visited directory entries, including ignored assets. */\nexport const ARTIFACT_VISITS = 32768\n\n/** Bounds directory nesting below each selected root. */\nexport const ARTIFACT_DEPTH = 64\n\n/** Bounds selected package roots before traversal begins. */\nexport const ARTIFACT_ROOTS = 128\nimport type { ArtifactErrorCode } from './types.js'\n\n/** Marks artifact errors across module formats and installations. */\nexport const ARTIFACT_ERROR_BRAND = Symbol.for('@orkestrel/study.ArtifactError')\n\n/** Lists the artifact refusal codes. */\nexport const ARTIFACT_ERROR_CODES: readonly ArtifactErrorCode[] = Object.freeze([\n\t'ARTIFACT',\n\t'TRAVERSAL',\n\t'REDIRECT',\n\t'ALIAS',\n\t'NAME',\n\t'DUPLICATE',\n\t'OCCUPIED',\n\t'OVERLAP',\n\t'STALE',\n\t'VOLUME',\n\t'DRIFT',\n\t'LIMIT',\n])\n","import type { ArtifactErrorCode } from './types.js'\nimport { holds, INTRINSICS, isString } from '@orkestrel/contract'\nimport { ARTIFACT_ERROR_BRAND, ARTIFACT_ERROR_CODES } from './constants.js'\n\n/** Reports an invalid or drifted artifact inventory. */\nexport class ArtifactError extends Error {\n\treadonly code: ArtifactErrorCode\n\n\t/** Records the refused artifact boundary.\n\t * @param message - The specific refusal.\n\t * @param code - The refused boundary. Default: ARTIFACT.\n\t */\n\tconstructor(message: string, code: ArtifactErrorCode = 'ARTIFACT') {\n\t\tsuper(message)\n\t\tINTRINSICS.define(this, ARTIFACT_ERROR_BRAND, { value: this })\n\t\tthis.name = 'ArtifactError'\n\t\tthis.code = code\n\t}\n}\n\n/** Narrows a caught value to an artifact refusal.\n * @remarks\n * Recognizes subclasses and other module copies by an own identity brand and valid members.\n * The brand is a recognition marker. A transparent proxy, a look-alike without the brand,\n * throwing accessors, and revoked proxies return false.\n * @param value - The caught value.\n * @returns True if the value is an artifact error; false otherwise.\n */\nexport function isArtifactError(value: unknown): value is ArtifactError {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!(value instanceof INTRINSICS.error) ||\n\t\t\tINTRINSICS.prototype(value) === INTRINSICS.error.prototype\n\t\t)\n\t\t\treturn false\n\t\tif (INTRINSICS.describe(value, ARTIFACT_ERROR_BRAND)?.value !== value) return false\n\t\tconst code: unknown = INTRINSICS.reflect.read(value, 'code')\n\t\tconst stack: unknown = INTRINSICS.reflect.read(value, 'stack')\n\t\treturn (\n\t\t\tARTIFACT_ERROR_CODES.some((candidate) => candidate === code) &&\n\t\t\tisString(INTRINSICS.reflect.read(value, 'name')) &&\n\t\t\tisString(INTRINSICS.reflect.read(value, 'message')) &&\n\t\t\t(stack === undefined || isString(stack))\n\t\t)\n\t})\n}\n","import type { ArtifactClosure, ArtifactLoaderOptions, ArtifactMember } from './types.js'\nimport { arrayOf, holds, isArray, isRecord, isString } from '@orkestrel/contract'\nimport { isStudyDigest } from '@src/core'\nimport { ARTIFACT_FILES, ARTIFACT_ROOTS } from './constants.js'\nimport { matchesArtifactCredential } from './helpers.js'\n\n/** Checks whether a key names portable, non-credential members within a closure.\n * @param value - The untrusted slash-separated key.\n * @returns True if every segment is safe and contained; false otherwise.\n */\nexport function isArtifactKey(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === 'string' &&\n\t\tvalue !== '' &&\n\t\t!/[\\\\<>:\"|?*]/u.test(value) &&\n\t\t!Array.from(value).some(\n\t\t\t(character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127,\n\t\t) &&\n\t\tvalue\n\t\t\t.split('/')\n\t\t\t.every(\n\t\t\t\t(name) =>\n\t\t\t\t\tname !== '' &&\n\t\t\t\t\tname !== '.' &&\n\t\t\t\t\tname !== '..' &&\n\t\t\t\t\t!/[. ]$/.test(name) &&\n\t\t\t\t\t!/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\\.|$)/i.test(name) &&\n\t\t\t\t\t!matchesArtifactCredential(name),\n\t\t\t)\n\t)\n}\n\n/** Checks the bounded loader selections retained in a publication.\n * @param value - The decoded selections.\n * @returns True if required selections and optional groups have their declared shapes; false otherwise.\n */\nexport function isArtifactLoaderOptions(value: unknown): value is ArtifactLoaderOptions {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tarrayOf(isString)(value.entries) &&\n\t\t\tarrayOf(isString)(value.roots) &&\n\t\t\tvalue.entries.length <= ARTIFACT_FILES &&\n\t\t\tvalue.roots.length <= ARTIFACT_ROOTS &&\n\t\t\t(value.source === undefined ||\n\t\t\t\t(isRecord(value.source) && isString(value.source.root) && isString(value.source.entry))) &&\n\t\t\t(value.instrument === undefined || isString(value.instrument)) &&\n\t\t\t(value.excluded === undefined || arrayOf(isString)(value.excluded)) &&\n\t\t\t(value.assets === undefined ||\n\t\t\t\t(arrayOf(isString)(value.assets) && value.assets.length <= ARTIFACT_FILES)),\n\t)\n}\n\n/** Checks the exact file identity and provenance of a closure member.\n * @param value - The decoded member.\n * @returns True if the member has a safe key, source, digest and bounded size; false otherwise.\n */\nexport function isArtifactMember(value: unknown): value is ArtifactMember {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tisString(value.source) &&\n\t\t\tisArtifactKey(value.key) &&\n\t\t\tisStudyDigest(value.digest) &&\n\t\t\ttypeof value.size === 'number' &&\n\t\t\tNumber.isSafeInteger(value.size) &&\n\t\t\tvalue.size >= 0,\n\t)\n}\n\n/** Checks a bounded materialization record before any path is used.\n * @param value - The decoded record.\n * @returns True if its selections and member records have the declared shapes; false otherwise.\n */\nexport function isArtifactClosure(value: unknown): value is ArtifactClosure {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tisString(value.destination) &&\n\t\t\tisStudyDigest(value.digest) &&\n\t\t\tisArtifactLoaderOptions(value.options) &&\n\t\t\tisArray(value.members) &&\n\t\t\tvalue.members.length > 0 &&\n\t\t\tvalue.members.length <= ARTIFACT_FILES &&\n\t\t\tvalue.members.every(isArtifactMember),\n\t)\n}\n","import type { Dir, Dirent, BigIntStats } from 'node:fs'\nimport type { ArtifactSource, ArtifactClosure, ArtifactMember, ArtifactPackage } from './types.js'\nimport { isRecord, parseJSON } from '@orkestrel/contract'\nimport {\n\tcloseSync,\n\tfstatSync,\n\tlstatSync,\n\topenSync,\n\topendirSync,\n\treadSync,\n\trealpathSync,\n} from 'node:fs'\nimport { dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path'\nimport { containsArtifact, encodeStudyJSON, hashStudyBytes } from '../helpers.js'\nimport {\n\tARTIFACT_BYTES,\n\tARTIFACT_DEPTH,\n\tARTIFACT_FILES,\n\tARTIFACT_FILE_BYTES,\n\tARTIFACT_VISITS,\n} from './constants.js'\nimport { ArtifactError } from './errors.js'\nimport { isArtifactClosure, isArtifactKey } from './validators.js'\n\n/** Checks whether a portable segment identifies credentials.\n * @param value - One untrusted path segment.\n * @returns True if the segment has a credential filename; false otherwise.\n */\nexport function matchesArtifactCredential(value: string): boolean {\n\treturn (\n\t\t/^(?:\\.env(?:\\..*)?|\\.npmrc|auth\\.json|id_(?:rsa|dsa|ecdsa|ed25519))$/i.test(value) ||\n\t\t/\\.(?:key|pem|p12|pfx)$/i.test(value) ||\n\t\t/(?:^|[._-])token(?:$|[._-])/i.test(value)\n\t)\n}\n\n/** Resolves a portable member key without traversing outside its destination.\n * @param destination - The canonical absolute destination.\n * @param key - The slash-separated member key.\n * @returns The contained host path.\n * @throws ArtifactError - Thrown for traversal or an unsafe name.\n */\nexport function resolveArtifactMember(destination: string, key: string): string {\n\tif (\n\t\tisAbsolute(key) ||\n\t\tkey.split('/').some((name) => name === '..' || name === '.') ||\n\t\t/[\\\\:]/.test(key)\n\t)\n\t\tthrow new ArtifactError('Artifact member traverses its boundary', 'TRAVERSAL')\n\tif (!isArtifactKey(key)) throw new ArtifactError('Artifact member name is unsafe', 'NAME')\n\tconst path = resolve(destination, ...key.split('/'))\n\tif (!containsArtifact(resolve(destination), path))\n\t\tthrow new ArtifactError('Artifact member traverses its boundary', 'TRAVERSAL')\n\treturn path\n}\n\n/** Checks every existing physical ancestor before using a canonical absolute path.\n * @param path - The existing absolute file or directory.\n * @returns Its physical filesystem metadata.\n * @throws ArtifactError - Thrown for traversal, unsafe names, aliases or redirects before reading bytes.\n */\nexport function readArtifactPhysical(path: string): BigIntStats {\n\tif (!isAbsolute(path) || resolve(path) !== path)\n\t\tthrow new ArtifactError('Artifact path must be canonical and absolute', 'TRAVERSAL')\n\tconst origin = parse(path).root\n\tconst names = relative(origin, path).split(sep).filter(Boolean)\n\tif (names.some((name) => !isArtifactKey(name)))\n\t\tthrow new ArtifactError('Artifact physical path has an unsafe name', 'NAME')\n\tfor (const [index] of names.entries()) {\n\t\tconst candidate = join(origin, ...names.slice(0, index + 1))\n\t\tconst stat = lstatSync(candidate, { bigint: true })\n\t\tif (stat.isSymbolicLink()) throw new ArtifactError('Artifact path is redirected', 'REDIRECT')\n\t\tconst physical = realpathSync(candidate)\n\t\tif (physical !== candidate)\n\t\t\tthrow new ArtifactError(\n\t\t\t\t'Artifact path has a physical alias or redirect',\n\t\t\t\tphysical.toLowerCase() === candidate.toLowerCase() ? 'ALIAS' : 'REDIRECT',\n\t\t\t)\n\t}\n\treturn lstatSync(path, { bigint: true })\n}\n\n/** Finds the common physical parent that preserves every selected path's relative resolution.\n * @param paths - Existing absolute members or selected roots on one volume.\n * @returns Their common ancestor directory.\n * @throws ArtifactError - Thrown when selections span volumes or contain no files.\n */\nexport function resolveArtifactBase(paths: readonly string[]): string {\n\tconst first = paths[0]\n\tif (first === undefined) throw new ArtifactError('Artifact population is empty')\n\tif (paths.some((path) => parse(path).root !== parse(first).root))\n\t\tthrow new ArtifactError('Artifact sources require one volume', 'VOLUME')\n\tconst origin = parse(first).root\n\tconst names = relative(origin, dirname(first)).split(sep).filter(Boolean)\n\tconst parents = Array.from({ length: names.length + 1 }, (_entry, index) =>\n\t\tjoin(origin, ...names.slice(0, index)),\n\t).reverse()\n\tconst base = parents.find((parent) =>\n\t\tpaths.every((path) => parent === path || containsArtifact(parent, path)),\n\t)\n\tif (base === undefined)\n\t\tthrow new ArtifactError('Artifact sources have no common parent', 'VOLUME')\n\treturn base\n}\n\n/** Relocates an original path through a closure's retained physical forest.\n * @param closure - The verified closure record.\n * @param path - An original member or ancestor within its forest.\n * @returns The corresponding destination path.\n * @throws ArtifactError - Thrown when provenance or containment is inconsistent.\n */\nexport function relocateArtifactPath(closure: ArtifactClosure, path: string): string {\n\tconst first = closure.members[0]\n\tif (first === undefined) throw new ArtifactError('Artifact population is empty')\n\tconst origin = resolve(first.source, ...first.key.split('/').map(() => '..'))\n\tif (path !== origin && !containsArtifact(origin, path))\n\t\tthrow new ArtifactError('Artifact relocation traverses its forest', 'TRAVERSAL')\n\tif (closure.members.some((member) => resolveArtifactMember(origin, member.key) !== member.source))\n\t\tthrow new ArtifactError('Artifact member provenance is inconsistent', 'TRAVERSAL')\n\treturn path === origin\n\t\t? closure.destination\n\t\t: resolveArtifactMember(closure.destination, relative(origin, path).split(sep).join('/'))\n}\n\n/** Computes a destination-independent digest of members and relative package identities.\n * @param members - Complete copied membership, with source provenance excluded from identity.\n * @param packages - Package identities with relocated roots.\n * @param destination - The common destination directory.\n * @returns The portable SHA-256 identity.\n */\nexport function computeArtifactClosureDigest(\n\tmembers: readonly ArtifactMember[],\n\tpackages: readonly ArtifactPackage[],\n\tdestination: string,\n): string {\n\treturn hashStudyBytes(\n\t\tencodeStudyJSON({\n\t\t\tmembers: members\n\t\t\t\t.map(({ key, digest, size }) => ({ key, digest, size }))\n\t\t\t\t.toSorted((left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0)),\n\t\t\tpackages: packages\n\t\t\t\t.map((entry) => ({\n\t\t\t\t\t...entry,\n\t\t\t\t\troot: relative(destination, entry.root).split(sep).join('/'),\n\t\t\t\t}))\n\t\t\t\t.toSorted((left, right) => (left.root < right.root ? -1 : left.root > right.root ? 1 : 0)),\n\t\t}),\n\t)\n}\n\n/** Verifies complete copied membership, path safety, exact bytes, and portable identity.\n * @param closure - The materialization record to verify independently.\n * @param published - If true, permits the root publication marker; if false, refuses every extra file. Default: false.\n * @returns Nothing when the entire forest matches.\n * @throws ArtifactError - Thrown for malformed records, changed membership, bytes, or physical paths.\n */\nexport function verifyArtifactClosure(closure: ArtifactClosure, published = false): void {\n\tif (!isArtifactClosure(closure))\n\t\tthrow new ArtifactError('Artifact closure record is invalid', 'NAME')\n\tif (!readArtifactPhysical(closure.destination).isDirectory())\n\t\tthrow new ArtifactError('Artifact closure requires a directory', 'DRIFT')\n\tconst keys = new Set(closure.members.map((member) => member.key))\n\tif (keys.size !== closure.members.length)\n\t\tthrow new ArtifactError('Artifact member key is duplicated', 'DUPLICATE')\n\tif (\n\t\tnew Set(closure.members.map((member) => member.key.toLowerCase())).size !==\n\t\tclosure.members.length\n\t)\n\t\tthrow new ArtifactError('Artifact member keys have a case alias', 'ALIAS')\n\tconst directories = [{ path: closure.destination, depth: 0 }]\n\tconst visited: string[] = []\n\tconst files: Array<{ readonly path: string; readonly identity: string; readonly size: number }> =\n\t\t[]\n\tfor (const directory of directories) {\n\t\tif (directory.depth > ARTIFACT_DEPTH)\n\t\t\tthrow new ArtifactError('Artifact directory depth limit exceeded', 'LIMIT')\n\t\tconst handle = opendirSync(directory.path)\n\t\ttry {\n\t\t\tfor (const entry of iterateArtifactEntries(handle)) {\n\t\t\t\tconst path = join(directory.path, entry.name)\n\t\t\t\tvisited.push(path)\n\t\t\t\tif (visited.length > ARTIFACT_VISITS)\n\t\t\t\t\tthrow new ArtifactError('Artifact traversal limit exceeded', 'LIMIT')\n\t\t\t\tconst stat = readArtifactPhysical(path)\n\t\t\t\tif (stat.isDirectory()) {\n\t\t\t\t\tif (\n\t\t\t\t\t\t!closure.members.some((member) =>\n\t\t\t\t\t\t\tcontainsArtifact(path, resolveArtifactMember(closure.destination, member.key)),\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new ArtifactError('Artifact closure membership drifted', 'DRIFT')\n\t\t\t\t\tdirectories.push({ path, depth: directory.depth + 1 })\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (!stat.isFile()) throw new ArtifactError('Artifact closure contains a non-file', 'DRIFT')\n\t\t\t\tif (published && path === join(closure.destination, 'closure.json')) continue\n\t\t\t\tconst key = relative(closure.destination, path).split(sep).join('/')\n\t\t\t\tif (!keys.has(key)) throw new ArtifactError('Artifact closure membership drifted', 'DRIFT')\n\t\t\t\tfiles.push({ path, identity: `${stat.dev}:${stat.ino}`, size: Number(stat.size) })\n\t\t\t\tif (files.length > ARTIFACT_FILES)\n\t\t\t\t\tthrow new ArtifactError('Artifact closure exceeds its capture allowance', 'LIMIT')\n\t\t\t}\n\t\t} finally {\n\t\t\thandle.closeSync()\n\t\t}\n\t}\n\tif (files.length !== closure.members.length)\n\t\tthrow new ArtifactError('Artifact closure membership drifted', 'DRIFT')\n\tif (files.reduce((sum, file) => sum + file.size, 0) > ARTIFACT_BYTES)\n\t\tthrow new ArtifactError('Artifact closure exceeds its capture allowance', 'LIMIT')\n\tif (new Set(files.map((file) => file.identity)).size !== files.length)\n\t\tthrow new ArtifactError('Artifact members have a physical alias', 'ALIAS')\n\tfor (const member of closure.members) {\n\t\tconst file = readArtifact(resolveArtifactMember(closure.destination, member.key))\n\t\tif (file.digest !== member.digest || file.size !== member.size)\n\t\t\tthrow new ArtifactError('Artifact closure bytes drifted', 'DRIFT')\n\t}\n\tconst selected = [\n\t\t...closure.options.entries,\n\t\t...(closure.options.assets ?? []),\n\t\t...(closure.options.excluded ?? []),\n\t\t...(closure.options.source === undefined ? [] : [closure.options.source.entry]),\n\t]\n\tif (\n\t\tselected.some((path) => !files.some((file) => file.path === path)) ||\n\t\tclosure.options.roots.some(\n\t\t\t(root) => root !== closure.destination && !containsArtifact(closure.destination, root),\n\t\t) ||\n\t\t(closure.options.source !== undefined &&\n\t\t\tclosure.options.source.root !== closure.destination &&\n\t\t\t!containsArtifact(closure.destination, closure.options.source.root))\n\t)\n\t\tthrow new ArtifactError('Artifact closure selection traverses its population', 'TRAVERSAL')\n\tconst packages = closure.options.roots.map((root): ArtifactPackage => {\n\t\tconst manifest = readArtifact(join(root, 'package.json'))\n\t\tconst value = parseJSON(Buffer.from(manifest.source).toString('utf8'))\n\t\tif (!isRecord(value) || typeof value.name !== 'string' || typeof value.version !== 'string')\n\t\t\tthrow new ArtifactError('Artifact closure manifest is invalid', 'DRIFT')\n\t\treturn { root, name: value.name, version: value.version }\n\t})\n\tif (\n\t\tcomputeArtifactClosureDigest(closure.members, packages, closure.destination) !== closure.digest\n\t)\n\t\tthrow new ArtifactError('Artifact closure identity drifted', 'DRIFT')\n}\n\n/** Fills a buffer from an open descriptor, one positioned read at a time.\n * @param descriptor - The open file descriptor to read.\n * @param target - The buffer to fill.\n * @param offset - The position in the file and the buffer to continue from; Default: 0.\n * @returns The bytes read, as the whole buffer when the file filled it or as its leading part when the file ended first.\n */\nexport function readArtifactBytes(descriptor: number, target: Buffer, offset = 0): Buffer {\n\tif (offset >= target.length) return target\n\tconst count = readSync(descriptor, target, offset, target.length - offset, offset)\n\treturn count === 0\n\t\t? target.subarray(0, offset)\n\t\t: readArtifactBytes(descriptor, target, offset + count)\n}\n\n/** Iterates the remaining entries of an open directory handle lazily, in read order.\n * @param handle - The open synchronous directory handle; the caller owns it and closes it.\n * @returns Each remaining entry until the handle reports the end. An entry is read only when the consumer asks for it, so a consumer that stops early leaves the rest unread.\n */\nexport function* iterateArtifactEntries(handle: Dir): Generator<Dirent, void> {\n\tfor (;;) {\n\t\tconst entry = handle.readSync()\n\t\tif (entry === null) return\n\t\tyield entry\n\t}\n}\n\n/** Reads a bounded regular file only through its canonical absolute path.\n * @param path - The absolute path to inspect.\n * @param maximum - The remaining capture budget; Default: 16 MiB.\n * @returns Captured bytes with their identity.\n * @throws Thrown when the path is linked, noncanonical, oversized, or changes while read.\n */\nexport function readArtifact(path: string, maximum = ARTIFACT_FILE_BYTES): ArtifactSource {\n\tif (\n\t\t!Number.isSafeInteger(maximum) ||\n\t\tmaximum < 0 ||\n\t\t!isAbsolute(path) ||\n\t\tresolve(path) !== path ||\n\t\trealpathSync(path) !== path ||\n\t\t!lstatSync(path).isFile()\n\t) {\n\t\tthrow new ArtifactError(`Artifact requires a canonical regular file and byte budget: ${path}`)\n\t}\n\treadArtifactPhysical(path)\n\tconst descriptor = openSync(path, 'r')\n\ttry {\n\t\tconst before = fstatSync(descriptor)\n\t\tif (!before.isFile() || before.size > Math.min(maximum, ARTIFACT_FILE_BYTES))\n\t\t\tthrow new ArtifactError(`Artifact byte limit exceeded: ${path}`)\n\t\tconst source = readArtifactBytes(descriptor, Buffer.alloc(before.size))\n\t\tif (source.length !== before.size)\n\t\t\tthrow new ArtifactError(`Artifact file drifted while reading: ${path}`)\n\t\tconst after = fstatSync(descriptor)\n\t\tif (\n\t\t\tbefore.size !== after.size ||\n\t\t\tbefore.mtimeMs !== after.mtimeMs ||\n\t\t\tbefore.ctimeMs !== after.ctimeMs ||\n\t\t\trealpathSync(path) !== path ||\n\t\t\t!lstatSync(path).isFile()\n\t\t)\n\t\t\tthrow new ArtifactError(`Artifact file drifted while reading: ${path}`)\n\t\treturn { path, digest: hashStudyBytes(source), size: source.byteLength, source }\n\t} finally {\n\t\tcloseSync(descriptor)\n\t}\n}\n","import type {\n\tLoadHookContext,\n\tLoadFnOutput,\n\tResolveHookContext,\n\tResolveFnOutput,\n} from 'node:module'\nimport type {\n\tArtifactHookInput,\n\tArtifactLoadHandler,\n\tArtifactResolveHandler,\n\tArtifactSource,\n} from './types.js'\nimport { isBuiltin, stripTypeScriptTypes } from 'node:module'\nimport { basename, extname, join } from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { containsArtifact } from '../helpers.js'\nimport { ArtifactError } from './errors.js'\nimport { readArtifact } from './helpers.js'\n\n/** Enforces captured inventory membership at every synchronous native import edge. */\nexport class Resolution {\n\t#input: ArtifactHookInput\n\t#files: ReadonlyMap<string, ArtifactSource>\n\n\t/** Retains the trusted captured inventory and its private namespace.\n\t * @param input - Captured built bytes and separate source selection.\n\t */\n\tconstructor(input: ArtifactHookInput) {\n\t\tthis.#input = input\n\t\tthis.#files = new Map(input.files.map((file) => [file.path, file]))\n\t}\n\n\t/** Resolves native edges with source-local JavaScript-to-TypeScript substitution.\n\t * @param specifier - The requested native specifier.\n\t * @param context - Node's resolution context.\n\t * @param next - The remaining native resolution chain.\n\t * @returns An admitted URL in the captured namespace.\n\t */\n\tresolve(\n\t\tspecifier: string,\n\t\tcontext: ResolveHookContext,\n\t\tnext: ArtifactResolveHandler,\n\t): ResolveFnOutput {\n\t\tconst parent = context.parentURL === undefined ? undefined : new URL(context.parentURL)\n\t\tconst initial = specifier.startsWith('file:') ? new URL(specifier) : undefined\n\t\tif (\n\t\t\tparent?.searchParams.get('artifact') !== this.#input.token &&\n\t\t\tinitial?.searchParams.get('artifact') !== this.#input.token\n\t\t)\n\t\t\treturn next(specifier, context)\n\t\tif (isBuiltin(specifier)) {\n\t\t\tconst instrument = this.#input.instrument\n\t\t\tconst trusted =\n\t\t\t\tinstrument !== undefined &&\n\t\t\t\tparent?.protocol === 'file:' &&\n\t\t\t\tcontainsArtifact(join(instrument, 'dist'), fileURLToPath(parent)) &&\n\t\t\t\tthis.#files.has(fileURLToPath(parent))\n\t\t\tif (\n\t\t\t\t!trusted &&\n\t\t\t\t['module', 'vm', 'worker_threads', 'child_process', 'cluster'].includes(\n\t\t\t\t\tspecifier.replace(/^node:/, ''),\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow new ArtifactError(`Artifact alternate loader is unsupported: ${specifier}`)\n\t\t\treturn next(specifier, context)\n\t\t}\n\t\tfor (const file of this.#input.files) {\n\t\t\tif (basename(file.path) === 'package.json' && readArtifact(file.path).digest !== file.digest)\n\t\t\t\tthrow new ArtifactError(`Artifact manifest drifted: ${file.path}`)\n\t\t}\n\t\tconst source = this.#input.source\n\t\tconst target = this.#locate(specifier, parent, initial)\n\t\tif (\n\t\t\tsource !== undefined &&\n\t\t\ttarget?.protocol === 'file:' &&\n\t\t\tcontainsArtifact(source.root, fileURLToPath(target))\n\t\t) {\n\t\t\tif (\n\t\t\t\tparent !== undefined &&\n\t\t\t\t(parent.protocol !== 'file:' || !containsArtifact(source.root, fileURLToPath(parent))) &&\n\t\t\t\tinitial?.searchParams.get('artifact') !== this.#input.token\n\t\t\t)\n\t\t\t\tthrow new ArtifactError('Artifact built modules cannot import consumer sources')\n\t\t\tif (\n\t\t\t\ttarget.hash !== '' ||\n\t\t\t\t(target.search !== '' && target.search !== `?artifact=${this.#input.token}`)\n\t\t\t)\n\t\t\t\tthrow new ArtifactError(`Artifact source URL is unsupported: ${target.href}`)\n\t\t\tconst file = this.#files.get(fileURLToPath(target))\n\t\t\tif (file === undefined || !['.ts', '.mts', '.js', '.mjs'].includes(extname(file.path)))\n\t\t\t\tthrow new ArtifactError(`Artifact source dependency is not admitted: ${target.href}`)\n\t\t\tif (readArtifact(file.path).digest !== file.digest)\n\t\t\t\tthrow new ArtifactError(`Artifact dependency drifted: ${file.path}`)\n\t\t\ttarget.searchParams.set('artifact', this.#input.token)\n\t\t\treturn {\n\t\t\t\turl: target.href,\n\t\t\t\tformat: 'module',\n\t\t\t\tshortCircuit: true,\n\t\t\t}\n\t\t}\n\t\tconst result = next(specifier, context)\n\t\tconst url = new URL(result.url)\n\t\tif (\n\t\t\turl.protocol !== 'file:' ||\n\t\t\turl.hash !== '' ||\n\t\t\t(url.search !== '' && url.search !== `?artifact=${this.#input.token}`)\n\t\t)\n\t\t\tthrow new ArtifactError(`Artifact URL is unsupported: ${result.url}`)\n\t\turl.search = ''\n\t\tconst file = this.#files.get(fileURLToPath(url))\n\t\tif (\n\t\t\tfile === undefined ||\n\t\t\t(source !== undefined && containsArtifact(source.root, file.path)) ||\n\t\t\t!['.js', '.mjs', '.json'].includes(extname(file.path)) ||\n\t\t\t(result.format !== 'module' && result.format !== 'json')\n\t\t)\n\t\t\tthrow new ArtifactError(`Artifact dependency is not admitted ESM: ${result.url}`)\n\t\tif (this.#input.excluded?.includes(file.path) === true)\n\t\t\tthrow new ArtifactError(`Artifact module is excluded: ${file.path}`)\n\t\tif (readArtifact(file.path).digest !== file.digest)\n\t\t\tthrow new ArtifactError(`Artifact dependency drifted: ${file.path}`)\n\t\turl.searchParams.set('artifact', this.#input.token)\n\t\treturn { ...result, url: url.href }\n\t}\n\n\t/** Returns captured bytes after verifying their live disk identity.\n\t * @param href - Node's resolved URL.\n\t * @param context - Node's load context.\n\t * @param next - The remaining native load chain.\n\t * @returns Captured ESM, JSON, or native strip-only TypeScript output.\n\t */\n\tload(href: string, context: LoadHookContext, next: ArtifactLoadHandler): LoadFnOutput {\n\t\tconst url = new URL(href)\n\t\tif (url.searchParams.get('artifact') !== this.#input.token) return next(href, context)\n\t\turl.search = ''\n\t\tconst file = this.#files.get(fileURLToPath(url))\n\t\tif (file === undefined || (context.format !== 'module' && context.format !== 'json'))\n\t\t\tthrow new ArtifactError(`Artifact load is unsupported: ${href}`)\n\t\tif (readArtifact(file.path).digest !== file.digest)\n\t\t\tthrow new ArtifactError(`Artifact dependency drifted: ${file.path}`)\n\t\tconst extension = extname(file.path)\n\t\treturn {\n\t\t\tformat: context.format,\n\t\t\tsource:\n\t\t\t\textension === '.ts' || extension === '.mts'\n\t\t\t\t\t? stripTypeScriptTypes(Buffer.from(file.source).toString('utf8'), { mode: 'strip' })\n\t\t\t\t\t: new Uint8Array(file.source),\n\t\t\tshortCircuit: true,\n\t\t}\n\t}\n\n\t// Locates a source-local relative edge, substituting the captured TypeScript twin of a\n\t// JavaScript specifier; any other edge keeps its initial target.\n\t#locate(specifier: string, parent: URL | undefined, initial: URL | undefined): URL | undefined {\n\t\tconst source = this.#input.source\n\t\tif (\n\t\t\tsource === undefined ||\n\t\t\tparent?.protocol !== 'file:' ||\n\t\t\t!containsArtifact(source.root, fileURLToPath(parent)) ||\n\t\t\t!(specifier.startsWith('./') || specifier.startsWith('../'))\n\t\t)\n\t\t\treturn initial\n\t\tconst target = new URL(specifier, parent)\n\t\tif (target.search !== '' || target.hash !== '')\n\t\t\tthrow new ArtifactError(`Artifact source URL is unsupported: ${specifier}`)\n\t\tconst path = fileURLToPath(target)\n\t\tif (!containsArtifact(source.root, path))\n\t\t\tthrow new ArtifactError(`Artifact source dependency escapes its root: ${specifier}`)\n\t\tconst extension = extname(path)\n\t\tif (extension !== '.js' && extension !== '.mjs') return target\n\t\tconst substitute = `${path.slice(0, -extension.length)}${extension === '.js' ? '.ts' : '.mts'}`\n\t\tif (!this.#files.has(substitute)) return target\n\t\tif (this.#files.has(path))\n\t\t\tthrow new ArtifactError(`Artifact source target is ambiguous: ${path}`)\n\t\treturn pathToFileURL(substitute)\n\t}\n}\n","import type {\n\tArtifactInventory,\n\tArtifactLoaderOptions,\n\tArtifactLoaderInterface,\n\tArtifactClosure,\n\tArtifactMember,\n\tArtifactPackage,\n\tArtifactSource,\n\tArtifactTally,\n} from './types.js'\nimport { isNonEmptyString, isRecord } from '@orkestrel/contract'\nimport { randomUUID } from 'node:crypto'\nimport { lstatSync, opendirSync, realpathSync, mkdirSync } from 'node:fs'\nimport { writeFile } from 'node:fs/promises'\nimport { registerHooks, stripTypeScriptTypes } from 'node:module'\nimport { dirname, extname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport {\n\tARTIFACT_BYTES,\n\tARTIFACT_DEPTH,\n\tARTIFACT_FILES,\n\tARTIFACT_ROOTS,\n\tARTIFACT_VISITS,\n} from './constants.js'\nimport { containsArtifact, hashStudyBytes, matchesSystemError } from '../helpers.js'\nimport { ArtifactError, isArtifactError } from './errors.js'\nimport {\n\tcomputeArtifactClosureDigest,\n\titerateArtifactEntries,\n\treadArtifact,\n\treadArtifactPhysical,\n\trelocateArtifactPath,\n\tresolveArtifactBase,\n\tresolveArtifactMember,\n\tverifyArtifactClosure,\n} from './helpers.js'\nimport { Resolution } from './Resolution.js'\n\n/** Captures built ESM and a separate strip-only consumer adapter in a fresh worker.\n * @remarks\n * Loads trusted code without sandboxing untrusted code. Native process APIs, eval and external\n * services are not replayed. One inventory may load per process; terminate it afterwards.\n */\nexport class ArtifactLoader implements ArtifactLoaderInterface {\n\tstatic #active = false\n\t#options: ArtifactLoaderOptions\n\t#inventory: ArtifactInventory | undefined\n\t#sources: readonly ArtifactSource[] = []\n\t#token: string | undefined\n\t#references: ReadonlyMap<string, string> = new Map()\n\n\t/** Captures selections without reading or executing selected modules.\n\t * @param options - Canonical built selections and optional consumer source selection.\n\t */\n\tconstructor(options: ArtifactLoaderOptions) {\n\t\tif (options.roots.length > ARTIFACT_ROOTS || options.entries.length > ARTIFACT_FILES)\n\t\t\tthrow new ArtifactError('Artifact selection exceeds its limit')\n\t\tthis.#options = {\n\t\t\t...options,\n\t\t\tentries: [...options.entries],\n\t\t\troots: [...options.roots],\n\t\t\t...(options.source === undefined\n\t\t\t\t? {}\n\t\t\t\t: { source: { root: options.source.root, entry: options.source.entry } }),\n\t\t\t...(options.excluded === undefined ? {} : { excluded: [...options.excluded] }),\n\t\t\t...(options.assets === undefined ? {} : { assets: [...options.assets] }),\n\t\t}\n\t}\n\n\t/** Reads and identifies admitted files without evaluating selected modules.\n\t * @returns Frozen evidence identifying all captured bytes and the native runtime.\n\t * @throws Thrown for invalid selections, unsupported TypeScript, limits, or drift.\n\t */\n\tinspect(): ArtifactInventory {\n\t\tif (this.#inventory !== undefined) {\n\t\t\tthis.verify()\n\t\t\treturn this.#inventory\n\t\t}\n\t\tif (\n\t\t\t(this.#options.entries.length === 0 && this.#options.source === undefined) ||\n\t\t\tthis.#options.roots.length > ARTIFACT_ROOTS ||\n\t\t\tthis.#options.entries.length > ARTIFACT_FILES\n\t\t)\n\t\t\tthrow new ArtifactError('Artifact selection is empty or exceeds its limit')\n\t\tif (\n\t\t\tthis.#options.instrument !== undefined &&\n\t\t\t!this.#options.roots.includes(this.#options.instrument)\n\t\t)\n\t\t\tthrow new ArtifactError('Artifact instrument must be an admitted package root')\n\t\tconst sources = this.#capture()\n\t\tconst packages = [...this.#options.roots].sort().map((root, index, sorted): ArtifactPackage => {\n\t\t\tconst manifest = sources.find((file) => file.path === join(root, 'package.json'))\n\t\t\tif (manifest === undefined) throw new ArtifactError(`Artifact manifest is missing: ${root}`)\n\t\t\tconst value: unknown = JSON.parse(Buffer.from(manifest.source).toString('utf8'))\n\t\t\tif (\n\t\t\t\t!isRecord(value) ||\n\t\t\t\tvalue.type !== 'module' ||\n\t\t\t\t!isNonEmptyString(value.name) ||\n\t\t\t\t!isNonEmptyString(value.version)\n\t\t\t)\n\t\t\t\tthrow new ArtifactError(`Artifact requires a named, versioned ESM package: ${root}`)\n\t\t\tif (sorted.indexOf(root) !== index)\n\t\t\t\tthrow new ArtifactError(`Artifact package identity is duplicated: ${value.name}`)\n\t\t\treturn Object.freeze({ root, name: value.name, version: value.version })\n\t\t})\n\t\tfor (const entry of this.#options.entries) {\n\t\t\tif (\n\t\t\t\t!['.js', '.mjs'].includes(extname(entry)) ||\n\t\t\t\t!sources.some((file) => file.path === entry) ||\n\t\t\t\t!packages.some((item) => containsArtifact(join(item.root, 'dist'), entry))\n\t\t\t)\n\t\t\t\tthrow new ArtifactError(`Artifact entry must be admitted built ESM: ${entry}`)\n\t\t}\n\t\tconst source = this.#options.source\n\t\tif (source !== undefined) {\n\t\t\tif (\n\t\t\t\t!['.ts', '.mts', '.js', '.mjs'].includes(extname(source.entry)) ||\n\t\t\t\t!containsArtifact(source.root, source.entry) ||\n\t\t\t\t!sources.some((file) => file.path === source.entry)\n\t\t\t)\n\t\t\t\tthrow new ArtifactError('Artifact source entry must be an admitted module')\n\t\t\tfor (const file of sources.filter((candidate) =>\n\t\t\t\tcontainsArtifact(source.root, candidate.path),\n\t\t\t)) {\n\t\t\t\tif (file.path.endsWith('.ts') || file.path.endsWith('.mts')) {\n\t\t\t\t\tconst counterpart = file.path.endsWith('.mts')\n\t\t\t\t\t\t? `${file.path.slice(0, -4)}.mjs`\n\t\t\t\t\t\t: `${file.path.slice(0, -3)}.js`\n\t\t\t\t\tif (sources.some((candidate) => candidate.path === counterpart))\n\t\t\t\t\t\tthrow new ArtifactError(`Artifact source target is ambiguous: ${file.path}`)\n\t\t\t\t\tstripTypeScriptTypes(Buffer.from(file.source).toString('utf8'), { mode: 'strip' })\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsources.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))\n\t\tconst settings = process.env.NODE_OPTIONS\n\t\tconst evidence = {\n\t\t\tnode: process.version,\n\t\t\truntime: Object.freeze({\n\t\t\t\targuments: Object.freeze([...process.execArgv]),\n\t\t\t\tplatform: process.platform,\n\t\t\t\tarchitecture: process.arch,\n\t\t\t\t...(settings === undefined ? {} : { options: settings }),\n\t\t\t}),\n\t\t\tentries: Object.freeze(\n\t\t\t\t[\n\t\t\t\t\t...new Set([...this.#options.entries, ...(source === undefined ? [] : [source.entry])]),\n\t\t\t\t].sort(),\n\t\t\t),\n\t\t\tpackages: Object.freeze(packages),\n\t\t\t...(source === undefined ? {} : { source: Object.freeze({ ...source }) }),\n\t\t\t...(this.#options.instrument === undefined ? {} : { instrument: this.#options.instrument }),\n\t\t\tfiles: Object.freeze(\n\t\t\t\tsources.map(({ path, digest, size }) => Object.freeze({ path, digest, size })),\n\t\t\t),\n\t\t\t...(this.#options.assets === undefined\n\t\t\t\t? {}\n\t\t\t\t: { assets: Object.freeze([...this.#options.assets].sort()) }),\n\t\t}\n\t\tthis.#sources = sources\n\t\tthis.#references = new Map(\n\t\t\tsources.map((file) => {\n\t\t\t\tconst stat = readArtifactPhysical(file.path)\n\t\t\t\treturn [file.path, `${stat.dev}:${stat.ino}:${stat.mtimeNs}:${stat.ctimeNs}`]\n\t\t\t}),\n\t\t)\n\t\tthis.#inventory = Object.freeze({\n\t\t\tdigest: hashStudyBytes(JSON.stringify(evidence)),\n\t\t\t...evidence,\n\t\t})\n\t\tthis.verify()\n\t\treturn this.#inventory\n\t}\n\n\t/** Refuses byte and population drift since inspection.\n\t * @throws Thrown when any admitted file or the admitted population changes.\n\t */\n\tverify(): void {\n\t\tif (this.#inventory === undefined) throw new ArtifactError('Artifact inspection is required')\n\t\tconst current = this.#capture()\n\t\tconst captured = new Map(this.#sources.map((file) => [file.path, file.digest]))\n\t\tif (\n\t\t\tcurrent.length !== this.#sources.length ||\n\t\t\tcurrent.some((file) => captured.get(file.path) !== file.digest)\n\t\t)\n\t\t\tthrow new ArtifactError('Artifact inventory drifted')\n\t}\n\n\t/** Imports one selected entry through synchronous captured-byte hooks.\n\t * @param entry - The exact canonical built entry or selected source adapter entry.\n\t * @returns The actual module namespace for the caller to narrow.\n\t * @throws Thrown for drift, unsupported edges, evaluation failures, or a reused worker.\n\t */\n\tasync load(entry: string): Promise<unknown> {\n\t\tconst inventory = this.inspect()\n\t\tif (!inventory.entries.includes(entry))\n\t\t\tthrow new ArtifactError('Artifact entry was not selected')\n\t\tif (this.#token === undefined) {\n\t\t\tif (ArtifactLoader.#active)\n\t\t\t\tthrow new ArtifactError('Artifact loading requires a fresh process')\n\t\t\tconst token = randomUUID()\n\t\t\tconst resolution = new Resolution({\n\t\t\t\ttoken,\n\t\t\t\tfiles: this.#sources.filter(\n\t\t\t\t\t(file) =>\n\t\t\t\t\t\tthis.#options.roots.some(\n\t\t\t\t\t\t\t(root) =>\n\t\t\t\t\t\t\t\tfile.path === join(root, 'package.json') ||\n\t\t\t\t\t\t\t\tcontainsArtifact(join(root, 'dist'), file.path),\n\t\t\t\t\t\t) ||\n\t\t\t\t\t\t(this.#options.source !== undefined &&\n\t\t\t\t\t\t\tcontainsArtifact(this.#options.source.root, file.path)),\n\t\t\t\t),\n\t\t\t\t...(inventory.source === undefined ? {} : { source: inventory.source }),\n\t\t\t\t...(inventory.instrument === undefined ? {} : { instrument: inventory.instrument }),\n\t\t\t\t...(this.#options.excluded === undefined ? {} : { excluded: this.#options.excluded }),\n\t\t\t})\n\t\t\tregisterHooks({\n\t\t\t\tresolve: (specifier, context, next) => resolution.resolve(specifier, context, next),\n\t\t\t\tload: (href, context, next) => resolution.load(href, context, next),\n\t\t\t})\n\t\t\tthis.#token = token\n\t\t\tArtifactLoader.#active = true\n\t\t}\n\t\tconst url = pathToFileURL(entry)\n\t\turl.searchParams.set('artifact', this.#token)\n\t\tconst namespace: unknown = await import(url.href)\n\t\tthis.verify()\n\t\treturn namespace\n\t}\n\n\t/** Copies the inspected physical forest into an exclusive absent destination.\n\t * @param destination - The canonical absent absolute directory under an existing physical parent.\n\t * @returns The independently verified copied membership and relocated selections.\n\t * @throws ArtifactError - Thrown at the refused path, stale-source, volume, or drift boundary.\n\t */\n\tasync materialize(destination: string): Promise<ArtifactClosure> {\n\t\tif (new Set(this.#options.roots).size !== this.#options.roots.length)\n\t\t\tthrow new ArtifactError('Artifact package root is duplicated', 'DUPLICATE')\n\t\tif (!isAbsolute(destination) || resolve(destination) !== destination)\n\t\t\tthrow new ArtifactError('Artifact destination must be canonical and absolute', 'TRAVERSAL')\n\t\tconst boundaries = [\n\t\t\t...this.#options.roots,\n\t\t\t...(this.#options.source === undefined ? [] : [this.#options.source.root]),\n\t\t\t...(this.#options.assets ?? []),\n\t\t]\n\t\tif (boundaries.some((path) => parse(path).root !== parse(destination).root))\n\t\t\tthrow new ArtifactError('Artifact closure requires one volume', 'VOLUME')\n\t\tif (\n\t\t\tboundaries.some(\n\t\t\t\t(path) =>\n\t\t\t\t\tpath === destination ||\n\t\t\t\t\tcontainsArtifact(path, destination) ||\n\t\t\t\t\tcontainsArtifact(destination, path),\n\t\t\t)\n\t\t)\n\t\t\tthrow new ArtifactError('Artifact destination overlaps a source', 'OVERLAP')\n\t\tconst parent = readArtifactPhysical(dirname(destination))\n\t\tresolveArtifactMember(dirname(destination), relative(dirname(destination), destination))\n\t\tif (!parent.isDirectory())\n\t\t\tthrow new ArtifactError('Artifact destination parent must be a directory', 'REDIRECT')\n\t\ttry {\n\t\t\tlstatSync(destination)\n\t\t\tthrow new ArtifactError('Artifact destination must be absent', 'OCCUPIED')\n\t\t} catch (error) {\n\t\t\tif (!matchesSystemError(error, 'ENOENT')) throw error\n\t\t}\n\t\tconst inspected = this.#inventory !== undefined\n\t\ttry {\n\t\t\tfor (const path of boundaries) readArtifactPhysical(path)\n\t\t\tthis.inspect()\n\t\t\tfor (const file of this.#sources) {\n\t\t\t\tconst stat = readArtifactPhysical(file.path)\n\t\t\t\tif (stat.dev !== parent.dev)\n\t\t\t\t\tthrow new ArtifactError('Artifact closure requires one volume', 'VOLUME')\n\t\t\t\tif (\n\t\t\t\t\t`${stat.dev}:${stat.ino}:${stat.mtimeNs}:${stat.ctimeNs}` !==\n\t\t\t\t\tthis.#references.get(file.path)\n\t\t\t\t)\n\t\t\t\t\tthrow new ArtifactError('Artifact source reference is stale', 'STALE')\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tinspected &&\n\t\t\t\t!(isArtifactError(error) && ['REDIRECT', 'ALIAS', 'NAME', 'VOLUME'].includes(error.code))\n\t\t\t)\n\t\t\t\tthrow new ArtifactError('Artifact source inspection is stale', 'STALE')\n\t\t\tthrow error\n\t\t}\n\t\tconst base = resolveArtifactBase([\n\t\t\t...this.#sources.map((file) => file.path),\n\t\t\t...this.#options.roots,\n\t\t\t...(this.#options.source === undefined ? [] : [this.#options.source.root]),\n\t\t])\n\t\tconst members: readonly ArtifactMember[] = Object.freeze(\n\t\t\tthis.#sources.map((file) =>\n\t\t\t\tObject.freeze({\n\t\t\t\t\tsource: file.path,\n\t\t\t\t\tkey: relative(base, file.path).split(sep).join('/'),\n\t\t\t\t\tdigest: file.digest,\n\t\t\t\t\tsize: file.size,\n\t\t\t\t}),\n\t\t\t),\n\t\t)\n\t\tconst keys = new Set(members.map((member) => member.key))\n\t\tif (keys.size !== members.length)\n\t\t\tthrow new ArtifactError('Artifact member key is duplicated', 'DUPLICATE')\n\t\tif (new Set(members.map((member) => member.key.toLowerCase())).size !== members.length)\n\t\t\tthrow new ArtifactError('Artifact member keys have a case alias', 'ALIAS')\n\t\tif (members.some((member) => member.key.split('/').length - 1 > ARTIFACT_DEPTH))\n\t\t\tthrow new ArtifactError('Artifact closure directory depth limit exceeded', 'LIMIT')\n\t\tconst directories = new Set(\n\t\t\tmembers.flatMap((member) =>\n\t\t\t\tmember.key\n\t\t\t\t\t.split('/')\n\t\t\t\t\t.slice(0, -1)\n\t\t\t\t\t.map((_name, index, names) => names.slice(0, index + 1).join('/')),\n\t\t\t),\n\t\t)\n\t\tif (directories.size + members.length > ARTIFACT_VISITS)\n\t\t\tthrow new ArtifactError('Artifact closure traversal limit exceeded', 'LIMIT')\n\t\tfor (const member of members) resolveArtifactMember(destination, member.key)\n\t\tconst identities = this.#sources.map((file) => {\n\t\t\tconst stat = readArtifactPhysical(file.path)\n\t\t\treturn `${stat.dev}:${stat.ino}`\n\t\t})\n\t\tif (new Set(identities).size !== identities.length)\n\t\t\tthrow new ArtifactError('Artifact members have a physical alias', 'ALIAS')\n\t\tconst relocation = { destination, digest: '', options: this.#options, members }\n\t\tconst options: ArtifactLoaderOptions = Object.freeze({\n\t\t\tentries: Object.freeze(\n\t\t\t\tthis.#options.entries.map((path) => relocateArtifactPath(relocation, path)),\n\t\t\t),\n\t\t\troots: Object.freeze(\n\t\t\t\tthis.#options.roots.map((path) => relocateArtifactPath(relocation, path)),\n\t\t\t),\n\t\t\t...(this.#options.source === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tsource: Object.freeze({\n\t\t\t\t\t\t\troot: relocateArtifactPath(relocation, this.#options.source.root),\n\t\t\t\t\t\t\tentry: relocateArtifactPath(relocation, this.#options.source.entry),\n\t\t\t\t\t\t}),\n\t\t\t\t\t}),\n\t\t\t...(this.#options.instrument === undefined\n\t\t\t\t? {}\n\t\t\t\t: { instrument: relocateArtifactPath(relocation, this.#options.instrument) }),\n\t\t\t...(this.#options.excluded === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\texcluded: Object.freeze(\n\t\t\t\t\t\t\tthis.#options.excluded.map((path) => relocateArtifactPath(relocation, path)),\n\t\t\t\t\t\t),\n\t\t\t\t\t}),\n\t\t\t...(this.#options.assets === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tassets: Object.freeze(\n\t\t\t\t\t\t\tthis.#options.assets.map((path) => relocateArtifactPath(relocation, path)),\n\t\t\t\t\t\t),\n\t\t\t\t\t}),\n\t\t})\n\t\tconst inventory = this.inspect()\n\t\tconst packages = inventory.packages.map((entry) => ({\n\t\t\t...entry,\n\t\t\troot: relocateArtifactPath(relocation, entry.root),\n\t\t}))\n\t\tconst closure = Object.freeze({\n\t\t\tdestination,\n\t\t\tdigest: computeArtifactClosureDigest(members, packages, destination),\n\t\t\toptions,\n\t\t\tmembers,\n\t\t})\n\t\tmkdirSync(destination)\n\t\tfor (const file of this.#sources) {\n\t\t\tconst target = relocateArtifactPath(closure, file.path)\n\t\t\tthis.#directory(closure.destination, dirname(target))\n\t\t\tawait writeFile(target, file.source, { flag: 'wx' })\n\t\t}\n\t\ttry {\n\t\t\tthis.verify()\n\t\t} catch {\n\t\t\tthrow new ArtifactError('Artifact source drifted during copying', 'DRIFT')\n\t\t}\n\t\tverifyArtifactClosure(closure)\n\t\treturn closure\n\t}\n\n\t#directory(destination: string, target: string): void {\n\t\tconst names = relative(destination, target).split(sep).filter(Boolean)\n\t\treadArtifactPhysical(destination)\n\t\tfor (const [index] of names.entries()) {\n\t\t\tconst path = join(destination, ...names.slice(0, index + 1))\n\t\t\ttry {\n\t\t\t\tmkdirSync(path)\n\t\t\t} catch (error) {\n\t\t\t\tif (!matchesSystemError(error, 'EEXIST')) throw error\n\t\t\t}\n\t\t\tif (!readArtifactPhysical(path).isDirectory())\n\t\t\t\tthrow new ArtifactError('Artifact destination ancestor is redirected', 'REDIRECT')\n\t\t}\n\t}\n\n\t// Captures every root's manifest and built files, then the optional source graph, threading the visit and byte tally through each step.\n\t#capture(): ArtifactSource[] {\n\t\tconst sources: ArtifactSource[] = []\n\t\tconst tally = this.#options.roots.reduce<ArtifactTally>(\n\t\t\t(counted, root) => {\n\t\t\t\tif (\n\t\t\t\t\t!isAbsolute(root) ||\n\t\t\t\t\tresolve(root) !== root ||\n\t\t\t\t\trealpathSync(root) !== root ||\n\t\t\t\t\t!lstatSync(root).isDirectory()\n\t\t\t\t)\n\t\t\t\t\tthrow new ArtifactError(`Artifact requires a canonical package root: ${root}`)\n\t\t\t\treturn this.#walk(\n\t\t\t\t\tjoin(root, 'dist'),\n\t\t\t\t\tsources,\n\t\t\t\t\tfalse,\n\t\t\t\t\t0,\n\t\t\t\t\tthis.#append(join(root, 'package.json'), sources, counted),\n\t\t\t\t)\n\t\t\t},\n\t\t\tObject.freeze({ visits: 0, bytes: 0 }),\n\t\t)\n\t\tconst source = this.#options.source\n\t\tif (source !== undefined) {\n\t\t\tif (\n\t\t\t\tthis.#options.roots.some(\n\t\t\t\t\t(root) =>\n\t\t\t\t\t\tjoin(root, 'dist') === source.root ||\n\t\t\t\t\t\tcontainsArtifact(join(root, 'dist'), source.root) ||\n\t\t\t\t\t\tcontainsArtifact(source.root, join(root, 'dist')),\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow new ArtifactError('Artifact source and built inventories must not overlap')\n\t\t\tconst counted = this.#walk(source.root, sources, true, 0, tally)\n\t\t\tthis.#assets(sources, counted)\n\t\t} else this.#assets(sources, tally)\n\t\treturn sources\n\t}\n\n\t#assets(sources: ArtifactSource[], tally: ArtifactTally): void {\n\t\tconst assets = this.#options.assets ?? []\n\t\tif (assets.length > ARTIFACT_FILES)\n\t\t\tthrow new ArtifactError('Artifact asset count limit exceeded', 'LIMIT')\n\t\tif (new Set(assets).size !== assets.length)\n\t\t\tthrow new ArtifactError('Artifact asset key is duplicated', 'DUPLICATE')\n\t\tassets.reduce((counted, path) => {\n\t\t\treadArtifactPhysical(path)\n\t\t\treturn sources.some((file) => file.path === path)\n\t\t\t\t? counted\n\t\t\t\t: this.#append(path, sources, counted)\n\t\t}, tally)\n\t}\n\n\t// Reads one admitted file under the bytes that remain and returns the tally including it.\n\t#append(path: string, sources: ArtifactSource[], tally: ArtifactTally): ArtifactTally {\n\t\tif (sources.length >= ARTIFACT_FILES)\n\t\t\tthrow new ArtifactError('Artifact file count limit exceeded')\n\t\tconst file = readArtifact(path, ARTIFACT_BYTES - tally.bytes)\n\t\tsources.push(file)\n\t\treturn Object.freeze({ visits: tally.visits, bytes: tally.bytes + file.size })\n\t}\n\n\t// Visits a directory's entries lazily, so a limit refusal stops reading it, and returns the tally including its subtree.\n\t#walk(\n\t\tdirectory: string,\n\t\tsources: ArtifactSource[],\n\t\tsource: boolean,\n\t\tdepth: number,\n\t\ttally: ArtifactTally,\n\t): ArtifactTally {\n\t\tif (depth > ARTIFACT_DEPTH) throw new ArtifactError('Artifact directory depth limit exceeded')\n\t\tif (\n\t\t\t!isAbsolute(directory) ||\n\t\t\tresolve(directory) !== directory ||\n\t\t\trealpathSync(directory) !== directory ||\n\t\t\t!lstatSync(directory).isDirectory()\n\t\t)\n\t\t\tthrow new ArtifactError(`Artifact directory must be canonical and not linked: ${directory}`)\n\t\tconst handle = opendirSync(directory)\n\t\ttry {\n\t\t\treturn iterateArtifactEntries(handle).reduce<ArtifactTally>((counted, entry) => {\n\t\t\t\tconst visited = Object.freeze({ visits: counted.visits + 1, bytes: counted.bytes })\n\t\t\t\tif (visited.visits > ARTIFACT_VISITS)\n\t\t\t\t\tthrow new ArtifactError('Artifact traversal limit exceeded')\n\t\t\t\tconst path = join(directory, entry.name)\n\t\t\t\tif (entry.isSymbolicLink())\n\t\t\t\t\tthrow new ArtifactError(`Artifact links are unsupported: ${path}`, 'REDIRECT')\n\t\t\t\tif (entry.isDirectory()) return this.#walk(path, sources, source, depth + 1, visited)\n\t\t\t\treturn (source\n\t\t\t\t\t? ['.ts', '.mts', '.js', '.mjs']\n\t\t\t\t\t: ['.js', '.mjs', '.cjs', '.json']\n\t\t\t\t).includes(extname(path)) &&\n\t\t\t\t\t!path.endsWith('.d.ts') &&\n\t\t\t\t\t!path.endsWith('.d.mts')\n\t\t\t\t\t? this.#append(path, sources, visited)\n\t\t\t\t\t: visited\n\t\t\t}, tally)\n\t\t} finally {\n\t\t\thandle.closeSync()\n\t\t}\n\t}\n}\n","import type {\n\tStudyAttempt,\n\tStudyEvidence,\n\tStudyJudgment,\n\tStudyLabeling,\n\tStudyManifest,\n\tStudyRubric,\n} from '@src/core'\nimport type {\n\tStudyFile,\n\tStudyExchangeAttempt,\n\tStudyExchangeDeclaration,\n\tStudyExchangeHistory,\n\tStudyExchangeIdentity,\n\tStudyExchangeRow,\n\tStudyRecordedExchange,\n\tStudyPacketBundle,\n\tStudyPacketEntry,\n\tStudyPacketLink,\n\tStudyResultReading,\n\tStudySealedResult,\n} from './types.js'\nimport type { FileHandle } from 'node:fs/promises'\nimport { StudyError } from '@src/core'\nimport { attempt, canonicalStringify, isRecord, parseJSON } from '@orkestrel/contract'\nimport { constants } from 'node:fs'\nimport { lstat, open, readdir } from 'node:fs/promises'\nimport { dirname, join, parse, relative, resolve, sep } from 'node:path'\nimport { decodeStudyJSON, encodeStudyJSON, hashStudyBytes } from '../helpers.js'\nimport { STUDY_CUSTODY_BYTES, STUDY_PACKET_DISCLOSURE } from './constants.js'\nimport {\n\tisStudyCustodyAttempt,\n\tisStudyCustodyEvidence,\n\tisStudyCustodyManifest,\n\tisStudyCustodySeal,\n\tisStudyExchangeHistory,\n\tisStudyExchangeRow,\n} from './validators.js'\n\n/**\n * Builds neutral semantic identities for the complete eligible sealed horizon.\n * @param result - The verified sealed execution\n * @param rubric - The compatible independently held rubric\n * @returns Deterministically sorted neutral mappings\n * @example\n * ```ts\n * buildStudyPacketLinks(result, rubric)\n * ```\n */\nexport function buildStudyPacketLinks(\n\tresult: StudySealedResult,\n\trubric: StudyRubric,\n): readonly StudyPacketLink[] {\n\t// The pairs are produced one at a time, and a hole is a position that reads as absent, so a hole\n\t// refuses after the links before it were counted, as visiting each position in turn does.\n\tconst pairs = result.manifest.schedule.values().flatMap((trial) =>\n\t\trubric.criteria\n\t\t\t.values()\n\t\t\t.filter(\n\t\t\t\t(criterion) => criterion.method === 'semantic' && criterion.scenario === trial.scenario,\n\t\t\t)\n\t\t\t.map((criterion) => ({ trial, criterion })),\n\t)\n\t// Each record carries the encoded bytes of every link up to and including its own.\n\tconst records: Array<{ readonly link: StudyPacketLink; readonly bytes: number }> = []\n\tfor (const { trial, criterion } of pairs) {\n\t\tconst link = {\n\t\t\ttrial: `t-${hashStudyBytes(encodeStudyJSON([result.seal.id, 'trial', trial.id]))}`,\n\t\t\tcriterion: `c-${hashStudyBytes(encodeStudyJSON([result.seal.id, 'criterion', criterion.id]))}`,\n\t\t\tsource: { trial: trial.id, criterion: criterion.id },\n\t\t}\n\t\tconst bytes = (records.at(-1)?.bytes ?? 256) + encodeStudyJSON(link).byteLength\n\t\tif (bytes > STUDY_CUSTODY_BYTES)\n\t\t\tthrow new StudyError('CAPACITY', 'Semantic packet mapping exceeds its custody allowance')\n\t\trecords.push({ link, bytes })\n\t}\n\tconst links = records.map(({ link }) => link)\n\treturn Object.freeze(\n\t\tlinks.sort((left, right) =>\n\t\t\t`${left.trial}/${left.criterion}` < `${right.trial}/${right.criterion}`\n\t\t\t\t? -1\n\t\t\t\t: `${left.trial}/${left.criterion}` > `${right.trial}/${right.criterion}`\n\t\t\t\t\t? 1\n\t\t\t\t\t: 0,\n\t\t),\n\t)\n}\n\n/**\n * Builds deterministic public semantic inputs and a separately retained private map.\n * @param result - The verified sealed execution\n * @param rubric - The compatible semantic criterion declaration\n * @param digest - The exact imported rubric-byte identity\n * @returns The packet bundle, or undefined for a purely mechanical rubric\n * @throws StudyError - Thrown when a semantic pair has no declared input or terminal record\n * @example\n * ```ts\n * buildStudyPacket(result, rubric, rubricDigest)\n * ```\n */\nexport function buildStudyPacket(\n\tresult: StudySealedResult,\n\trubric: StudyRubric,\n\tdigest: string,\n): StudyPacketBundle | undefined {\n\tconst links = buildStudyPacketLinks(result, rubric)\n\tif (links.length === 0) return undefined\n\tconst opening = encodeStudyJSON({ disclosure: STUDY_PACKET_DISCLOSURE, entries: [] }).byteLength\n\t// Each link is looked up, refused or counted before the next one is read; each record carries the\n\t// encoded bytes of every entry up to and including its own.\n\tconst records: Array<{ readonly entry: StudyPacketEntry; readonly length: number }> = []\n\tfor (const link of links) {\n\t\tconst trial = result.manifest.schedule.find((entry) => entry.id === link.source.trial)\n\t\tconst criterion = rubric.criteria.find((entry) => entry.id === link.source.criterion)\n\t\tconst scenario = result.manifest.scenarios.find((entry) => entry.id === trial?.scenario)\n\t\tconst goal = scenario?.goals.find((entry) => entry.id === criterion?.goal)\n\t\tconst observation = result.attempts\n\t\t\t.find((entry) => entry.trial.id === link.source.trial)\n\t\t\t?.observations.find((entry) => entry.goal === criterion?.goal)\n\t\tif (criterion === undefined || goal === undefined || observation === undefined)\n\t\t\tthrow new StudyError('EVIDENCE', 'Semantic packet refers to an absent sealed horizon')\n\t\tconst entry = {\n\t\t\ttrial: link.trial,\n\t\t\tcriterion: link.criterion,\n\t\t\tinput: goal.input,\n\t\t\tproduct: observation.product,\n\t\t\tassertion: criterion.assertion,\n\t\t}\n\t\tconst length = (records.at(-1)?.length ?? opening) + encodeStudyJSON(entry).byteLength\n\t\tif (length > STUDY_CUSTODY_BYTES)\n\t\t\tthrow new StudyError('CAPACITY', 'Semantic packet content exceeds its custody allowance')\n\t\trecords.push({ entry, length })\n\t}\n\tconst entries = records.map(({ entry }) => entry)\n\treturn Object.freeze({\n\t\tcontent: encodeStudyJSON({ disclosure: STUDY_PACKET_DISCLOSURE, entries }),\n\t\tmapping: encodeStudyJSON({\n\t\t\tresult: result.seal.id,\n\t\t\trubric: digest,\n\t\t\tentries: links,\n\t\t}),\n\t})\n}\n\n/**\n * Computes a bundle identity binding exact public packet and private map bytes.\n * @param packet - The immutable grading packet bundle\n * @returns The exact bundle digest\n * @example\n * ```ts\n * computeStudyPacketDigest(packet)\n * ```\n */\nexport function computeStudyPacketDigest(packet: StudyPacketBundle): string {\n\treturn hashStudyBytes(\n\t\tencodeStudyJSON({\n\t\t\tcontent: hashStudyBytes(packet.content),\n\t\t\tmapping: hashStudyBytes(packet.mapping),\n\t\t}),\n\t)\n}\n\n/**\n * Translates bound neutral imported labels through the sealed semantic horizon.\n * @param result - The verified sealed execution\n * @param rubric - The retained rubric\n * @param digest - The exact retained rubric-byte identity\n * @param labels - The original imported neutral labels\n * @returns Judgments translated to scheduled trial and criterion identities\n * @throws StudyError - Thrown when the packet or a label identity is foreign\n * @example\n * ```ts\n * translateStudyPacketLabeling(result, rubric, rubricDigest, labels)\n * ```\n */\nexport function translateStudyPacketLabeling(\n\tresult: StudySealedResult,\n\trubric: StudyRubric,\n\tdigest: string,\n\tlabels: StudyLabeling,\n): readonly StudyJudgment[] {\n\tconst packet = buildStudyPacket(result, rubric, digest)\n\tif (packet === undefined || labels.packet !== hashStudyBytes(packet.content))\n\t\tthrow new StudyError('EVIDENCE', 'Labels bind a different semantic packet')\n\tconst links = buildStudyPacketLinks(result, rubric)\n\treturn Object.freeze(\n\t\tlabels.judgments.map((judgment) => {\n\t\t\tconst link = links.find(\n\t\t\t\t(entry) => entry.trial === judgment.trial && entry.criterion === judgment.criterion,\n\t\t\t)\n\t\t\tif (link === undefined || (judgment.method !== 'human' && judgment.method !== 'model'))\n\t\t\t\tthrow new StudyError('EVIDENCE', 'Label refers to a foreign semantic packet identity')\n\t\t\treturn { ...judgment, trial: link.source.trial, criterion: link.source.criterion }\n\t\t}),\n\t)\n}\n\n/**\n * Refuses symbolic links and non-directory ancestors before custody operations.\n * @param directory - The absolute or relative directory\n * @returns The resolved checked directory\n * @throws StudyError - Thrown when any ancestor is linked or is not a directory\n * @example\n * ```ts\n * await checkStudyDirectory(directory)\n * ```\n */\nexport async function checkStudyDirectory(directory: string): Promise<string> {\n\tconst absolute = resolve(directory)\n\tconst root = parse(absolute).root\n\tconst names = relative(root, absolute).split(sep).filter(Boolean)\n\tfor (const [index] of names.entries()) {\n\t\tconst stat = await lstat(join(root, ...names.slice(0, index + 1)))\n\t\tif (!stat.isDirectory() || stat.isSymbolicLink())\n\t\t\tthrow new StudyError('CUSTODY', 'Linked or invalid custody directory')\n\t}\n\treturn absolute\n}\n\n/**\n * Reads from an open file handle into a buffer until the buffer is full or the file ends.\n * @param handle - The open file handle to read\n * @param target - The buffer to fill from the start of the file\n * @param offset - The position in the file and the buffer to continue from; Default: 0\n * @returns The bytes read, as the whole buffer when the file filled it or as its leading part when the file ended first\n */\nexport async function readStudyHandle(\n\thandle: FileHandle,\n\ttarget: Buffer,\n\toffset = 0,\n): Promise<Buffer> {\n\tif (offset >= target.length) return target\n\tconst reading = await handle.read(target, offset, target.length - offset, offset)\n\treturn reading.bytesRead === 0\n\t\t? target.subarray(0, offset)\n\t\t: readStudyHandle(handle, target, offset + reading.bytesRead)\n}\n\n/**\n * Reads bounded regular-file bytes without following a symbolic link.\n * @param path - The custody file path\n * @param limit - The byte allowance\n * @returns Exact retained bytes\n * @throws StudyError - Thrown when the file is linked, oversized, changed, or not regular\n * @example\n * ```ts\n * await readStudyBytes(path, 1024)\n * ```\n */\nexport async function readStudyBytes(path: string, limit: number): Promise<Uint8Array> {\n\tif (!Number.isSafeInteger(limit) || limit < 0)\n\t\tthrow new StudyError('CONFIG', 'Invalid custody byte allowance')\n\tawait checkStudyDirectory(dirname(path))\n\tconst prior = await lstat(path)\n\tif (prior.isSymbolicLink() || !prior.isFile() || prior.size > limit)\n\t\tthrow new StudyError('CUSTODY', 'Invalid or oversized custody file')\n\tconst handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))\n\ttry {\n\t\tconst stat = await handle.stat()\n\t\tif (!stat.isFile() || stat.size > limit || stat.dev !== prior.dev || stat.ino !== prior.ino)\n\t\t\tthrow new StudyError('CUSTODY', 'Custody file changed during admission')\n\t\tconst bytes = await readStudyHandle(handle, Buffer.alloc(stat.size + 1))\n\t\tif (bytes.length !== stat.size)\n\t\t\tthrow new StudyError('CUSTODY', 'Custody file changed while reading')\n\t\treturn bytes\n\t} finally {\n\t\tawait handle.close()\n\t}\n}\n\n/**\n * Writes an exclusive regular record and synchronizes it before reporting success.\n * @param path - The new custody path\n * @param bytes - The exact encoded record\n * @returns Nothing after the record is synchronized\n * @example\n * ```ts\n * await writeStudyBytes(path, bytes)\n * ```\n */\nexport async function writeStudyBytes(path: string, bytes: Uint8Array): Promise<void> {\n\tawait checkStudyDirectory(dirname(path))\n\tconst handle = await open(path, 'wx')\n\ttry {\n\t\tawait handle.writeFile(bytes)\n\t\tawait handle.sync()\n\t} finally {\n\t\tawait handle.close()\n\t}\n}\n\n/**\n * Scans regular execution files while refusing unknown directories and linked paths.\n * @param directory - The execution directory\n * @param manifest - The authoritative population\n * @returns Sorted exact inventory entries\n * @throws StudyError - Thrown when inventory escapes its declared tree\n * @example\n * ```ts\n * await scanStudyExecution(directory, manifest)\n * ```\n */\nexport async function scanStudyExecution(\n\tdirectory: string,\n\tmanifest: StudyManifest,\n): Promise<readonly StudyFile[]> {\n\tawait checkStudyDirectory(directory)\n\tconst known = new Set(manifest.schedule.map((trial) => trial.id))\n\tconst files = await scanStudyTree(\n\t\tdirectory,\n\t\t'',\n\t\tknown,\n\t\tmanifest.bounds.series.bytes,\n\t\tmanifest.record !== undefined,\n\t)\n\treturn Object.freeze(\n\t\t[...files].sort((left, right) =>\n\t\t\tleft.path < right.path ? -1 : left.path > right.path ? 1 : 0,\n\t\t),\n\t)\n}\n\n/**\n * Scans one execution directory and the subdirectories it admits, reading each admitted file under the series bytes that remain.\n * @param directory - The execution directory\n * @param prefix - The slash-separated path of the scanned directory; the empty string names the execution root\n * @param known - The scheduled trial identities\n * @param allowance - The series bytes that remain before this directory\n * @returns The admitted files in read order: this directory's files, then each admitted subdirectory's, last listed first\n * @throws StudyError - Thrown when the tree holds a link, an unknown directory or file, or a file beyond the remaining allowance\n */\nexport async function scanStudyTree(\n\tdirectory: string,\n\tprefix: string,\n\tknown: ReadonlySet<string>,\n\tallowance: number,\n\trecording = false,\n): Promise<readonly StudyFile[]> {\n\tconst files: StudyFile[] = []\n\tconst directories: string[] = []\n\tfor (const entry of await readdir(join(directory, ...prefix.split('/').filter(Boolean)), {\n\t\twithFileTypes: true,\n\t})) {\n\t\tconst path = prefix === '' ? entry.name : `${prefix}/${entry.name}`\n\t\tif (entry.isSymbolicLink())\n\t\t\tthrow new StudyError('CUSTODY', 'Execution contains a symbolic link')\n\t\tif (entry.isDirectory()) {\n\t\t\tif (path !== 'trials' && !(prefix === 'trials' && known.has(entry.name)))\n\t\t\t\tthrow new StudyError('CUSTODY', 'Execution contains an unknown directory')\n\t\t\tdirectories.push(path)\n\t\t\tcontinue\n\t\t}\n\t\tconst names = path.split('/')\n\t\tif (\n\t\t\t!entry.isFile() ||\n\t\t\t!(\n\t\t\t\tpath === 'manifest.json' ||\n\t\t\t\t(names.length === 3 &&\n\t\t\t\t\tnames[0] === 'trials' &&\n\t\t\t\t\tknown.has(names[1] ?? '') &&\n\t\t\t\t\t(names[2] === 'attempt.json' ||\n\t\t\t\t\t\tnames[2] === 'evidence.jsonl' ||\n\t\t\t\t\t\t(recording && names[2] === 'exchanges.jsonl')))\n\t\t\t)\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Execution contains an unknown file')\n\t\t// A directory admits at most two file names, so the sum over its earlier files is constant work.\n\t\tconst bytes = await readStudyBytes(\n\t\t\tjoin(directory, ...names),\n\t\t\tfiles.reduce((left, file) => left - file.bytes, allowance),\n\t\t)\n\t\tfiles.push(Object.freeze({ path, bytes: bytes.byteLength, digest: hashStudyBytes(bytes) }))\n\t}\n\tconst remaining = files.reduce((left, file) => left - file.bytes, allowance)\n\t// Each step carries the allowance its subtree left, computed once from the step before it.\n\tconst steps: Array<{ readonly found: readonly StudyFile[]; readonly left: number }> = []\n\tfor (const child of [...directories].reverse()) {\n\t\tconst before = steps.at(-1)?.left ?? remaining\n\t\tconst found = await scanStudyTree(directory, child, known, before, recording)\n\t\tsteps.push({ found, left: found.reduce((left, file) => left - file.bytes, before) })\n\t}\n\treturn [...files, ...steps.flatMap((step) => step.found)]\n}\n\n/**\n * Validates complete evidence lines and per-goal encoded evidence bounds.\n * @param bytes - The exact JSONL file\n * @param manifest - The bounds and scenario declarations\n * @param trial - The scheduled trial identity\n * @returns Nothing when evidence satisfies its custody contract\n * @throws StudyError - Thrown when evidence is partial, invalid, foreign, or oversized\n * @example\n * ```ts\n * validateStudyEvidenceBytes(bytes, manifest, trial)\n * ```\n */\nexport function validateStudyEvidenceBytes(\n\tbytes: Uint8Array,\n\tmanifest: StudyManifest,\n\ttrial: string,\n): void {\n\tconst scheduled = manifest.schedule.find((entry) => entry.id === trial)\n\tconst scenario = manifest.scenarios.find((entry) => entry.id === scheduled?.scenario)\n\tif (scenario === undefined || bytes.byteLength > manifest.bounds.trial.bytes)\n\t\tthrow new StudyError('CUSTODY', 'Evidence exceeds the declared trial')\n\tconst text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\tif (text !== '' && !text.endsWith('\\n'))\n\t\tthrow new StudyError('CUSTODY', 'Evidence ends with a partial record')\n\t// A line's goal is undefined where it is not valid evidence for a declared goal.\n\tconst records = text\n\t\t.split(/\\r\\n|\\n/)\n\t\t.slice(0, -1)\n\t\t.map((line) => {\n\t\t\tconst evidence = parseJSON(line)\n\t\t\treturn {\n\t\t\t\tgoal:\n\t\t\t\t\tisStudyCustodyEvidence(evidence) &&\n\t\t\t\t\tscenario.goals.some((goal) => goal.id === evidence.goal)\n\t\t\t\t\t\t? evidence.goal\n\t\t\t\t\t\t: undefined,\n\t\t\t\tsize: Buffer.byteLength(`${line}\\n`, 'utf8'),\n\t\t\t}\n\t\t})\n\t// Only the lines before the first invalid one count: an overflow among them is the earlier refusal.\n\tconst invalid = records.findIndex(({ goal }) => goal === undefined)\n\tconst admitted = invalid === -1 ? records : records.slice(0, invalid)\n\tif (\n\t\t[...Map.groupBy(admitted, ({ goal }) => goal).values()].some(\n\t\t\t(group) => group.reduce((total, { size }) => total + size, 0) > manifest.bounds.goal.bytes,\n\t\t)\n\t)\n\t\tthrow new StudyError('CUSTODY', 'Evidence exceeds a goal allowance')\n\tif (invalid !== -1) throw new StudyError('CUSTODY', 'Evidence refers to an invalid goal')\n}\n\n/**\n * Computes an execution seal identity from its exact sorted inventory.\n * @param result - The manifest result identity\n * @param files - The sorted inventory\n * @returns The deterministic seal digest\n * @example\n * ```ts\n * computeStudySealId('execution', files)\n * ```\n */\nexport function computeStudySealId(result: string, files: readonly StudyFile[]): string {\n\treturn hashStudyBytes(encodeStudyJSON({ result, files }))\n}\n\n/**\n * Inspects custody bytes offline and verifies complete execution before grading.\n * @param directory - The result directory\n * @returns A sealed result or explicitly interrupted safe metadata\n * @throws StudyError - Thrown when existing custody bytes are invalid or tampered\n * @example\n * ```ts\n * await readStudyResult(directory)\n * ```\n */\nexport async function readStudyResult(directory: string): Promise<StudyResultReading> {\n\tconst absolute = await checkStudyDirectory(directory)\n\tconst root = await readdir(absolute, { withFileTypes: true })\n\tfor (const entry of root) {\n\t\tif (entry.isSymbolicLink()) throw new StudyError('CUSTODY', 'Result contains a symbolic link')\n\t\tif (\n\t\t\tentry.name === 'execution' || entry.name === 'grades' || entry.name === 'reports'\n\t\t\t\t? !entry.isDirectory()\n\t\t\t\t: entry.name !== 'seal.json' || !entry.isFile()\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Result contains an unknown path')\n\t}\n\tconst sealed = root.some((entry) => entry.name === 'seal.json')\n\tif (!root.some((entry) => entry.name === 'execution')) {\n\t\tif (sealed) throw new StudyError('CUSTODY', 'Sealed result is missing execution')\n\t\treturn Object.freeze({\n\t\t\tstatus: 'interrupted',\n\t\t\tdirectory: absolute,\n\t\t\tmanifest: undefined,\n\t\t\tattempts: Object.freeze([]),\n\t\t})\n\t}\n\tconst execution = join(absolute, 'execution')\n\tconst entries = await readdir(execution, { withFileTypes: true })\n\tif (!entries.some((entry) => entry.name === 'manifest.json')) {\n\t\tif (entries.length !== 0 || sealed)\n\t\t\tthrow new StudyError('CUSTODY', 'Execution is missing its manifest')\n\t\treturn Object.freeze({\n\t\t\tstatus: 'interrupted',\n\t\t\tdirectory: absolute,\n\t\t\tmanifest: undefined,\n\t\t\tattempts: Object.freeze([]),\n\t\t})\n\t}\n\tconst manifestBytes = await readStudyBytes(join(execution, 'manifest.json'), STUDY_CUSTODY_BYTES)\n\tconst decoded = attempt((): unknown => decodeStudyJSON(manifestBytes))\n\tif (!decoded.success && sealed) throw decoded.error\n\tconst manifest: unknown = decoded.success ? decoded.value : undefined\n\tif (!isStudyCustodyManifest(manifest)) {\n\t\tif (sealed) throw new StudyError('CUSTODY', 'Invalid execution manifest')\n\t\treturn Object.freeze({\n\t\t\tstatus: 'interrupted',\n\t\t\tdirectory: absolute,\n\t\t\tmanifest: undefined,\n\t\t\tattempts: Object.freeze([]),\n\t\t})\n\t}\n\tconst files = await scanStudyExecution(execution, manifest)\n\tif (\n\t\tfiles.find((entry) => entry.path === 'manifest.json')?.digest !== hashStudyBytes(manifestBytes)\n\t)\n\t\tthrow new StudyError('CUSTODY', 'Manifest changed during inventory reading')\n\tconst attempts: StudyAttempt[] = []\n\tfor (const trial of manifest.schedule) {\n\t\tconst evidence = files.find((entry) => entry.path === `trials/${trial.id}/evidence.jsonl`)\n\t\tif (evidence !== undefined && sealed) {\n\t\t\tconst bytes = await readStudyBytes(\n\t\t\t\tjoin(execution, 'trials', trial.id, 'evidence.jsonl'),\n\t\t\t\tmanifest.bounds.trial.bytes,\n\t\t\t)\n\t\t\tif (hashStudyBytes(bytes) !== evidence.digest)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Evidence changed during inventory reading')\n\t\t\tvalidateStudyEvidenceBytes(bytes, manifest, trial.id)\n\t\t}\n\t\tconst terminal = files.find((entry) => entry.path === `trials/${trial.id}/attempt.json`)\n\t\tif (terminal === undefined) continue\n\t\tif (evidence === undefined)\n\t\t\tthrow new StudyError('CUSTODY', 'Terminal attempt is missing its evidence file')\n\t\tconst bytes = await readStudyBytes(\n\t\t\tjoin(execution, 'trials', trial.id, 'attempt.json'),\n\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t)\n\t\tif (hashStudyBytes(bytes) !== terminal.digest)\n\t\t\tthrow new StudyError('CUSTODY', 'Attempt changed during inventory reading')\n\t\tconst reading = attempt((): unknown => decodeStudyJSON(bytes))\n\t\tif (!reading.success && sealed) throw reading.error\n\t\tconst record: unknown = reading.success ? reading.value : undefined\n\t\tif (!isStudyCustodyAttempt(record, manifest) || record.trial.id !== trial.id) {\n\t\t\tif (sealed) throw new StudyError('CUSTODY', 'Invalid or foreign terminal attempt')\n\t\t\tcontinue\n\t\t}\n\t\tattempts.push(record)\n\t}\n\tif (!sealed)\n\t\treturn Object.freeze({\n\t\t\tstatus: 'interrupted',\n\t\t\tdirectory: absolute,\n\t\t\tmanifest,\n\t\t\tattempts: Object.freeze(attempts),\n\t\t})\n\tconst sealBytes = await readStudyBytes(join(absolute, 'seal.json'), STUDY_CUSTODY_BYTES)\n\tif (\n\t\tfiles.reduce((total, file) => total + file.bytes, sealBytes.byteLength) >\n\t\tmanifest.bounds.series.bytes\n\t)\n\t\tthrow new StudyError('CUSTODY', 'Seal and execution exceed the series allowance')\n\tconst seal = decodeStudyJSON(sealBytes)\n\tif (\n\t\t!isStudyCustodySeal(seal) ||\n\t\tseal.result !== manifest.id ||\n\t\tseal.id !== computeStudySealId(manifest.id, files) ||\n\t\tcanonicalStringify(seal.files) !== canonicalStringify(files) ||\n\t\tattempts.length !== manifest.schedule.length ||\n\t\tfiles.length !== 1 + manifest.schedule.length * (manifest.record === undefined ? 2 : 3)\n\t)\n\t\tthrow new StudyError('CUSTODY', 'Execution seal does not match the complete byte inventory')\n\tif (manifest.record !== undefined) {\n\t\tfor (const trial of manifest.schedule) {\n\t\t\tconst file = files.find((entry) => entry.path === `trials/${trial.id}/exchanges.jsonl`)\n\t\t\tif (file === undefined)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Recorded trial is missing its exchange sidecar')\n\t\t\tawait readStudyTrialExchanges(absolute, manifest, trial.id, file)\n\t\t}\n\t}\n\treturn Object.freeze({\n\t\tstatus: 'sealed',\n\t\tdirectory: absolute,\n\t\tmanifest,\n\t\tattempts: Object.freeze(attempts),\n\t\tseal,\n\t})\n}\n\n/** Projects the declaration onto its complete ordered HTTP identity population.\n * @param declaration - The validated opening row.\n * @returns Maintenance, preflight, model and postflight identities in declaration order.\n */\nexport function buildStudyExchangeSequence(\n\tdeclaration: StudyExchangeDeclaration,\n): readonly StudyExchangeIdentity[] {\n\tconst first = declaration.procedure[0]\n\tconst last = declaration.procedure.at(-1)\n\tif (first === undefined || last === undefined)\n\t\tthrow new StudyError('CUSTODY', 'Exchange procedure is empty')\n\tconst models = Object.values(declaration.models).filter(\n\t\t(model, index, entries) => entries.findIndex((entry) => entry.name === model.name) === index,\n\t)\n\tconst maintenance: readonly StudyExchangeIdentity[] = declaration.maintenance.map(\n\t\t(_model, index) => ({\n\t\t\tordinal: index + 1,\n\t\t\tgoal: first.goal,\n\t\t\trole: 'maintenance',\n\t\t\tpath: '/api/generate',\n\t\t\tmethod: 'POST',\n\t\t\tstage: 'maintenance',\n\t\t}),\n\t)\n\tconst preflight: readonly StudyExchangeIdentity[] = [\n\t\t'/api/version',\n\t\t'/api/tags',\n\t\t...models.map(() => '/api/show'),\n\t].map((path, index) => ({\n\t\tordinal: maintenance.length + index + 1,\n\t\tgoal: first.goal,\n\t\trole: 'metadata',\n\t\tpath:\n\t\t\tpath === '/api/version' ? '/api/version' : path === '/api/tags' ? '/api/tags' : '/api/show',\n\t\tmethod: path === '/api/show' ? 'POST' : 'GET',\n\t\tstage: 'preflight',\n\t}))\n\tconst execution: readonly StudyExchangeIdentity[] = declaration.procedure.map((step, index) => ({\n\t\tordinal: maintenance.length + preflight.length + index + 1,\n\t\tgoal: step.goal,\n\t\trole: step.role,\n\t\tpath: step.path,\n\t\tmethod: 'POST',\n\t\tstage: 'execution',\n\t\tstep: step.ordinal,\n\t}))\n\tconst postflight: readonly StudyExchangeIdentity[] = preflight.map((identity, index) => ({\n\t\t...identity,\n\t\tordinal: maintenance.length + preflight.length + execution.length + index + 1,\n\t\tgoal: last.goal,\n\t\tstage: 'postflight',\n\t}))\n\treturn [...maintenance, ...preflight, ...execution, ...postflight]\n}\n\n/** Projects only the repeated identity fields of a retained HTTP exchange.\n * @param identity - The row whose body and lifecycle fields are omitted.\n * @returns The identity repeated by its attempt and terminal.\n */\nexport function projectStudyExchangeIdentity(\n\tidentity: StudyExchangeIdentity,\n): StudyExchangeIdentity {\n\treturn {\n\t\tordinal: identity.ordinal,\n\t\tgoal: identity.goal,\n\t\trole: identity.role,\n\t\tpath: identity.path,\n\t\tmethod: identity.method,\n\t\tstage: identity.stage,\n\t\t...(identity.step === undefined ? {} : { step: identity.step }),\n\t}\n}\n\n/** Validates the exact declaration order and request bytes of an admitted exchange.\n * @param declaration - The complete opening procedure.\n * @param request - The admitted request to join.\n * @returns Nothing after identity, exact-body or capture-length validation.\n */\nexport function validateStudyExchangeRequest(\n\tdeclaration: StudyExchangeDeclaration,\n\trequest: StudyExchangeAttempt,\n): void {\n\tconst expected = buildStudyExchangeSequence(declaration)[request.ordinal - 1]\n\tif (\n\t\texpected === undefined ||\n\t\tcanonicalStringify(expected) !== canonicalStringify(projectStudyExchangeIdentity(request))\n\t)\n\t\tthrow new StudyError('CUSTODY', 'Exchange differs from its declared order')\n\tconst bytes = Buffer.from(request.body, 'base64')\n\tif (request.stage === 'execution') {\n\t\tconst step = declaration.procedure.find((entry) => entry.ordinal === request.step)\n\t\tif (\n\t\t\tstep === undefined ||\n\t\t\t(step.admission === 'exact'\n\t\t\t\t? !bytes.equals(Buffer.from(step.body)) || request.digest !== step.input\n\t\t\t\t: bytes.length !== step.bytes)\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Exchange request differs from its declared admission')\n\t\treturn\n\t}\n\tif (request.stage === 'maintenance') {\n\t\tconst model = declaration.maintenance[request.ordinal - 1]\n\t\tconst body = parseJSON(bytes.toString('utf8'))\n\t\tif (\n\t\t\tmodel === undefined ||\n\t\t\t!isRecord(body) ||\n\t\t\tbody.model !== model.name ||\n\t\t\tbody.keep_alive !== 0\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Maintenance request differs from its declaration')\n\t\treturn\n\t}\n\tconst models = Object.values(declaration.models).filter(\n\t\t(model, index, entries) => entries.findIndex((entry) => entry.name === model.name) === index,\n\t)\n\tconst population = models.length + 2\n\tconst offset =\n\t\trequest.ordinal -\n\t\tdeclaration.maintenance.length -\n\t\t(request.stage === 'postflight' ? population + declaration.procedure.length : 0) -\n\t\t1\n\tconst model = models[offset - 2]\n\tconst body =\n\t\trequest.path === '/api/show' && model !== undefined ? JSON.stringify({ model: model.name }) : ''\n\tif (!bytes.equals(Buffer.from(body)))\n\t\tthrow new StudyError('CUSTODY', 'Metadata request differs from its declaration')\n}\n\n/** Validates a serialized journal prefix or its complete successful population.\n * @param rows - The owned rows in physical append order.\n * @param complete - If true, requires successful completion; if false, admits an unfinished prefix.\n * @returns Nothing when every row joins its preceding attempt and declared sequence.\n */\nexport function validateStudyExchangeRows(\n\trows: readonly StudyExchangeRow[],\n\tcomplete = true,\n): void {\n\tconst declaration = rows[0]\n\tif (declaration?.phase !== 'declaration' || !rows.every(isStudyExchangeRow))\n\t\tthrow new StudyError('CUSTODY', 'Exchange declaration or row is invalid')\n\tconst attempts = rows.filter((row) => row.phase === 'attempt')\n\tfor (const [index, row] of rows.entries()) {\n\t\tif (index === 0) continue\n\t\tconst previous = rows[index - 1]\n\t\tif (row.phase === 'attempt') {\n\t\t\tif (previous?.phase !== 'declaration' && previous?.phase !== 'response')\n\t\t\t\tthrow new StudyError('CUSTODY', 'Exchange attempt overlaps an unfinished attempt')\n\t\t\tif (\n\t\t\t\trow.ordinal !==\n\t\t\t\trows.slice(0, index).filter((entry) => entry.phase === 'attempt').length + 1\n\t\t\t)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Exchange ordinals are not contiguous')\n\t\t\tvalidateStudyExchangeRequest(declaration, row)\n\t\t} else if (row.phase === 'response' || row.phase === 'failure') {\n\t\t\tif (\n\t\t\t\tprevious?.phase !== 'attempt' ||\n\t\t\t\tcanonicalStringify(projectStudyExchangeIdentity(previous)) !==\n\t\t\t\t\tcanonicalStringify(projectStudyExchangeIdentity(row))\n\t\t\t)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Exchange terminal has no matching attempt')\n\t\t} else if (row.phase === 'complete') {\n\t\t\tif (\n\t\t\t\tindex !== rows.length - 1 ||\n\t\t\t\tprevious?.phase !== 'response' ||\n\t\t\t\trow.count !== attempts.length ||\n\t\t\t\trow.count !== buildStudyExchangeSequence(declaration).length ||\n\t\t\t\trows.some((entry) => entry.phase === 'failure')\n\t\t\t)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Exchange completion is partial or failed')\n\t\t} else throw new StudyError('CUSTODY', 'Exchange declaration repeats')\n\t}\n\tif (complete && rows.at(-1)?.phase !== 'complete')\n\t\tthrow new StudyError('CUSTODY', 'Exchange history has no successful completion')\n}\n\n/** Reads strict complete LF-framed exchange rows with verified bodies and declaration joins.\n * @param bytes - The bounded retained sidecar bytes.\n * @param complete - If true, requires completion; if false, admits a verified unfinished prefix.\n * @returns Owned rows in physical order.\n */\nexport function readStudyExchangeRows(\n\tbytes: Uint8Array,\n\tcomplete = true,\n): readonly StudyExchangeRow[] {\n\ttry {\n\t\tconst text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\t\tif (!text.endsWith('\\n'))\n\t\t\tthrow new StudyError('CUSTODY', 'Exchange sidecar ends with a partial record')\n\t\tconst rows = text\n\t\t\t.split(/\\r\\n|\\n/)\n\t\t\t.slice(0, -1)\n\t\t\t.map((line) => {\n\t\t\t\tconst row = parseJSON(line)\n\t\t\t\tif (!isStudyExchangeRow(row))\n\t\t\t\t\tthrow new StudyError('CUSTODY', 'Exchange sidecar contains an invalid row')\n\t\t\t\treturn row\n\t\t\t})\n\t\tvalidateStudyExchangeRows(rows, complete)\n\t\treturn rows\n\t} catch (error) {\n\t\tthrow new StudyError(\n\t\t\t'CUSTODY',\n\t\t\terror instanceof Error ? error.message : 'Invalid exchange bytes',\n\t\t)\n\t}\n}\n\n/** Validates complete history envelopes again before a replay may perform dependent work.\n * @param history - The strict-reader result, treated as untrusted at this boundary.\n * @returns Nothing after complete row, file and declaration verification.\n */\nexport function validateStudyExchangeHistory(history: StudyExchangeHistory): void {\n\tif (\n\t\t!isStudyExchangeHistory(history) ||\n\t\thistory.file.path !== `trials/${history.declaration.trial}/exchanges.jsonl`\n\t)\n\t\tthrow new StudyError('CUSTODY', 'Replay requires a verified sealed exchange history')\n\tconst rows = [\n\t\thistory.declaration,\n\t\t...history.exchanges.flatMap((pair) => [pair.attempt, pair.response]),\n\t\thistory.completion,\n\t]\n\tvalidateStudyExchangeRows(rows)\n\tconst bytes = Buffer.from(rows.map((row) => JSON.stringify(row) + '\\n').join(''))\n\tif (history.file.bytes !== bytes.length || history.file.digest !== hashStudyBytes(bytes))\n\t\tthrow new StudyError('CUSTODY', 'Replay history differs from its retained file identity')\n}\n\n/** Joins recorded exchanges to exactly one dispatch and wire evidence identity per ordinal.\n * @param rows - The complete successful sidecar rows.\n * @param evidence - The validated trial evidence rows.\n * @returns Nothing when all retained exchange identities have exact evidence counterparts.\n */\nexport function validateStudyExchangeEvidence(\n\trows: readonly StudyExchangeRow[],\n\tevidence: readonly StudyEvidence[],\n): void {\n\tconst attempts = rows.filter((row) => row.phase === 'attempt')\n\tfor (const event of ['dispatch', 'wire']) {\n\t\tconst joined = evidence.filter(\n\t\t\t(row) => row.event === event && isRecord(row.value) && row.value.ordinal !== undefined,\n\t\t)\n\t\tif (\n\t\t\tjoined.length !== attempts.length ||\n\t\t\t!joined.every((row, index) => {\n\t\t\t\tconst request = attempts[index]\n\t\t\t\treturn (\n\t\t\t\t\trequest !== undefined &&\n\t\t\t\t\tisRecord(row.value) &&\n\t\t\t\t\trow.value.ordinal === request.ordinal &&\n\t\t\t\t\trow.goal === request.goal &&\n\t\t\t\t\trow.value.role === request.role &&\n\t\t\t\t\trow.value.path === request.path\n\t\t\t\t)\n\t\t\t})\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Exchange sidecar and evidence ordinals do not join exactly')\n\t}\n}\n\n/** Reads and joins a complete trial sidecar before or after sealing.\n * @param directory - The result directory.\n * @param manifest - The verified manifest declaring recording and bounds.\n * @param trial - The exact scheduled trial id.\n * @param file - The inventory identity read for this sidecar.\n * @returns Complete rows after byte, declaration and evidence joins.\n */\nexport async function readStudyTrialExchanges(\n\tdirectory: string,\n\tmanifest: StudyManifest,\n\ttrial: string,\n\tfile: StudyFile,\n): Promise<readonly StudyExchangeRow[]> {\n\tif (manifest.record === undefined || file.path !== `trials/${trial}/exchanges.jsonl`)\n\t\tthrow new StudyError('CUSTODY', 'Sidecar has no recording declaration')\n\tconst bytes = await readStudyBytes(\n\t\tjoin(directory, 'execution', 'trials', trial, 'exchanges.jsonl'),\n\t\tmanifest.record.bytes,\n\t)\n\tif (bytes.length !== file.bytes || hashStudyBytes(bytes) !== file.digest)\n\t\tthrow new StudyError('CUSTODY', 'Exchange sidecar changed during reading')\n\tconst rows = readStudyExchangeRows(bytes)\n\tconst declaration = rows[0]\n\tconst scheduled = manifest.schedule.find((entry) => entry.id === trial)\n\tconst scenario = manifest.scenarios.find((entry) => entry.id === scheduled?.scenario)\n\tif (\n\t\tdeclaration?.phase !== 'declaration' ||\n\t\tdeclaration.trial !== trial ||\n\t\tscenario === undefined ||\n\t\t!declaration.procedure.every((step) => scenario.goals.some((goal) => goal.id === step.goal))\n\t)\n\t\tthrow new StudyError('CUSTODY', 'Exchange declaration differs from its trial')\n\tconst evidenceBytes = await readStudyBytes(\n\t\tjoin(directory, 'execution', 'trials', trial, 'evidence.jsonl'),\n\t\tmanifest.bounds.trial.bytes,\n\t)\n\tvalidateStudyEvidenceBytes(evidenceBytes, manifest, trial)\n\tconst evidence = new TextDecoder('utf-8', { fatal: true })\n\t\t.decode(evidenceBytes)\n\t\t.split(/\\r\\n|\\n/)\n\t\t.slice(0, -1)\n\t\t.map((line) => {\n\t\t\tconst row = parseJSON(line)\n\t\t\tif (!isStudyCustodyEvidence(row)) throw new StudyError('CUSTODY', 'Invalid exchange evidence')\n\t\t\treturn row\n\t\t})\n\tvalidateStudyExchangeEvidence(rows, evidence)\n\treturn rows\n}\n\n/** Reads a sealed trial's exact complete exchange history after reverifying its entire result.\n * @param result - The sealed execution selected for replay.\n * @param trial - The scheduled trial id.\n * @returns Complete ordered request and response pairs with their verified file and seal identities.\n */\nexport async function readStudyExchanges(\n\tresult: StudySealedResult,\n\ttrial: string,\n): Promise<StudyExchangeHistory> {\n\tconst reading = await readStudyResult(result.directory)\n\tif (reading.status !== 'sealed' || reading.seal.id !== result.seal.id)\n\t\tthrow new StudyError('CUSTODY', 'Replay result is unsealed or changed')\n\tconst file = reading.seal.files.find((entry) => entry.path === `trials/${trial}/exchanges.jsonl`)\n\tif (file === undefined)\n\t\tthrow new StudyError('CUSTODY', 'Recorded trial is missing its exchange sidecar')\n\tconst rows = await readStudyTrialExchanges(reading.directory, reading.manifest, trial, file)\n\tconst declaration = rows[0]\n\tconst completion = rows.at(-1)\n\tif (declaration?.phase !== 'declaration' || completion?.phase !== 'complete')\n\t\tthrow new StudyError('CUSTODY', 'Exchange boundaries are missing')\n\tconst exchanges: readonly StudyRecordedExchange[] = rows.flatMap((row, index) => {\n\t\tconst response = rows[index + 1]\n\t\treturn row.phase === 'attempt' && response?.phase === 'response'\n\t\t\t? [{ attempt: row, response }]\n\t\t\t: []\n\t})\n\tconst history = { seal: reading.seal.id, file, declaration, exchanges, completion }\n\tvalidateStudyExchangeHistory(history)\n\treturn history\n}\n","import type { StudyEvidence } from '@src/core'\nimport type { StudyCustodySinkInterface, StudyEvidenceSinkOptions } from './types.js'\nimport { StudyError } from '@src/core'\nimport { encodeStudyJSON } from '../helpers.js'\nimport { isStudyCustodyEvidence } from './validators.js'\n\n/** Retains admitted evidence in order and closes admission before terminal records. */\nexport class StudyEvidenceSink implements StudyCustodySinkInterface {\n\treadonly #options: StudyEvidenceSinkOptions\n\treadonly #goals = new Map<string, number>()\n\t// The admitted writes not yet settled; a write joins when admitted and leaves when it settles, and each waits for every earlier one.\n\treadonly #writes = new Set<Promise<void>>()\n\t#bytes = 0\n\t// Wraps the first failed write so every later append and the close refuse with that failure.\n\t#fault: { readonly error: unknown } | undefined\n\t#closing: Promise<void> | undefined\n\n\t/**\n\t * Owns the descriptor selection and constraints while retaining the live file and budget.\n\t * @param options - The owned descriptor, goal names, and byte admission bounds\n\t */\n\tconstructor(options: StudyEvidenceSinkOptions) {\n\t\tthis.#options = { ...options, goals: [...options.goals] }\n\t}\n\n\t/**\n\t * Admits exact encoded bytes before queuing an append in call order.\n\t * @param evidence - The validated domain record\n\t * @returns Nothing after the admitted append completes\n\t * @throws StudyError - Thrown when admission is closed or a byte limit is exceeded\n\t */\n\tappend(evidence: StudyEvidence): Promise<void> {\n\t\ttry {\n\t\t\tif (this.#closing !== undefined)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Evidence admission is closed')\n\t\t\tif (!isStudyCustodyEvidence(evidence) || !this.#options.goals.includes(evidence.goal))\n\t\t\t\tthrow new StudyError('EVIDENCE', 'Evidence refers to an undeclared goal')\n\t\t\tconst bytes = encodeStudyJSON(evidence)\n\t\t\tconst used = (this.#goals.get(evidence.goal) ?? 0) + bytes.byteLength\n\t\t\tconst trial = this.#bytes + bytes.byteLength\n\t\t\tif (used > this.#options.goal || trial > this.#options.trial) {\n\t\t\t\tconst message = 'Encoded evidence exceeds its allowance'\n\t\t\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\t\t\tcause: 'capacity',\n\t\t\t\t\tmessage,\n\t\t\t\t\trole: undefined,\n\t\t\t\t\tstop:\n\t\t\t\t\t\tused > this.#options.goal\n\t\t\t\t\t\t\t? { layer: 'custody', id: 'Goal evidence', max: this.#options.goal, consumed: used }\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tlayer: 'custody',\n\t\t\t\t\t\t\t\t\tid: 'Trial evidence',\n\t\t\t\t\t\t\t\t\tmax: this.#options.trial,\n\t\t\t\t\t\t\t\t\tconsumed: trial,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\tthis.#options.budget.reserve(bytes.byteLength)\n\t\t\tthis.#goals.set(evidence.goal, used)\n\t\t\tthis.#bytes += bytes.byteLength\n\t\t\tconst previous = Promise.allSettled([...this.#writes])\n\t\t\tconst write = previous.then(() => this.#write(bytes))\n\t\t\tthis.#writes.add(write)\n\t\t\tvoid write.then(\n\t\t\t\t() => this.#writes.delete(write),\n\t\t\t\t() => this.#writes.delete(write),\n\t\t\t)\n\t\t\treturn write\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error)\n\t\t}\n\t}\n\n\t/**\n\t * Closes admission immediately and synchronizes all previously admitted writes.\n\t * @returns Nothing when the evidence descriptor has closed\n\t */\n\tclose(): Promise<void> {\n\t\tthis.#closing ??= Promise.allSettled([...this.#writes])\n\t\t\t.then(async () => {\n\t\t\t\tif (this.#fault !== undefined) throw this.#fault.error\n\t\t\t\tawait this.#options.file.sync()\n\t\t\t})\n\t\t\t.finally(async () => {\n\t\t\t\tawait this.#options.file.close()\n\t\t\t})\n\t\treturn this.#closing\n\t}\n\n\t// Writes after every earlier write settled, and refuses after any earlier write failed.\n\tasync #write(bytes: Uint8Array): Promise<void> {\n\t\tif (this.#fault !== undefined) throw this.#fault.error\n\t\ttry {\n\t\t\tawait this.#options.file.writeFile(bytes)\n\t\t} catch (error) {\n\t\t\tthis.#fault ??= { error }\n\t\t\tthrow error\n\t\t}\n\t}\n}\n","import type {\n\tStudyExchangeRow,\n\tStudyExchangeSinkInterface,\n\tStudyExchangeSinkOptions,\n} from './types.js'\nimport { StudyError } from '@src/core'\nimport { parseJSON } from '@orkestrel/contract'\nimport { validateStudyExchangeRows } from './helpers.js'\nimport { isStudyExchangeRow } from './validators.js'\n\n/** Retains ordered exchange rows under a parent-reserved serialized byte allowance. */\nexport class StudyExchangeSink implements StudyExchangeSinkInterface {\n\treadonly #options: StudyExchangeSinkOptions\n\treadonly #writes = new Set<Promise<void>>()\n\t#rows: readonly StudyExchangeRow[] = []\n\t#bytes = 0\n\t#fault: { readonly error: unknown } | undefined\n\t#closing: Promise<void> | undefined\n\n\t/** Owns the descriptor and restores a verified prefix without rewriting it.\n\t * @param options - The exclusive descriptor, byte bound and optional retained rows.\n\t */\n\tconstructor(options: StudyExchangeSinkOptions) {\n\t\tif (!Number.isSafeInteger(options.record.bytes) || options.record.bytes <= 0)\n\t\t\tthrow new StudyError('CONFIG', 'Invalid exchange byte allowance')\n\t\tthis.#options = { ...options, record: { ...options.record } }\n\t\tif (options.retained !== undefined) {\n\t\t\tconst rows = structuredClone(options.retained)\n\t\t\tvalidateStudyExchangeRows(rows, false)\n\t\t\tthis.#rows = rows\n\t\t\tthis.#bytes = rows.reduce(\n\t\t\t\t(total, row) => total + Buffer.byteLength(JSON.stringify(row) + '\\n'),\n\t\t\t\t0,\n\t\t\t)\n\t\t\tif (this.#bytes > this.#options.record.bytes)\n\t\t\t\tthrow new StudyError('CAPACITY', 'Retained exchange prefix exceeds its allowance')\n\t\t}\n\t}\n\n\t/** Holds the next contiguous one-based HTTP ordinal, including the retained prefix. */\n\tget next(): number {\n\t\treturn this.#rows.filter((row) => row.phase === 'attempt').length + 1\n\t}\n\n\t/** Appends one owned row after validating order and reserving its complete serialized size.\n\t * @param row - The next declaration, attempt, terminal or completion.\n\t * @returns Completion after synchronized retention; callers await each append before proceeding.\n\t */\n\tappend(row: StudyExchangeRow): Promise<void> {\n\t\ttry {\n\t\t\tif (this.#closing !== undefined || this.#writes.size !== 0)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Exchange append requires drained open admission')\n\t\t\tconst text = JSON.stringify(row) + '\\n'\n\t\t\tconst owned = parseJSON(text)\n\t\t\tif (!isStudyExchangeRow(owned)) throw new StudyError('CUSTODY', 'Invalid exchange row')\n\t\t\tif (this.#fault !== undefined && owned.phase !== 'failure') throw this.#fault.error\n\t\t\tconst rows = [...this.#rows, owned]\n\t\t\tvalidateStudyExchangeRows(rows, false)\n\t\t\tconst bytes = Buffer.from(text)\n\t\t\tconst reservation =\n\t\t\t\towned.phase === 'attempt'\n\t\t\t\t\t? Buffer.byteLength(\n\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\t...owned,\n\t\t\t\t\t\t\t\tphase: 'failure',\n\t\t\t\t\t\t\t\treason: 'Exchange failed',\n\t\t\t\t\t\t\t\tbody: undefined,\n\t\t\t\t\t\t\t\tdigest: undefined,\n\t\t\t\t\t\t\t\tsize: undefined,\n\t\t\t\t\t\t\t}) + '\\n',\n\t\t\t\t\t\t) + 1024\n\t\t\t\t\t: 0\n\t\t\tif (this.#bytes + bytes.length + reservation > this.#options.record.bytes)\n\t\t\t\tthrow new StudyError('CAPACITY', 'Serialized exchange bytes exceed the trial allowance')\n\t\t\tthis.#rows = rows\n\t\t\tthis.#bytes += bytes.length\n\t\t\tconst pending = this.#write(bytes)\n\t\t\tthis.#writes.add(pending)\n\t\t\tvoid pending.then(\n\t\t\t\t() => this.#writes.delete(pending),\n\t\t\t\t() => this.#writes.delete(pending),\n\t\t\t)\n\t\t\treturn pending\n\t\t} catch (error) {\n\t\t\tthis.#fault ??= { error }\n\t\t\treturn Promise.reject(error)\n\t\t}\n\t}\n\n\t/** Closes admission, drains accepted writes and synchronizes the owned descriptor.\n\t * @returns Completion after descriptor release, with a retained refusal propagated.\n\t */\n\tclose(): Promise<void> {\n\t\tthis.#closing ??= Promise.allSettled([...this.#writes])\n\t\t\t.then(async () => {\n\t\t\t\tawait this.#options.file.sync()\n\t\t\t\tif (this.#fault !== undefined) throw this.#fault.error\n\t\t\t})\n\t\t\t.finally(async () => {\n\t\t\t\tawait this.#options.file.close()\n\t\t\t})\n\t\treturn this.#closing\n\t}\n\n\tasync #write(bytes: Uint8Array): Promise<void> {\n\t\ttry {\n\t\t\tawait this.#options.file.writeFile(bytes)\n\t\t\tawait this.#options.file.sync()\n\t\t} catch (error) {\n\t\t\tthis.#fault ??= { error }\n\t\t\tthrow error\n\t\t}\n\t}\n}\n","import type { StudyAttempt, StudyManifest, StudySinkInterface, StudyTrial } from '@src/core'\nimport type {\n\tStudyCustodyPhase,\n\tStudyExchangeDestination,\n\tStudyResultStoreOptions,\n\tStudyResultStoreInterface,\n\tStudySeal,\n\tStudyTrialCustody,\n} from './types.js'\nimport { StudyError } from '@src/core'\nimport { canonicalStringify } from '@orkestrel/contract'\nimport { mkdir, open } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\nimport { decodeStudyJSON, encodeStudyJSON } from '../helpers.js'\nimport { STUDY_CUSTODY_BYTES } from './constants.js'\nimport {\n\tcheckStudyDirectory,\n\tcomputeStudySealId,\n\treadStudyBytes,\n\treadStudyResult,\n\treadStudyTrialExchanges,\n\tscanStudyExecution,\n\tvalidateStudyEvidenceBytes,\n\twriteStudyBytes,\n} from './helpers.js'\nimport { StudyEvidenceSink } from './StudyEvidenceSink.js'\nimport { isStudyCustodyAttempt, isStudyCustodyManifest, isStudyCustodyTrial } from './validators.js'\n\n/** Owns append-only execution bytes and seals only a complete terminal population. */\nexport class StudyResultStore implements StudyResultStoreInterface {\n\treadonly #directory: string\n\treadonly #manifest: StudyManifest\n\treadonly #trials = new Map<string, StudyTrialCustody>()\n\treadonly #starting = new Set<string>()\n\treadonly #exchanges = new Map<string, StudyExchangeDestination>()\n\t#phase: StudyCustodyPhase = 'new'\n\t#bytes = 0\n\n\t/**\n\t * Owns a validated manifest snapshot without creating any files.\n\t * @param options - The new result directory and execution declaration\n\t * @throws StudyError - Thrown when the manifest is invalid\n\t */\n\tconstructor(options: StudyResultStoreOptions) {\n\t\tif (!isStudyCustodyManifest(options.manifest))\n\t\t\tthrow new StudyError('CONFIG', 'Invalid execution manifest')\n\t\tconst snapshot = decodeStudyJSON(encodeStudyJSON(options.manifest))\n\t\tif (!isStudyCustodyManifest(snapshot))\n\t\t\tthrow new StudyError('CONFIG', 'Invalid manifest snapshot')\n\t\tthis.#manifest = snapshot\n\t\tthis.#directory = resolve(options.directory)\n\t}\n\n\t/**\n\t * Exclusively creates the result directory and initial manifest bytes.\n\t * @returns Nothing after the manifest is synchronized\n\t * @throws StudyError - Thrown when creation repeats or custody bounds are exceeded\n\t */\n\tasync create(): Promise<void> {\n\t\tif (this.#phase !== 'new') throw new StudyError('CUSTODY', 'Result creation has already begun')\n\t\tthis.#phase = 'creating'\n\t\ttry {\n\t\t\tconst bytes = encodeStudyJSON(this.#manifest)\n\t\t\tif (bytes.byteLength > STUDY_CUSTODY_BYTES)\n\t\t\t\tthrow new StudyError('CAPACITY', 'Manifest exceeds the metadata allowance')\n\t\t\tthis.#reserve(bytes.byteLength)\n\t\t\tawait checkStudyDirectory(dirname(this.#directory))\n\t\t\tawait mkdir(this.#directory)\n\t\t\tawait mkdir(join(this.#directory, 'execution'))\n\t\t\tawait mkdir(join(this.#directory, 'execution', 'trials'))\n\t\t\tawait writeStudyBytes(join(this.#directory, 'execution', 'manifest.json'), bytes)\n\t\t\tthis.#phase = 'ready'\n\t\t} catch (error) {\n\t\t\tthis.#phase = 'failed'\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/** Reserves a trial's entire exchange allowance before any worker starts.\n\t * @param trial - The exact scheduled trial whose manifest declares recording.\n\t * @returns Its exclusive sidecar destination, without creating the trial directory.\n\t */\n\tasync exchanges(trial: StudyTrial): Promise<StudyExchangeDestination> {\n\t\tconst scheduled = this.#manifest.schedule.find((entry) => entry.id === trial.id)\n\t\tif (\n\t\t\tthis.#phase !== 'ready' ||\n\t\t\t!isStudyCustodyTrial(trial) ||\n\t\t\tscheduled === undefined ||\n\t\t\tthis.#manifest.record === undefined ||\n\t\t\tcanonicalStringify(scheduled) !== canonicalStringify(trial) ||\n\t\t\tthis.#exchanges.has(trial.id) ||\n\t\t\tthis.#trials.has(trial.id) ||\n\t\t\tthis.#starting.has(trial.id)\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Trial sidecar cannot be reserved')\n\t\tthis.#reserve(this.#manifest.record.bytes)\n\t\tconst destination = Object.freeze({\n\t\t\tpath: join(this.#directory, 'execution', 'trials', scheduled.id, 'exchanges.jsonl'),\n\t\t\trecord: Object.freeze({ ...this.#manifest.record }),\n\t\t})\n\t\tthis.#exchanges.set(scheduled.id, destination)\n\t\treturn destination\n\t}\n\n\t/**\n\t * Exclusively creates the evidence sink for an exact scheduled trial.\n\t * @param trial - The scheduled trajectory\n\t * @returns The bounded append-only sink\n\t * @throws StudyError - Thrown when the trial is foreign, repeated, or late\n\t */\n\tasync start(trial: StudyTrial): Promise<StudySinkInterface> {\n\t\tif (\n\t\t\tthis.#phase !== 'ready' ||\n\t\t\t!isStudyCustodyTrial(trial) ||\n\t\t\tthis.#trials.has(trial.id) ||\n\t\t\tthis.#starting.has(trial.id)\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Trial cannot start in the current state')\n\t\tconst scheduled = this.#manifest.schedule.find((entry) => entry.id === trial.id)\n\t\tconst scenario = this.#manifest.scenarios.find((entry) => entry.id === trial.scenario)\n\t\tif (\n\t\t\tscheduled === undefined ||\n\t\t\tscenario === undefined ||\n\t\t\t(this.#manifest.record !== undefined && !this.#exchanges.has(trial.id)) ||\n\t\t\tcanonicalStringify(scheduled) !== canonicalStringify(trial)\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Trial differs from the execution schedule')\n\t\tthis.#starting.add(scheduled.id)\n\t\ttry {\n\t\t\tconst directory = join(this.#directory, 'execution', 'trials', scheduled.id)\n\t\t\tawait checkStudyDirectory(dirname(directory))\n\t\t\tawait mkdir(directory)\n\t\t\tconst file = await open(join(directory, 'evidence.jsonl'), 'wx')\n\t\t\tconst sink = new StudyEvidenceSink({\n\t\t\t\tfile,\n\t\t\t\tgoals: scenario.goals.map((goal) => goal.id),\n\t\t\t\tgoal: this.#manifest.bounds.goal.bytes,\n\t\t\t\ttrial: this.#manifest.bounds.trial.bytes,\n\t\t\t\tbudget: { reserve: (bytes) => this.#reserve(bytes) },\n\t\t\t})\n\t\t\tthis.#trials.set(scheduled.id, { sink, terminal: undefined })\n\t\t\treturn sink\n\t\t} catch (error) {\n\t\t\tthis.#phase = 'failed'\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tthis.#starting.delete(scheduled.id)\n\t\t}\n\t}\n\n\t/**\n\t * Closes evidence admission, drains admitted appends, and writes a terminal record.\n\t * @param attempt - The complete scheduled goal horizon\n\t * @returns Nothing after the terminal record is synchronized\n\t * @throws StudyError - Thrown when the terminal record is invalid, repeated, or late\n\t */\n\tfinish(attempt: StudyAttempt): Promise<void> {\n\t\ttry {\n\t\t\tif (this.#phase !== 'ready' || !isStudyCustodyAttempt(attempt, this.#manifest))\n\t\t\t\tthrow new StudyError('CUSTODY', 'Attempt differs from the declared horizon')\n\t\t\tconst custody = this.#trials.get(attempt.trial.id)\n\t\t\tif (custody === undefined || custody.terminal !== undefined)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Trial is unknown or already terminal')\n\t\t\tconst bytes = encodeStudyJSON(attempt)\n\t\t\tif (bytes.byteLength > STUDY_CUSTODY_BYTES)\n\t\t\t\tthrow new StudyError('CAPACITY', 'Attempt exceeds the metadata allowance')\n\t\t\tconst drained = custody.sink.close()\n\t\t\tconst terminal = this.#finish(attempt.trial.id, bytes, drained)\n\t\t\tthis.#trials.set(attempt.trial.id, { ...custody, terminal })\n\t\t\treturn terminal\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error)\n\t\t}\n\t}\n\n\t/**\n\t * Seals exact execution inventory after every scheduled trial has terminated.\n\t * @returns The immutable deterministic execution seal\n\t * @throws StudyError - Thrown when custody is incomplete, invalid, or already sealed\n\t */\n\tasync seal(): Promise<StudySeal> {\n\t\tif (\n\t\t\tthis.#phase !== 'ready' ||\n\t\t\tthis.#starting.size !== 0 ||\n\t\t\tthis.#trials.size !== this.#manifest.schedule.length ||\n\t\t\t[...this.#trials.values()].some((trial) => trial.terminal === undefined)\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Execution is not terminally accounted')\n\t\tthis.#phase = 'sealing'\n\t\ttry {\n\t\t\tawait Promise.all([...this.#trials.values()].map((trial) => trial.terminal))\n\t\t\tconst reading = await readStudyResult(this.#directory)\n\t\t\tif (\n\t\t\t\treading.status !== 'interrupted' ||\n\t\t\t\treading.manifest === undefined ||\n\t\t\t\treading.attempts.length !== this.#manifest.schedule.length ||\n\t\t\t\tcanonicalStringify(reading.manifest) !== canonicalStringify(this.#manifest)\n\t\t\t)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Execution changed before sealing')\n\t\t\tconst files = await scanStudyExecution(join(this.#directory, 'execution'), this.#manifest)\n\t\t\tif (\n\t\t\t\tfiles.length !==\n\t\t\t\t1 + this.#manifest.schedule.length * (this.#manifest.record === undefined ? 2 : 3)\n\t\t\t)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Execution inventory is incomplete')\n\t\t\tfor (const trial of this.#manifest.schedule) {\n\t\t\t\tif (this.#manifest.record !== undefined) {\n\t\t\t\t\tconst file = files.find((entry) => entry.path === `trials/${trial.id}/exchanges.jsonl`)\n\t\t\t\t\tif (file === undefined || !this.#exchanges.has(trial.id))\n\t\t\t\t\t\tthrow new StudyError('CUSTODY', 'Recorded trial has no reserved complete sidecar')\n\t\t\t\t\tawait readStudyTrialExchanges(this.#directory, this.#manifest, trial.id, file)\n\t\t\t\t}\n\t\t\t\tvalidateStudyEvidenceBytes(\n\t\t\t\t\tawait readStudyBytes(\n\t\t\t\t\t\tjoin(this.#directory, 'execution', 'trials', trial.id, 'evidence.jsonl'),\n\t\t\t\t\t\tthis.#manifest.bounds.trial.bytes,\n\t\t\t\t\t),\n\t\t\t\t\tthis.#manifest,\n\t\t\t\t\ttrial.id,\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst seal: StudySeal = Object.freeze({\n\t\t\t\tresult: this.#manifest.id,\n\t\t\t\tid: computeStudySealId(this.#manifest.id, files),\n\t\t\t\tfiles,\n\t\t\t})\n\t\t\tconst bytes = encodeStudyJSON(seal)\n\t\t\tif (bytes.byteLength > STUDY_CUSTODY_BYTES)\n\t\t\t\tthrow new StudyError('CAPACITY', 'Seal exceeds the metadata allowance')\n\t\t\tif (\n\t\t\t\tfiles.reduce((total, file) => total + file.bytes, bytes.byteLength) >\n\t\t\t\tthis.#manifest.bounds.series.bytes\n\t\t\t)\n\t\t\t\tthrow new StudyError('CAPACITY', 'Seal and execution exceed the series allowance')\n\t\t\tthis.#reserve(bytes.byteLength)\n\t\t\tawait writeStudyBytes(join(this.#directory, 'seal.json'), bytes)\n\t\t\tconst verified = await readStudyResult(this.#directory)\n\t\t\tif (verified.status !== 'sealed' || verified.seal.id !== seal.id)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Execution changed while sealing')\n\t\t\tthis.#phase = 'sealed'\n\t\t\treturn seal\n\t\t} catch (error) {\n\t\t\tthis.#phase = 'failed'\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t#reserve(bytes: number): void {\n\t\tif (this.#bytes + bytes > this.#manifest.bounds.series.bytes)\n\t\t\tthrow new StudyError('CAPACITY', 'Execution bytes exceed the series allowance')\n\t\tthis.#bytes += bytes\n\t}\n\n\tasync #finish(trial: string, bytes: Uint8Array, drained: Promise<void>): Promise<void> {\n\t\ttry {\n\t\t\tawait drained\n\t\t\tthis.#reserve(bytes.byteLength)\n\t\t\tawait writeStudyBytes(\n\t\t\t\tjoin(this.#directory, 'execution', 'trials', trial, 'attempt.json'),\n\t\t\t\tbytes,\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tthis.#phase = 'failed'\n\t\t\tthrow error\n\t\t}\n\t}\n}\n","import type { StudyGrading, StudyLabeling, StudyRubric } from '@src/core'\nimport type { StudyGradingStoreOptions, StudyPacketBundle, StudySealedResult } from './types.js'\nimport {\n\tStudyError,\n\tcomputeStudyScores,\n\tparseStudyGrading,\n\tparseStudyLabeling,\n\tparseStudyRubric,\n\tisStudyDigest,\n} from '@src/core'\nimport { canonicalStringify } from '@orkestrel/contract'\nimport { lstat, mkdir, readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { decodeStudyJSON, encodeStudyJSON, hashStudyBytes, matchesSystemError } from '../helpers.js'\nimport { STUDY_CUSTODY_BYTES } from './constants.js'\nimport {\n\tcheckStudyDirectory,\n\tbuildStudyPacket,\n\tcomputeStudyPacketDigest,\n\treadStudyBytes,\n\treadStudyResult,\n\ttranslateStudyPacketLabeling,\n\twriteStudyBytes,\n} from './helpers.js'\n\n/** Retains immutable deterministic grading versions independently of execution bytes. */\nexport class StudyGradingStore {\n\treadonly #directory: string\n\treadonly #seal: string\n\treadonly #rubric: StudyRubric\n\treadonly #rubricBytes: Uint8Array\n\treadonly #rubricDigest: string\n\treadonly #labels: StudyLabeling | undefined\n\treadonly #labelsBytes: Uint8Array | undefined\n\treadonly #labelsDigest: string | undefined\n\treadonly #packet: StudyPacketBundle | undefined\n\t// The writes not yet settled; a write joins when called and leaves when it settles, and each waits for every earlier one.\n\treadonly #writes = new Set<Promise<string>>()\n\n\t/**\n\t * Owns exact imported grading bytes without writing any custody files.\n\t * @param options - The verified execution and exact rubric and optional labels bytes\n\t * @throws StudyError - Thrown when imported bytes exceed bounds or fail validation\n\t */\n\tconstructor(options: StudyGradingStoreOptions) {\n\t\tif (options.result.status !== 'sealed')\n\t\t\tthrow new StudyError('CUSTODY', 'Grading requires a sealed execution')\n\t\tif (\n\t\t\toptions.rubric.byteLength > STUDY_CUSTODY_BYTES ||\n\t\t\t(options.labels !== undefined && options.labels.byteLength > STUDY_CUSTODY_BYTES)\n\t\t)\n\t\t\tthrow new StudyError('CAPACITY', 'Imported grading bytes exceed the metadata allowance')\n\t\tthis.#directory = options.result.directory\n\t\tthis.#seal = options.result.seal.id\n\t\tthis.#rubricBytes = new Uint8Array(options.rubric)\n\t\tthis.#rubricDigest = hashStudyBytes(this.#rubricBytes)\n\t\tthis.#rubric = parseStudyRubric(decodeStudyJSON(this.#rubricBytes))\n\t\tthis.#labelsBytes = options.labels === undefined ? undefined : new Uint8Array(options.labels)\n\t\tthis.#labelsDigest =\n\t\t\tthis.#labelsBytes === undefined ? undefined : hashStudyBytes(this.#labelsBytes)\n\t\tthis.#labels =\n\t\t\tthis.#labelsBytes === undefined\n\t\t\t\t? undefined\n\t\t\t\t: parseStudyLabeling(decodeStudyJSON(this.#labelsBytes))\n\t\tif (\n\t\t\toptions.packet !== undefined &&\n\t\t\t(options.packet.content.byteLength > STUDY_CUSTODY_BYTES ||\n\t\t\t\toptions.packet.mapping.byteLength > STUDY_CUSTODY_BYTES)\n\t\t)\n\t\t\tthrow new StudyError('CAPACITY', 'Packet exceeds the grading metadata allowance')\n\t\tthis.#packet =\n\t\t\toptions.packet === undefined\n\t\t\t\t? undefined\n\t\t\t\t: {\n\t\t\t\t\t\tcontent: new Uint8Array(options.packet.content),\n\t\t\t\t\t\tmapping: new Uint8Array(options.packet.mapping),\n\t\t\t\t\t}\n\t}\n\n\t/**\n\t * Retains a deterministic grading version or verifies identical existing bytes.\n\t * @param grading - The complete evidence-backed judgments and artifact bindings\n\t * @returns The exact grading-byte SHA-256 identity\n\t * @throws StudyError - Thrown when coverage, bindings, or existing bytes are invalid\n\t */\n\twrite(grading: StudyGrading): Promise<string> {\n\t\ttry {\n\t\t\tconst snapshot = parseStudyGrading(grading)\n\t\t\tconst bytes = encodeStudyJSON(snapshot)\n\t\t\tif (bytes.byteLength > STUDY_CUSTODY_BYTES)\n\t\t\t\tthrow new StudyError('CAPACITY', 'Grading exceeds the metadata allowance')\n\t\t\tconst previous = Promise.allSettled([...this.#writes])\n\t\t\tconst operation = previous.then(() => this.#write(snapshot, bytes))\n\t\t\tthis.#writes.add(operation)\n\t\t\tvoid operation.then(\n\t\t\t\t() => this.#writes.delete(operation),\n\t\t\t\t() => this.#writes.delete(operation),\n\t\t\t)\n\t\t\treturn operation\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error)\n\t\t}\n\t}\n\n\t/**\n\t * Reads an immutable grading version and verifies every bound artifact byte.\n\t * @param id - The grading-byte SHA-256 identity\n\t * @returns The verified grading, or undefined when the version does not exist\n\t * @throws StudyError - Thrown when an existing version is partial or tampered\n\t */\n\tasync read(id: string): Promise<StudyGrading | undefined> {\n\t\tif (!isStudyDigest(id)) throw new StudyError('EVIDENCE', 'Invalid grading identity')\n\t\tconst result = await this.#verifyResult()\n\t\tconst directory = join(result.directory, 'grades', id)\n\t\ttry {\n\t\t\tawait lstat(directory)\n\t\t} catch (error) {\n\t\t\tif (matchesSystemError(error, 'ENOENT')) return undefined\n\t\t\tthrow error\n\t\t}\n\t\tawait checkStudyDirectory(directory)\n\t\tconst bytes = await readStudyBytes(join(directory, 'grading.json'), STUDY_CUSTODY_BYTES)\n\t\tif (hashStudyBytes(bytes) !== id)\n\t\t\tthrow new StudyError('CUSTODY', 'Grading identity differs from its exact bytes')\n\t\tconst grading = parseStudyGrading(decodeStudyJSON(bytes))\n\t\tconst expected = [\n\t\t\t'grading.json',\n\t\t\t`${grading.rubric}.rubric.json`,\n\t\t\t...(grading.labels === undefined ? [] : [`${grading.labels}.labels.json`]),\n\t\t\t...(grading.packet === undefined\n\t\t\t\t? []\n\t\t\t\t: [`${grading.packet}.packet.json`, `${grading.packet}.mapping.json`]),\n\t\t]\n\t\tconst entries = await readdir(directory, { withFileTypes: true })\n\t\tif (\n\t\t\tentries.length !== expected.length ||\n\t\t\tentries.some(\n\t\t\t\t(entry) => !entry.isFile() || entry.isSymbolicLink() || !expected.includes(entry.name),\n\t\t\t)\n\t\t)\n\t\t\tthrow new StudyError('CUSTODY', 'Grading inventory differs from its bound artifacts')\n\t\tconst rubricBytes = await readStudyBytes(\n\t\t\tjoin(directory, `${grading.rubric}.rubric.json`),\n\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t)\n\t\tif (hashStudyBytes(rubricBytes) !== grading.rubric)\n\t\t\tthrow new StudyError('CUSTODY', 'Rubric bytes differ from the grading identity')\n\t\tconst rubric = parseStudyRubric(decodeStudyJSON(rubricBytes))\n\t\tconst labels =\n\t\t\tgrading.labels === undefined ? undefined : await this.#retrieve(directory, grading.labels)\n\t\tconst packet: StudyPacketBundle | undefined =\n\t\t\tgrading.packet === undefined\n\t\t\t\t? undefined\n\t\t\t\t: {\n\t\t\t\t\t\tcontent: await readStudyBytes(\n\t\t\t\t\t\t\tjoin(directory, `${grading.packet}.packet.json`),\n\t\t\t\t\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tmapping: await readStudyBytes(\n\t\t\t\t\t\t\tjoin(directory, `${grading.packet}.mapping.json`),\n\t\t\t\t\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t\t\t\t\t),\n\t\t\t\t\t}\n\t\tthis.#validate(grading, result, rubric, labels, packet)\n\t\tawait this.#verifyResult()\n\t\treturn grading\n\t}\n\n\tasync #retrieve(directory: string, digest: string): Promise<StudyLabeling> {\n\t\tconst bytes = await readStudyBytes(\n\t\t\tjoin(directory, `${digest}.labels.json`),\n\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t)\n\t\tif (hashStudyBytes(bytes) !== digest)\n\t\t\tthrow new StudyError('CUSTODY', 'Labels bytes differ from the grading identity')\n\t\treturn parseStudyLabeling(decodeStudyJSON(bytes))\n\t}\n\n\tasync #write(grading: StudyGrading, bytes: Uint8Array): Promise<string> {\n\t\tconst result = await this.#verifyResult()\n\t\tif (grading.rubric !== this.#rubricDigest || grading.labels !== this.#labelsDigest)\n\t\t\tthrow new StudyError('EVIDENCE', 'Grading does not bind the imported artifact bytes')\n\t\tthis.#validate(grading, result, this.#rubric, this.#labels, this.#packet)\n\t\tconst id = hashStudyBytes(bytes)\n\t\tconst root = join(result.directory, 'grades')\n\t\ttry {\n\t\t\tawait mkdir(root)\n\t\t} catch (error) {\n\t\t\tif (!matchesSystemError(error, 'EEXIST')) throw error\n\t\t}\n\t\tawait checkStudyDirectory(root)\n\t\tconst directory = join(root, id)\n\t\ttry {\n\t\t\tawait mkdir(directory)\n\t\t} catch (error) {\n\t\t\tif (!matchesSystemError(error, 'EEXIST')) throw error\n\t\t\tconst existing = await this.read(id)\n\t\t\tif (\n\t\t\t\texisting === undefined ||\n\t\t\t\tcanonicalStringify(existing) !== canonicalStringify(grading) ||\n\t\t\t\thashStudyBytes(\n\t\t\t\t\tawait readStudyBytes(join(directory, 'grading.json'), STUDY_CUSTODY_BYTES),\n\t\t\t\t) !== id\n\t\t\t)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Existing grading version is incompatible')\n\t\t\treturn id\n\t\t}\n\t\tawait writeStudyBytes(join(directory, `${this.#rubricDigest}.rubric.json`), this.#rubricBytes)\n\t\tif (this.#packet !== undefined && grading.packet !== undefined) {\n\t\t\tawait writeStudyBytes(join(directory, `${grading.packet}.packet.json`), this.#packet.content)\n\t\t\tawait writeStudyBytes(join(directory, `${grading.packet}.mapping.json`), this.#packet.mapping)\n\t\t}\n\t\tif (this.#labelsBytes !== undefined && this.#labelsDigest !== undefined)\n\t\t\tawait writeStudyBytes(join(directory, `${this.#labelsDigest}.labels.json`), this.#labelsBytes)\n\t\tawait writeStudyBytes(join(directory, 'grading.json'), bytes)\n\t\tawait this.read(id)\n\t\treturn id\n\t}\n\n\tasync #verifyResult(): Promise<StudySealedResult> {\n\t\tconst result = await readStudyResult(this.#directory)\n\t\tif (result.status !== 'sealed' || result.seal.id !== this.#seal)\n\t\t\tthrow new StudyError('CUSTODY', 'Execution no longer matches the verified seal')\n\t\treturn result\n\t}\n\n\t#validate(\n\t\tgrading: StudyGrading,\n\t\tresult: StudySealedResult,\n\t\trubric: StudyRubric,\n\t\tlabels: StudyLabeling | undefined,\n\t\tpacket: StudyPacketBundle | undefined,\n\t): void {\n\t\tif (grading.result !== result.seal.id)\n\t\t\tthrow new StudyError('EVIDENCE', 'Grading binds a different execution seal')\n\t\tcomputeStudyScores(result.manifest, rubric, grading)\n\t\tif (grading.packet !== (packet === undefined ? undefined : computeStudyPacketDigest(packet)))\n\t\t\tthrow new StudyError('CUSTODY', 'Grading packet bytes do not match their bundle identity')\n\t\tif (packet !== undefined) {\n\t\t\tconst expected = buildStudyPacket(result, rubric, grading.rubric)\n\t\t\tif (\n\t\t\t\texpected === undefined ||\n\t\t\t\thashStudyBytes(expected.content) !== hashStudyBytes(packet.content) ||\n\t\t\t\thashStudyBytes(expected.mapping) !== hashStudyBytes(packet.mapping)\n\t\t\t)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Grading packet differs from the sealed semantic horizon')\n\t\t}\n\t\tif (labels !== undefined && packet === undefined)\n\t\t\tthrow new StudyError('EVIDENCE', 'Imported labels require a retained semantic packet')\n\t\tconst translated =\n\t\t\tlabels === undefined\n\t\t\t\t? []\n\t\t\t\t: translateStudyPacketLabeling(result, rubric, grading.rubric, labels)\n\t\tfor (const trial of result.manifest.schedule) {\n\t\t\tfor (const criterion of rubric.criteria) {\n\t\t\t\tif (criterion.scenario !== trial.scenario) continue\n\t\t\t\tconst judgment = grading.judgments.find(\n\t\t\t\t\t(entry) => entry.trial === trial.id && entry.criterion === criterion.id,\n\t\t\t\t)\n\t\t\t\tif (judgment === undefined)\n\t\t\t\t\tthrow new StudyError('EVIDENCE', 'Grading must record every scheduled criterion judgment')\n\t\t\t\tif (\n\t\t\t\t\tcriterion.method === 'semantic' &&\n\t\t\t\t\tjudgment.verdict !== 'unknown' &&\n\t\t\t\t\t!translated.some((entry) => canonicalStringify(entry) === canonicalStringify(judgment))\n\t\t\t\t)\n\t\t\t\t\tthrow new StudyError('EVIDENCE', 'Semantic verdict has no bound imported label')\n\t\t\t}\n\t\t}\n\t\tfor (const judgment of translated) {\n\t\t\tif (\n\t\t\t\t!grading.judgments.some(\n\t\t\t\t\t(entry) => canonicalStringify(entry) === canonicalStringify(judgment),\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow new StudyError(\n\t\t\t\t\t'EVIDENCE',\n\t\t\t\t\t'Imported label is absent or differs from its recorded judgment',\n\t\t\t\t)\n\t\t}\n\t}\n}\n","/** Caps declared execution duration at the native supervisor's host ceiling. */\nexport const STUDY_COMMAND_DURATION = 86400000\n\n/** Names the trusted command's independent offline predicate. */\nexport const STUDY_COMMAND_GRADER = 'consumer-adapter'\n\n/** Defines the complete public CLI reference shared by help and grammar diagnostics. */\nexport const STUDY_COMMAND_HELP = `study check <study> [--profile <name>] [--closure <directory>]\nstudy freeze <study> --profile <name> --to <directory>\nstudy execute <study> [--profile <name>] [--out <path>] [--expected <sha256>] [--closure <directory>] [--replay <result> --prefix <JSON trial counts> --offline <true|false>]\nstudy grade <result> --rubric <path>\nstudy label <result> --grading <sha256> --labels <path>\nstudy report <result> --grading <sha256>\nstudy --help\nstudy --version\n\nProfiles default to local; freeze requires --profile. Flags require values and may appear only once.\nResults default to tmp/studies/<result>; scratch also uses tmp/studies.\nA result is its id under tmp/studies, a root-relative path, or an absolute path.\nRelative paths, including --out, must stay inside the consumer working directory.\nOutput directories must be new; existing results are never overwritten.\n--expected pins the fingerprint returned by check. --grading selects an exact grading.\n--rubric selects independent criteria. --labels imports caller-supplied semantic labels.\n--closure selects retained artifacts. Replay requires explicit prefix counts and offline behavior.\nSuccess writes one JSON document; next contains suggested argv, never executed automatically.\ncheck, freeze, grade, label and report have a fixed allowance of 60 seconds.\nexecute checks first, then uses the declared series duration plus 15 seconds for cleanup.\nExit codes: 0 success, 64 invalid input, 124 deadline, 130 interruption, 1 operational failure.\n`\n","import type { StudyCharge, StudyEvidence, StudyFailure, StudyTrial, StudyIdentity } from '@src/core'\nimport type { StudyFrame } from './types.js'\nimport type { StudyExchangeDestination } from '../stores/types.js'\nimport type { StudyOllamaReplaySelection } from '../ollama/types.js'\nimport {\n\tisStudyCause,\n\tisStudyDigest,\n\tisStudyName,\n\tisStudyRole,\n\tisStudyRecord,\n\tisStudyStop,\n\tmatchesStudyKeys,\n} from '@src/core'\nimport { isAbsolute, basename } from 'node:path'\nimport { isStudyCustodyFile, isStudyCustodyName } from '../stores/validators.js'\nimport { holds, isJSONValue, isRecord } from '@orkestrel/contract'\n\n/** Checks whether a worker destination has an absolute sidecar path and finite reservation.\n * @param value - The decoded destination.\n * @returns True if its path, allowance and optional retained identity are valid; false otherwise.\n */\nexport function isStudyExchangeDestination(value: unknown): value is StudyExchangeDestination {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['path', 'record'], ['retained']) &&\n\t\t\ttypeof value.path === 'string' &&\n\t\t\tisAbsolute(value.path) &&\n\t\t\tbasename(value.path) === 'exchanges.jsonl' &&\n\t\t\tisStudyRecord(value.record) &&\n\t\t\t(value.retained === undefined || isStudyCustodyFile(value.retained)),\n\t)\n}\n\n/** Checks whether replay explicitly selects a sealed directory and per-trial prefix counts.\n * @param value - The decoded replay selection.\n * @returns True if result, offline and every prefix are declared; false otherwise.\n */\nexport function isStudyReplaySelection(value: unknown): value is StudyOllamaReplaySelection {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(value, ['result', 'prefix', 'offline']) &&\n\t\t\ttypeof value.result === 'string' &&\n\t\t\tvalue.result.length > 0 &&\n\t\t\ttypeof value.offline === 'boolean' &&\n\t\t\tisRecord(value.prefix) &&\n\t\t\tObject.keys(value.prefix).length > 0 &&\n\t\t\tObject.entries(value.prefix).every(\n\t\t\t\t([trial, count]) =>\n\t\t\t\t\tisStudyCustodyName(trial) &&\n\t\t\t\t\ttypeof count === 'number' &&\n\t\t\t\t\tNumber.isSafeInteger(count) &&\n\t\t\t\t\tcount > 0,\n\t\t\t),\n\t)\n}\n\n/** Checks the complete transport envelope before domain handling.\n * @param value - Native IPC decoded value.\n * @returns True if the envelope is bounded in shape and JSON-compatible; false otherwise.\n */\nexport function isStudyFrame(value: unknown): value is StudyFrame {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tObject.keys(value).length === 3 &&\n\t\t\tObject.hasOwn(value, 'id') &&\n\t\t\tObject.hasOwn(value, 'operation') &&\n\t\t\tObject.hasOwn(value, 'value') &&\n\t\t\ttypeof value.id === 'number' &&\n\t\t\tNumber.isSafeInteger(value.id) &&\n\t\t\tvalue.id >= 0 &&\n\t\t\ttypeof value.operation === 'string' &&\n\t\t\t[\n\t\t\t\t'open',\n\t\t\t\t'goal',\n\t\t\t\t'close',\n\t\t\t\t'admit',\n\t\t\t\t'finish',\n\t\t\t\t'fail',\n\t\t\t\t'evidence',\n\t\t\t\t'reply',\n\t\t\t\t'error',\n\t\t\t\t'abort',\n\t\t\t].includes(value.operation) &&\n\t\t\tisJSONValue(value.value),\n\t)\n}\n\n/** Checks operational failure attribution arriving over IPC.\n * @param value - Decoded failure value.\n * @returns True if the failure carries a known cause, an optional role, and an optional stop that satisfies `isStudyStop` on a `capacity` or `deadline` cause; false otherwise.\n */\nexport function isStudyProcessFailure(value: unknown): value is StudyFailure {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\ttypeof value.message === 'string' &&\n\t\t\tisStudyCause(value.cause) &&\n\t\t\t(value.role === undefined || isStudyRole(value.role)) &&\n\t\t\t(value.stop === undefined ||\n\t\t\t\t((value.cause === 'capacity' || value.cause === 'deadline') && isStudyStop(value.stop))),\n\t)\n}\n\n/** Checks a request's declared role and finite cost ceilings.\n * @param value - Decoded charge.\n * @returns True if all charge leaves are valid; false otherwise.\n */\nexport function isStudyCharge(value: unknown): value is StudyCharge {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tisStudyRole(value.role) &&\n\t\t\ttypeof value.tokens === 'number' &&\n\t\t\tNumber.isSafeInteger(value.tokens) &&\n\t\t\tvalue.tokens >= 0 &&\n\t\t\ttypeof value.bytes === 'number' &&\n\t\t\tNumber.isSafeInteger(value.bytes) &&\n\t\t\tvalue.bytes >= 0,\n\t)\n}\n\n/** Checks append-only public evidence.\n * @param value - Decoded evidence.\n * @returns True if event, goal and payload are valid; false otherwise.\n */\nexport function isStudyEvidence(value: unknown): value is StudyEvidence {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tisStudyName(value.event) &&\n\t\t\tisStudyName(value.goal) &&\n\t\t\tisJSONValue(value.value),\n\t)\n}\n\n/** Checks a fresh trial's declared identifiers.\n * @param value - Decoded trial.\n * @returns True if every identifier and repetition is valid; false otherwise.\n */\nexport function isStudyTrial(value: unknown): value is StudyTrial {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tisStudyName(value.id) &&\n\t\t\tisStudyName(value.scenario) &&\n\t\t\tisStudyName(value.arm) &&\n\t\t\ttypeof value.repetition === 'number' &&\n\t\t\tNumber.isSafeInteger(value.repetition) &&\n\t\t\tvalue.repetition >= 0,\n\t)\n}\n\n/** Checks the exact digest fields carried by the execution declaration.\n * @param value - Decoded identity.\n * @returns True if all required identities are digests; false otherwise.\n */\nexport function isStudyIdentity(value: unknown): value is StudyIdentity {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tisStudyDigest(value.agent) &&\n\t\t\tisStudyDigest(value.subject) &&\n\t\t\t(value.provider === undefined || isStudyDigest(value.provider)) &&\n\t\t\tisStudyDigest(value.instrument) &&\n\t\t\tisStudyDigest(value.fixtures) &&\n\t\t\tisStudyDigest(value.profile),\n\t)\n}\n","import type { StudyClosure } from './types.js'\nimport { isStudyDigest, isStudyName } from '@src/core'\nimport { holds, isRecord, isString } from '@orkestrel/contract'\nimport { isArtifactClosure } from '../artifacts/validators.js'\nimport { isStudyIdentity } from '../processes/validators.js'\n\n/** Checks a closure publication before using its command inputs.\n * @param value - The decoded closure.json value.\n * @returns True if relocation, selectors, and both identities are declared; false otherwise.\n */\nexport function isStudyClosure(value: unknown): value is StudyClosure {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tisArtifactClosure(value.closure) &&\n\t\t\tisString(value.root) &&\n\t\t\tisString(value.entry) &&\n\t\t\tisStudyName(value.target) &&\n\t\t\tisStudyName(value.profile) &&\n\t\t\tisStudyIdentity(value.source) &&\n\t\t\tisStudyIdentity(value.identity) &&\n\t\t\tisStudyDigest(value.fingerprint),\n\t)\n}\n","import type {\n\tStudyAttempt,\n\tStudyBounds,\n\tStudyDefinition,\n\tStudyEvidence,\n\tStudyGrading,\n\tStudyIdentity,\n\tStudyObservation,\n\tStudyProfile,\n\tStudyRubric,\n\tStudyScenario,\n} from '@src/core'\nimport type { StudyAttributionSource, StudyCommandArtifact, StudyDeclaration } from './types.js'\nimport type { StudyClosure } from './types.js'\nimport type { ArtifactClosure } from '../artifacts/types.js'\nimport type { StudySealedResult } from '../stores/types.js'\nimport type { JSONValue } from '@orkestrel/contract'\nimport {\n\tSTUDY_CAUSES,\n\tSTUDY_LAYERS,\n\tSTUDY_ROLES,\n\tStudyError,\n\tcomputeStudyScores,\n\tstudyStopToJSON,\n\tparseStudyDefinition,\n\tparseStudyScenario,\n\tparseStudyRubric,\n} from '@src/core'\nimport { parseJSON } from '@orkestrel/contract'\nimport { lstat } from 'node:fs/promises'\nimport { realpathSync } from 'node:fs'\nimport { isAbsolute, join, parse, relative, resolve, sep } from 'node:path'\nimport {\n\tcontainsArtifact,\n\tdecodeStudyJSON,\n\tencodeStudyJSON,\n\thashStudyBytes,\n\tmatchesSystemError,\n} from '../helpers.js'\nimport { readStudyBytes } from '../stores/helpers.js'\nimport { isStudyCustodyEvidence } from '../stores/validators.js'\nimport { STUDY_CUSTODY_BYTES, STUDY_RESERVED_NAME } from '../stores/constants.js'\nimport { readArtifact, verifyArtifactClosure, relocateArtifactPath } from '../artifacts/helpers.js'\nimport { isStudyClosure } from './validators.js'\n\n/** Reads and independently verifies an exclusively published closure.\n * @param directory - The canonical closure destination.\n * @returns The verified publication and its copied physical forest.\n * @throws StudyError - Thrown when publication or its command inputs are invalid.\n */\nexport function readStudyClosure(directory: string): StudyClosure {\n\tconst marker = readArtifact(join(directory, 'closure.json'), STUDY_CUSTODY_BYTES)\n\tconst value = decodeStudyJSON(marker.source)\n\tif (!isStudyClosure(value) || value.closure.destination !== directory)\n\t\tthrow new StudyError('CONFIG', 'Study closure publication is invalid')\n\tverifyArtifactClosure(value.closure, true)\n\tif (\n\t\t(value.root !== directory && !containsArtifact(directory, value.root)) ||\n\t\t!value.closure.members.some(\n\t\t\t(member) => resolve(directory, ...member.key.split('/')) === value.entry,\n\t\t)\n\t)\n\t\tthrow new StudyError('CONFIG', 'Study closure command inputs leave the copied forest')\n\tif (readArtifact(join(directory, 'closure.json'), STUDY_CUSTODY_BYTES).digest !== marker.digest)\n\t\tthrow new StudyError('FAULT', 'Study closure publication changed while reading')\n\treturn value\n}\n\n/** Resolves a profile path through a retained physical relocation when selected.\n * @param root - The active consumer root.\n * @param path - The profile's absolute or consumer-relative selection.\n * @param closure - The optional verified physical forest.\n * @returns The active canonical selection.\n */\nexport function resolveStudyClosurePath(\n\troot: string,\n\tpath: string,\n\tclosure?: ArtifactClosure,\n): string {\n\tconst absolute = resolve(root, path)\n\treturn closure === undefined ||\n\t\tabsolute === closure.destination ||\n\t\tcontainsArtifact(closure.destination, absolute)\n\t\t? absolute\n\t\t: relocateArtifactPath(closure, absolute)\n}\n\n/** Reads one declaration file and refuses a missing or linked path with its root-relative path.\n * @param root - The consumer root used to describe a missing or linked declaration.\n * @param path - The already resolved and contained declaration path.\n * @returns The exact declaration bytes under the custody metadata allowance.\n * @throws StudyError - Thrown with code `CONFIG` when the path is missing or linked; other custody refusals retain their codes.\n * @example Read declaration bytes\n * ```ts\n * import { readStudyDeclarationBytes } from '@orkestrel/study/server'\n *\n * declare const root: string\n * declare const path: string\n * await readStudyDeclarationBytes(root, path)\n * ```\n */\nexport async function readStudyDeclarationBytes(root: string, path: string): Promise<Uint8Array> {\n\ttry {\n\t\tconst absolute = resolve(path)\n\t\tconst origin = parse(absolute).root\n\t\tconst names = relative(origin, absolute).split(sep).filter(Boolean)\n\t\t// Classify consumer input before custody admission without traversing a linked ancestor.\n\t\tfor (const [index] of names.entries()) {\n\t\t\tconst candidate = join(origin, ...names.slice(0, index + 1))\n\t\t\tconst stat = await lstat(candidate)\n\t\t\tif (stat.isSymbolicLink())\n\t\t\t\tthrow new StudyError(\n\t\t\t\t\t'CONFIG',\n\t\t\t\t\t`Declaration path is linked: ${relative(root, candidate).split(sep).join('/')}`,\n\t\t\t\t)\n\t\t\tif (!stat.isDirectory()) break\n\t\t}\n\t\treturn await readStudyBytes(path, STUDY_CUSTODY_BYTES)\n\t} catch (error) {\n\t\tif (matchesSystemError(error, 'ENOENT'))\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t`Declaration is missing: ${relative(root, path).split(sep).join('/')}`,\n\t\t\t)\n\t\tthrow error\n\t}\n}\n\n/** Reads a study declaration, its driver's scenarios, and its rubric as the command resolves them.\n * @param root - The consumer root containing the studies directory.\n * @param study - The selected study name.\n * @param signal - Optional cancellation checked between scenario reads.\n * @returns The parsed declaration, driver bundle, ordered scenarios, fixtures, and selected rubric.\n * @throws StudyError - Thrown when declarations are missing, invalid, or incompatible.\n * @example Read a study declaration\n * ```ts\n * import type { StudyDeclaration } from '@orkestrel/study/server'\n * import { readStudyDeclaration } from '@orkestrel/study/server'\n *\n * declare const root: string\n * const declaration: StudyDeclaration = await readStudyDeclaration(root, 'assessment')\n * ```\n */\nexport async function readStudyDeclaration(\n\troot: string,\n\tstudy: string,\n\tsignal?: AbortSignal,\n): Promise<StudyDeclaration> {\n\tconst directory = resolveStudyPath(join(root, 'studies'), study)\n\tconst definition = parseStudyDefinition(\n\t\tdecodeStudyJSON(\n\t\t\tawait readStudyDeclarationBytes(root, resolveStudyPath(directory, 'study.json')),\n\t\t),\n\t)\n\tif (definition.name !== study)\n\t\tthrow new StudyError('CONFIG', 'Study name differs from its selected directory')\n\tconst bundle = resolveStudyPath(join(root, 'studies'), definition.driver)\n\tconst steps: Array<{ readonly scenario: StudyScenario; readonly fixture: StudyCommandArtifact }> =\n\t\t[]\n\tfor (const id of definition.scenarios) {\n\t\tsignal?.throwIfAborted()\n\t\tconst path = `scenarios/${id}.json`\n\t\tconst bytes = await readStudyDeclarationBytes(root, resolveStudyPath(bundle, path))\n\t\tconst scenario = parseStudyScenario(decodeStudyJSON(bytes))\n\t\tif (scenario.id !== id) throw new StudyError('CONFIG', 'Scenario identity is incompatible')\n\t\tsteps.push({ scenario, fixture: { path, digest: hashStudyBytes(bytes) } })\n\t}\n\tconst rubric = parseStudyRubric(\n\t\tdecodeStudyJSON(\n\t\t\tawait readStudyDeclarationBytes(root, resolveStudyPath(directory, definition.rubric)),\n\t\t),\n\t)\n\treturn {\n\t\tbundle,\n\t\tdefinition,\n\t\tscenarios: Object.freeze(steps.map((step) => step.scenario)),\n\t\tfixtures: Object.freeze(steps.map((step) => step.fixture)),\n\t\trubric,\n\t}\n}\n\n/**\n * Resolves a portable relative artifact path strictly inside its selected directory.\n * @param directory - The selected custody or study directory\n * @param path - The slash-separated relative artifact path\n * @returns The contained absolute host path\n * @throws StudyError - Thrown when a path is malformed, reserved, absolute, or escaping\n * @example\n * ```ts\n * resolveStudyPath(directory, 'profiles/local.json')\n * ```\n */\nexport function resolveStudyPath(directory: string, path: string): string {\n\tconst names = path.split('/')\n\tif (\n\t\tpath === '' ||\n\t\tisAbsolute(path) ||\n\t\t/[\\\\<>:\"|?*]/.test(path) ||\n\t\tArray.from(path).some(\n\t\t\t(character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127,\n\t\t) ||\n\t\tnames.some(\n\t\t\t(name) =>\n\t\t\t\tname === '' ||\n\t\t\t\tname === '.' ||\n\t\t\t\tname === '..' ||\n\t\t\t\tname.endsWith('.') ||\n\t\t\t\tname.endsWith(' ') ||\n\t\t\t\tSTUDY_RESERVED_NAME.test(name.split('.')[0] ?? ''),\n\t\t)\n\t)\n\t\tthrow new StudyError('CONFIG', 'Artifact path must be a portable contained relative path')\n\tconst absolute = resolve(directory, ...names)\n\tif (!containsArtifact(resolve(directory), absolute))\n\t\tthrow new StudyError('CONFIG', 'Artifact path escapes its selected directory')\n\treturn absolute\n}\n\n/**\n * Resolves the execution profile's caller-selected built artifact paths.\n * @param root - The repository root\n * @param profile - The validated source profile\n * @param closure - The optional verified physical forest used to relocate executable selections\n * @returns The reproducible resolved execution profile\n * @example\n * ```ts\n * resolveStudyProfile(root, profile)\n * ```\n */\nexport function resolveStudyProfile(\n\troot: string,\n\tprofile: StudyProfile,\n\tclosure?: ArtifactClosure,\n): StudyProfile {\n\tconst daemon = profile.provider?.daemon\n\tif (\n\t\tdaemon !== undefined &&\n\t\t(!isAbsolute(daemon.executable) || realpathSync(daemon.executable) !== daemon.executable)\n\t)\n\t\tthrow new StudyError('CONFIG', 'Daemon executable must name its canonical absolute path')\n\treturn {\n\t\t...profile,\n\t\tqualification:\n\t\t\tprofile.qualification === undefined ? undefined : resolve(root, profile.qualification),\n\t\tagent: resolveStudyClosurePath(root, profile.agent, closure),\n\t\tsubject: resolveStudyClosurePath(root, profile.subject, closure),\n\t\troots: profile.roots.map((path) => resolveStudyClosurePath(root, path, closure)),\n\t\tprovider:\n\t\t\tprofile.provider === undefined\n\t\t\t\t? undefined\n\t\t\t\t: {\n\t\t\t\t\t\t...profile.provider,\n\t\t\t\t\t\tentry: resolveStudyClosurePath(root, profile.provider.entry, closure),\n\t\t\t\t\t},\n\t}\n}\n\n/**\n * Computes the native supervisor's exact validated execution fingerprint.\n * @param identity - The reproducible executable identities\n * @param bounds - The validated nested execution limits\n * @param definition - The optional full declaration binding supervisor check to execute\n * @returns The fingerprint that execute must compare before any writes or child work\n * @example\n * ```ts\n * computeStudyCommandFingerprint(identity, bounds)\n * ```\n */\nexport function computeStudyCommandFingerprint(\n\tidentity: StudyIdentity,\n\tbounds: StudyBounds,\n\tdefinition?: StudyDefinition,\n): string {\n\treturn hashStudyBytes(\n\t\tencodeStudyJSON({ identity, bounds, ...(definition === undefined ? {} : { definition }) }),\n\t)\n}\n\n/**\n * Computes public fixture identity from execution policy and exact scenario bytes.\n * @param definition - The complete retained study declaration\n * @param scenarios - The exact public scenario artifact identities\n * @returns The digest shared by compatible capacity and memory executions\n * @example\n * ```ts\n * computeStudyFixtureDigest(definition, scenarios)\n * ```\n */\nexport function computeStudyFixtureDigest(\n\tdefinition: StudyDefinition,\n\tscenarios: readonly StudyCommandArtifact[],\n): string {\n\treturn hashStudyBytes(\n\t\tencodeStudyJSON({\n\t\t\tdriver: definition.driver,\n\t\t\tarms: definition.arms,\n\t\t\torder: definition.order,\n\t\t\tretries: definition.retries,\n\t\t\tscenarios,\n\t\t}),\n\t)\n}\n\n/**\n * Reads sealed evidence bytes through custody checks without loading executable code.\n * @param result - The independently verified sealed execution\n * @returns Evidence records keyed by scheduled trial identity\n * @throws StudyError - Thrown when evidence drifts, becomes partial, or fails validation\n * @example\n * ```ts\n * await collectStudyEvidence(result)\n * ```\n */\nexport async function collectStudyEvidence(\n\tresult: StudySealedResult,\n): Promise<Readonly<Record<string, readonly StudyEvidence[]>>> {\n\tconst retained: Array<readonly [string, readonly StudyEvidence[]]> = []\n\tfor (const trial of result.manifest.schedule) {\n\t\tconst path = `trials/${trial.id}/evidence.jsonl`\n\t\tconst file = result.seal.files.find((entry) => entry.path === path)\n\t\tconst bytes = await readStudyBytes(\n\t\t\tjoin(result.directory, 'execution', 'trials', trial.id, 'evidence.jsonl'),\n\t\t\tresult.manifest.bounds.trial.bytes,\n\t\t)\n\t\tif (file === undefined || hashStudyBytes(bytes) !== file.digest)\n\t\t\tthrow new StudyError('CUSTODY', 'Evidence changed after execution verification')\n\t\tconst text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\t\tif (text !== '' && !text.endsWith('\\n'))\n\t\t\tthrow new StudyError('CUSTODY', 'Evidence is incomplete')\n\t\tconst rows = text\n\t\t\t.split(/\\r\\n|\\n/)\n\t\t\t.slice(0, -1)\n\t\t\t.map((line): StudyEvidence => {\n\t\t\t\tconst row = parseJSON(line)\n\t\t\t\tif (!isStudyCustodyEvidence(row)) throw new StudyError('CUSTODY', 'Evidence row is invalid')\n\t\t\t\treturn row\n\t\t\t})\n\t\tretained.push([trial.id, Object.freeze(rows)])\n\t}\n\treturn Object.freeze(Object.fromEntries(retained))\n}\n\n/**\n * Partitions records by their explicit execution fact without inferring any.\n * @param records - The attempts, observations, or attribution sources to partition\n * @returns Counts of executed and unexecuted records, which sum to the record count\n * @example\n * ```ts\n * computeStudyPartition(attempts) // { executed: 2, unexecuted: 1 }\n * ```\n */\nexport function computeStudyPartition(\n\trecords: ReadonlyArray<StudyAttempt | StudyObservation | StudyAttributionSource>,\n): Readonly<Record<'executed' | 'unexecuted', number>> {\n\treturn {\n\t\texecuted: records.filter((record) => record.executed).length,\n\t\tunexecuted: records.filter((record) => !record.executed).length,\n\t}\n}\n\n/**\n * Groups failed records by cause, role, and layer, each group carrying its source readings.\n * @remarks\n * A group exists for each cause, role, and layer that holds at least one record. Groups follow\n * `STUDY_CAUSES`, then `STUDY_ROLES` with an absent role last, then `STUDY_LAYERS` with an absent\n * layer last. `role` and `layer` are null when absent. `executed` and `unexecuted` partition the\n * group by each record's own execution fact. `readings` lists every record of the group that carries\n * a stop, in source order, with `trial`, `goal` at the goal level only, `id`, `max`, and `consumed`\n * (null when the source reported none). A failure sealed before the `stop` member existed groups with\n * a null layer and no reading; the helper infers no layer from a message.\n * @param sources - The failed records, in source order\n * @returns The JSON groups\n * @example\n * ```ts\n * computeStudyAttributions([{ trial: 'r1-s1-a1', goal: undefined, failure, executed: true }])\n * ```\n */\nexport function computeStudyAttributions(sources: readonly StudyAttributionSource[]): JSONValue {\n\treturn STUDY_CAUSES.flatMap((cause) =>\n\t\t[...STUDY_ROLES, undefined].flatMap((role) =>\n\t\t\t[...STUDY_LAYERS, undefined].flatMap((layer) => {\n\t\t\t\tconst group = sources.filter(\n\t\t\t\t\t(source) =>\n\t\t\t\t\t\tsource.failure.cause === cause &&\n\t\t\t\t\t\tsource.failure.role === role &&\n\t\t\t\t\t\tsource.failure.stop?.layer === layer,\n\t\t\t\t)\n\t\t\t\tif (group.length === 0) return []\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tcause,\n\t\t\t\t\t\trole: role ?? null,\n\t\t\t\t\t\tlayer: layer ?? null,\n\t\t\t\t\t\t...computeStudyPartition(group),\n\t\t\t\t\t\treadings: group.flatMap((source) => {\n\t\t\t\t\t\t\tconst stop = source.failure.stop\n\t\t\t\t\t\t\treturn stop === undefined\n\t\t\t\t\t\t\t\t? []\n\t\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\ttrial: source.trial,\n\t\t\t\t\t\t\t\t\t\t\t...(source.goal === undefined ? {} : { goal: source.goal }),\n\t\t\t\t\t\t\t\t\t\t\t...Object.fromEntries(\n\t\t\t\t\t\t\t\t\t\t\t\tObject.entries(studyStopToJSON(stop) ?? {}).filter(\n\t\t\t\t\t\t\t\t\t\t\t\t\t([key]) => key !== 'layer',\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t}),\n\t\t),\n\t)\n}\n\n/**\n * Computes whole-horizon results with operational costs and repetitions kept distinct.\n * @param result - The verified complete execution\n * @param rubric - The retained compatible rubric\n * @param grading - The independently verified selected grading\n * @returns The JSON report without pooling identities or inventing absent measurements\n * @remarks\n * Operations count affected trial and goal records, not independent failure events, and the\n * trial and goal counts overlap and are never added. Completion is operational: a goal is\n * completed when it holds a non-partial product and no failure, and a trial when it holds no\n * failure and every goal completed. It is neither task success nor a qualification gate.\n * @example\n * ```ts\n * computeStudyReport(result, rubric, grading)\n * ```\n */\nexport function computeStudyReport(\n\tresult: StudySealedResult,\n\trubric: StudyRubric,\n\tgrading: StudyGrading,\n): JSONValue {\n\tconst scores = computeStudyScores(result.manifest, rubric, grading)\n\tconst observations = result.attempts.flatMap((attempt) => attempt.observations)\n\tconst usage = observations.flatMap((observation) => observation.usage)\n\tconst completed = new Set(\n\t\tobservations.filter(\n\t\t\t(observation) =>\n\t\t\t\tobservation.product !== undefined &&\n\t\t\t\t!observation.product.partial &&\n\t\t\t\tobservation.failure === undefined,\n\t\t),\n\t)\n\tconst repetitions = result.manifest.definition.order.map((order, repetition) => ({\n\t\trepetition,\n\t\torder: [...order],\n\t\tarms: result.manifest.definition.arms.map((arm) => {\n\t\t\tconst trials = new Set(\n\t\t\t\tresult.manifest.schedule\n\t\t\t\t\t.filter((trial) => trial.repetition === repetition && trial.arm === arm)\n\t\t\t\t\t.map((trial) => trial.id),\n\t\t\t)\n\t\t\tconst applicable = result.manifest.schedule\n\t\t\t\t.filter((trial) => trials.has(trial.id))\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) => ({ trial: trial.id, criterion })),\n\t\t\t\t)\n\t\t\tconst judgments = applicable.map((pair) => ({\n\t\t\t\tcriterion: pair.criterion,\n\t\t\t\tjudgment: grading.judgments.find(\n\t\t\t\t\t(entry) => entry.trial === pair.trial && entry.criterion === pair.criterion.id,\n\t\t\t\t),\n\t\t\t}))\n\t\t\tconst achieved = judgments.filter((entry) => entry.judgment?.verdict === 'achieved').length\n\t\t\tconst unsuccessful = judgments.filter(\n\t\t\t\t(entry) => entry.judgment?.verdict === 'unsuccessful',\n\t\t\t).length\n\t\t\tconst unknown = applicable.length - achieved - unsuccessful\n\t\t\treturn {\n\t\t\t\tarm,\n\t\t\t\ttotal: applicable.length,\n\t\t\t\tachieved,\n\t\t\t\tunsuccessful,\n\t\t\t\tunknown,\n\t\t\t\tcritical: judgments.filter(\n\t\t\t\t\t(entry) => entry.criterion.critical && entry.judgment?.verdict === 'unsuccessful',\n\t\t\t\t).length,\n\t\t\t\tlower: achieved / applicable.length,\n\t\t\t\tupper: (achieved + unknown) / applicable.length,\n\t\t\t\tcoverage: (achieved + unsuccessful) / applicable.length,\n\t\t\t}\n\t\t}),\n\t}))\n\tconst identity = result.manifest.identity\n\treturn {\n\t\tcommand: 'report',\n\t\tresult: result.manifest.id,\n\t\tseal: result.seal.id,\n\t\tidentity: {\n\t\t\tagent: identity.agent,\n\t\t\tsubject: identity.subject,\n\t\t\tinstrument: identity.instrument,\n\t\t\tfixtures: identity.fixtures,\n\t\t\tprofile: identity.profile,\n\t\t\t...(identity.provider === undefined ? {} : { provider: identity.provider }),\n\t\t},\n\t\tpurpose: result.manifest.definition.purpose,\n\t\tpopulation: 'Complete declared trial and criterion horizon',\n\t\tuncertainty:\n\t\t\trepetitions.length === 1\n\t\t\t\t? 'One repetition is descriptive and does not establish replicated capacity or quality.'\n\t\t\t\t: 'Repetitions are retained separately; intervals represent unresolved grading, not statistical confidence.',\n\t\tscores: scores.map((score) => ({ ...score })),\n\t\trepetitions,\n\t\toperations: {\n\t\t\ttrials: {\n\t\t\t\tscheduled: result.manifest.schedule.length,\n\t\t\t\tterminal: result.attempts.length,\n\t\t\t\t...computeStudyPartition(result.attempts),\n\t\t\t\tcompleted: result.attempts.filter(\n\t\t\t\t\t(attempt) =>\n\t\t\t\t\t\tattempt.failure === undefined &&\n\t\t\t\t\t\tattempt.observations.every((observation) => completed.has(observation)),\n\t\t\t\t).length,\n\t\t\t\tfaults: STUDY_CAUSES.map((cause) => ({\n\t\t\t\t\tcause,\n\t\t\t\t\t...computeStudyPartition(\n\t\t\t\t\t\tresult.attempts.filter((attempt) => attempt.failure?.cause === cause),\n\t\t\t\t\t),\n\t\t\t\t})),\n\t\t\t\tattributions: computeStudyAttributions(\n\t\t\t\t\tresult.attempts.flatMap((attempt) =>\n\t\t\t\t\t\tattempt.failure === undefined\n\t\t\t\t\t\t\t? []\n\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttrial: attempt.trial.id,\n\t\t\t\t\t\t\t\t\t\tgoal: undefined,\n\t\t\t\t\t\t\t\t\t\tfailure: attempt.failure,\n\t\t\t\t\t\t\t\t\t\texecuted: attempt.executed,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t},\n\t\t\tgoals: {\n\t\t\t\tscheduled: observations.length,\n\t\t\t\t...computeStudyPartition(observations),\n\t\t\t\tproducts: observations.filter((observation) => observation.product !== undefined).length,\n\t\t\t\tpartial: observations.filter((observation) => observation.product?.partial === true).length,\n\t\t\t\tcompleted: observations.filter((observation) => completed.has(observation)).length,\n\t\t\t\tfaults: STUDY_CAUSES.map((cause) => ({\n\t\t\t\t\tcause,\n\t\t\t\t\t...computeStudyPartition(\n\t\t\t\t\t\tobservations.filter((observation) => observation.failure?.cause === cause),\n\t\t\t\t\t),\n\t\t\t\t})),\n\t\t\t\tattributions: computeStudyAttributions(\n\t\t\t\t\tresult.attempts.flatMap((attempt) =>\n\t\t\t\t\t\tattempt.observations.flatMap((observation) =>\n\t\t\t\t\t\t\tobservation.failure === undefined\n\t\t\t\t\t\t\t\t? []\n\t\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\ttrial: attempt.trial.id,\n\t\t\t\t\t\t\t\t\t\t\tgoal: observation.goal,\n\t\t\t\t\t\t\t\t\t\t\tfailure: observation.failure,\n\t\t\t\t\t\t\t\t\t\t\texecuted: observation.executed,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\tcosts: {\n\t\t\tduration: result.attempts.reduce((total, attempt) => total + attempt.duration, 0),\n\t\t\troles: STUDY_ROLES.map((role) => {\n\t\t\t\tconst charges = usage.filter((entry) => entry.role === role)\n\t\t\t\treturn {\n\t\t\t\t\trole,\n\t\t\t\t\tmeasurements: charges.length,\n\t\t\t\t\tcalls: charges.reduce((total, entry) => total + entry.calls, 0),\n\t\t\t\t\tduration: charges.reduce((total, entry) => total + entry.duration, 0),\n\t\t\t\t\ttokens: {\n\t\t\t\t\t\tknown: charges.reduce((total, entry) => total + (entry.tokens ?? 0), 0),\n\t\t\t\t\t\tunknown: charges.filter((entry) => entry.tokens === undefined).length,\n\t\t\t\t\t},\n\t\t\t\t\tbytes: {\n\t\t\t\t\t\tknown: charges.reduce((total, entry) => total + (entry.bytes ?? 0), 0),\n\t\t\t\t\t\tunknown: charges.filter((entry) => entry.bytes === undefined).length,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}),\n\t\t},\n\t}\n}\n","import type { StudyCommandRequest } from './types.js'\nimport { StudyError, isStudyDigest } from '@src/core'\nimport { isRecord, parseJSON } from '@orkestrel/contract'\nimport { isAbsolute, resolve } from 'node:path'\nimport { isStudyCustodyName } from '../stores/validators.js'\nimport { STUDY_COMMAND_HELP } from './constants.js'\nimport { resolveStudyPath } from './helpers.js'\n\n/** Parses public command tokens with operation-specific grammar diagnostics.\n * @param arguments_ - Exact command tokens, after the CLI help boundary.\n * @returns The independent operation request.\n * @throws StudyError when a token, required flag, or portable path is invalid.\n * @example Parse a study command\n * ```ts\n * import { parseStudyArguments } from '@orkestrel/study/server'\n *\n * parseStudyArguments(['check', 'files', '--profile', 'local'])\n * ```\n */\nexport function parseStudyArguments(arguments_: readonly string[]): StudyCommandRequest {\n\tconst command = arguments_[0]\n\tconst target = arguments_[1]\n\tconst usage =\n\t\tSTUDY_COMMAND_HELP.split('\\n').find((line) => line.startsWith('study ' + command + ' ')) ??\n\t\t'Expected study check, freeze, execute, grade, label, or report; use study --help.'\n\tif (!['check', 'freeze', 'execute', 'grade', 'label', 'report'].includes(command ?? ''))\n\t\tthrow new StudyError(\n\t\t\t'CONFIG',\n\t\t\t'Unknown or missing command ' + JSON.stringify(command ?? '<command>') + '. ' + usage,\n\t\t)\n\tif (target === undefined || target === '' || target.startsWith('-'))\n\t\tthrow new StudyError(\n\t\t\t'CONFIG',\n\t\t\t'Missing <' +\n\t\t\t\t(command === 'check' || command === 'execute' || command === 'freeze'\n\t\t\t\t\t? 'study'\n\t\t\t\t\t: 'result') +\n\t\t\t\t'> before ' +\n\t\t\t\tJSON.stringify(target ?? '<end>') +\n\t\t\t\t'. ' +\n\t\t\t\tusage,\n\t\t)\n\tconst allowed =\n\t\tcommand === 'check'\n\t\t\t? ['--profile', '--closure']\n\t\t\t: command === 'execute'\n\t\t\t\t? ['--profile', '--out', '--expected', '--closure', '--replay', '--prefix', '--offline']\n\t\t\t\t: command === 'freeze'\n\t\t\t\t\t? ['--profile', '--to']\n\t\t\t\t\t: command === 'grade'\n\t\t\t\t\t\t? ['--rubric']\n\t\t\t\t\t\t: command === 'label'\n\t\t\t\t\t\t\t? ['--grading', '--labels']\n\t\t\t\t\t\t\t: ['--grading']\n\tconst tokens: ReadonlyArray<string | undefined> = arguments_.slice(2)\n\t// Positions, not present elements: a sparse token array keeps each hole as an absent flag or value.\n\tconst pairs = [...tokens.entries()].flatMap(([index, flag]) =>\n\t\tindex % 2 === 0 ? [{ flag, value: tokens[index + 1] }] : [],\n\t)\n\t// Reversed so the earliest index of each flag is the one the lookup retains.\n\tconst firsts = new Map(pairs.map(({ flag }, index) => [flag, index] as const).reverse())\n\tfor (const [index, { flag, value }] of pairs.entries()) {\n\t\tif (flag === undefined || !allowed.includes(flag))\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\tJSON.stringify(flag ?? '<end>') +\n\t\t\t\t\t' is not a ' +\n\t\t\t\t\tcommand +\n\t\t\t\t\t' flag; accepts ' +\n\t\t\t\t\tallowed.join(', ') +\n\t\t\t\t\t'. ' +\n\t\t\t\t\tusage,\n\t\t\t)\n\t\tif (firsts.get(flag) !== index) throw new StudyError('CONFIG', flag + ' is duplicate. ' + usage)\n\t\tif (value === undefined || value === '' || value.startsWith('-'))\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\tflag + ' requires a value before ' + JSON.stringify(value ?? '<end>') + '. ' + usage,\n\t\t\t)\n\t}\n\tconst flags = new Map(\n\t\tpairs.flatMap(({ flag, value }) =>\n\t\t\tflag === undefined || value === undefined ? [] : [[flag, value] as const],\n\t\t),\n\t)\n\tif (command === 'check' || command === 'execute' || command === 'freeze') {\n\t\tif (!isStudyCustodyName(target))\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'Invalid study token ' + JSON.stringify(target) + '; use a portable study name. ' + usage,\n\t\t\t)\n\t\tconst profile = flags.get('--profile') ?? 'local'\n\t\tconst out = flags.get('--out')\n\t\tconst expected = flags.get('--expected')\n\t\tif (!isStudyCustodyName(profile))\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'--profile ' + JSON.stringify(profile) + ' must be a portable name. ' + usage,\n\t\t\t)\n\t\tif (command === 'freeze') {\n\t\t\tif (!flags.has('--profile')) throw new StudyError('CONFIG', 'Missing --profile. ' + usage)\n\t\t\tconst destination = flags.get('--to')\n\t\t\tif (destination === undefined) throw new StudyError('CONFIG', 'Missing --to. ' + usage)\n\t\t\tif (!isAbsolute(destination)) resolveStudyPath(resolve('.'), destination)\n\t\t\treturn { command, target, profile, destination }\n\t\t}\n\t\tif (out !== undefined && !isAbsolute(out)) {\n\t\t\ttry {\n\t\t\t\tresolveStudyPath(resolve('.'), out)\n\t\t\t} catch {\n\t\t\t\tthrow new StudyError(\n\t\t\t\t\t'CONFIG',\n\t\t\t\t\t'--out ' +\n\t\t\t\t\t\tJSON.stringify(out) +\n\t\t\t\t\t\t' must be a portable contained path and cannot escape the consumer root. ' +\n\t\t\t\t\t\tusage,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tif (expected !== undefined && !isStudyDigest(expected))\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'--expected ' + JSON.stringify(expected) + ' must be a SHA-256 fingerprint. ' + usage,\n\t\t\t)\n\t\tconst closure = flags.get('--closure')\n\t\tif (closure !== undefined && !isAbsolute(closure)) resolveStudyPath(resolve('.'), closure)\n\t\tconst result = flags.get('--replay')\n\t\tconst prefix = flags.get('--prefix')\n\t\tconst offline = flags.get('--offline')\n\t\tif (result === undefined && (prefix !== undefined || offline !== undefined))\n\t\t\tthrow new StudyError('CONFIG', '--prefix and --offline require --replay. ' + usage)\n\t\tconst replay = result === undefined ? undefined : parseJSON(prefix ?? '')\n\t\tif (\n\t\t\tresult !== undefined &&\n\t\t\t(!isRecord(replay) ||\n\t\t\t\tObject.keys(replay).length === 0 ||\n\t\t\t\t!Object.entries(replay).every(\n\t\t\t\t\t([trial, count]) =>\n\t\t\t\t\t\tisStudyCustodyName(trial) &&\n\t\t\t\t\t\ttypeof count === 'number' &&\n\t\t\t\t\t\tNumber.isSafeInteger(count) &&\n\t\t\t\t\t\tcount > 0,\n\t\t\t\t) ||\n\t\t\t\t(offline !== 'true' && offline !== 'false'))\n\t\t)\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'--replay requires --prefix trial counts and --offline true or false. ' + usage,\n\t\t\t)\n\t\treturn {\n\t\t\tcommand,\n\t\t\ttarget,\n\t\t\tprofile,\n\t\t\tout,\n\t\t\texpected,\n\t\t\t...(closure === undefined ? {} : { closure }),\n\t\t\t...(result === undefined || !isRecord(replay)\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\treplay: {\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\tprefix: Object.fromEntries(\n\t\t\t\t\t\t\t\tObject.entries(replay).map(([trial, count]) => [trial, Number(count)]),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\toffline: offline === 'true',\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t}\n\t}\n\tif (command === 'grade') {\n\t\tconst rubric = flags.get('--rubric')\n\t\tif (rubric === undefined) throw new StudyError('CONFIG', 'Missing --rubric. ' + usage)\n\t\treturn { command, target, rubric }\n\t}\n\tconst grading = flags.get('--grading')\n\tif (!isStudyDigest(grading))\n\t\tthrow new StudyError(\n\t\t\t'CONFIG',\n\t\t\t'--grading ' +\n\t\t\t\tJSON.stringify(grading ?? '<missing>') +\n\t\t\t\t' must be an exact SHA-256 grading identity. ' +\n\t\t\t\tusage,\n\t\t)\n\tif (command === 'label') {\n\t\tconst labels = flags.get('--labels')\n\t\tif (labels === undefined) throw new StudyError('CONFIG', 'Missing --labels. ' + usage)\n\t\treturn { command, target, grading, labels }\n\t}\n\treturn { command: 'report', target, grading }\n}\n","/** Limits each serialized IPC envelope, including its JSON framing. */\nexport const STUDY_FRAME_BYTES = 16 * 1024 * 1024\n\n/** Limits outstanding bidirectional protocol work per process. */\nexport const STUDY_PENDING_LIMIT = 64\n\n/** Limits combined worker stdout and stderr before termination. */\nexport const STUDY_LOG_BYTES = 64 * 1024\n\n/** Bounds how long inherited output handles stay open after native exit, in milliseconds. */\nexport const STUDY_DRAIN_DURATION = 1000\n\n/** Attributes an expired process handshake or cleanup deadline. */\nexport const STUDY_PROCESS_LABEL = 'Process lifecycle'\n\n/** Names the worker operation routed by the built application entry. */\nexport const STUDY_WORKER_OPERATION = 'study-worker'\n\n/** Names the private bounded validation and grading route. */\nexport const STUDY_TASK_OPERATION = 'study-adapter'\n\n/** Names the command route beneath the native supervisor. */\nexport const STUDY_COMMAND_OPERATION = 'study-command'\n\n/** Caps pure domain work independently of its event loop. */\nexport const STUDY_TASK_DURATION = 60000\n","import type { StudyProvider, StudyRole, StudyRoom, StudyStop } from '@src/core'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type { OllamaTiming } from '@orkestrel/ollama'\nimport type {\n\tStudyOllamaPolicy,\n\tStudyOllamaRequest,\n\tStudyOllamaOptions,\n\tStudyOllamaTerminal,\n\tStudyOllamaTransportOptions,\n\tStudyOllamaStep,\n} from './types.js'\nimport type { StudyExchangeBytes } from '../stores/types.js'\nimport { hashStudyBytes } from '../helpers.js'\nimport { isStudyOllamaMetadata, isStudyOllamaModel, isStudyOllamaStep } from './validators.js'\nimport { StudyError, parseStudyReading } from '@src/core'\nimport {\n\tattempt,\n\tcanonicalStringify,\n\tisArray,\n\tisInteger,\n\tisObject,\n\tisRecord,\n\tparseJSON,\n} from '@orkestrel/contract'\n\n/**\n * Declares the pinned serving identities the Ollama transport verifies, keyed by the label their inventory evidence carries.\n * @param provider - Declared serving identities\n * @returns The model pin, plus the judge pin when the provider declares both the judge name and its digest\n */\nexport function buildStudyOllamaModels(\n\tprovider: StudyProvider,\n): StudyOllamaTransportOptions['models'] {\n\treturn {\n\t\tmodel: { name: provider.model, digest: provider.digest.model },\n\t\t...(provider.judge === undefined || provider.digest.judge === undefined\n\t\t\t? {}\n\t\t\t: { judge: { name: provider.judge, digest: provider.digest.judge } }),\n\t}\n}\n\n/**\n * Builds the provider options one role's declared wire policy determines.\n * @remarks\n * The policy's `options` object keeps its identity and key order. A strict policy adds `truncate`\n * and `shift` as `false`; any other policy omits both keys. The `length` allowance is read by the\n * transport and projects nothing.\n * @param policy - The role's declared wire policy\n * @returns The model, think flag, options object, and the strict native fields when declared\n */\nexport function buildStudyOllamaOptions(policy: StudyOllamaPolicy): StudyOllamaOptions {\n\treturn {\n\t\tmodel: policy.model,\n\t\toptions: policy.options,\n\t\tthink: policy.think,\n\t\t...(policy.strict ? { truncate: false, shift: false } : {}),\n\t}\n}\n\n/**\n * Validates declared role policies against the pinned inventory before any dispatch.\n * @param roles - The declared wire policy of each model role\n * @param models - The pinned served identities\n * @returns Nothing when every policy names a pinned model and a positive output allowance\n * @throws StudyError - Thrown with code `CONFIG` when a policy names an unpinned model, declares no positive safe-integer `num_predict`, or makes the raw judge wire strict\n */\nexport function validateStudyOllamaRoles(\n\troles: StudyOllamaTransportOptions['roles'],\n\tmodels: StudyOllamaTransportOptions['models'],\n): void {\n\tconst names = Object.values(models).map((model) => model.name)\n\tfor (const [role, policy] of Object.entries(roles)) {\n\t\tif (policy === undefined) continue\n\t\tif (!names.includes(policy.model))\n\t\t\tthrow new StudyError('CONFIG', 'Ollama role policy names a model the inventory does not pin')\n\t\tconst output = policy.options.num_predict\n\t\tif (output === undefined || !Number.isSafeInteger(output) || output <= 0)\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'Ollama role policy declares no positive num_predict allowance',\n\t\t\t)\n\t\tif (role === 'judge' && policy.strict)\n\t\t\tthrow new StudyError('CONFIG', 'Ollama strict fields apply only to chat roles')\n\t}\n}\n\n/** Encodes exact application bytes with their decoded size and SHA-256 identity.\n * @param bytes - The request or response application bytes.\n * @returns Canonical base64 and the independent byte receipt.\n */\nexport function buildStudyOllamaBytes(bytes: Uint8Array): StudyExchangeBytes {\n\treturn {\n\t\tbody: Buffer.from(bytes).toString('base64'),\n\t\tdigest: hashStudyBytes(bytes),\n\t\tsize: bytes.byteLength,\n\t}\n}\n\n/** Validates independent metadata bounds and the complete optional recording group.\n * @param options - The owned transport configuration.\n * @returns Nothing when declarations are executable.\n * @throws StudyError - Thrown with CONFIG for invalid bounds, groups, identities or ordered policies.\n */\nexport function validateStudyOllamaRecording(options: StudyOllamaTransportOptions): void {\n\tif (!isStudyOllamaMetadata(options.metadata))\n\t\tthrow new StudyError('CONFIG', 'Invalid independent metadata budget')\n\tif (!Object.values(options.models).every(isStudyOllamaModel))\n\t\tthrow new StudyError('CONFIG', 'Invalid pinned model identity')\n\tconst declared = [options.version, options.procedure, options.exchanges].filter(\n\t\t(value) => value !== undefined,\n\t).length\n\tif (declared === 0) return\n\tif (\n\t\tdeclared !== 3 ||\n\t\ttypeof options.version !== 'string' ||\n\t\toptions.version.length === 0 ||\n\t\t!Array.isArray(options.procedure) ||\n\t\toptions.exchanges === undefined ||\n\t\t!Number.isSafeInteger(options.exchanges.next) ||\n\t\toptions.exchanges.next < 1\n\t)\n\t\tthrow new StudyError('CONFIG', 'Recording requires version, procedure and an exchange sink')\n\tfor (const [index, step] of options.procedure.entries()) {\n\t\tif (\n\t\t\t!isStudyOllamaStep(step) ||\n\t\t\tstep.ordinal !== index + 1 ||\n\t\t\tcanonicalStringify(step.policy) !== canonicalStringify(options.roles[step.role])\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Invalid ordered model-step declaration')\n\t\tif (step.admission === 'exact')\n\t\t\treadStudyOllamaRequest(options, step.role, new URL(step.path, options.url), {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: step.body,\n\t\t\t})\n\t}\n}\n\n/** Admits one model request against its next exact or capture declaration.\n * @param step - The next model step, absent after the procedure ends.\n * @param goal - The bound goal identity.\n * @param request - The independently validated request policy and byte length.\n * @param body - The owned encoded request body.\n * @returns Nothing when identity, policy and bytes match the declaration.\n * @throws StudyError - Thrown with FAULT before sending any mismatched request.\n */\nexport function validateStudyOllamaStep(\n\tstep: StudyOllamaStep | undefined,\n\tgoal: string,\n\trequest: StudyOllamaRequest,\n\tbody: RequestInit['body'],\n): void {\n\tif (\n\t\tstep === undefined ||\n\t\tstep.goal !== goal ||\n\t\tstep.role !== request.role ||\n\t\tstep.path !== request.path ||\n\t\ttypeof body !== 'string' ||\n\t\t(step.admission === 'exact'\n\t\t\t? !Buffer.from(step.body).equals(Buffer.from(body))\n\t\t\t: step.bytes !== request.bytes)\n\t)\n\t\tthrow new StudyError('FAULT', 'Request differs from the declared model step')\n}\n\n/**\n * Reads exact outbound Ollama facts and refuses a request outside its declared policy.\n * @remarks\n * The refusal happens before admission, so a refused request is never accounted.\n * @param options - The admitted origin, pinned inventory, and declared role policies\n * @param role - The responsible request role\n * @param input - The requested URL\n * @param init - The native fetch settings\n * @returns The validated dispatch facts\n * @throws StudyError - Thrown with code `CONFIG` when the endpoint, model, options, flags, or strict fields differ from the declaration, or the role declares no policy\n */\nexport function readStudyOllamaRequest(\n\toptions: Pick<StudyOllamaTransportOptions, 'url' | 'models' | 'roles'>,\n\trole: StudyRole,\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n): StudyOllamaRequest {\n\tif (input instanceof Request)\n\t\tthrow new StudyError('CONFIG', 'Ollama transport requires explicit URL requests')\n\tconst url = new URL(input)\n\tconst path =\n\t\trole === 'metadata'\n\t\t\t? init?.method === 'POST'\n\t\t\t\t? '/api/show'\n\t\t\t\t: url.pathname === '/api/version'\n\t\t\t\t\t? '/api/version'\n\t\t\t\t\t: '/api/tags'\n\t\t\t: role === 'judge'\n\t\t\t\t? '/api/generate'\n\t\t\t\t: '/api/chat'\n\tif (\n\t\turl.origin !== new URL(options.url).origin ||\n\t\turl.pathname !== path ||\n\t\turl.search !== '' ||\n\t\turl.hash !== '' ||\n\t\turl.username !== '' ||\n\t\turl.password !== ''\n\t)\n\t\tthrow new StudyError(\n\t\t\t'CONFIG',\n\t\t\t'Ollama transport endpoint differs from the admitted origin and path',\n\t\t)\n\tif (role === 'metadata') {\n\t\tif (path === '/api/show') {\n\t\t\tif (typeof init?.body !== 'string')\n\t\t\t\tthrow new StudyError('CONFIG', 'Invalid model metadata request')\n\t\t\tconst body: unknown = JSON.parse(init.body)\n\t\t\tif (\n\t\t\t\t!isRecord(body) ||\n\t\t\t\tObject.keys(body).length !== 1 ||\n\t\t\t\ttypeof body.model !== 'string' ||\n\t\t\t\t!Object.values(options.models).some((model) => model.name === body.model)\n\t\t\t)\n\t\t\t\tthrow new StudyError('CONFIG', 'Invalid model metadata identity')\n\t\t\treturn {\n\t\t\t\trole,\n\t\t\t\tpath,\n\t\t\t\tmodel: body.model,\n\t\t\t\toutput: 0,\n\t\t\t\tbytes: new TextEncoder().encode(init.body).byteLength,\n\t\t\t\toptions: {},\n\t\t\t\tstrict: false,\n\t\t\t\tlength: false,\n\t\t\t}\n\t\t}\n\t\tif (init?.method !== 'GET' || init.body !== undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Invalid inventory request')\n\t\treturn {\n\t\t\trole,\n\t\t\tpath,\n\t\t\tmodel: undefined,\n\t\t\toutput: 0,\n\t\t\tbytes: 0,\n\t\t\toptions: {},\n\t\t\tstrict: false,\n\t\t\tlength: false,\n\t\t}\n\t}\n\tif (init?.method !== 'POST' || typeof init.body !== 'string')\n\t\tthrow new StudyError('CONFIG', 'Ollama transport requires an encoded JSON POST')\n\tconst policy = role === 'tool' || role === 'maintenance' ? undefined : options.roles[role]\n\tif (policy === undefined)\n\t\tthrow new StudyError('CONFIG', 'Ollama transport role has no declared wire policy')\n\tconst output = policy.options.num_predict\n\tif (output === undefined || !Number.isSafeInteger(output) || output <= 0)\n\t\tthrow new StudyError('CONFIG', 'Ollama role policy declares no positive num_predict allowance')\n\tconst body: unknown = JSON.parse(init.body)\n\tif (\n\t\t!isRecord(body) ||\n\t\tbody.model !== policy.model ||\n\t\t!isRecord(body.options) ||\n\t\tcanonicalStringify(body.options) !== canonicalStringify(policy.options) ||\n\t\tbody.stream !== (role !== 'judge')\n\t)\n\t\tthrow new StudyError(\n\t\t\t'CONFIG',\n\t\t\t'Ollama transport model or effective options differ from the declared policy',\n\t\t)\n\tif (\n\t\trole === 'judge'\n\t\t\t? body.raw !== true || body.logprobs !== true\n\t\t\t: typeof body.think !== 'boolean' || (body.think === true && !policy.think)\n\t)\n\t\tthrow new StudyError('CONFIG', 'Ollama transport flags differ from the declared policy')\n\t// The strict fields govern chat requests only; the judge's raw generate wire is outside them.\n\tconst strict = policy.strict && role !== 'judge'\n\tif (strict && (body.truncate !== false || body.shift !== false))\n\t\tthrow new StudyError('CONFIG', 'Ollama transport must disable native truncation and shifting')\n\treturn {\n\t\trole,\n\t\tpath,\n\t\tmodel: policy.model,\n\t\toutput,\n\t\tbytes: new TextEncoder().encode(init.body).byteLength,\n\t\toptions: { ...policy.options },\n\t\tstrict,\n\t\tlength: policy.length,\n\t}\n}\n\n/**\n * Reads the declared model context ceiling without claiming daemon allocation.\n * @param value - The parsed Ollama show response\n * @param context - The requested total context\n * @returns The unambiguous model context ceiling\n * @throws StudyError - Thrown with code `FAULT` when context metadata is missing, or `CAPACITY` when it is ambiguous or below the requested context\n */\nexport function readStudyOllamaSupport(value: unknown, context: number): number {\n\tif (\n\t\t!isRecord(value) ||\n\t\t!isRecord(value.model_info) ||\n\t\ttypeof value.model_info['general.architecture'] !== 'string'\n\t)\n\t\tthrow new StudyError('FAULT', 'Missing model context metadata')\n\tconst architecture = value.model_info['general.architecture']\n\tconst keys = Object.keys(value.model_info).filter((key) => key.endsWith('.context_length'))\n\tconst ceiling = value.model_info[`${architecture}.context_length`]\n\tif (\n\t\tkeys.length !== 1 ||\n\t\ttypeof ceiling !== 'number' ||\n\t\t!Number.isSafeInteger(ceiling) ||\n\t\tceiling < context\n\t) {\n\t\tconst message = 'Model context metadata does not support the requested context'\n\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\tcause: 'capacity',\n\t\t\tmessage,\n\t\t\trole: undefined,\n\t\t\tstop: {\n\t\t\t\tlayer: 'model',\n\t\t\t\tid: 'context_length',\n\t\t\t\tmax:\n\t\t\t\t\tkeys.length === 1 && Number.isSafeInteger(ceiling)\n\t\t\t\t\t\t? parseStudyReading(ceiling)\n\t\t\t\t\t\t: undefined,\n\t\t\t\tconsumed: context,\n\t\t\t},\n\t\t})\n\t}\n\treturn ceiling\n}\n\n/**\n * Reads a native Ollama error member as the attributable failure it names, without usage.\n * @remarks\n * No token usage is read from the member.\n * The failure is `CAPACITY` when the member, a string or an object, names the exact structured\n * type `exceed_context_size_error` with a finite positive integer `n_prompt_tokens` above `n_ctx`,\n * a `code` of 400 if supplied, and a status of 400 if supplied. Every other member, a malformed\n * one included, is `FAULT` with its readable reason.\n * @param value - The parsed HTTP error body or wire row\n * @param role - The responsibility whose request was dispatched; the failure retains it\n * @param status - The HTTP status of the carrying response; undefined for a row of a stream that answered 200\n * @returns Undefined when the value carries no `error` member; otherwise the attributable failure\n */\nexport function readStudyOllamaFailure(\n\tvalue: unknown,\n\trole: StudyRole,\n\tstatus?: number,\n): StudyError | undefined {\n\tif (!isRecord(value) || !('error' in value)) return undefined\n\tconst field = value.error\n\t// The live daemon sends structured JSON inside a string; decode it once and unwrap one error object.\n\tconst decoded = typeof field === 'string' ? parseJSON(field) : field\n\tconst structured = isRecord(decoded)\n\t\t? isRecord(decoded.error)\n\t\t\t? decoded.error\n\t\t\t: decoded\n\t\t: undefined\n\tconst native = structured?.message\n\tconst text =\n\t\ttypeof native === 'string' && native.trim() !== ''\n\t\t\t? native\n\t\t\t: typeof field === 'string'\n\t\t\t\t? field\n\t\t\t\t: ''\n\tconst label = structured?.type\n\tconst type = typeof label === 'string' && label !== '' ? label : undefined\n\tconst origin = status === undefined ? 'Ollama error' : `Ollama HTTP ${status} error`\n\tconst prompt = structured?.n_prompt_tokens\n\tconst limit = structured?.n_ctx\n\tconst capacity =\n\t\ttype === 'exceed_context_size_error' &&\n\t\tisInteger(prompt) &&\n\t\tprompt > 0 &&\n\t\tisInteger(limit) &&\n\t\tlimit > 0 &&\n\t\tprompt > limit &&\n\t\t(structured?.code === undefined || structured?.code === 400) &&\n\t\t(status === undefined || status === 400)\n\tconst reason =\n\t\ttext.trim() === '' && type === undefined\n\t\t\t? `Malformed ${origin}`\n\t\t\t: `${origin}${type === undefined ? '' : ` (${type})`}${text.trim() === '' ? '' : `: ${text}`}`\n\treturn new StudyError(capacity ? 'CAPACITY' : 'FAULT', reason, {\n\t\tcause: capacity ? 'capacity' : 'infrastructure',\n\t\tmessage: reason,\n\t\trole,\n\t\tstop: capacity\n\t\t\t? {\n\t\t\t\t\tlayer: 'model',\n\t\t\t\t\tid: 'num_ctx',\n\t\t\t\t\tmax: parseStudyReading(limit),\n\t\t\t\t\tconsumed: parseStudyReading(prompt),\n\t\t\t\t}\n\t\t\t: undefined,\n\t})\n}\n\n/**\n * Reads one Ollama response row without inventing absent usage.\n * @param value - The parsed wire row\n * @param request - The admitted dispatch\n * @returns The terminal facts, or undefined for a nonterminal row\n * @throws StudyError - Thrown with the recognized provider failure when the row carries an `error` member, before any other row check; `FAULT` for a malformed row, model, message, finish reason, or usage\n */\nexport function readStudyOllamaTerminal(\n\tvalue: unknown,\n\trequest: StudyOllamaRequest,\n): StudyOllamaTerminal | undefined {\n\tconst failure = readStudyOllamaFailure(value, request.role)\n\tif (failure !== undefined) throw failure\n\tif (!isRecord(value) || typeof value.done !== 'boolean')\n\t\tthrow new StudyError('FAULT', 'Malformed Ollama response row')\n\tif (value.model !== request.model)\n\t\tthrow new StudyError('FAULT', 'Ollama response model differs from the dispatched model')\n\tif (request.role !== 'judge') {\n\t\tif (\n\t\t\t!isRecord(value.message) ||\n\t\t\ttypeof value.message.content !== 'string' ||\n\t\t\t(value.message.thinking !== undefined && typeof value.message.thinking !== 'string')\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Malformed Ollama message')\n\t\tif (value.message.tool_calls !== undefined) {\n\t\t\tif (!isArray(value.message.tool_calls))\n\t\t\t\tthrow new StudyError('FAULT', 'Malformed Ollama tool calls')\n\t\t\tfor (const call of value.message.tool_calls)\n\t\t\t\tif (\n\t\t\t\t\t!isRecord(call) ||\n\t\t\t\t\t!isRecord(call.function) ||\n\t\t\t\t\ttypeof call.function.name !== 'string' ||\n\t\t\t\t\t!isRecord(call.function.arguments)\n\t\t\t\t)\n\t\t\t\t\tthrow new StudyError('FAULT', 'Malformed Ollama tool call')\n\t\t}\n\t}\n\tif (!value.done) return undefined\n\tif (typeof value.done_reason !== 'string' || value.done_reason.length === 0)\n\t\tthrow new StudyError('FAULT', 'Missing Ollama finish reason')\n\tfor (const key of ['prompt_eval_count', 'eval_count'])\n\t\tif (\n\t\t\tvalue[key] !== undefined &&\n\t\t\t(typeof value[key] !== 'number' || !Number.isSafeInteger(value[key]) || value[key] < 0)\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Malformed Ollama usage', {\n\t\t\t\tcause: 'infrastructure',\n\t\t\t\tmessage: 'Malformed Ollama usage',\n\t\t\t\trole: request.role,\n\t\t\t\tstop: undefined,\n\t\t\t})\n\tconst prompt = typeof value.prompt_eval_count === 'number' ? value.prompt_eval_count : undefined\n\tconst completion = typeof value.eval_count === 'number' ? value.eval_count : undefined\n\treturn { prompt, completion, reason: value.done_reason }\n}\n\n/**\n * Checks terminal policy after the actual wire cost has been retained.\n * @param terminal - The valid terminal facts\n * @param room - The reserved context and safety margin\n * @param request - The admitted dispatch and its declared finish policy; every refusal retains its role\n * @returns Nothing when the completion satisfies the declared policy\n * @throws StudyError - Thrown with code `CAPACITY` when the actual prompt exceeds its room, generation exceeds its allowance, or an undeclared `length` finish or capped generation occurs; `FAULT` for another unsupported finish reason\n */\nexport function validateStudyOllamaCompletion(\n\tterminal: StudyOllamaTerminal,\n\troom: Pick<StudyRoom, 'context' | 'safety'>,\n\trequest: StudyOllamaRequest,\n): void {\n\tconst { prompt, completion, reason } = terminal\n\tconst { role } = request\n\tconst capped: StudyStop = {\n\t\tlayer: 'model',\n\t\tid: 'num_predict',\n\t\tmax: request.output,\n\t\tconsumed: completion,\n\t}\n\tconst ceiling = room.context - request.output - room.safety\n\tif (prompt !== undefined && prompt > ceiling) {\n\t\tconst message = 'Actual prompt exceeded reserved context capacity'\n\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\tcause: 'capacity',\n\t\t\tmessage,\n\t\t\trole,\n\t\t\tstop: { layer: 'window', id: 'Context room', max: ceiling, consumed: prompt },\n\t\t})\n\t}\n\tif (completion !== undefined && completion > request.output) {\n\t\tconst message = 'Actual generation exceeded the output allowance'\n\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\tcause: 'capacity',\n\t\t\tmessage,\n\t\t\trole,\n\t\t\tstop: capped,\n\t\t})\n\t}\n\tif (\n\t\t!request.length &&\n\t\t(reason === 'length' || (completion !== undefined && completion >= request.output))\n\t) {\n\t\tconst message = 'Substantive generation reached its output cap'\n\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\tcause: 'capacity',\n\t\t\tmessage,\n\t\t\trole,\n\t\t\tstop: capped,\n\t\t})\n\t}\n\tif (reason !== 'stop' && !(request.length && reason === 'length')) {\n\t\tconst message = 'Unsupported Ollama finish reason'\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 * Verifies that each pinned name resolves to one inventory entry with its pinned digest.\n * @param value - The parsed inventory response\n * @param models - The pinned served identities\n * @returns Nothing for a matching inventory\n * @throws StudyError - Thrown with code `FAULT` when the inventory is unsupported or a pinned identity does not match\n */\nexport function validateStudyOllamaInventory(\n\tvalue: unknown,\n\tmodels: StudyOllamaTransportOptions['models'],\n): void {\n\tif (!isObject(value) || !('models' in value) || !isArray(value.models))\n\t\tthrow new StudyError('FAULT', 'Unsupported Ollama inventory')\n\tconst served = value.models\n\tfor (const { name, digest } of Object.values(models)) {\n\t\tconst matches = served.filter((model) => isRecord(model) && model.name === name)\n\t\tconst model = matches[0]\n\t\tif (\n\t\t\tmatches.length !== 1 ||\n\t\t\t!isRecord(model) ||\n\t\t\ttypeof model.digest !== 'string' ||\n\t\t\tmodel.digest.replace(/^sha256:/, '') !== digest.replace(/^sha256:/, '')\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Serving inventory does not match the required model digest')\n\t}\n}\n\n/**\n * Reads the pinned serving digest of an admitted request's model.\n * @param models - The pinned served identities\n * @param request - The admitted dispatch\n * @returns The pinned digest, or undefined for an inventory request or an unpinned model\n */\nexport function readStudyOllamaDigest(\n\tmodels: StudyOllamaTransportOptions['models'],\n\trequest: StudyOllamaRequest,\n): string | undefined {\n\tif (request.model === undefined) return undefined\n\treturn Object.values(models).find((model) => model.name === request.model)?.digest\n}\n\n/**\n * Reads daemon timing from a terminal row without letting an observation fail the request.\n * @param extract - The admitted extractor\n * @param record - The validated terminal row\n * @returns The raw timing, or undefined when absent or the extractor throws\n */\nexport function readStudyOllamaTiming(\n\textract: StudyOllamaTransportOptions['timing'],\n\trecord: Readonly<Record<string, unknown>>,\n): OllamaTiming | undefined {\n\ttry {\n\t\treturn extract(record)\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Builds the JSON evidence form of a timing observation with raw nanoseconds and counts.\n * @param timing - The extracted timing\n * @returns Null when no terminal timing was observed; otherwise every unreported member as null\n */\nexport function buildStudyOllamaTiming(timing: OllamaTiming | undefined): JSONValue {\n\tif (timing === undefined) return null\n\treturn {\n\t\tdurations: {\n\t\t\ttotal: timing.durations.total ?? null,\n\t\t\tload: timing.durations.load ?? null,\n\t\t\tprompt: timing.durations.prompt ?? null,\n\t\t\tdecode: timing.durations.decode ?? null,\n\t\t},\n\t\tcounts: {\n\t\t\tprompt: timing.counts.prompt ?? null,\n\t\t\tdecode: timing.counts.decode ?? null,\n\t\t\tcached: timing.counts.cached ?? null,\n\t\t},\n\t\tinvalid: [...timing.invalid],\n\t}\n}\n\n/**\n * Builds a reading of the raw prompt text an encoded request body carries, as sent.\n * @param body - The encoded request body\n * @returns The prompt's UTF-16 code units and UTF-8 bytes, labeled with its encoding, or undefined when there is no string prompt; these are readings of the actual text, not token allocations\n */\nexport function buildStudyOllamaRaw(body: unknown): JSONValue | undefined {\n\tif (typeof body !== 'string') return undefined\n\tconst parsed = attempt((): unknown => JSON.parse(body))\n\tif (!parsed.success || !isRecord(parsed.value) || typeof parsed.value.prompt !== 'string')\n\t\treturn undefined\n\treturn {\n\t\tencoding: 'utf-8',\n\t\tunits: parsed.value.prompt.length,\n\t\tbytes: new TextEncoder().encode(parsed.value.prompt).byteLength,\n\t}\n}\n","import type { StudyFailure, StudyProfile, StudyTrial } from '@src/core'\nimport type {\n\tStudyExchangeDeclaration,\n\tStudyExchangeDestination,\n\tStudyExchangeHistory,\n} from '../stores/types.js'\nimport type { StudyOllamaReplaySelection } from '../ollama/types.js'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type { ChildProcess } from 'node:child_process'\nimport { StudyError } from '@src/core'\nimport { canonicalStringify, isJSONValue, isRecord } from '@orkestrel/contract'\nimport { execFileSync } from 'node:child_process'\nimport { existsSync, readFileSync, realpathSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, join } from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { hashStudyBytes, matchesSystemError } from '../helpers.js'\nimport { STUDY_DRAIN_DURATION } from './constants.js'\nimport { buildStudyOllamaModels } from '../ollama/helpers.js'\nimport { readStudyExchanges, readStudyResult } from '../stores/helpers.js'\nimport { isStudyExchangeDeclaration } from '../stores/validators.js'\nimport { isStudyExchangeDestination, isStudyReplaySelection } from './validators.js'\n\n/** Reads the executing profile's explicit recording declarations before a worker starts.\n * @param profile - The validated executing profile.\n * @param trial - The scheduled trial identity.\n * @returns A validated opening row, with no inferred metadata or replay allowance.\n */\nexport function readStudyRecordingDeclaration(\n\tprofile: StudyProfile,\n\ttrial: StudyTrial,\n): StudyExchangeDeclaration {\n\tif (profile.provider === undefined || profile.settings === undefined)\n\t\tthrow new StudyError('CONFIG', 'Recording requires provider and explicit wire declarations')\n\tconst declaration = {\n\t\tphase: 'declaration',\n\t\ttrial: trial.id,\n\t\tversion: profile.settings.version,\n\t\tmetadata: profile.settings.metadata,\n\t\tprocedure: profile.settings.procedure,\n\t\tmodels: buildStudyOllamaModels(profile.provider),\n\t\tmaintenance: [],\n\t}\n\tif (!isStudyExchangeDeclaration(declaration))\n\t\tthrow new StudyError(\n\t\t\t'CONFIG',\n\t\t\t'Recording requires valid version, metadata and ordered procedure settings',\n\t\t)\n\treturn declaration\n}\n\n/** Validates parent preparation output without permitting a destination or allowance substitution.\n * @param original - The parent-reserved destination, or undefined without recording.\n * @param prepared - The callback's retained destination.\n * @returns The validated destination for the worker.\n */\nexport function readStudyPreparedDestination(\n\toriginal: StudyExchangeDestination | undefined,\n\tprepared: StudyExchangeDestination | undefined,\n): StudyExchangeDestination | undefined {\n\tif (\n\t\toriginal === undefined\n\t\t\t? prepared !== undefined\n\t\t\t: !isStudyExchangeDestination(prepared) ||\n\t\t\t\tprepared.path !== original.path ||\n\t\t\t\tcanonicalStringify(prepared.record) !== canonicalStringify(original.record)\n\t)\n\t\tthrow new StudyError('CUSTODY', 'Trial preparation changed its reserved destination')\n\treturn prepared\n}\n\n/** Rechecks the sealed source and this trial's prefix under the executing profile declaration.\n * @param selection - The explicit sealed source and offline behavior.\n * @param profile - The executing profile, whose bounds remain authoritative.\n * @param trial - The trial whose history must be present.\n * @returns Complete verified history before any dependent sender or worker starts.\n */\nexport async function readStudyReplayHistory(\n\tselection: StudyOllamaReplaySelection,\n\tprofile: StudyProfile,\n\ttrial: StudyTrial,\n): Promise<StudyExchangeHistory> {\n\tif (!isStudyReplaySelection(selection)) throw new StudyError('CONFIG', 'Invalid replay selection')\n\tconst result = await readStudyResult(selection.result)\n\tif (result.status !== 'sealed') throw new StudyError('CUSTODY', 'Replay requires a sealed result')\n\tconst history = await readStudyExchanges(result, trial.id)\n\tconst prefix = selection.prefix[trial.id]\n\tif (\n\t\tprefix === undefined ||\n\t\tprefix > history.exchanges.length ||\n\t\t(selection.offline && prefix !== history.exchanges.length)\n\t)\n\t\tthrow new StudyError('CONFIG', 'Replay prefix does not cover its declared trial')\n\tconst declaration = readStudyRecordingDeclaration(profile, trial)\n\tconst { metadata: _metadata, maintenance: _maintenance, ...current } = declaration\n\tconst {\n\t\tmetadata: _recordedMetadata,\n\t\tmaintenance: _recordedMaintenance,\n\t\t...recorded\n\t} = history.declaration\n\tif (canonicalStringify(current) !== canonicalStringify(recorded))\n\t\tthrow new StudyError('CONFIG', 'Replay declaration differs from recorded execution')\n\treturn history\n}\n\n/** Projects optional domain fields into the JSON wire representation.\n * @param value - An owned domain value with optional undefined fields.\n * @returns A JSON-compatible snapshot.\n * @example Project a wire value\n * ```ts\n * import { valueToWire } from '@orkestrel/study/server'\n *\n * valueToWire({ state: 'ready', failure: undefined }) // { state: 'ready' }\n * ```\n */\nexport function valueToWire(value: unknown): JSONValue {\n\tconst parsed: unknown = JSON.parse(JSON.stringify(value))\n\tif (!isJSONValue(parsed)) throw new StudyError('FAULT', 'Invalid study wire value')\n\treturn parsed\n}\n\n/** Creates attributable protocol infrastructure failure.\n * @param message - The refused operation or broken boundary.\n * @returns A domain failure that never awards task credit.\n */\nexport function createStudyProcessFailure(message: string): StudyFailure {\n\treturn { cause: 'infrastructure', message, role: undefined, stop: undefined }\n}\n\n/** Binds the canonical fully resolved execution profile carried over IPC.\n * @param profile - The resolved execution settings, with optional absent leaves.\n * @returns The SHA256 digest of the canonical JSON wire representation.\n */\nexport function computeStudyProfileDigest(profile: StudyProfile): string {\n\tconst encoded = canonicalStringify(valueToWire(profile))\n\tif (encoded === undefined) throw new StudyError('CONFIG', 'Study profile is not JSON-compatible')\n\treturn hashStudyBytes(encoded)\n}\n\n/** Collects the executable entries a profile selects, each canonical path once.\n * @param profile - The resolved execution profile.\n * @returns The agent, subject, and provider entries without repeating a shared entry.\n * @remarks The declared roles stay separate in the profile; only capture and loading deduplicate.\n */\nexport function collectStudyEntries(profile: StudyProfile): readonly string[] {\n\treturn [\n\t\t...new Set([\n\t\t\tprofile.agent,\n\t\t\tprofile.subject,\n\t\t\t...(profile.provider === undefined ? [] : [profile.provider.entry]),\n\t\t]),\n\t]\n}\n\n/** Computes the instrument identity binding trusted runtime bytes to the adapter inventory.\n * @param entry - The SHA-256 identity of the trusted runtime entry bytes.\n * @param inventory - The captured adapter inventory digest.\n * @returns The identity that validation, grading, and trial children must share.\n */\nexport function computeStudyInstrumentDigest(entry: string, inventory: string): string {\n\treturn hashStudyBytes(JSON.stringify([entry, inventory]))\n}\n\n/** Resolves the actual host package from its trusted executable entry.\n * @param entry - The runtime's own executable, never a consumer-supplied module.\n * @returns The canonical study package root.\n */\nexport function resolveStudyInstrument(entry: string): string {\n\tconst root = collectStudyAncestors(dirname(realpathSync(entry))).find((directory) => {\n\t\tconst manifest = join(directory, 'package.json')\n\t\tif (!existsSync(manifest)) return false\n\t\tconst value: unknown = JSON.parse(readFileSync(manifest, 'utf8'))\n\t\treturn isRecord(value) && value.name === '@orkestrel/study'\n\t})\n\tif (root === undefined) throw new StudyError('CONFIG', 'Cannot locate the study runtime package')\n\treturn root\n}\n\n/** Reads the version of the study package that owns an executable entry.\n * @param entry - The installed runtime's executable entry.\n * @returns The non-empty version declared by the owning study package.\n * @throws StudyError - Thrown when no study package owns the entry or its version is absent or empty.\n * @example Read the installed version\n * ```ts\n * import { readStudyVersion } from '@orkestrel/study/server'\n *\n * declare const entry: string\n * readStudyVersion(entry)\n * ```\n */\nexport function readStudyVersion(entry: string): string {\n\tconst value: unknown = JSON.parse(\n\t\treadFileSync(join(resolveStudyInstrument(entry), 'package.json'), 'utf8'),\n\t)\n\tif (!isRecord(value) || typeof value.version !== 'string' || value.version.length === 0)\n\t\tthrow new StudyError('CONFIG', 'Study runtime package declares no version')\n\treturn value.version\n}\n\n/** Collects a directory and each of its ancestors up to the filesystem root, nearest first.\n * @param directory - The absolute directory to start from.\n * @returns The directory followed by every parent directory, ending at the root.\n */\nexport function collectStudyAncestors(directory: string): readonly string[] {\n\tconst parent = dirname(directory)\n\treturn parent === directory ? [directory] : [directory, ...collectStudyAncestors(parent)]\n}\n\n/** Refuses a profile that omits the actual host runtime's declared dependency bytes.\n * @param instrument - The canonical package owning the trusted runtime entry.\n * @param roots - Explicitly admitted package roots, including the instrument.\n */\nexport function validateStudyRuntime(instrument: string, roots: readonly string[]): void {\n\tconst pending = [instrument]\n\tconst visited = new Set<string>()\n\twhile (pending.length > 0) {\n\t\tconst root = pending.pop()\n\t\tif (root === undefined || visited.has(root)) continue\n\t\tvisited.add(root)\n\t\tif (!roots.includes(root))\n\t\t\tthrow new StudyError('CONFIG', `Profile roots omit a runtime dependency: ${root}`)\n\t\tconst manifest = join(root, 'package.json')\n\t\tconst value: unknown = JSON.parse(readFileSync(manifest, 'utf8'))\n\t\tif (!isRecord(value) || value.dependencies === undefined) continue\n\t\tif (!isRecord(value.dependencies))\n\t\t\tthrow new StudyError('CONFIG', 'Runtime dependency declarations are invalid')\n\t\tconst resolver = createRequire(manifest)\n\t\tfor (const dependency of Object.keys(value.dependencies))\n\t\t\tpending.push(dirname(realpathSync(resolver.resolve(`${dependency}/package.json`))))\n\t}\n}\n\n/** Releases inherited output handles a bounded time after native exit.\n * @param child - A newly spawned child, subscribed before native exit.\n * @remarks A descendant that outlives an exited root is outside discoverable-tree cleanup; this only stops the parent from waiting on its pipes.\n */\nexport function drainStudyChild(child: ChildProcess): void {\n\tconst closed = new AbortController()\n\tchild.once('exit', () => {\n\t\t// A close before the allowance ends aborts the wait, which is the only rejection it can have.\n\t\tvoid delay(STUDY_DRAIN_DURATION, undefined, { signal: closed.signal }).then(\n\t\t\t() => {\n\t\t\t\tchild.stdout?.destroy()\n\t\t\t\tchild.stderr?.destroy()\n\t\t\t},\n\t\t\t() => undefined,\n\t\t)\n\t})\n\tchild.once('close', () => closed.abort())\n}\n\n/** Terminates the recorded native process tree under a finite cleanup allowance.\n * @param child - The exclusively owned child process.\n */\nexport function terminateStudyChild(child: ChildProcess): void {\n\tif (child.pid === undefined || child.exitCode !== null || child.signalCode !== null) return\n\ttry {\n\t\tif (process.platform === 'win32')\n\t\t\texecFileSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], {\n\t\t\t\twindowsHide: true,\n\t\t\t\ttimeout: 2000,\n\t\t\t\tstdio: 'ignore',\n\t\t\t})\n\t\telse {\n\t\t\tconst rows = execFileSync('ps', ['-eo', 'pid=,ppid='], {\n\t\t\t\ttimeout: 2000,\n\t\t\t\tencoding: 'utf8',\n\t\t\t\tmaxBuffer: 1024 * 1024,\n\t\t\t})\n\t\t\t\t.trim()\n\t\t\t\t.split(/\\r\\n|\\n/)\n\t\t\t\t.map((row) => row.trim().split(/\\s+/).map(Number))\n\t\t\tconst descendants = new Set([child.pid])\n\t\t\t// One pass per row bounds the depth of any parent chain the table can hold.\n\t\t\trows.forEach(() => {\n\t\t\t\tfor (const [pid, parent] of rows)\n\t\t\t\t\tif (pid !== undefined && parent !== undefined && descendants.has(parent))\n\t\t\t\t\t\tdescendants.add(pid)\n\t\t\t})\n\t\t\tfor (const pid of [...descendants].reverse()) {\n\t\t\t\ttry {\n\t\t\t\t\tprocess.kill(pid, 'SIGKILL')\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!matchesSystemError(error, 'ESRCH')) throw error\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\ttry {\n\t\t\tprocess.kill(child.pid, 0)\n\t\t} catch (status) {\n\t\t\tif (matchesSystemError(status, 'ESRCH')) return\n\t\t\tthrow status\n\t\t}\n\t\tif (child.exitCode === null && child.signalCode === null) {\n\t\t\tchild.kill('SIGKILL')\n\t\t\tthrow error\n\t\t}\n\t}\n}\n","import type {\n\tStudyArtifactIdentity,\n\tStudyArtifactModule,\n\tStudyArtifactLoaderOptions,\n} from './types.js'\nimport type { StudyAdapterInterface } from '../adapters/types.js'\nimport { StudyError } from '@src/core'\nimport { dirname, isAbsolute } from 'node:path'\nimport { readFileSync } from 'node:fs'\nimport { ArtifactLoader } from '../artifacts/ArtifactLoader.js'\nimport { verifyArtifactClosure } from '../artifacts/helpers.js'\nimport { readStudyAdapter } from '../adapters/helpers.js'\nimport { hashStudyBytes } from '../helpers.js'\nimport { readStudyBytes } from '../stores/helpers.js'\nimport { STUDY_CUSTODY_BYTES } from '../stores/constants.js'\nimport {\n\tcollectStudyEntries,\n\tcomputeStudyInstrumentDigest,\n\tresolveStudyInstrument,\n\tvalidateStudyRuntime,\n} from './helpers.js'\n\n/** Binds consumer instrumentation separately from selected executable identities. */\nexport class StudyArtifactLoader {\n\t#options: StudyArtifactLoaderOptions\n\t#loader: ArtifactLoader | undefined\n\t#instrument: ArtifactLoader | undefined\n\t#identity: StudyArtifactIdentity | undefined\n\t#entry: string | undefined\n\t/** Owns resolved built and consumer source selections.\n\t * @param options - The trusted host, adapter, and profile.\n\t */\n\tconstructor(options: StudyArtifactLoaderOptions) {\n\t\tthis.#options = structuredClone(options)\n\t\tif (\n\t\t\t![\n\t\t\t\toptions.entry,\n\t\t\t\toptions.root,\n\t\t\t\toptions.adapter,\n\t\t\t\t...collectStudyEntries(options.profile),\n\t\t\t\t...options.profile.roots,\n\t\t\t].every(isAbsolute)\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Study artifact paths must be absolute')\n\t}\n\t/** Inventories bytes without importing selected code.\n\t * @returns Bound executable and instrumentation identities.\n\t */\n\tasync inspect(): Promise<StudyArtifactIdentity> {\n\t\tconst closure = this.#options.closure\n\t\tif (closure !== undefined) verifyArtifactClosure(closure.closure, true)\n\t\tif (this.#identity !== undefined) {\n\t\t\tthis.verify()\n\t\t\treturn this.#identity\n\t\t}\n\t\tconst profile = this.#options.profile\n\t\tconst instrument = resolveStudyInstrument(this.#options.entry)\n\t\tconst roots = [...new Set([...profile.roots, instrument])]\n\t\tvalidateStudyRuntime(instrument, roots)\n\t\tconst source = { root: dirname(this.#options.adapter), entry: this.#options.adapter }\n\t\tthis.#instrument = new ArtifactLoader({ entries: [], roots, source, instrument })\n\t\tconst entry = hashStudyBytes(await readStudyBytes(this.#options.entry, STUDY_CUSTODY_BYTES))\n\t\tthis.#entry = entry\n\t\tthis.#loader = new ArtifactLoader(\n\t\t\tclosure === undefined\n\t\t\t\t? {\n\t\t\t\t\t\tentries: collectStudyEntries(profile),\n\t\t\t\t\t\troots,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tinstrument,\n\t\t\t\t\t}\n\t\t\t\t: closure.closure.options,\n\t\t)\n\t\tconst inventory = this.#loader.inspect()\n\t\tthis.#identity = Object.freeze({\n\t\t\tagent: inventory.digest,\n\t\t\tsubject: inventory.digest,\n\t\t\tprovider: profile.provider === undefined ? undefined : inventory.digest,\n\t\t\tinstrument: computeStudyInstrumentDigest(entry, this.#instrument.inspect().digest),\n\t\t})\n\t\tthis.verify()\n\t\treturn this.#identity\n\t}\n\t/** Loads the adapter from the trial inventory.\n\t * @returns The complete consumer adapter.\n\t */\n\tasync adapter(): Promise<StudyAdapterInterface> {\n\t\tawait this.inspect()\n\t\tif (this.#loader === undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Artifact inspection is required')\n\t\treturn readStudyAdapter(await this.#loader.load(this.#options.adapter))\n\t}\n\t/** Loads admitted built namespaces inside the trial child.\n\t * @returns The agent, subject and optional provider; a shared entry loads once and keeps each role.\n\t */\n\tasync load(): Promise<StudyArtifactModule> {\n\t\tawait this.inspect()\n\t\tif (this.#loader === undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Artifact inspection is required')\n\t\tconst profile = this.#options.profile\n\t\tconst loaded: Array<readonly [string, unknown]> = []\n\t\tfor (const entry of collectStudyEntries(profile))\n\t\t\tloaded.push([entry, await this.#loader.load(entry)])\n\t\tconst namespaces = new Map(loaded)\n\t\tthis.verify()\n\t\tconst provider = profile.provider\n\t\treturn Object.freeze({\n\t\t\tagent: namespaces.get(profile.agent),\n\t\t\tsubject: namespaces.get(profile.subject),\n\t\t\tprovider: provider === undefined ? undefined : namespaces.get(provider.entry),\n\t\t})\n\t}\n\t/** Refuses instrument and inventory drift after inspection. */\n\tverify(): void {\n\t\tif (this.#loader === undefined || this.#instrument === undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Artifact inspection is required')\n\t\tif (hashStudyBytes(readFileSync(this.#options.entry)) !== this.#entry)\n\t\t\tthrow new StudyError('FAULT', 'Study instrument bytes drifted')\n\t\tthis.#loader.verify()\n\t\tthis.#instrument.verify()\n\t\tif (this.#options.closure !== undefined)\n\t\t\tverifyArtifactClosure(this.#options.closure.closure, true)\n\t}\n}\n","import type { StudyChannelOptions, StudyFrame, StudyOperation, StudyResponse } from './types.js'\nimport type { JSONValue } from '@orkestrel/contract'\nimport { StudyControl, failureToStudyError, readStudyFailure } from '@src/core'\nimport { STUDY_FRAME_BYTES, STUDY_PENDING_LIMIT } from './constants.js'\nimport { createStudyProcessFailure, valueToWire } from './helpers.js'\nimport { isStudyFrame, isStudyProcessFailure } from './validators.js'\n\n/** Correlates bounded IPC work and rejects every outstanding request on transport failure. */\nexport class StudyChannel {\n\t#options: StudyChannelOptions\n\t#control = new StudyControl()\n\treadonly #pending = new Map<number, StudyResponse>()\n\t#next = 0\n\t#received = 0\n\treadonly #working = new Set<symbol>()\n\t#message: (value: unknown) => void\n\t#disconnect: () => void\n\t#error: (error: Error) => void\n\n\t/** Subscribes to one native IPC endpoint.\n\t * @param options - Native endpoint and owning domain handlers; the bag is snapshotted while selected collaborators keep their identity.\n\t */\n\tconstructor(options: StudyChannelOptions) {\n\t\tthis.#options = { ...options }\n\t\tthis.#message = this.#onMessage.bind(this)\n\t\tthis.#disconnect = this.#onDisconnect.bind(this)\n\t\tthis.#error = this.close.bind(this)\n\t\tthis.#options.endpoint.on('message', this.#message)\n\t\tthis.#options.endpoint.on('disconnect', this.#disconnect)\n\t\tthis.#options.endpoint.on('error', this.#error)\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.#control.signal\n\t}\n\n\t#onMessage(value: unknown): void {\n\t\tvoid this.#receive(value).catch((error: unknown) => this.close(error))\n\t}\n\n\t#onDisconnect(): void {\n\t\tthis.close(failureToStudyError(createStudyProcessFailure('Study process disconnected')))\n\t}\n\n\t/** Sends one correlated domain request.\n\t * @param operation - The domain operation expected by the peer.\n\t * @param value - Public JSON payload.\n\t * @returns The peer's acknowledged result.\n\t */\n\trequest(operation: StudyOperation, value: JSONValue): Promise<JSONValue> {\n\t\tif (this.#control.failure !== undefined)\n\t\t\treturn Promise.reject(failureToStudyError(this.#control.failure))\n\t\tif (this.#pending.size >= STUDY_PENDING_LIMIT)\n\t\t\treturn Promise.reject(\n\t\t\t\tfailureToStudyError(createStudyProcessFailure('Study IPC pending limit exceeded')),\n\t\t\t)\n\t\tconst id = ++this.#next\n\t\treturn new Promise<JSONValue>((resolve, reject) => {\n\t\t\tthis.#pending.set(id, { resolve, reject })\n\t\t\tthis.#send({ id, operation, value }).catch((error: unknown) => this.close(error))\n\t\t})\n\t}\n\n\t/** Forwards cancellation without closing the cleanup transport.\n\t * @param value - Validated goal, trial or ticket cancellation attribution.\n\t */\n\tabort(value: JSONValue): void {\n\t\tvoid this.#send({ id: 0, operation: 'abort', value }).catch((error: unknown) =>\n\t\t\tthis.close(error),\n\t\t)\n\t}\n\n\t/** Removes endpoint handlers and rejects all unresolved calls.\n\t * @param error - The first transport or owning lifecycle failure.\n\t */\n\tclose(\n\t\terror: unknown = failureToStudyError(createStudyProcessFailure('Study channel closed')),\n\t): void {\n\t\tthis.#control.fail(readStudyFailure(error))\n\t\tthis.#options.endpoint.removeListener('message', this.#message)\n\t\tthis.#options.endpoint.removeListener('disconnect', this.#disconnect)\n\t\tthis.#options.endpoint.removeListener('error', this.#error)\n\t\tfor (const pending of this.#pending.values())\n\t\t\tpending.reject(failureToStudyError(this.#control.failure ?? readStudyFailure(error)))\n\t\tthis.#pending.clear()\n\t\tthis.#control.close()\n\t}\n\n\tasync #send(frame: StudyFrame): Promise<void> {\n\t\tif (Buffer.byteLength(JSON.stringify(frame)) > STUDY_FRAME_BYTES)\n\t\t\tthrow failureToStudyError(createStudyProcessFailure('Study IPC frame limit exceeded'))\n\t\tif (!this.#options.endpoint.connected || this.#options.endpoint.send === undefined)\n\t\t\tthrow failureToStudyError(createStudyProcessFailure('Study IPC is unavailable'))\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tthis.#options.endpoint.send?.(frame, undefined, {}, (error: Error | null) =>\n\t\t\t\terror === null ? resolve() : reject(error),\n\t\t\t)\n\t\t})\n\t}\n\n\tasync #receive(value: unknown): Promise<void> {\n\t\tif (!isStudyFrame(value) || Buffer.byteLength(JSON.stringify(value)) > STUDY_FRAME_BYTES)\n\t\t\tthrow failureToStudyError(createStudyProcessFailure('Malformed study IPC frame'))\n\t\tif (value.operation === 'abort') {\n\t\t\tif (value.id !== 0)\n\t\t\t\tthrow failureToStudyError(createStudyProcessFailure('Foreign study cancellation'))\n\t\t\tthis.#options.abort(value.value)\n\t\t\treturn\n\t\t}\n\t\tif (value.operation === 'reply' || value.operation === 'error') {\n\t\t\tconst pending = this.#pending.get(value.id)\n\t\t\tif (pending === undefined)\n\t\t\t\tthrow failureToStudyError(createStudyProcessFailure('Unknown study IPC reply'))\n\t\t\tif (value.operation === 'reply') pending.resolve(value.value)\n\t\t\telse {\n\t\t\t\tif (!isStudyProcessFailure(value.value))\n\t\t\t\t\tthrow failureToStudyError(createStudyProcessFailure('Invalid study IPC failure'))\n\t\t\t\tpending.reject(failureToStudyError(value.value))\n\t\t\t}\n\t\t\tthis.#pending.delete(value.id)\n\t\t\treturn\n\t\t}\n\t\tif (value.id !== this.#received + 1 || this.#working.size >= STUDY_PENDING_LIMIT)\n\t\t\tthrow failureToStudyError(\n\t\t\t\tcreateStudyProcessFailure('Out-of-order or excessive study IPC request'),\n\t\t\t)\n\t\tconst id = value.id\n\t\tthis.#received = id\n\t\t// The request joins the registry before its handler can run, so a request the handler admits\n\t\t// on its synchronous path meets the limit.\n\t\tconst working = Symbol('request')\n\t\tthis.#working.add(working)\n\t\ttry {\n\t\t\tconst result = await this.#options.handle(value.operation, value.value)\n\t\t\t// The admitted id answers both outcomes: another listener on the shared endpoint may edit\n\t\t\t// the borrowed frame while the handler is pending.\n\t\t\tawait this.#send({ id, operation: 'reply', value: result })\n\t\t} catch (error) {\n\t\t\tawait this.#send({\n\t\t\t\tid,\n\t\t\t\toperation: 'error',\n\t\t\t\tvalue: valueToWire(readStudyFailure(error)),\n\t\t\t})\n\t\t} finally {\n\t\t\tthis.#working.delete(working)\n\t\t}\n\t}\n}\n","import type { StudyContext } from '@src/core'\n\n/** Holds one goal's parent context and the worker admission sequence it issues while the goal runs.\n * @example Issue worker admissions in sequence\n * ```ts\n * import type { StudyContext } from '@orkestrel/study'\n * import { StudyProcessGoal } from '@orkestrel/study/server'\n *\n * declare const context: StudyContext\n *\n * const goal = new StudyProcessGoal(context)\n * goal.issue(2) // undefined\n * goal.issue(1) // 1\n * goal.issue(1) // undefined\n * goal.issue(2) // 2\n * ```\n */\nexport class StudyProcessGoal {\n\treadonly #context: StudyContext\n\t#issued = 0\n\n\t/** Binds one goal to the parent meter and evidence sink it runs under.\n\t * @param context - The actual parent meter, evidence sink and cancellation of the goal.\n\t */\n\tconstructor(context: StudyContext) {\n\t\tthis.#context = context\n\t}\n\n\t/** Reports the parent meter and evidence sink the goal runs under. */\n\tget context(): StudyContext {\n\t\treturn this.#context\n\t}\n\n\t/** Issues the identifier of the next worker admission when the worker asked for exactly that one.\n\t * @param requested - The identifier the worker supplied.\n\t * @returns The issued identifier, or undefined when the requested one is not the next in sequence.\n\t */\n\tissue(requested: unknown): number | undefined {\n\t\tif (requested !== this.#issued + 1) return undefined\n\t\tthis.#issued++\n\t\treturn this.#issued\n\t}\n}\n","import type { StudyContext, StudyGoal, StudyProduct, StudySessionInterface } from '@src/core'\nimport type { StudyOperation, StudyParentTicket, StudyProcessSessionOptions } from './types.js'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type { ChildProcess } from 'node:child_process'\nimport {\n\tStudyControl,\n\tStudyDeadline,\n\tfailureToStudyError,\n\treadStudyFailure,\n\tStudyError,\n\tisStudyProduct,\n\tisStudyUsage,\n} from '@src/core'\nimport { isRecord } from '@orkestrel/contract'\nimport { execFile, fork } from 'node:child_process'\nimport { mkdtemp } from 'node:fs/promises'\nimport { isAbsolute, join } from 'node:path'\nimport { STUDY_LOG_BYTES, STUDY_PROCESS_LABEL, STUDY_WORKER_OPERATION } from './constants.js'\nimport { createStudyProcessFailure, drainStudyChild, valueToWire } from './helpers.js'\nimport { StudyChannel } from './StudyChannel.js'\nimport { StudyProcessGoal } from './StudyProcessGoal.js'\nimport {\n\tisStudyCharge,\n\tisStudyEvidence,\n\tisStudyExchangeDestination,\n\tisStudyProcessFailure,\n} from './validators.js'\n\n/** Keeps admission and evidence custody in the parent of one fresh trial process. */\nexport class StudyProcessSession implements StudySessionInterface {\n\t#options: StudyProcessSessionOptions\n\t#control: StudyControl\n\t#listeners = new AbortController()\n\t#child: ChildProcess | undefined\n\t#channel: StudyChannel | undefined\n\t#exit: Promise<void> | undefined\n\t#closing: Promise<void> | undefined\n\treadonly #goals = new Set<StudyProcessGoal>()\n\treadonly #tickets = new Map<number, StudyParentTicket>()\n\treadonly #appends = new Set<Promise<void>>()\n\t#logs = 0\n\t#started = false\n\t#deadline: ReturnType<typeof setTimeout> | undefined\n\n\t/** Owns one trial's process lifecycle without starting host work.\n\t * @param options - Public trial and process configuration; the configuration is snapshotted while the borrowed signal keeps its identity.\n\t */\n\tconstructor(options: StudyProcessSessionOptions) {\n\t\tconst { signal, ...configuration } = options\n\t\tthis.#options = { ...structuredClone(configuration), signal }\n\t\tthis.#control = new StudyControl(signal)\n\t}\n\n\t/** Starts the child and verifies its artifact-bound readiness. */\n\tasync start(): Promise<void> {\n\t\tif (this.#started || this.#closing !== undefined)\n\t\t\tthrow new StudyError('FAULT', 'Study process start is single use')\n\t\tthis.#started = true\n\t\tif (this.#control.failure !== undefined) throw failureToStudyError(this.#control.failure)\n\t\tif (![this.#options.entry, this.#options.root, this.#options.directory].every(isAbsolute))\n\t\t\tthrow new StudyError('CONFIG', 'Study process paths must be absolute')\n\t\tconst destination = this.#options.exchanges?.[this.#options.trial.id]\n\t\tif (\n\t\t\tthis.#options.profile.record === undefined\n\t\t\t\t? destination !== undefined\n\t\t\t\t: !isStudyExchangeDestination(destination) ||\n\t\t\t\t\tdestination.record.bytes !== this.#options.profile.record.bytes\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Session recording differs from its reserved allowance')\n\t\tconst directory = await mkdtemp(join(this.#options.directory, 'trial-'))\n\t\tif (this.#control.failure !== undefined) throw failureToStudyError(this.#control.failure)\n\t\tconst child = fork(this.#options.entry, [STUDY_WORKER_OPERATION], {\n\t\t\tcwd: this.#options.root,\n\t\t\texecArgv: [...process.execArgv],\n\t\t\tsilent: true,\n\t\t\tserialization: 'json',\n\t\t\twindowsHide: true,\n\t\t\tdetached: process.platform !== 'win32',\n\t\t})\n\t\tdrainStudyChild(child)\n\t\tthis.#child = child\n\t\tthis.#deadline = setTimeout(() => {\n\t\t\tthis.#control.fail({\n\t\t\t\tcause: 'deadline',\n\t\t\t\tmessage: 'Trial native deadline exceeded',\n\t\t\t\trole: undefined,\n\t\t\t\t// The session holds no start time, so the timer firing proves only that the elapsed time reached the limit.\n\t\t\t\tstop: {\n\t\t\t\t\tlayer: 'scope',\n\t\t\t\t\tid: 'Trial duration',\n\t\t\t\t\tmax: this.#options.profile.bounds.trial.duration,\n\t\t\t\t\tconsumed: undefined,\n\t\t\t\t},\n\t\t\t})\n\t\t\tvoid this.#terminate().catch((error: unknown) => this.#control.fail(readStudyFailure(error)))\n\t\t}, this.#options.profile.bounds.trial.duration)\n\t\tthis.#exit = new Promise<void>((resolve) => child.once('close', () => resolve()))\n\t\tthis.#channel = new StudyChannel({\n\t\t\tendpoint: child,\n\t\t\thandle: (operation, value) =>\n\t\t\t\tthis.#handle(operation, value).catch((error: unknown) => {\n\t\t\t\t\tthis.#control.fail(readStudyFailure(error))\n\t\t\t\t\tthrow error\n\t\t\t\t}),\n\t\t\tabort: () => {\n\t\t\t\tthrow new StudyError('FAULT', 'Worker cannot cancel parent authority')\n\t\t\t},\n\t\t})\n\t\tthis.#channel.signal.addEventListener(\n\t\t\t'abort',\n\t\t\t() => this.#control.fail(readStudyFailure(this.#channel?.signal.reason)),\n\t\t\t{ once: true, signal: this.#listeners.signal },\n\t\t)\n\t\tthis.#control.signal.addEventListener(\n\t\t\t'abort',\n\t\t\t() => this.#channel?.abort(valueToWire({ failure: this.#control.failure })),\n\t\t\t{ once: true, signal: this.#listeners.signal },\n\t\t)\n\t\tchild.stdout?.on('data', (value: Buffer) => this.#readLog(value))\n\t\tchild.stderr?.on('data', (value: Buffer) => this.#readLog(value))\n\t\tconst ready = await this.#control.wait(\n\t\t\tnew StudyDeadline({\n\t\t\t\tduration: this.#options.profile.bounds.trial.duration,\n\t\t\t\tlabel: STUDY_PROCESS_LABEL,\n\t\t\t}).wait(\n\t\t\t\tthis.#channel.request(\n\t\t\t\t\t'open',\n\t\t\t\t\tvalueToWire({ ...this.#options, signal: undefined, directory }),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t\tif (\n\t\t\t!isRecord(ready) ||\n\t\t\tready.pid !== child.pid ||\n\t\t\tready.agent !== this.#options.identity.agent ||\n\t\t\tready.subject !== this.#options.identity.subject ||\n\t\t\tready.instrument !== this.#options.identity.instrument\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Worker readiness identity differs')\n\t}\n\n\t/** Runs one ordered goal through parent-authorized requests and acknowledged evidence.\n\t * @param goal - Public goal without grading truth.\n\t * @param context - Actual parent meter and evidence sink.\n\t * @returns The retained child product after every admitted operation settles.\n\t */\n\tasync execute(goal: StudyGoal, context: StudyContext): Promise<StudyProduct> {\n\t\tif (this.#goals.size !== 0 || this.#closing !== undefined || this.#channel === undefined)\n\t\t\tthrow new StudyError('FAULT', 'Study process cannot execute in its current state')\n\t\tif (this.#control.failure !== undefined) throw failureToStudyError(this.#control.failure)\n\t\tconst running = new StudyProcessGoal(context)\n\t\tthis.#goals.add(running)\n\t\tconst listeners = new AbortController()\n\t\tconst control = new StudyControl(context.signal)\n\t\tthis.#control.signal.addEventListener(\n\t\t\t'abort',\n\t\t\t() =>\n\t\t\t\tcontrol.fail(this.#control.failure ?? createStudyProcessFailure('Study process failed')),\n\t\t\t{ once: true, signal: listeners.signal },\n\t\t)\n\t\tcontrol.signal.addEventListener(\n\t\t\t'abort',\n\t\t\t() => this.#channel?.abort(valueToWire({ failure: control.failure })),\n\t\t\t{ once: true, signal: listeners.signal },\n\t\t)\n\t\ttry {\n\t\t\tconst product = await control.wait(this.#channel.request('goal', valueToWire(goal)))\n\t\t\tif (this.#tickets.size !== 0 || this.#appends.size !== 0)\n\t\t\t\tthrow new StudyError('FAULT', 'Worker goal ended with unsettled admission or evidence')\n\t\t\tif (!isStudyProduct(product)) throw new StudyError('FAULT', 'Worker product is invalid')\n\t\t\treturn product\n\t\t} catch (error) {\n\t\t\tthis.#control.fail(readStudyFailure(error))\n\t\t\tthrow failureToStudyError(this.#control.failure ?? readStudyFailure(error))\n\t\t} finally {\n\t\t\tlisteners.abort()\n\t\t\tcontrol.close()\n\t\t\tthis.#goals.delete(running)\n\t\t}\n\t}\n\n\t/** Requests verified cleanup, then terminates only this recorded process tree. */\n\tclose(): Promise<void> {\n\t\tthis.#closing ??= this.#close()\n\t\treturn this.#closing\n\t}\n\n\tasync #handle(operation: StudyOperation, value: JSONValue): Promise<JSONValue> {\n\t\tconst [running] = this.#goals\n\t\tif (running === undefined) throw new StudyError('FAULT', 'Worker requested work outside a goal')\n\t\tconst context = running.context\n\t\tif (operation === 'admit') {\n\t\t\tif (!isRecord(value) || !isStudyCharge(value.charge))\n\t\t\t\tthrow new StudyError('FAULT', 'Invalid worker admission')\n\t\t\tconst id = running.issue(value.id)\n\t\t\tif (id === undefined) throw new StudyError('FAULT', 'Invalid worker admission')\n\t\t\tconst ticket = await context.meter.admit(value.charge)\n\t\t\tconst listeners = new AbortController()\n\t\t\tthis.#tickets.set(id, { ticket, listeners })\n\t\t\tticket.signal.addEventListener(\n\t\t\t\t'abort',\n\t\t\t\t() =>\n\t\t\t\t\tthis.#channel?.abort(\n\t\t\t\t\t\tvalueToWire({ id, failure: readStudyFailure(ticket.signal.reason) }),\n\t\t\t\t\t),\n\t\t\t\t{ once: true, signal: listeners.signal },\n\t\t\t)\n\t\t\tif (ticket.signal.aborted) throw ticket.signal.reason\n\t\t\treturn { id }\n\t\t}\n\t\tif (operation === 'finish' || operation === 'fail') {\n\t\t\tif (!isRecord(value) || typeof value.id !== 'number')\n\t\t\t\tthrow new StudyError('FAULT', 'Invalid worker settlement')\n\t\t\tconst entry = this.#tickets.get(value.id)\n\t\t\tif (entry === undefined)\n\t\t\t\tthrow new StudyError('FAULT', 'Foreign or repeated worker settlement')\n\t\t\tif (\n\t\t\t\t(operation === 'finish' && !isStudyUsage(value.usage)) ||\n\t\t\t\t(operation === 'fail' && !isStudyProcessFailure(value.failure))\n\t\t\t)\n\t\t\t\tthrow new StudyError('FAULT', 'Invalid worker settlement payload')\n\t\t\tthis.#tickets.delete(value.id)\n\t\t\tentry.listeners.abort()\n\t\t\tif (operation === 'finish' && isStudyUsage(value.usage)) entry.ticket.finish(value.usage)\n\t\t\telse if (isStudyProcessFailure(value.failure)) entry.ticket.fail(value.failure)\n\t\t\treturn true\n\t\t}\n\t\tif (operation === 'evidence') {\n\t\t\tif (!isStudyEvidence(value)) throw new StudyError('FAULT', 'Invalid worker evidence')\n\t\t\tconst appending = context.evidence.append(value)\n\t\t\tthis.#appends.add(appending)\n\t\t\ttry {\n\t\t\t\tawait appending\n\t\t\t\treturn true\n\t\t\t} finally {\n\t\t\t\tthis.#appends.delete(appending)\n\t\t\t}\n\t\t}\n\t\tthrow new StudyError('FAULT', 'Worker requested a forbidden operation')\n\t}\n\n\t#readLog(value: Buffer): void {\n\t\tthis.#logs += value.byteLength\n\t\tif (this.#logs > STUDY_LOG_BYTES) {\n\t\t\tthis.#control.fail(createStudyProcessFailure('Worker output limit exceeded'))\n\t\t\tvoid this.close().catch(() => undefined)\n\t\t}\n\t}\n\n\tasync #close(): Promise<void> {\n\t\tconst failure = await this.#acknowledge()\n\t\tfor (const entry of this.#tickets.values()) {\n\t\t\tentry.listeners.abort()\n\t\t\tif (!entry.ticket.signal.aborted) {\n\t\t\t\ttry {\n\t\t\t\t\tentry.ticket.fail(\n\t\t\t\t\t\tthis.#control.failure ??\n\t\t\t\t\t\t\tcreateStudyProcessFailure('Worker closed with an unfinished request'),\n\t\t\t\t\t)\n\t\t\t\t} catch {\n\t\t\t\t\t/* First parent failure is already retained. */\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.#tickets.clear()\n\t\tthis.#listeners.abort()\n\t\tthis.#channel?.close(failure)\n\t\tawait this.#terminate()\n\t\tthis.#control.close()\n\t\tif (failure !== undefined) throw failure\n\t}\n\n\t// Asks the worker to clean up and returns the failure that stopped it, or undefined when it acknowledged.\n\tasync #acknowledge(): Promise<unknown> {\n\t\ttry {\n\t\t\tif (this.#channel !== undefined && !this.#channel.signal.aborted) {\n\t\t\t\tconst closed = await new StudyDeadline({\n\t\t\t\t\tduration: this.#options.profile.bounds.request.duration,\n\t\t\t\t\tlabel: STUDY_PROCESS_LABEL,\n\t\t\t\t}).wait(this.#channel.request('close', true))\n\t\t\t\tif (closed !== true)\n\t\t\t\t\tthrow new StudyError('FAULT', 'Worker cleanup acknowledgment is invalid')\n\t\t\t}\n\t\t\treturn undefined\n\t\t} catch (error) {\n\t\t\treturn error\n\t\t}\n\t}\n\n\tasync #terminate(): Promise<void> {\n\t\tclearTimeout(this.#deadline)\n\t\tconst child = this.#child\n\t\tif (child === undefined) return\n\t\tif (child.exitCode === null && child.signalCode === null && child.pid !== undefined) {\n\t\t\tif (process.platform === 'win32') {\n\t\t\t\tawait new Promise<void>((resolve, reject) =>\n\t\t\t\t\texecFile(\n\t\t\t\t\t\t'taskkill',\n\t\t\t\t\t\t['/PID', String(child.pid), '/T', '/F'],\n\t\t\t\t\t\t{ windowsHide: true, timeout: 2000 },\n\t\t\t\t\t\t(error) =>\n\t\t\t\t\t\t\terror === null || child.exitCode !== null || child.signalCode !== null\n\t\t\t\t\t\t\t\t? resolve()\n\t\t\t\t\t\t\t\t: reject(error),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t} else process.kill(-child.pid, 'SIGKILL')\n\t\t}\n\t\tif (this.#exit !== undefined)\n\t\t\tawait new StudyDeadline({ duration: 2000, label: STUDY_PROCESS_LABEL }).wait(this.#exit)\n\t}\n}\n","import type { StudyDriverInterface, StudySessionInterface, StudyTrial } from '@src/core'\nimport type {\n\tStudyProcessDriverOptions,\n\tStudyProcessOptions,\n\tStudyTrialPreparationFunction,\n} from './types.js'\nimport { StudyError } from '@src/core'\nimport { readStudyPreparedDestination, readStudyReplayHistory } from './helpers.js'\nimport { isStudyExchangeDestination } from './validators.js'\nimport { StudyProcessSession } from './StudyProcessSession.js'\n\n/** Opens one fresh native child for each scheduled trial. */\nexport class StudyProcessDriver implements StudyDriverInterface {\n\t#options: StudyProcessOptions\n\treadonly #prepare: StudyTrialPreparationFunction | undefined\n\n\t/** Owns immutable resolved launch settings.\n\t * @param options - Built entry, admitted identities and exclusive scratch parent.\n\t */\n\tconstructor(options: StudyProcessDriverOptions) {\n\t\tconst { prepare, ...configuration } = options\n\t\tif (prepare !== undefined && typeof prepare !== 'function')\n\t\t\tthrow new StudyError('CONFIG', 'Trial preparation must be callable')\n\t\tif (options.replay?.offline === true && prepare !== undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Offline replay cannot prepare external resources')\n\t\tthis.#options = structuredClone(configuration)\n\t\tthis.#prepare = prepare\n\t}\n\n\t/** Opens isolated child state and waits for its verified readiness.\n\t * @param trial - The public scheduled trial.\n\t * @param signal - Authoritative parent cancellation.\n\t * @returns A ready process-backed session.\n\t */\n\tasync open(trial: StudyTrial, signal: AbortSignal): Promise<StudySessionInterface> {\n\t\tsignal.throwIfAborted()\n\t\tconst owned = structuredClone(trial)\n\t\tconst destination = this.#options.exchanges?.[owned.id]\n\t\tif (\n\t\t\tthis.#options.profile.record !== undefined &&\n\t\t\t(!isStudyExchangeDestination(destination) ||\n\t\t\t\tdestination.record.bytes !== this.#options.profile.record.bytes)\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Recorded trial requires its reserved destination')\n\t\tif (this.#options.profile.record === undefined && destination !== undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Unrecorded trial cannot receive a sidecar')\n\t\tif (this.#options.replay !== undefined)\n\t\t\tawait readStudyReplayHistory(this.#options.replay, this.#options.profile, owned)\n\t\tconst prepared =\n\t\t\tthis.#prepare === undefined\n\t\t\t\t? destination\n\t\t\t\t: readStudyPreparedDestination(\n\t\t\t\t\t\tdestination,\n\t\t\t\t\t\tawait this.#prepare(structuredClone(owned), signal, structuredClone(destination)),\n\t\t\t\t\t)\n\t\tsignal.throwIfAborted()\n\t\tconst session = new StudyProcessSession({\n\t\t\t...this.#options,\n\t\t\ttrial: owned,\n\t\t\tsignal,\n\t\t\t...(prepared === undefined ? {} : { exchanges: { [owned.id]: prepared } }),\n\t\t})\n\t\ttry {\n\t\t\tawait session.start()\n\t\t\treturn session\n\t\t} catch (error) {\n\t\t\tawait session.close().catch(() => undefined)\n\t\t\tthrow error\n\t\t}\n\t}\n}\n","import type { OllamaDaemonInterface } from '@orkestrel/ollama/server'\nimport type { StudyDaemonTrialOptions } from './types.js'\nimport type {\n\tStudyExchangeDestination,\n\tStudyExchangeIdentity,\n\tStudyExchangeReply,\n\tStudyExchangeSinkInterface,\n} from '../stores/types.js'\nimport { StudyError } from '@src/core'\nimport { open } from 'node:fs/promises'\nimport { StudyExchangeSink } from '../stores/StudyExchangeSink.js'\nimport { readStudyBytes } from '../stores/helpers.js'\nimport { buildStudyOllamaBytes } from '../ollama/helpers.js'\nimport { hashStudyBytes } from '../helpers.js'\n\n/** Records one trial's daemon maintenance before handing its verified prefix to a worker.\n * @example\n * ```ts\n * const trial = new StudyDaemonTrial(options)\n * await trial.execute(daemon)\n * ```\n */\nexport class StudyDaemonTrial {\n\treadonly #options: StudyDaemonTrialOptions\n\treadonly #pending = new Map<StudyExchangeIdentity, StudyExchangeReply>()\n\t#sink: StudyExchangeSinkInterface | undefined\n\n\t/** Owns the declaration and reserved destination for one preparation.\n\t * @param options - The immutable trial declaration, destination, and cancellation.\n\t */\n\tconstructor(options: StudyDaemonTrialOptions) {\n\t\tthis.#options = {\n\t\t\t...options,\n\t\t\tdeclaration: structuredClone(options.declaration),\n\t\t\tdestination: structuredClone(options.destination),\n\t\t}\n\t}\n\n\t/** Unloads declared models, drains the journal, and returns its exact retained identity.\n\t * @remarks The daemon's unload sender must call this instance's fetch method. Startup metadata must forward without recording.\n\t * @param daemon - The verified execution-owned daemon.\n\t * @returns The original destination with its closed maintenance prefix identity.\n\t */\n\tasync execute(daemon: OllamaDaemonInterface): Promise<StudyExchangeDestination> {\n\t\tif (this.#sink !== undefined) throw new StudyError('FAULT', 'Daemon preparation cannot repeat')\n\t\tconst file = await open(this.#options.destination.path, 'wx')\n\t\tthis.#sink = new StudyExchangeSink({ file, record: this.#options.destination.record })\n\t\ttry {\n\t\t\tawait this.#sink.append(this.#options.declaration)\n\t\t\tawait daemon.unload()\n\t\t\tawait this.#finish()\n\t\t} catch (error) {\n\t\t\tawait this.#finish(error)\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tawait this.#sink.close()\n\t\t}\n\t\tconst bytes = await readStudyBytes(\n\t\t\tthis.#options.destination.path,\n\t\t\tthis.#options.destination.record.bytes,\n\t\t)\n\t\treturn {\n\t\t\t...this.#options.destination,\n\t\t\tretained: {\n\t\t\t\tpath: `trials/${this.#options.declaration.trial}/exchanges.jsonl`,\n\t\t\t\tbytes: bytes.length,\n\t\t\t\tdigest: hashStudyBytes(bytes),\n\t\t\t},\n\t\t}\n\t}\n\n\t/** Retains each request before sending and preserves the sender's native response chunks.\n\t * @param input - The daemon's exact HTTP input.\n\t * @param init - The daemon's method, body, redirect policy, and cancellation.\n\t * @returns An unread response carrying the same body bytes for daemon validation.\n\t */\n\tasync fetch(\n\t\tinput: Parameters<typeof globalThis.fetch>[0],\n\t\tinit?: RequestInit,\n\t): Promise<Response> {\n\t\tconst sink = this.#sink\n\t\tif (sink === undefined) throw new StudyError('FAULT', 'Daemon journal is not open')\n\t\tawait this.#finish()\n\t\tconst request = new Request(input, {\n\t\t\t...init,\n\t\t\tsignal: AbortSignal.any([\n\t\t\t\tthis.#options.signal,\n\t\t\t\t...(init?.signal === undefined || init.signal === null ? [] : [init.signal]),\n\t\t\t]),\n\t\t})\n\t\tconst first = this.#options.declaration.procedure[0]\n\t\tif (\n\t\t\tfirst === undefined ||\n\t\t\tnew URL(request.url).pathname !== '/api/generate' ||\n\t\t\trequest.method !== 'POST'\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Unexpected maintenance request')\n\t\tconst identity: StudyExchangeIdentity = {\n\t\t\tordinal: sink.next,\n\t\t\tgoal: first.goal,\n\t\t\trole: 'maintenance',\n\t\t\tpath: '/api/generate',\n\t\t\tmethod: 'POST',\n\t\t\tstage: 'maintenance',\n\t\t}\n\t\tawait sink.append({\n\t\t\t...identity,\n\t\t\tphase: 'attempt',\n\t\t\t...buildStudyOllamaBytes(Buffer.from(await request.clone().arrayBuffer())),\n\t\t})\n\t\tconst chunks: Uint8Array[] = []\n\t\ttry {\n\t\t\tconst response = await globalThis.fetch(request)\n\t\t\tconst headers: ReadonlyArray<readonly [string, string]> = [...response.headers].filter(\n\t\t\t\t([name]) => name === 'content-type' || name === 'content-encoding',\n\t\t\t)\n\t\t\tconst reader = response.body?.getReader()\n\t\t\ttry {\n\t\t\t\tif (reader !== undefined)\n\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\tconst step = await reader.read()\n\t\t\t\t\t\tif (step.done) break\n\t\t\t\t\t\tconst size = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0)\n\t\t\t\t\t\tif (size + step.value.byteLength > this.#options.declaration.metadata.bytes)\n\t\t\t\t\t\t\tthrow new StudyError(\n\t\t\t\t\t\t\t\t'CAPACITY',\n\t\t\t\t\t\t\t\t'Maintenance reply exceeds its declared byte allowance',\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\tif (step.value.byteLength > 0) chunks.push(Buffer.from(step.value))\n\t\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tawait reader?.cancel().catch(() => undefined)\n\t\t\t\treader?.releaseLock()\n\t\t\t}\n\t\t\tconst bytes = Buffer.concat(chunks)\n\t\t\tthis.#pending.set(identity, {\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders,\n\t\t\t\tchunks: chunks.map((chunk) => chunk.byteLength),\n\t\t\t\t...buildStudyOllamaBytes(bytes),\n\t\t\t})\n\t\t\treturn new Response(response.body === null ? null : bytes, {\n\t\t\t\tstatus: response.status,\n\t\t\t\tstatusText: response.statusText,\n\t\t\t\theaders: response.headers,\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tawait sink.append({\n\t\t\t\t...identity,\n\t\t\t\tphase: 'failure',\n\t\t\t\treason: error instanceof Error ? error.message : 'Maintenance request failed',\n\t\t\t})\n\t\t\tthrow error\n\t\t}\n\t}\n\n\tasync #finish(error?: unknown): Promise<void> {\n\t\tfor (const [identity, reply] of this.#pending) {\n\t\t\ttry {\n\t\t\t\tawait this.#sink?.append(\n\t\t\t\t\terror === undefined\n\t\t\t\t\t\t? { ...identity, ...reply, phase: 'response' }\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t...identity,\n\t\t\t\t\t\t\t\tphase: 'failure',\n\t\t\t\t\t\t\t\treason: error instanceof Error ? error.message : 'Maintenance refused',\n\t\t\t\t\t\t\t\tresponse: reply,\n\t\t\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t} finally {\n\t\t\t\tthis.#pending.delete(identity)\n\t\t\t}\n\t\t}\n\t}\n}\n","import type { OllamaDaemonIdentity, OllamaDaemonInterface } from '@orkestrel/ollama/server'\nimport type { StudyTrial } from '@src/core'\nimport type { StudyDaemonSessionOptions } from './types.js'\nimport type { StudyExchangeDestination } from '../stores/types.js'\nimport { StudyError } from '@src/core'\nimport { readStudyRecordingDeclaration } from '../processes/helpers.js'\nimport { StudyDaemonTrial } from './StudyDaemonTrial.js'\n\n/** Owns the declared daemon and its serial trial preparation through permanent cleanup.\n * @example\n * ```ts\n * const session = new StudyDaemonSession(options)\n * try { await session.start() } finally { await session.stop() }\n * ```\n */\nexport class StudyDaemonSession {\n\treadonly #options: StudyDaemonSessionOptions\n\t#daemon: OllamaDaemonInterface | undefined\n\t#stopped = false\n\treadonly #trials = new Set<StudyDaemonTrial>()\n\n\t/** Captures resolved declarations without loading the daemon runtime.\n\t * @param options - The execution profile, scenarios, workspace, and cancellation.\n\t */\n\tconstructor(options: StudyDaemonSessionOptions) {\n\t\tconst provider = options.profile.provider\n\t\tconst daemon = provider?.daemon\n\t\tif (provider === undefined || daemon === undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Execution has no declared daemon')\n\t\tif (\n\t\t\toptions.profile.record !== undefined &&\n\t\t\toptions.profile.settings?.version !== daemon.version\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Daemon and recording versions differ')\n\t\tthis.#options = {\n\t\t\t...options,\n\t\t\tprofile: structuredClone(options.profile),\n\t\t\tscenarios: structuredClone(options.scenarios),\n\t\t}\n\t}\n\n\t/** Starts the daemon and returns its verified execution provenance.\n\t * @returns The executable, endpoint, owned pid, and model receipt.\n\t */\n\tasync start(): Promise<OllamaDaemonIdentity> {\n\t\tthis.#options.signal.throwIfAborted()\n\t\tconst { createOllamaDaemon } = await import('@orkestrel/ollama/server')\n\t\tif (this.#stopped) throw new StudyError('FAULT', 'Daemon session has stopped')\n\t\tconst provider = this.#options.profile.provider\n\t\tconst daemon = provider?.daemon\n\t\tif (provider === undefined || daemon === undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Execution has no declared daemon')\n\t\tthis.#daemon ??= createOllamaDaemon({\n\t\t\texecutable: { path: daemon.executable, digest: daemon.digest, version: daemon.version },\n\t\t\turl: provider.url,\n\t\t\tmodels: daemon.models,\n\t\t\tworkspace: this.#options.workspace,\n\t\t\t...(daemon.environment === undefined ? {} : { environment: daemon.environment }),\n\t\t\tsignal: this.#options.signal,\n\t\t\treadiness: this.#options.profile.bounds.request.duration,\n\t\t\tmetadata: {\n\t\t\t\ttimeout: this.#options.profile.bounds.request.duration,\n\t\t\t\tbytes: this.#options.profile.bounds.request.bytes,\n\t\t\t},\n\t\t\tfetch: (input, init) => this.#send(input, init),\n\t\t})\n\t\treturn this.#daemon.start()\n\t}\n\n\t/** Unloads the declared population before opening one trial worker.\n\t * @param trial - The scheduled trial.\n\t * @param signal - The trial's cancellation.\n\t * @param destination - The optional reserved recording destination.\n\t * @returns The unchanged destination with its verified maintenance prefix when recording.\n\t */\n\tasync prepare(\n\t\ttrial: StudyTrial,\n\t\tsignal: AbortSignal,\n\t\tdestination?: StudyExchangeDestination,\n\t): Promise<StudyExchangeDestination | undefined> {\n\t\tsignal.throwIfAborted()\n\t\tconst daemon = this.#daemon\n\t\tif (daemon === undefined) throw new StudyError('FAULT', 'Daemon startup is required')\n\t\tif (this.#trials.size !== 0) throw new StudyError('FAULT', 'Daemon preparations cannot overlap')\n\t\tif (destination === undefined) {\n\t\t\tif (this.#options.profile.record !== undefined)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Daemon maintenance requires its reserved sidecar')\n\t\t\tawait daemon.unload()\n\t\t\treturn undefined\n\t\t}\n\t\tconst declaration = readStudyRecordingDeclaration(this.#options.profile, trial)\n\t\tconst models = this.#options.profile.provider?.daemon?.models\n\t\tconst first = this.#options.scenarios.find((scenario) => scenario.id === trial.scenario)\n\t\t\t?.goals[0]\n\t\tif (models === undefined || first?.id !== declaration.procedure[0]?.goal)\n\t\t\tthrow new StudyError('CONFIG', 'Maintenance must join the first declared goal')\n\t\tconst preparation = new StudyDaemonTrial({\n\t\t\tdestination,\n\t\t\tdeclaration: { ...declaration, maintenance: models },\n\t\t\tsignal,\n\t\t})\n\t\tthis.#trials.add(preparation)\n\t\ttry {\n\t\t\treturn await preparation.execute(daemon)\n\t\t} finally {\n\t\t\tthis.#trials.delete(preparation)\n\t\t}\n\t}\n\n\t/** Stops and joins the owned tree and refuses an unconfirmed cleanup.\n\t * @returns Completion after daemon and emitter teardown.\n\t */\n\tasync stop(): Promise<void> {\n\t\tthis.#stopped = true\n\t\tconst daemon = this.#daemon\n\t\tif (daemon === undefined) return\n\t\tconst confirmed = await daemon.stop()\n\t\tawait daemon.destroy()\n\t\tif (!confirmed) throw new StudyError('FAULT', 'Daemon cleanup was not confirmed')\n\t}\n\n\t#send(input: Parameters<typeof globalThis.fetch>[0], init?: RequestInit): Promise<Response> {\n\t\tfor (const trial of this.#trials) return trial.fetch(input, init)\n\t\treturn globalThis.fetch(input, init)\n\t}\n}\n","import type { ChildProcess } from 'node:child_process'\nimport type { StudyTaskOptions, StudyTaskResult } from './types.js'\nimport { StudyError, isStudyDigest } from '@src/core'\nimport { isJSONValue, isRecord } from '@orkestrel/contract'\nimport { fork } from 'node:child_process'\nimport { STUDY_FRAME_BYTES, STUDY_LOG_BYTES, STUDY_TASK_OPERATION } from './constants.js'\nimport { drainStudyChild, terminateStudyChild } from './helpers.js'\n\n/** Supervises one forked adapter child until it closes with one verified response. */\nexport class StudyTaskChild {\n\treadonly #options: StudyTaskOptions\n\treadonly #duration: number\n\treadonly #signal: AbortSignal\n\t#failure: unknown\n\t#result: StudyTaskResult | undefined\n\t#logs = 0\n\t#executed = false\n\n\t/** Binds one adapter evaluation to its owned route, validated deadline and caller cancellation.\n\t * @param options - The owning task's snapshotted entry, root and selection.\n\t * @param duration - The validated deadline in milliseconds.\n\t * @param signal - Caller cancellation.\n\t */\n\tconstructor(options: StudyTaskOptions, duration: number, signal: AbortSignal) {\n\t\tthis.#options = options\n\t\tthis.#duration = duration\n\t\tthis.#signal = signal\n\t}\n\n\t/** Forks the adapter child, sends one request frame and settles with its single verified response.\n\t * @param input - The validated request frame.\n\t * @returns The verified adapter output and instrumentation identity.\n\t * @throws StudyError - Thrown with code `CONFIG` when this child is already supervised.\n\t */\n\texecute(input: Readonly<Record<string, unknown>>): Promise<StudyTaskResult> {\n\t\tif (this.#executed) throw new StudyError('CONFIG', 'Study task child can execute only once')\n\t\tthis.#executed = true\n\t\tconst signal = this.#signal\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst child = fork(this.#options.entry, [STUDY_TASK_OPERATION], {\n\t\t\t\tcwd: this.#options.root,\n\t\t\t\texecArgv: [...process.execArgv],\n\t\t\t\tsilent: true,\n\t\t\t\twindowsHide: true,\n\t\t\t\tdetached: process.platform !== 'win32',\n\t\t\t\tserialization: 'json',\n\t\t\t})\n\t\t\tdrainStudyChild(child)\n\t\t\tconst listeners = new AbortController()\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.#failure = new StudyError('FAULT', 'Adapter deadline exceeded', {\n\t\t\t\t\tcause: 'deadline',\n\t\t\t\t\tmessage: 'Adapter deadline exceeded',\n\t\t\t\t\trole: undefined,\n\t\t\t\t\tstop: {\n\t\t\t\t\t\tlayer: 'scope',\n\t\t\t\t\t\tid: 'Adapter duration',\n\t\t\t\t\t\tmax: this.#duration,\n\t\t\t\t\t\tconsumed: undefined,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tthis.#terminate(child)\n\t\t\t}, this.#duration)\n\t\t\tsignal.addEventListener(\n\t\t\t\t'abort',\n\t\t\t\t() => {\n\t\t\t\t\tthis.#failure = signal.reason\n\t\t\t\t\tthis.#terminate(child)\n\t\t\t\t},\n\t\t\t\t{ once: true, signal: listeners.signal },\n\t\t\t)\n\t\t\tchild.on('message', (value: unknown) => {\n\t\t\t\ttry {\n\t\t\t\t\tif (\n\t\t\t\t\t\tthis.#result !== undefined ||\n\t\t\t\t\t\t!isRecord(value) ||\n\t\t\t\t\t\tBuffer.byteLength(JSON.stringify(value)) > STUDY_FRAME_BYTES\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new StudyError('FAULT', 'Adapter response is oversized or repeated')\n\t\t\t\t\tif (typeof value.error === 'string')\n\t\t\t\t\t\tthrow new StudyError(value.code === 'CONFIG' ? 'CONFIG' : 'FAULT', value.error)\n\t\t\t\t\tif (!isStudyDigest(value.instrument) || !isJSONValue(value.value))\n\t\t\t\t\t\tthrow new StudyError('FAULT', 'Adapter response is malformed')\n\t\t\t\t\tthis.#result = { instrument: value.instrument, value: value.value }\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.#failure = error\n\t\t\t\t}\n\t\t\t\tthis.#terminate(child)\n\t\t\t})\n\t\t\tfor (const stream of [child.stdout, child.stderr])\n\t\t\t\tstream?.on('data', (chunk: Buffer) => {\n\t\t\t\t\tthis.#logs += chunk.byteLength\n\t\t\t\t\tif (this.#logs <= STUDY_LOG_BYTES) return\n\t\t\t\t\tthis.#failure = new StudyError('FAULT', 'Adapter output exceeds the log allowance')\n\t\t\t\t\tthis.#terminate(child)\n\t\t\t\t})\n\t\t\tchild.once('error', (error) => {\n\t\t\t\tthis.#failure = error\n\t\t\t})\n\t\t\tchild.once('close', () => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tlisteners.abort()\n\t\t\t\tconst result = this.#result\n\t\t\t\tif (this.#failure !== undefined) reject(this.#failure)\n\t\t\t\telse if (result === undefined)\n\t\t\t\t\treject(new StudyError('FAULT', 'Adapter exited without a complete response'))\n\t\t\t\telse resolve(result)\n\t\t\t})\n\t\t\tchild.send(input, (error: Error | null) => {\n\t\t\t\tif (error === null) return\n\t\t\t\tthis.#failure = error\n\t\t\t\tthis.#terminate(child)\n\t\t\t})\n\t\t\tif (signal.aborted) {\n\t\t\t\tthis.#failure = signal.reason\n\t\t\t\tthis.#terminate(child)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Terminates the child tree; a termination failure replaces the failure that requested it.\n\t#terminate(child: ChildProcess): void {\n\t\ttry {\n\t\t\tterminateStudyChild(child)\n\t\t} catch (error) {\n\t\t\tthis.#failure = error\n\t\t}\n\t}\n}\n","import type { StudyTaskOptions, StudyTaskRequest, StudyTaskResult } from './types.js'\nimport { StudyError } from '@src/core'\nimport { isRecord } from '@orkestrel/contract'\nimport { STUDY_FRAME_BYTES, STUDY_TASK_DURATION } from './constants.js'\nimport { valueToWire } from './helpers.js'\nimport { StudyTaskChild } from './StudyTaskChild.js'\n\n/** Bounds adapter evaluation by an independent native parent timer. */\nexport class StudyTask {\n\t#options: StudyTaskOptions\n\t/** Owns the built child route and captured source selection.\n\t * @param options - Consumer root, runtime entry, adapter, and admitted dependencies.\n\t */\n\tconstructor(options: StudyTaskOptions) {\n\t\tthis.#options = structuredClone(options)\n\t}\n\t/** Executes one validation or grading operation in a fresh child.\n\t * @param request - Declarations or retained evidence, never a trial payload.\n\t * @param signal - Caller cancellation.\n\t * @returns Verified adapter output and active instrumentation identity.\n\t */\n\texecute(request: StudyTaskRequest, signal: AbortSignal): Promise<StudyTaskResult> {\n\t\tsignal.throwIfAborted()\n\t\tconst duration = this.#options.duration ?? STUDY_TASK_DURATION\n\t\tif (!Number.isSafeInteger(duration) || duration <= 0 || duration > STUDY_TASK_DURATION)\n\t\t\tthrow new StudyError('CONFIG', 'Adapter deadline must be finite and at most 60 seconds')\n\t\tconst input = valueToWire({ ...this.#options, ...request })\n\t\tif (!isRecord(input)) throw new StudyError('CONFIG', 'Adapter input must be an object')\n\t\tif (Buffer.byteLength(JSON.stringify(input)) > STUDY_FRAME_BYTES)\n\t\t\tthrow new StudyError('CONFIG', 'Adapter input exceeds the frame allowance')\n\t\t// Each call supervises its own child, so concurrent calls never share event state.\n\t\treturn new StudyTaskChild(this.#options, duration, signal).execute(input)\n\t}\n}\n","import type { StudyGrading, StudyManifest } from '@src/core'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type { StudySealedResult } from '../stores/types.js'\nimport type { StudyOllamaReplaySelection } from '../ollama/types.js'\nimport type {\n\tStudyCommandOptions,\n\tStudyExecutionRequest,\n\tStudyGradeRequest,\n\tStudyGradingContext,\n\tStudyLabelRequest,\n\tStudyPreparation,\n\tStudyReportRequest,\n\tStudyFreezeRequest,\n\tStudyClosure,\n} from './types.js'\nimport {\n\tStudyError,\n\tbuildStudySchedule,\n\tvalidateStudyInputs,\n\tparseStudyGrading,\n\tparseStudyLabeling,\n\tparseStudyProfile,\n\tparseStudyRubric,\n\tStudySeries,\n\tisStudyJudgment,\n} from '@src/core'\nimport { arrayOf, canonicalStringify, isArray, isString, parseJSON } from '@orkestrel/contract'\nimport { randomUUID } from 'node:crypto'\nimport { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'\nimport { isAbsolute, join, resolve } from 'node:path'\nimport { StudyArtifactLoader } from '../processes/StudyArtifactLoader.js'\nimport { StudyProcessDriver } from '../processes/StudyProcessDriver.js'\nimport { StudyDaemonSession } from './StudyDaemonSession.js'\nimport {\n\tcomputeStudyInstrumentDigest,\n\tcomputeStudyProfileDigest,\n\tresolveStudyInstrument,\n\treadStudyReplayHistory,\n\tvalueToWire,\n} from '../processes/helpers.js'\nimport { ArtifactLoader } from '../artifacts/ArtifactLoader.js'\nimport { relocateArtifactPath, verifyArtifactClosure } from '../artifacts/helpers.js'\nimport { decodeStudyJSON, encodeStudyJSON, hashStudyBytes, matchesSystemError } from '../helpers.js'\nimport { STUDY_CUSTODY_BYTES, STUDY_PACKET_DISCLOSURE } from '../stores/constants.js'\nimport {\n\tbuildStudyPacket,\n\tcheckStudyDirectory,\n\tcomputeStudyPacketDigest,\n\treadStudyBytes,\n\treadStudyResult,\n\ttranslateStudyPacketLabeling,\n} from '../stores/helpers.js'\nimport { StudyGradingStore } from '../stores/StudyGradingStore.js'\nimport { StudyResultStore } from '../stores/StudyResultStore.js'\nimport { StudyTask } from '../processes/StudyTask.js'\nimport { STUDY_COMMAND_DURATION, STUDY_COMMAND_GRADER } from './constants.js'\nimport {\n\tcollectStudyEvidence,\n\tcomputeStudyCommandFingerprint,\n\tcomputeStudyFixtureDigest,\n\tcomputeStudyReport,\n\tresolveStudyPath,\n\tresolveStudyProfile,\n\treadStudyDeclaration,\n\treadStudyDeclarationBytes,\n\treadStudyClosure,\n} from './helpers.js'\nimport { parseStudyArguments } from './parsers.js'\nimport { isStudyReplaySelection } from '../processes/validators.js'\n\n/** Executes validated study operations with execution and grading custody kept independent. */\nexport class StudyCommand {\n\treadonly #root: string\n\treadonly #entry: string\n\n\t/**\n\t * Owns the trusted host entry and repository location without reading or writing files.\n\t * @param options - The repository root and built trusted application entry\n\t */\n\tconstructor(options: StudyCommandOptions) {\n\t\tthis.#root = resolve(options.root)\n\t\tthis.#entry = resolve(this.#root, options.entry)\n\t}\n\n\t/**\n\t * Parses command tokens once and executes their independent operation.\n\t * @param arguments_ - The exact command tokens\n\t * @param signal - The caller's execution cancellation\n\t * @returns Truthful operation metadata or a verified whole-horizon report\n\t * @throws StudyError - Thrown when arguments, declarations, identities, or custody fail\n\t */\n\tasync execute(arguments_: readonly string[], signal: AbortSignal): Promise<JSONValue> {\n\t\tconst request = parseStudyArguments(arguments_)\n\t\tsignal.throwIfAborted()\n\t\tif (request.command === 'check') return this.#check(await this.#prepare(request, signal))\n\t\tif (request.command === 'execute') return this.#execution(request, signal)\n\t\tif (request.command === 'freeze') return this.#freeze(request, signal)\n\t\tif (request.command === 'grade') return this.#grade(request, signal)\n\t\tif (request.command === 'label') return this.#label(request, signal)\n\t\tif (request.command === 'report') return this.#report(request, signal)\n\t\tthrow new StudyError('CONFIG', 'Unsupported study operation')\n\t}\n\n\tasync #freeze(request: StudyFreezeRequest, signal: AbortSignal): Promise<JSONValue> {\n\t\tconst selection: StudyExecutionRequest = {\n\t\t\tcommand: 'check',\n\t\t\ttarget: request.target,\n\t\t\tprofile: request.profile,\n\t\t\tout: undefined,\n\t\t\texpected: undefined,\n\t\t}\n\t\tconst original = await this.#prepare(selection, signal)\n\t\tconst instrument = resolveStudyInstrument(this.#entry)\n\t\tconst directory = resolveStudyPath(join(this.#root, 'studies'), request.target)\n\t\tconst assets = [\n\t\t\t...new Set([\n\t\t\t\tthis.#entry,\n\t\t\t\tjoin(directory, 'study.json'),\n\t\t\t\tresolveStudyPath(directory, original.definition.rubric),\n\t\t\t\tresolveStudyPath(original.bundle, `profiles/${request.profile}.json`),\n\t\t\t\t...original.definition.scenarios.map((id) =>\n\t\t\t\t\tresolveStudyPath(original.bundle, `scenarios/${id}.json`),\n\t\t\t\t),\n\t\t\t]),\n\t\t]\n\t\tconst loader = new ArtifactLoader({\n\t\t\tentries: [\n\t\t\t\t...new Set([\n\t\t\t\t\toriginal.profile.agent,\n\t\t\t\t\toriginal.profile.subject,\n\t\t\t\t\t...(original.profile.provider === undefined ? [] : [original.profile.provider.entry]),\n\t\t\t\t]),\n\t\t\t],\n\t\t\troots: [...new Set([...original.profile.roots, instrument])],\n\t\t\tsource: { root: original.bundle, entry: join(original.bundle, 'index.ts') },\n\t\t\tinstrument,\n\t\t\tassets,\n\t\t})\n\t\tloader.inspect()\n\t\tsignal.throwIfAborted()\n\t\tconst closure = await loader.materialize(request.destination)\n\t\tconst candidate: StudyClosure = {\n\t\t\tclosure,\n\t\t\troot: relocateArtifactPath(closure, this.#root),\n\t\t\tentry: relocateArtifactPath(closure, this.#entry),\n\t\t\ttarget: request.target,\n\t\t\tprofile: request.profile,\n\t\t\tsource: original.identity,\n\t\t\tidentity: original.identity,\n\t\t\tfingerprint: computeStudyCommandFingerprint(\n\t\t\t\toriginal.identity,\n\t\t\t\toriginal.profile.bounds,\n\t\t\t\toriginal.definition,\n\t\t\t),\n\t\t}\n\t\tconst checked = await this.#prepare(selection, signal, candidate)\n\t\tif (\n\t\t\tchecked.source !== original.source ||\n\t\t\tchecked.identity.fixtures !== original.identity.fixtures ||\n\t\t\thashStudyBytes(encodeStudyJSON(checked.definition)) !==\n\t\t\t\thashStudyBytes(encodeStudyJSON(original.definition)) ||\n\t\t\thashStudyBytes(encodeStudyJSON(checked.rubric)) !==\n\t\t\t\thashStudyBytes(encodeStudyJSON(original.rubric))\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Study declarations changed during freezing')\n\t\tconst publication: StudyClosure = {\n\t\t\t...candidate,\n\t\t\tidentity: checked.identity,\n\t\t\tfingerprint: computeStudyCommandFingerprint(\n\t\t\t\tchecked.identity,\n\t\t\t\tchecked.profile.bounds,\n\t\t\t\tchecked.definition,\n\t\t\t),\n\t\t}\n\t\toriginal.artifacts.verify()\n\t\tloader.verify()\n\t\tchecked.artifacts.verify()\n\t\tverifyArtifactClosure(closure)\n\t\tsignal.throwIfAborted()\n\t\tawait writeFile(join(closure.destination, 'closure.json'), encodeStudyJSON(publication), {\n\t\t\tflag: 'wx',\n\t\t})\n\t\treturn valueToWire({\n\t\t\tcommand: 'freeze',\n\t\t\tpath: closure.destination,\n\t\t\tdigest: closure.digest,\n\t\t\tfingerprint: publication.fingerprint,\n\t\t})\n\t}\n\n\t#closure(request: StudyExecutionRequest): StudyClosure {\n\t\tif (request.closure === undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Study closure selection is absent')\n\t\tconst closure = readStudyClosure(resolve(this.#root, request.closure))\n\t\tif (closure.target !== request.target || closure.profile !== request.profile)\n\t\t\tthrow new StudyError('CONFIG', 'Study closure selectors differ from the checked selection')\n\t\treturn closure\n\t}\n\n\tasync #prepare(\n\t\trequest: StudyExecutionRequest,\n\t\tsignal: AbortSignal,\n\t\tretained?: StudyClosure,\n\t): Promise<StudyPreparation> {\n\t\tconst closure = retained ?? (request.closure === undefined ? undefined : this.#closure(request))\n\t\tconst root = closure?.root ?? this.#root\n\t\tconst entry = closure?.entry ?? this.#entry\n\t\tconst { bundle, definition, scenarios, fixtures, rubric } = await readStudyDeclaration(\n\t\t\troot,\n\t\t\trequest.target,\n\t\t\tsignal,\n\t\t)\n\t\tconst profileBytes = await readStudyDeclarationBytes(\n\t\t\troot,\n\t\t\tresolveStudyPath(bundle, `profiles/${request.profile}.json`),\n\t\t)\n\t\tconst source = parseStudyProfile(decodeStudyJSON(profileBytes))\n\t\tif (source.name !== request.profile)\n\t\t\tthrow new StudyError('CONFIG', 'Profile name differs from its selected file')\n\t\tif (source.bounds.series.duration > STUDY_COMMAND_DURATION)\n\t\t\tthrow new StudyError('CONFIG', 'Series duration exceeds the 24-hour host ceiling')\n\t\tconst profile = resolveStudyProfile(root, source, closure?.closure)\n\t\tvalidateStudyInputs(definition, scenarios, rubric, profile)\n\t\tsignal.throwIfAborted()\n\t\tconst artifacts = new StudyArtifactLoader({\n\t\t\troot,\n\t\t\tentry,\n\t\t\tprofile,\n\t\t\tadapter: join(bundle, 'index.ts'),\n\t\t\t...(closure === undefined ? {} : { closure }),\n\t\t})\n\t\tconst selected = await artifacts.inspect()\n\t\tconst validation = await new StudyTask({\n\t\t\troot,\n\t\t\tentry,\n\t\t\tadapter: join(bundle, 'index.ts'),\n\t\t\troots: profile.roots,\n\t\t\t...(closure === undefined ? {} : { closure }),\n\t\t}).execute({ operation: 'validate', input: { definition, scenarios, rubric, profile } }, signal)\n\t\tif (validation.value !== true || validation.instrument !== selected.instrument)\n\t\t\tthrow new StudyError('FAULT', 'Adapter validation identity differs')\n\t\tartifacts.verify()\n\t\tconst preparation: StudyPreparation = {\n\t\t\tbundle,\n\t\t\tdefinition,\n\t\t\tscenarios: Object.freeze(scenarios),\n\t\t\trubric,\n\t\t\tprofile,\n\t\t\tidentity: {\n\t\t\t\t...selected,\n\t\t\t\tfixtures: computeStudyFixtureDigest(definition, fixtures),\n\t\t\t\tprofile: computeStudyProfileDigest(profile),\n\t\t\t},\n\t\t\tartifacts,\n\t\t\tsource: hashStudyBytes(profileBytes),\n\t\t\t...(closure === undefined ? {} : { closure }),\n\t\t}\n\t\tif (\n\t\t\trequest.closure !== undefined &&\n\t\t\tclosure !== undefined &&\n\t\t\t(computeStudyCommandFingerprint(preparation.identity, profile.bounds, definition) !==\n\t\t\t\tclosure.fingerprint ||\n\t\t\t\thashStudyBytes(encodeStudyJSON(preparation.identity)) !==\n\t\t\t\t\thashStudyBytes(encodeStudyJSON(closure.identity)))\n\t\t)\n\t\t\tthrow new StudyError(\n\t\t\t\t'FAULT',\n\t\t\t\t`Study closure checked identity differs: ${Object.entries(preparation.identity)\n\t\t\t\t\t.filter(([name, digest]) =>\n\t\t\t\t\t\tObject.entries(closure.identity).some(\n\t\t\t\t\t\t\t([key, expected]) => key === name && digest !== expected,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\t.map(([name]) => name)\n\t\t\t\t\t.join(', ')}`,\n\t\t\t)\n\t\treturn preparation\n\t}\n\n\t#check(preparation: StudyPreparation): JSONValue {\n\t\tconst fingerprint = computeStudyCommandFingerprint(\n\t\t\tpreparation.identity,\n\t\t\tpreparation.profile.bounds,\n\t\t\tpreparation.definition,\n\t\t)\n\t\treturn valueToWire({\n\t\t\tcommand: 'check',\n\t\t\tstudy: preparation.definition.name,\n\t\t\tpurpose: preparation.definition.purpose,\n\t\t\tdriver: preparation.definition.driver,\n\t\t\tprofile: preparation.profile.name,\n\t\t\tbounds: preparation.profile.bounds,\n\t\t\tidentity: preparation.identity,\n\t\t\tprovenance: { profile: preparation.source },\n\t\t\t...(preparation.closure === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tclosure: {\n\t\t\t\t\t\t\tdigest: preparation.closure.closure.digest,\n\t\t\t\t\t\t\tsource: preparation.closure.source,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\tfingerprint,\n\t\t\tnext: [\n\t\t\t\t'execute',\n\t\t\t\tpreparation.definition.name,\n\t\t\t\t'--profile',\n\t\t\t\tpreparation.profile.name,\n\t\t\t\t'--expected',\n\t\t\t\tfingerprint,\n\t\t\t\t...(preparation.closure === undefined\n\t\t\t\t\t? []\n\t\t\t\t\t: ['--closure', preparation.closure.closure.destination]),\n\t\t\t],\n\t\t\tschedule: buildStudySchedule(preparation.definition, preparation.scenarios),\n\t\t})\n\t}\n\n\tasync #execution(request: StudyExecutionRequest, signal: AbortSignal): Promise<JSONValue> {\n\t\tconst replay = request.replay === undefined ? undefined : await this.#replay(request, signal)\n\t\tconst preparation = await this.#prepare(request, signal)\n\t\tconst fingerprint = computeStudyCommandFingerprint(\n\t\t\tpreparation.identity,\n\t\t\tpreparation.profile.bounds,\n\t\t\tpreparation.definition,\n\t\t)\n\t\tif (request.expected !== undefined && request.expected !== fingerprint)\n\t\t\tthrow new StudyError('CONFIG', 'Validated execution changed after the supervisor check')\n\t\tsignal.throwIfAborted()\n\t\tconst id = randomUUID()\n\t\tconst qualification = await this.#qualification(preparation)\n\t\tsignal.throwIfAborted()\n\t\tconst parent = await this.#temporary()\n\t\tsignal.throwIfAborted()\n\t\tconst directory = request.out === undefined ? join(parent, id) : this.#file(request.out)\n\t\tconst scratch = await mkdtemp(join(parent, 'scratch-'))\n\t\ttry {\n\t\t\tconst daemon =\n\t\t\t\tpreparation.profile.provider?.daemon === undefined || replay?.offline === true\n\t\t\t\t\t? undefined\n\t\t\t\t\t: new StudyDaemonSession({\n\t\t\t\t\t\t\tprofile: preparation.profile,\n\t\t\t\t\t\t\tscenarios: preparation.scenarios,\n\t\t\t\t\t\t\tworkspace: scratch,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t})\n\t\t\ttry {\n\t\t\t\tconst startup = await daemon?.start()\n\t\t\t\tconst manifest: StudyManifest = {\n\t\t\t\t\tid,\n\t\t\t\t\tcreated: new Date().toISOString(),\n\t\t\t\t\tdefinition: preparation.definition,\n\t\t\t\t\tscenarios: preparation.scenarios,\n\t\t\t\t\tidentity: preparation.identity,\n\t\t\t\t\tschedule: buildStudySchedule(preparation.definition, preparation.scenarios),\n\t\t\t\t\tbounds: preparation.profile.bounds,\n\t\t\t\t\t...(preparation.profile.record === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { record: preparation.profile.record }),\n\t\t\t\t\tqualification,\n\t\t\t\t\thost: {\n\t\t\t\t\t\tnode: process.version,\n\t\t\t\t\t\tplatform: process.platform,\n\t\t\t\t\t\tarchitecture: process.arch,\n\t\t\t\t\t\tprofile: preparation.source,\n\t\t\t\t\t\troots: JSON.stringify(preparation.profile.roots),\n\t\t\t\t\t\t...(startup === undefined ? {} : { daemon: JSON.stringify(startup) }),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tconst store = new StudyResultStore({ directory, manifest })\n\t\t\t\tawait store.create()\n\t\t\t\tconst destinations =\n\t\t\t\t\tpreparation.profile.record === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: Object.fromEntries(\n\t\t\t\t\t\t\t\tawait Promise.all(\n\t\t\t\t\t\t\t\t\tmanifest.schedule.map(\n\t\t\t\t\t\t\t\t\t\tasync (trial) => [trial.id, await store.exchanges(trial)] as const,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t)\n\t\t\t\tconst driver = new StudyProcessDriver({\n\t\t\t\t\troot: preparation.closure?.root ?? this.#root,\n\t\t\t\t\tentry: preparation.closure?.entry ?? this.#entry,\n\t\t\t\t\tprofile: preparation.profile,\n\t\t\t\t\tidentity: preparation.identity,\n\t\t\t\t\tdriver: preparation.definition.driver,\n\t\t\t\t\tadapter: join(preparation.bundle, 'index.ts'),\n\t\t\t\t\tdirectory: scratch,\n\t\t\t\t\t...(preparation.closure === undefined ? {} : { closure: preparation.closure }),\n\t\t\t\t\t...(destinations === undefined ? {} : { exchanges: destinations }),\n\t\t\t\t\t...(replay === undefined ? {} : { replay }),\n\t\t\t\t\t...(daemon === undefined ? {} : { prepare: daemon.prepare.bind(daemon) }),\n\t\t\t\t})\n\t\t\t\tconst attempts = await new StudySeries({ manifest, driver, store, signal }).execute()\n\t\t\t\tawait daemon?.stop()\n\t\t\t\tpreparation.artifacts.verify()\n\t\t\t\tconst seal = await store.seal()\n\t\t\t\treturn valueToWire({\n\t\t\t\t\tcommand: 'execute',\n\t\t\t\t\tstatus: attempts.some((attempt) => attempt.failure !== undefined)\n\t\t\t\t\t\t? 'operational-failure'\n\t\t\t\t\t\t: 'completed',\n\t\t\t\t\tresult: id,\n\t\t\t\t\tpath: directory,\n\t\t\t\t\tseal: seal.id,\n\t\t\t\t\tfingerprint,\n\t\t\t\t\tnext: [\n\t\t\t\t\t\t'grade',\n\t\t\t\t\t\tdirectory,\n\t\t\t\t\t\t'--rubric',\n\t\t\t\t\t\tresolveStudyPath(\n\t\t\t\t\t\t\tresolveStudyPath(join(this.#root, 'studies'), preparation.definition.name),\n\t\t\t\t\t\t\tpreparation.definition.rubric,\n\t\t\t\t\t\t),\n\t\t\t\t\t],\n\t\t\t\t})\n\t\t\t} finally {\n\t\t\t\tawait daemon?.stop()\n\t\t\t}\n\t\t} finally {\n\t\t\tawait rm(scratch, { recursive: true, force: true, maxRetries: 3 })\n\t\t}\n\t}\n\n\tasync #replay(\n\t\trequest: StudyExecutionRequest,\n\t\tsignal: AbortSignal,\n\t): Promise<StudyOllamaReplaySelection> {\n\t\tif (!isStudyReplaySelection(request.replay))\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'Replay requires an explicit sealed source, prefixes and offline behavior',\n\t\t\t)\n\t\tconst selection = {\n\t\t\t...structuredClone(request.replay),\n\t\t\tresult: this.#file(request.replay.result),\n\t\t}\n\t\tconst source = await readStudyResult(selection.result)\n\t\tif (source.status !== 'sealed') throw new StudyError('CUSTODY', 'Replay source is not sealed')\n\t\tconst closure = request.closure === undefined ? undefined : this.#closure(request)\n\t\tconst root = closure?.root ?? this.#root\n\t\tconst entry = closure?.entry ?? this.#entry\n\t\tconst { bundle, definition, scenarios, fixtures } = await readStudyDeclaration(\n\t\t\troot,\n\t\t\trequest.target,\n\t\t\tsignal,\n\t\t)\n\t\tconst bytes = await readStudyDeclarationBytes(\n\t\t\troot,\n\t\t\tresolveStudyPath(bundle, `profiles/${request.profile}.json`),\n\t\t)\n\t\tconst profile = resolveStudyProfile(\n\t\t\troot,\n\t\t\tparseStudyProfile(decodeStudyJSON(bytes)),\n\t\t\tclosure?.closure,\n\t\t)\n\t\tconst schedule = buildStudySchedule(definition, scenarios)\n\t\tif (\n\t\t\tcanonicalStringify(definition) !== canonicalStringify(source.manifest.definition) ||\n\t\t\tcanonicalStringify(scenarios) !== canonicalStringify(source.manifest.scenarios) ||\n\t\t\tcanonicalStringify(schedule) !== canonicalStringify(source.manifest.schedule) ||\n\t\t\tcomputeStudyFixtureDigest(definition, fixtures) !== source.manifest.identity.fixtures ||\n\t\t\tObject.keys(selection.prefix).length !== schedule.length ||\n\t\t\t!schedule.every((trial) => Object.hasOwn(selection.prefix, trial.id))\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Replay declaration or scheduled membership changed')\n\t\tfor (const trial of schedule) {\n\t\t\tsignal.throwIfAborted()\n\t\t\tawait readStudyReplayHistory(selection, profile, trial)\n\t\t}\n\t\tconst artifacts = new StudyArtifactLoader({\n\t\t\troot,\n\t\t\tentry,\n\t\t\tprofile,\n\t\t\tadapter: join(bundle, 'index.ts'),\n\t\t\t...(closure === undefined ? {} : { closure }),\n\t\t})\n\t\tconst selected = await artifacts.inspect()\n\t\tconst identity = {\n\t\t\t...selected,\n\t\t\tfixtures: computeStudyFixtureDigest(definition, fixtures),\n\t\t\tprofile: computeStudyProfileDigest(profile),\n\t\t}\n\t\tif (\n\t\t\tselected.agent !== source.manifest.identity.agent ||\n\t\t\tselected.subject !== source.manifest.identity.subject ||\n\t\t\tselected.instrument !== source.manifest.identity.instrument ||\n\t\t\tselected.provider !== source.manifest.identity.provider\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Replay artifact declaration changed')\n\t\tif (\n\t\t\trequest.expected !== undefined &&\n\t\t\trequest.expected !== computeStudyCommandFingerprint(identity, profile.bounds, definition)\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Replay execution bounds or declaration changed after check')\n\t\tartifacts.verify()\n\t\treturn selection\n\t}\n\n\tasync #grade(request: StudyGradeRequest, signal: AbortSignal): Promise<JSONValue> {\n\t\tconst result = await this.#result(request.target)\n\t\tconst bytes = await readStudyBytes(this.#file(request.rubric), STUDY_CUSTODY_BYTES)\n\t\tconst rubric = parseStudyRubric(decodeStudyJSON(bytes))\n\t\tconst evidence = await collectStudyEvidence(result)\n\t\tsignal.throwIfAborted()\n\t\tconst roots = parseJSON(result.manifest.host.roots ?? '')\n\t\tif (!arrayOf(isString)(roots))\n\t\t\tthrow new StudyError('CONFIG', 'Execution does not retain adapter dependency roots')\n\t\tconst evaluated = await new StudyTask({\n\t\t\troot: this.#root,\n\t\t\tentry: this.#entry,\n\t\t\tadapter: join(\n\t\t\t\tresolveStudyPath(join(this.#root, 'studies'), result.manifest.definition.driver),\n\t\t\t\t'index.ts',\n\t\t\t),\n\t\t\troots,\n\t\t}).execute(\n\t\t\t{\n\t\t\t\toperation: 'grade',\n\t\t\t\tinput: { manifest: result.manifest, rubric, attempts: result.attempts, evidence },\n\t\t\t},\n\t\t\tsignal,\n\t\t)\n\t\tconst judgments: unknown = evaluated.value\n\t\tif (!isArray(judgments) || !judgments.every(isStudyJudgment))\n\t\t\tthrow new StudyError('FAULT', 'Grader returned invalid judgments')\n\t\tconst digest = hashStudyBytes(bytes)\n\t\tconst packet = buildStudyPacket(result, rubric, digest)\n\t\tconst grading: StudyGrading = {\n\t\t\tresult: result.seal.id,\n\t\t\trubric: digest,\n\t\t\tgrader: STUDY_COMMAND_GRADER,\n\t\t\tinstrument: evaluated.instrument,\n\t\t\tattempts: result.manifest.schedule.map((trial) => trial.id),\n\t\t\tlabels: undefined,\n\t\t\tjudgments,\n\t\t\t...(packet === undefined ? {} : { packet: computeStudyPacketDigest(packet) }),\n\t\t}\n\t\tconst store = new StudyGradingStore({\n\t\t\tresult,\n\t\t\trubric: bytes,\n\t\t\t...(packet === undefined ? {} : { packet }),\n\t\t})\n\t\tconst id = await store.write(grading)\n\t\treturn valueToWire({\n\t\t\tcommand: 'grade',\n\t\t\tresult: result.manifest.id,\n\t\t\tgrading: id,\n\t\t\tnext: ['report', result.directory, '--grading', id],\n\t\t\t...(packet === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tpacket: {\n\t\t\t\t\t\t\tid: hashStudyBytes(packet.content),\n\t\t\t\t\t\t\tpath: join(result.directory, 'grades', id, `${grading.packet}.packet.json`),\n\t\t\t\t\t\t\tdisclosure: STUDY_PACKET_DISCLOSURE,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t})\n\t}\n\n\tasync #label(request: StudyLabelRequest, signal: AbortSignal): Promise<JSONValue> {\n\t\tconst result = await this.#result(request.target)\n\t\tconst previous = await this.#grading(result, request.grading)\n\t\tif (previous.packet === undefined || previous.grading.packet === undefined)\n\t\t\tthrow new StudyError('EVIDENCE', 'Selected grading has no semantic packet')\n\t\tconst bytes = await readStudyBytes(this.#file(request.labels), STUDY_CUSTODY_BYTES)\n\t\tconst labels = parseStudyLabeling(decodeStudyJSON(bytes))\n\t\tconst translated = translateStudyPacketLabeling(\n\t\t\tresult,\n\t\t\tprevious.rubric,\n\t\t\tprevious.grading.rubric,\n\t\t\tlabels,\n\t\t)\n\t\tsignal.throwIfAborted()\n\t\tconst grading: StudyGrading = {\n\t\t\t...previous.grading,\n\t\t\t// Binds the preceding grader so equal labels over distinct gradings stay distinct.\n\t\t\tinstrument: hashStudyBytes(\n\t\t\t\tJSON.stringify([previous.grading.instrument, await this.#instrument()]),\n\t\t\t),\n\t\t\tlabels: hashStudyBytes(bytes),\n\t\t\tjudgments: previous.grading.judgments.map((judgment) => {\n\t\t\t\tconst imported = translated.find(\n\t\t\t\t\t(entry) => entry.trial === judgment.trial && entry.criterion === judgment.criterion,\n\t\t\t\t)\n\t\t\t\tif (imported !== undefined) return imported\n\t\t\t\tif (\n\t\t\t\t\tprevious.rubric.criteria.find((criterion) => criterion.id === judgment.criterion)\n\t\t\t\t\t\t?.method !== 'semantic'\n\t\t\t\t)\n\t\t\t\t\treturn judgment\n\t\t\t\treturn {\n\t\t\t\t\t...judgment,\n\t\t\t\t\tverdict: 'unknown',\n\t\t\t\t\tmethod: 'human',\n\t\t\t\t\treason: 'No label in the selected imported packet',\n\t\t\t\t\treferences: [],\n\t\t\t\t}\n\t\t\t}),\n\t\t}\n\t\tconst store = new StudyGradingStore({\n\t\t\tresult,\n\t\t\trubric: previous.bytes,\n\t\t\tlabels: bytes,\n\t\t\tpacket: previous.packet,\n\t\t})\n\t\tconst id = await store.write(grading)\n\t\treturn valueToWire({\n\t\t\tcommand: 'label',\n\t\t\tresult: result.manifest.id,\n\t\t\tprevious: request.grading,\n\t\t\tgrading: id,\n\t\t\tpacket: labels.packet,\n\t\t\tnext: ['report', result.directory, '--grading', id],\n\t\t})\n\t}\n\n\tasync #report(request: StudyReportRequest, signal: AbortSignal): Promise<JSONValue> {\n\t\tconst result = await this.#result(request.target)\n\t\tconst context = await this.#grading(result, request.grading)\n\t\tsignal.throwIfAborted()\n\t\tconst labels =\n\t\t\tcontext.labels === undefined ? undefined : parseStudyLabeling(decodeStudyJSON(context.labels))\n\t\treturn valueToWire({\n\t\t\tcommand: 'report',\n\t\t\tgrading: request.grading,\n\t\t\treport: computeStudyReport(result, context.rubric, context.grading),\n\t\t\tlabeling:\n\t\t\t\tlabels === undefined\n\t\t\t\t\t? { status: 'absent' }\n\t\t\t\t\t: { labeler: labels.labeler, version: labels.version, usage: labels.usage },\n\t\t})\n\t}\n\n\tasync #result(target: string): Promise<StudySealedResult> {\n\t\tconst path = isAbsolute(target)\n\t\t\t? resolve(target)\n\t\t\t: target.includes('/')\n\t\t\t\t? resolveStudyPath(this.#root, target)\n\t\t\t\t: resolveStudyPath(join(this.#root, 'tmp', 'studies'), target)\n\t\tconst result = await readStudyResult(path).catch((error: unknown) => {\n\t\t\tif (matchesSystemError(error, 'ENOENT'))\n\t\t\t\tthrow new StudyError('CUSTODY', `Selected result is missing: ${target}`)\n\t\t\tthrow error\n\t\t})\n\t\tif (result.status !== 'sealed')\n\t\t\tthrow new StudyError('CUSTODY', 'Interrupted execution cannot be graded or reported')\n\t\treturn result\n\t}\n\n\tasync #grading(result: StudySealedResult, id: string): Promise<StudyGradingContext> {\n\t\tconst directory = join(result.directory, 'grades', id)\n\t\tconst raw = await readStudyBytes(join(directory, 'grading.json'), STUDY_CUSTODY_BYTES).catch(\n\t\t\t(error: unknown) => {\n\t\t\t\tif (matchesSystemError(error, 'ENOENT'))\n\t\t\t\t\tthrow new StudyError(\n\t\t\t\t\t\t'CUSTODY',\n\t\t\t\t\t\t`Selected grading is missing: ${join(directory, 'grading.json')}`,\n\t\t\t\t\t)\n\t\t\t\tthrow error\n\t\t\t},\n\t\t)\n\t\tif (hashStudyBytes(raw) !== id)\n\t\t\tthrow new StudyError('CUSTODY', 'Selected grading differs from its byte identity')\n\t\tconst declared = parseStudyGrading(decodeStudyJSON(raw))\n\t\tconst bytes = await readStudyBytes(\n\t\t\tjoin(directory, `${declared.rubric}.rubric.json`),\n\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t)\n\t\tconst rubric = parseStudyRubric(decodeStudyJSON(bytes))\n\t\tconst grading = await new StudyGradingStore({ result, rubric: bytes }).read(id)\n\t\tif (grading === undefined)\n\t\t\tthrow new StudyError('CUSTODY', `Selected grading is missing: ${directory}`)\n\t\tconst packet =\n\t\t\tgrading.packet === undefined\n\t\t\t\t? undefined\n\t\t\t\t: {\n\t\t\t\t\t\tcontent: await readStudyBytes(\n\t\t\t\t\t\t\tjoin(directory, `${grading.packet}.packet.json`),\n\t\t\t\t\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tmapping: await readStudyBytes(\n\t\t\t\t\t\t\tjoin(directory, `${grading.packet}.mapping.json`),\n\t\t\t\t\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t\t\t\t\t),\n\t\t\t\t\t}\n\t\tconst labels =\n\t\t\tgrading.labels === undefined\n\t\t\t\t? undefined\n\t\t\t\t: await readStudyBytes(\n\t\t\t\t\t\tjoin(directory, `${grading.labels}.labels.json`),\n\t\t\t\t\t\tSTUDY_CUSTODY_BYTES,\n\t\t\t\t\t)\n\t\tif (\n\t\t\thashStudyBytes(bytes) !== grading.rubric ||\n\t\t\t(packet !== undefined && computeStudyPacketDigest(packet) !== grading.packet) ||\n\t\t\t(labels !== undefined && hashStudyBytes(labels) !== grading.labels)\n\t\t)\n\t\t\tthrow new StudyError(\n\t\t\t\t'CUSTODY',\n\t\t\t\t'Grading artifacts changed while reading their verified context',\n\t\t\t)\n\t\treturn { grading, rubric, bytes, packet, labels }\n\t}\n\n\t#file(path: string): string {\n\t\treturn isAbsolute(path) ? resolve(path) : resolveStudyPath(this.#root, path)\n\t}\n\n\t#temporary(): Promise<string> {\n\t\treturn ['tmp', 'studies'].reduce(async (previous, name) => {\n\t\t\tconst directory = join(await previous, name)\n\t\t\ttry {\n\t\t\t\tawait mkdir(directory)\n\t\t\t} catch (error) {\n\t\t\t\tif (!matchesSystemError(error, 'EEXIST')) throw error\n\t\t\t}\n\t\t\treturn checkStudyDirectory(directory)\n\t\t}, checkStudyDirectory(this.#root))\n\t}\n\n\tasync #qualification(preparation: StudyPreparation): Promise<string | undefined> {\n\t\tif (\n\t\t\tpreparation.profile.qualification === undefined ||\n\t\t\tpreparation.definition.purpose === 'capacity'\n\t\t)\n\t\t\treturn undefined\n\t\tconst result = await this.#result(preparation.profile.qualification)\n\t\tif (\n\t\t\tresult.manifest.definition.purpose !== 'capacity' ||\n\t\t\thashStudyBytes(encodeStudyJSON(result.manifest.identity)) !==\n\t\t\t\thashStudyBytes(encodeStudyJSON(preparation.identity)) ||\n\t\t\thashStudyBytes(encodeStudyJSON(result.manifest.bounds)) !==\n\t\t\t\thashStudyBytes(encodeStudyJSON(preparation.profile.bounds)) ||\n\t\t\thashStudyBytes(encodeStudyJSON(result.manifest.schedule)) !==\n\t\t\t\thashStudyBytes(\n\t\t\t\t\tencodeStudyJSON(buildStudySchedule(preparation.definition, preparation.scenarios)),\n\t\t\t\t) ||\n\t\t\thashStudyBytes(encodeStudyJSON(result.manifest.scenarios)) !==\n\t\t\t\thashStudyBytes(encodeStudyJSON(preparation.scenarios)) ||\n\t\t\tresult.attempts.some(\n\t\t\t\t(attempt) =>\n\t\t\t\t\tattempt.failure !== undefined ||\n\t\t\t\t\tattempt.observations.some(\n\t\t\t\t\t\t(observation) => observation.failure !== undefined || observation.product === undefined,\n\t\t\t\t\t),\n\t\t\t)\n\t\t)\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'Qualification requires a compatible complete capacity result with no operational failures',\n\t\t\t)\n\t\treturn result.seal.id\n\t}\n\n\tasync #instrument(): Promise<string> {\n\t\treturn computeStudyInstrumentDigest(\n\t\t\thashStudyBytes(await readStudyBytes(this.#entry, STUDY_CUSTODY_BYTES)),\n\t\t\tnew ArtifactLoader({\n\t\t\t\tentries: [this.#entry],\n\t\t\t\troots: [resolveStudyInstrument(this.#entry)],\n\t\t\t}).inspect().digest,\n\t\t)\n\t}\n}\n","import type { StudyFailure, StudyTicket, StudyUsage } from '@src/core'\nimport type { StudyRemoteTicketOptions } from './types.js'\nimport { StudyError } from '@src/core'\n\n/** Transmits one settlement without inventing local admission authority. */\nexport class StudyRemoteTicket implements StudyTicket {\n\t#options: StudyRemoteTicketOptions\n\t#settled = false\n\n\t/** Owns the parent's ticket identity and composed cancellation.\n\t * @param options - Transported ticket state and settlement callback, snapshotted at construction.\n\t */\n\tconstructor(options: StudyRemoteTicketOptions) {\n\t\tthis.#options = { ...options }\n\t}\n\tget signal(): AbortSignal {\n\t\treturn this.#options.signal\n\t}\n\tget settled(): boolean {\n\t\treturn this.#settled\n\t}\n\n\t/** Sends actual usage for authoritative parent settlement.\n\t * @param usage - Actual measured request usage.\n\t */\n\tfinish(usage: StudyUsage): void {\n\t\tthis.#settle('finish', usage)\n\t}\n\n\t/** Sends operational failure while preserving unknown actual cost.\n\t * @param failure - The first observed request failure.\n\t */\n\tfail(failure: StudyFailure): void {\n\t\tthis.#settle('fail', failure)\n\t}\n\n\t#settle(operation: 'finish' | 'fail', value: StudyUsage | StudyFailure): void {\n\t\tif (this.#settled) {\n\t\t\tthis.#options.settle('fail', {\n\t\t\t\tcause: 'infrastructure',\n\t\t\t\tmessage: 'Worker ticket settled more than once',\n\t\t\t\trole: undefined,\n\t\t\t\tstop: undefined,\n\t\t\t})\n\t\t\tthrow new StudyError('FAULT', 'Worker ticket settled more than once')\n\t\t}\n\t\tthis.#settled = true\n\t\tthis.#options.settle(operation, value)\n\t}\n}\n","import type { StudyCharge, StudyFailure, StudyTicket, StudyUsage } from '@src/core'\nimport type { StudyRemoteMeterInterface, StudyRemoteMeterOptions } from './types.js'\nimport { failureToStudyError, readStudyFailure, StudyError, isStudyUsage } from '@src/core'\nimport { isRecord } from '@orkestrel/contract'\nimport { createStudyProcessFailure, valueToWire } from './helpers.js'\nimport { StudyRemoteTicket } from './StudyRemoteTicket.js'\nimport { isStudyProcessFailure } from './validators.js'\n\n/** Waits for authoritative parent admission and drains acknowledged settlements. */\nexport class StudyRemoteMeter implements StudyRemoteMeterInterface {\n\t#options: StudyRemoteMeterOptions\n\t#next = 0\n\t#admissions = 0\n\treadonly #tickets = new Map<number, AbortController>()\n\treadonly #pending = new Set<Promise<void>>()\n\t#usage: StudyUsage[] = []\n\t#closed = false\n\n\t/** Owns one goal's transported tickets without local budget decisions.\n\t * @param options - Parent transport and shared worker failure control, snapshotted at construction.\n\t */\n\tconstructor(options: StudyRemoteMeterOptions) {\n\t\tthis.#options = { ...options }\n\t}\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/** Requests and awaits the parent's dispatch grant.\n\t * @param charge - Upper bounds that the parent reserves before replying.\n\t * @returns A ticket only after authoritative admission succeeds.\n\t */\n\tasync admit(charge: StudyCharge): Promise<StudyTicket> {\n\t\tif (this.#closed || this.#options.control.failure !== undefined)\n\t\t\tthrow failureToStudyError(\n\t\t\t\tthis.#options.control.failure ?? createStudyProcessFailure('Worker meter is closed'),\n\t\t\t)\n\t\tconst id = ++this.#next\n\t\tthis.#admissions++\n\t\ttry {\n\t\t\tconst response = await this.#options.control.wait(\n\t\t\t\tthis.#options.channel.request('admit', valueToWire({ id, charge })),\n\t\t\t)\n\t\t\tif (!isRecord(response) || response.id !== id)\n\t\t\t\tthrow new StudyError('FAULT', 'Worker admission grant is invalid')\n\t\t\tif (this.#closed) throw new StudyError('FAULT', 'Worker goal ended during admission')\n\t\t\tconst controller = new AbortController()\n\t\t\tthis.#tickets.set(id, controller)\n\t\t\treturn new StudyRemoteTicket({\n\t\t\t\tid,\n\t\t\t\tsignal: AbortSignal.any([controller.signal, this.signal]),\n\t\t\t\tsettle: (operation, value) => this.#settle(id, operation, value),\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthis.#options.control.fail(readStudyFailure(error))\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tthis.#admissions--\n\t\t}\n\t}\n\n\t/** Propagates the parent's ticket cancellation without changing its cause.\n\t * @param id - Parent-issued ticket identity.\n\t * @param failure - Authoritative parent attribution.\n\t */\n\tabort(id: number, failure: StudyFailure): void {\n\t\tconst ticket = this.#tickets.get(id)\n\t\tif (ticket === undefined)\n\t\t\tthrow new StudyError('FAULT', 'Cancellation names an unknown worker ticket')\n\t\tticket.abort(failureToStudyError(failure))\n\t\tthis.#options.control.fail(failure)\n\t}\n\n\t/** Closes admission and requires every ticket and acknowledgment to finish. */\n\tasync close(): Promise<void> {\n\t\tthis.#closed = true\n\t\tif (this.#tickets.size !== 0 || this.#admissions !== 0)\n\t\t\tthis.#options.control.fail(\n\t\t\t\tcreateStudyProcessFailure('Worker goal ended with unfinished requests'),\n\t\t\t)\n\t\tawait Promise.all(this.#pending)\n\t\tif (this.#options.control.failure !== undefined)\n\t\t\tthrow failureToStudyError(this.#options.control.failure)\n\t}\n\n\t#settle(id: number, operation: 'finish' | 'fail', value: StudyUsage | StudyFailure): void {\n\t\tif (!this.#tickets.delete(id)) {\n\t\t\tthis.#options.control.fail(\n\t\t\t\tcreateStudyProcessFailure('Worker ticket settlement is repeated or foreign'),\n\t\t\t)\n\t\t\tthrow failureToStudyError(\n\t\t\t\tthis.#options.control.failure ?? createStudyProcessFailure('Worker settlement failed'),\n\t\t\t)\n\t\t}\n\t\tconst accepted = Object.freeze({ ...value })\n\t\tconst work = this.#options.channel\n\t\t\t.request(\n\t\t\t\toperation,\n\t\t\t\tvalueToWire(operation === 'finish' ? { id, usage: accepted } : { id, failure: accepted }),\n\t\t\t)\n\t\t\t.then(\n\t\t\t\t() => {\n\t\t\t\t\tif (operation === 'finish' && isStudyUsage(accepted)) this.#usage.push(accepted)\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tthis.#options.control.fail(readStudyFailure(error))\n\t\t\t\t},\n\t\t\t)\n\t\tthis.#pending.add(work)\n\t\tvoid work.finally(() => this.#pending.delete(work))\n\t\tif (operation === 'fail' && isStudyProcessFailure(accepted))\n\t\t\tthis.#options.control.fail(accepted)\n\t}\n}\n","import type { StudyRole } from '@src/core'\nimport type {\n\tStudyOllamaFetchFunction,\n\tStudyOllamaReplayInterface,\n\tStudyOllamaReplayOptions,\n\tStudyOllamaStep,\n} from './types.js'\nimport { StudyError } from '@src/core'\nimport { validateStudyExchangeHistory } from '../stores/helpers.js'\nimport { isStudyOllamaMetadata } from './validators.js'\n\n/** Answers declared HTTP prefixes from complete ordered recorded application bytes. */\nexport class StudyOllamaReplay implements StudyOllamaReplayInterface {\n\treadonly #options: StudyOllamaReplayOptions\n\treadonly #readers = new Set<ReadableStream<Uint8Array>>()\n\treadonly #pending = new Set<Promise<Response>>()\n\treadonly #started = performance.now()\n\t#cursor: number\n\t#bytes = 0\n\t#calls = 0\n\t#fault: { readonly error: unknown } | undefined\n\t#closed = false\n\treadonly #procedure: readonly StudyOllamaStep[]\n\n\t/** Owns and revalidates the complete selected history before any sender can be reached.\n\t * @param options - Verified history, explicit prefix, executing origin and independent bounds.\n\t */\n\tconstructor(options: StudyOllamaReplayOptions) {\n\t\tconst { signal, fetch, ...configuration } = options\n\t\tconst owned = structuredClone(configuration)\n\t\tvalidateStudyExchangeHistory(owned.history)\n\t\tconst url = new URL(owned.url)\n\t\tif (\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\t!Number.isSafeInteger(owned.prefix) ||\n\t\t\towned.prefix <= 0 ||\n\t\t\towned.prefix > owned.history.exchanges.length ||\n\t\t\t(fetch === undefined && owned.prefix !== owned.history.exchanges.length) ||\n\t\t\t(fetch !== undefined && typeof fetch !== 'function') ||\n\t\t\t!isStudyOllamaMetadata(owned.limit)\n\t\t)\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'Replay requires an explicit valid origin, prefix and current bounds',\n\t\t\t)\n\t\tif (owned.prefix < owned.history.declaration.maintenance.length)\n\t\t\tthrow new StudyError('CONFIG', 'Replay prefix omits recorded maintenance')\n\t\tsignal.throwIfAborted()\n\t\tthis.#options = { ...owned, signal, ...(fetch === undefined ? {} : { fetch }) }\n\t\tthis.#cursor = owned.history.declaration.maintenance.length\n\t\tthis.#procedure = owned.history.declaration.procedure.map((step) => {\n\t\t\tconst pair = owned.history.exchanges.find(\n\t\t\t\t(entry) => entry.attempt.step === step.ordinal && entry.attempt.ordinal <= owned.prefix,\n\t\t\t)\n\t\t\tif (pair === undefined) return step\n\t\t\tconst { admission: _admission, ...identity } = step\n\t\t\tconst { bytes: _bytes, ...exact } = identity\n\t\t\treturn {\n\t\t\t\t...exact,\n\t\t\t\tadmission: 'exact',\n\t\t\t\tbody: new TextDecoder('utf-8', { fatal: true }).decode(\n\t\t\t\t\tBuffer.from(pair.attempt.body, 'base64'),\n\t\t\t\t),\n\t\t\t\tinput: pair.attempt.digest,\n\t\t\t}\n\t\t})\n\t}\n\n\t/** Holds exact recorded bodies for model requests inside the declared prefix. */\n\tget procedure(): readonly StudyOllamaStep[] {\n\t\treturn structuredClone(this.#procedure)\n\t}\n\n\t/** Supplies recorded native responses, forwarding only after the exact declared prefix.\n\t * @param role - The validated Study responsibility.\n\t * @param input - The executing origin and exact route.\n\t * @param init - The method, encoded body and bounded signal.\n\t * @returns The recorded response or the explicit live collaborator's response.\n\t */\n\treadonly fetch: StudyOllamaFetchFunction = (role, input, init) => {\n\t\tif (\n\t\t\tthis.#closed ||\n\t\t\tthis.#fault !== undefined ||\n\t\t\tthis.#pending.size !== 0 ||\n\t\t\tthis.#readers.size !== 0\n\t\t) {\n\t\t\tconst error =\n\t\t\t\tthis.#fault?.error ??\n\t\t\t\tnew StudyError(\n\t\t\t\t\t'FAULT',\n\t\t\t\t\t'Replay request is closed, concurrent or follows an unread response',\n\t\t\t\t)\n\t\t\tthis.#fault ??= { error }\n\t\t\treturn Promise.reject(error)\n\t\t}\n\t\tconst pending = this.#fetch(role, input, init).catch((error: unknown) => {\n\t\t\tthis.#fault ??= { error }\n\t\t\tthrow error\n\t\t})\n\t\tthis.#pending.add(pending)\n\t\tvoid pending.then(\n\t\t\t() => this.#pending.delete(pending),\n\t\t\t() => this.#pending.delete(pending),\n\t\t)\n\t\treturn pending\n\t}\n\n\t/** Refuses a mismatch, an unread response or an incompletely consumed prefix. */\n\tcheck(): void {\n\t\tif (this.#fault !== undefined) throw this.#fault.error\n\t\tthis.#options.signal.throwIfAborted()\n\t\tif (this.#cursor < this.#options.prefix || this.#readers.size !== 0 || this.#pending.size !== 0)\n\t\t\tthrow new StudyError('FAULT', 'Replay prefix is incomplete or still being read')\n\t}\n\n\t/** Closes admission and cancels retained replay responses.\n\t * @returns Completion after pending sends and owned readers settle.\n\t */\n\tasync close(): Promise<void> {\n\t\tthis.#closed = true\n\t\tawait Promise.allSettled([...this.#readers].map((reader) => reader.cancel()))\n\t\tthis.#readers.clear()\n\t\tawait Promise.allSettled([...this.#pending])\n\t}\n\n\tasync #fetch(role: StudyRole, input: string | URL, init: RequestInit): Promise<Response> {\n\t\tthis.#options.signal.throwIfAborted()\n\t\tinit.signal?.throwIfAborted()\n\t\tif (this.#cursor >= this.#options.prefix) {\n\t\t\tif (this.#options.fetch === undefined)\n\t\t\t\tthrow new StudyError('FAULT', 'Offline replay has no later sender')\n\t\t\treturn this.#options.fetch(role, input, init)\n\t\t}\n\t\tconst pair = this.#options.history.exchanges[this.#cursor]\n\t\tconst url = new URL(input)\n\t\tconst request = new Request(url, init)\n\t\tconst body = Buffer.from(await request.arrayBuffer())\n\t\tif (\n\t\t\tpair === undefined ||\n\t\t\turl.origin !== new URL(this.#options.url).origin ||\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 !== pair.attempt.path ||\n\t\t\trequest.method !== pair.attempt.method ||\n\t\t\trole !== pair.attempt.role ||\n\t\t\t!body.equals(Buffer.from(pair.attempt.body, 'base64'))\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Replay request differs from the next recorded exchange')\n\t\tthis.#calls += 1\n\t\tthis.#bytes += body.length + pair.response.size\n\t\tif (this.#calls > this.#options.limit.calls || this.#bytes > this.#options.limit.bytes)\n\t\t\tthrow new StudyError('CAPACITY', 'Replay exceeds the executing allowance')\n\t\tif (performance.now() - this.#started >= this.#options.limit.duration)\n\t\t\tthrow new StudyError('DEADLINE', 'Replay exceeds the executing duration')\n\t\tthis.#cursor += 1\n\t\tconst bytes = Buffer.from(pair.response.body, 'base64')\n\t\tconst chunks = pair.response.chunks.map((size, index, sizes) => {\n\t\t\tconst offset = sizes.slice(0, index).reduce((total, length) => total + length, 0)\n\t\t\treturn bytes.subarray(offset, offset + size)\n\t\t})\n\t\tconst source = chunks.values()\n\t\tconst stream = new ReadableStream<Uint8Array>(\n\t\t\t{\n\t\t\t\tpull: (controller) => {\n\t\t\t\t\tif (this.#options.signal.aborted || init.signal?.aborted || this.#closed) {\n\t\t\t\t\t\tconst error =\n\t\t\t\t\t\t\tthis.#options.signal.reason ??\n\t\t\t\t\t\t\tinit.signal?.reason ??\n\t\t\t\t\t\t\tnew StudyError('FAULT', 'Replay response was closed')\n\t\t\t\t\t\tthis.#fault ??= { error }\n\t\t\t\t\t\tthis.#readers.delete(stream)\n\t\t\t\t\t\tcontroller.error(error)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tconst chunk = source.next()\n\t\t\t\t\tif (chunk.done) {\n\t\t\t\t\t\tcontroller.close()\n\t\t\t\t\t\tthis.#readers.delete(stream)\n\t\t\t\t\t} else controller.enqueue(chunk.value)\n\t\t\t\t},\n\t\t\t\tcancel: () => {\n\t\t\t\t\tthis.#readers.delete(stream)\n\t\t\t\t\tthis.#fault ??= { error: new StudyError('FAULT', 'Replay response was abandoned') }\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ highWaterMark: 0 },\n\t\t)\n\t\tthis.#readers.add(stream)\n\t\treturn new Response(stream, {\n\t\t\tstatus: pair.response.status,\n\t\t\theaders: pair.response.headers\n\t\t\t\t.filter(([name]) => name !== 'content-encoding')\n\t\t\t\t.map(([name, value]): [string, string] => [name, value]),\n\t\t})\n\t}\n}\n","import type { StudyRole, StudySessionInterface } from '@src/core'\nimport type { StudyOperation } from './types.js'\nimport type { StudyExchangeSinkInterface, StudyExchangeRow } from '../stores/types.js'\nimport type { StudyOllamaReplayInterface } from '../ollama/types.js'\nimport type { JSONValue } from '@orkestrel/contract'\nimport {\n\tStudyControl,\n\tStudyDeadline,\n\tfailureToStudyError,\n\treadStudyFailure,\n\tStudyError,\n\tisStudyGoal,\n\tisStudyProduct,\n\tisStudyProfile,\n} from '@src/core'\nimport { canonicalStringify, isRecord } from '@orkestrel/contract'\nimport { open } from 'node:fs/promises'\nimport { STUDY_PROCESS_LABEL } from './constants.js'\nimport {\n\tcomputeStudyProfileDigest,\n\tcreateStudyProcessFailure,\n\treadStudyRecordingDeclaration,\n\treadStudyReplayHistory,\n\tvalueToWire,\n} from './helpers.js'\nimport { readStudyBytes, readStudyExchangeRows } from '../stores/helpers.js'\nimport { hashStudyBytes } from '../helpers.js'\nimport { StudyExchangeSink } from '../stores/StudyExchangeSink.js'\nimport { StudyOllamaReplay } from '../ollama/StudyOllamaReplay.js'\nimport { isStudyClosure } from '../commands/validators.js'\nimport { StudyArtifactLoader } from './StudyArtifactLoader.js'\nimport { StudyChannel } from './StudyChannel.js'\nimport { StudyRemoteMeter } from './StudyRemoteMeter.js'\nimport {\n\tisStudyExchangeDestination,\n\tisStudyReplaySelection,\n\tisStudyIdentity,\n\tisStudyProcessFailure,\n\tisStudyTrial,\n} from './validators.js'\n\n/** Executes one verified trial behind parent-authorized admission and custody. */\nexport class StudyWorker {\n\t#control = new StudyControl()\n\t#channel: StudyChannel | undefined\n\t#artifacts: StudyArtifactLoader | undefined\n\t#session: StudySessionInterface | undefined\n\treadonly #meters = new Set<StudyRemoteMeter>()\n\t#opening = false\n\t#closing = false\n\t#duration = 1000\n\t#executed = false\n\t#exchanges: StudyExchangeSinkInterface | undefined\n\t#replay: StudyOllamaReplayInterface | undefined\n\t#maintenance: readonly StudyExchangeRow[] = []\n\treadonly #evidence = new Set<Promise<void>>()\n\n\t/** Serves the inherited IPC channel until its parent disconnects.\n\t * @returns Completion after channel and acquired session cleanup.\n\t */\n\tasync execute(): Promise<void> {\n\t\tif (this.#executed || process.send === undefined || !process.connected)\n\t\t\tthrow new StudyError('CONFIG', 'Study worker requires one inherited IPC channel')\n\t\tthis.#executed = true\n\t\tthis.#channel = new StudyChannel({\n\t\t\tendpoint: process,\n\t\t\thandle: (operation, value) => this.#handle(operation, value),\n\t\t\tabort: (value) => this.#abort(value),\n\t\t})\n\t\ttry {\n\t\t\tawait new Promise<void>((resolve) =>\n\t\t\t\tthis.#channel?.signal.addEventListener('abort', () => resolve(), { once: true }),\n\t\t\t)\n\t\t} finally {\n\t\t\tthis.#control.fail(createStudyProcessFailure('Study worker disconnected'))\n\t\t\tif (this.#session !== undefined)\n\t\t\t\tawait new StudyDeadline({ duration: this.#duration, label: STUDY_PROCESS_LABEL })\n\t\t\t\t\t.wait(this.#session.close())\n\t\t\t\t\t.catch(() => undefined)\n\t\t\tthis.#session = undefined\n\t\t\tawait Promise.allSettled([this.#exchanges?.close(), this.#replay?.close()])\n\t\t\tthis.#channel.close()\n\t\t\tthis.#control.close()\n\t\t}\n\t}\n\n\tasync #handle(operation: StudyOperation, value: JSONValue): Promise<JSONValue> {\n\t\ttry {\n\t\t\tif (operation === 'open') return await this.#open(value)\n\t\t\tif (operation === 'goal') return await this.#goal(value)\n\t\t\tif (operation === 'close') {\n\t\t\t\tif (this.#closing) throw new StudyError('FAULT', 'Worker cleanup repeated')\n\t\t\t\tthis.#closing = true\n\t\t\t\tif (this.#meters.size !== 0 || this.#control.failure !== undefined)\n\t\t\t\t\tthis.#control.fail({\n\t\t\t\t\t\tcause: 'interrupted',\n\t\t\t\t\t\tmessage: 'Worker cleanup requested',\n\t\t\t\t\t\trole: undefined,\n\t\t\t\t\t\tstop: undefined,\n\t\t\t\t\t})\n\t\t\t\tif (this.#session !== undefined)\n\t\t\t\t\tawait new StudyDeadline({ duration: this.#duration, label: STUDY_PROCESS_LABEL }).wait(\n\t\t\t\t\t\tthis.#session.close(),\n\t\t\t\t\t)\n\t\t\t\tthis.#session = undefined\n\t\t\t\ttry {\n\t\t\t\t\tthis.#replay?.check()\n\t\t\t\t} finally {\n\t\t\t\t\tawait this.#replay?.close()\n\t\t\t\t\tawait this.#exchanges?.close()\n\t\t\t\t}\n\t\t\t\tthis.#artifacts?.verify()\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tthrow new StudyError('FAULT', 'Parent requested a forbidden worker operation')\n\t\t} catch (error) {\n\t\t\tthis.#control.fail(readStudyFailure(error))\n\t\t\tthrow error\n\t\t}\n\t}\n\n\tasync #open(value: JSONValue): Promise<JSONValue> {\n\t\tif (this.#opening || this.#closing || this.#control.failure !== undefined)\n\t\t\tthrow new StudyError('FAULT', 'Worker trial can open only once')\n\t\tthis.#opening = true\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\ttypeof value.entry !== 'string' ||\n\t\t\ttypeof value.root !== 'string' ||\n\t\t\ttypeof value.directory !== 'string' ||\n\t\t\ttypeof value.driver !== 'string' ||\n\t\t\ttypeof value.adapter !== 'string' ||\n\t\t\t!isStudyProfile(value.profile) ||\n\t\t\t!isStudyIdentity(value.identity) ||\n\t\t\t!isStudyTrial(value.trial)\n\t\t)\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'Worker opening declaration is invalid or driver is unsupported',\n\t\t\t)\n\t\tthis.#duration = value.profile.bounds.request.duration\n\t\tif (value.closure !== undefined && !isStudyClosure(value.closure))\n\t\t\tthrow new StudyError('CONFIG', 'Worker closure selection is malformed')\n\t\tif (value.replay !== undefined) {\n\t\t\tif (!isStudyReplaySelection(value.replay) || value.profile.provider === undefined)\n\t\t\t\tthrow new StudyError('CONFIG', 'Worker replay selection is invalid')\n\t\t\tconst history = await readStudyReplayHistory(value.replay, value.profile, value.trial)\n\t\t\tconst prefix = value.replay.prefix[value.trial.id]\n\t\t\tif (prefix === undefined) throw new StudyError('CONFIG', 'Worker replay prefix is absent')\n\t\t\tthis.#replay = new StudyOllamaReplay({\n\t\t\t\thistory,\n\t\t\t\tprefix,\n\t\t\t\turl: value.profile.provider.url,\n\t\t\t\tlimit: readStudyRecordingDeclaration(value.profile, value.trial).metadata,\n\t\t\t\tsignal: this.#control.signal,\n\t\t\t\t...(value.replay.offline ? {} : { fetch: this.#forward.bind(this) }),\n\t\t\t})\n\t\t}\n\t\tconst destination = isRecord(value.exchanges) ? value.exchanges[value.trial.id] : undefined\n\t\tif (value.profile.record === undefined && destination !== undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Unrecorded worker received a sidecar')\n\t\tif (value.profile.record !== undefined) {\n\t\t\tif (\n\t\t\t\t!isStudyExchangeDestination(destination) ||\n\t\t\t\tdestination.record.bytes !== value.profile.record.bytes\n\t\t\t)\n\t\t\t\tthrow new StudyError('CONFIG', 'Recorded worker has no matching reserved sidecar')\n\t\t\tconst declaration = readStudyRecordingDeclaration(value.profile, value.trial)\n\t\t\tconst retained =\n\t\t\t\tdestination.retained === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: await readStudyBytes(destination.path, destination.record.bytes)\n\t\t\tif (\n\t\t\t\tretained !== undefined &&\n\t\t\t\t(hashStudyBytes(retained) !== destination.retained?.digest ||\n\t\t\t\t\tretained.length !== destination.retained.bytes ||\n\t\t\t\t\tdestination.retained.path !== `trials/${value.trial.id}/exchanges.jsonl`)\n\t\t\t)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Maintenance prefix changed before worker opening')\n\t\t\tconst rows = retained === undefined ? undefined : readStudyExchangeRows(retained, false)\n\t\t\tif (\n\t\t\t\trows !== undefined &&\n\t\t\t\t(rows[0]?.phase !== 'declaration' ||\n\t\t\t\t\trows[0].trial !== value.trial.id ||\n\t\t\t\t\trows.some(\n\t\t\t\t\t\t(row) =>\n\t\t\t\t\t\t\trow.phase !== 'declaration' &&\n\t\t\t\t\t\t\t((row.phase !== 'attempt' && row.phase !== 'response') ||\n\t\t\t\t\t\t\t\trow.stage !== 'maintenance'),\n\t\t\t\t\t) ||\n\t\t\t\t\trows.at(-1)?.phase !== 'response')\n\t\t\t)\n\t\t\t\tthrow new StudyError('CUSTODY', 'Retained prefix is not completed maintenance')\n\t\t\tif (rows !== undefined && rows[0]?.phase === 'declaration') {\n\t\t\t\tconst { maintenance: _retainedMaintenance, ...opening } = rows[0]\n\t\t\t\tconst { maintenance: _maintenance, ...expected } = declaration\n\t\t\t\tif (\n\t\t\t\t\tcanonicalStringify(opening) !== canonicalStringify(expected) ||\n\t\t\t\t\trows.filter((row) => row.phase === 'response').length !== rows[0].maintenance.length\n\t\t\t\t)\n\t\t\t\t\tthrow new StudyError(\n\t\t\t\t\t\t'CUSTODY',\n\t\t\t\t\t\t'Retained maintenance declaration differs from the executing profile',\n\t\t\t\t\t)\n\t\t\t}\n\t\t\tconst file = await open(destination.path, rows === undefined ? 'wx' : 'a')\n\t\t\ttry {\n\t\t\t\tthis.#exchanges = new StudyExchangeSink({\n\t\t\t\t\tfile,\n\t\t\t\t\trecord: destination.record,\n\t\t\t\t\t...(rows === undefined ? {} : { retained: rows }),\n\t\t\t\t})\n\t\t\t} catch (error) {\n\t\t\t\tawait file.close()\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tif (rows === undefined)\n\t\t\t\tawait this.#exchanges.append({\n\t\t\t\t\t...declaration,\n\t\t\t\t\tprocedure: this.#replay?.procedure ?? declaration.procedure,\n\t\t\t\t})\n\t\t\telse this.#maintenance = rows\n\t\t}\n\t\tthis.#artifacts = new StudyArtifactLoader({\n\t\t\tentry: value.entry,\n\t\t\troot: value.root,\n\t\t\tprofile: value.profile,\n\t\t\tadapter: value.adapter,\n\t\t\t...(value.closure === undefined ? {} : { closure: value.closure }),\n\t\t})\n\t\tconst identity = await this.#artifacts.inspect()\n\t\tif (\n\t\t\tidentity.agent !== value.identity.agent ||\n\t\t\tidentity.subject !== value.identity.subject ||\n\t\t\tidentity.provider !== value.identity.provider ||\n\t\t\tidentity.instrument !== value.identity.instrument ||\n\t\t\tcomputeStudyProfileDigest(value.profile) !== value.identity.profile\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Worker artifact identity differs from parent declaration')\n\t\tconst modules = await this.#artifacts.load()\n\t\tconst adapter = await this.#artifacts.adapter()\n\t\tconst driver = adapter.driver({\n\t\t\t...modules,\n\t\t\tprofile: value.profile,\n\t\t\tdirectory: value.directory,\n\t\t\t...(this.#exchanges === undefined ? {} : { exchanges: this.#exchanges }),\n\t\t\t...(this.#replay === undefined ? {} : { replay: this.#replay }),\n\t\t})\n\t\tthis.#session = await driver.open(value.trial, this.#control.signal)\n\t\tif (this.#control.failure !== undefined) throw failureToStudyError(this.#control.failure)\n\t\treturn valueToWire({ ...identity, pid: process.pid })\n\t}\n\n\tasync #goal(value: JSONValue): Promise<JSONValue> {\n\t\tif (\n\t\t\tthis.#session === undefined ||\n\t\t\tthis.#channel === undefined ||\n\t\t\tthis.#meters.size !== 0 ||\n\t\t\tthis.#closing ||\n\t\t\tthis.#control.failure !== undefined ||\n\t\t\t!isStudyGoal(value)\n\t\t)\n\t\t\tthrow new StudyError('FAULT', 'Worker goal is invalid or out of order')\n\t\tconst meter = new StudyRemoteMeter({ channel: this.#channel, control: this.#control })\n\t\tthis.#meters.add(meter)\n\t\ttry {\n\t\t\tfor (const row of this.#maintenance) {\n\t\t\t\tif (row.phase === 'attempt' || row.phase === 'response')\n\t\t\t\t\tawait this.#append(\n\t\t\t\t\t\tvalueToWire({\n\t\t\t\t\t\t\tevent: row.phase === 'attempt' ? 'dispatch' : 'wire',\n\t\t\t\t\t\t\tgoal: value.id,\n\t\t\t\t\t\t\tvalue: { ordinal: row.ordinal, role: row.role, path: row.path },\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t}\n\t\t\tthis.#maintenance = []\n\t\t\tconst product = await this.#control.wait(\n\t\t\t\tthis.#session.execute(value, {\n\t\t\t\t\tsignal: this.#control.signal,\n\t\t\t\t\tmeter,\n\t\t\t\t\tevidence: { append: (evidence) => this.#append(valueToWire(evidence)) },\n\t\t\t\t}),\n\t\t\t)\n\t\t\tawait meter.close()\n\t\t\tawait Promise.all(this.#evidence)\n\t\t\tif (this.#control.failure !== undefined) throw failureToStudyError(this.#control.failure)\n\t\t\tif (!isStudyProduct(product))\n\t\t\t\tthrow new StudyError('FAULT', 'Worker driver returned an invalid product')\n\t\t\treturn valueToWire(product)\n\t\t} finally {\n\t\t\tthis.#meters.delete(meter)\n\t\t}\n\t}\n\n\t#append(value: JSONValue): Promise<void> {\n\t\tif (\n\t\t\tthis.#channel === undefined ||\n\t\t\tthis.#meters.size === 0 ||\n\t\t\tthis.#control.failure !== undefined\n\t\t)\n\t\t\treturn Promise.reject(new StudyError('FAULT', 'Worker evidence is outside an active goal'))\n\t\tconst pending = this.#channel\n\t\t\t.request('evidence', value)\n\t\t\t.then((acknowledged) => {\n\t\t\t\tif (acknowledged !== true)\n\t\t\t\t\tthrow new StudyError('FAULT', 'Worker evidence was not acknowledged')\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tthis.#control.fail(readStudyFailure(error))\n\t\t\t\tthrow error\n\t\t\t})\n\t\tthis.#evidence.add(pending)\n\t\tvoid pending.then(\n\t\t\t() => this.#evidence.delete(pending),\n\t\t\t() => this.#evidence.delete(pending),\n\t\t)\n\t\treturn pending\n\t}\n\n\t#abort(value: JSONValue): void {\n\t\tif (!isRecord(value) || !isStudyProcessFailure(value.failure))\n\t\t\tthrow new StudyError('FAULT', 'Worker cancellation is malformed')\n\t\tif (value.id === undefined) this.#control.fail(value.failure)\n\t\telse {\n\t\t\tconst [meter] = this.#meters\n\t\t\tif (typeof value.id !== 'number' || meter === undefined)\n\t\t\t\tthrow new StudyError('FAULT', 'Worker ticket cancellation is foreign')\n\t\t\tmeter.abort(value.id, value.failure)\n\t\t}\n\t}\n\n\t#forward(_role: StudyRole, input: string | URL, init: RequestInit): Promise<Response> {\n\t\treturn globalThis.fetch(input, {\n\t\t\t...init,\n\t\t\tsignal: AbortSignal.any([\n\t\t\t\tthis.#control.signal,\n\t\t\t\t...(init.signal === undefined || init.signal === null ? [] : [init.signal]),\n\t\t\t]),\n\t\t})\n\t}\n}\n","import type { StudyEvidence, StudyAttempt, StudyProfile } from '@src/core'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type { StudyAdapterInterface } from '../adapters/types.js'\nimport {\n\tisStudyError,\n\tStudyError,\n\tparseStudyDefinition,\n\tparseStudyProfile,\n\tparseStudyRubric,\n\tparseStudyScenario,\n\tisStudyJudgment,\n} from '@src/core'\nimport { arrayOf, isArray, isRecord, isString } from '@orkestrel/contract'\nimport { dirname } from 'node:path'\nimport { ArtifactLoader } from '../artifacts/ArtifactLoader.js'\nimport { verifyArtifactClosure } from '../artifacts/helpers.js'\nimport { isStudyClosure } from '../commands/validators.js'\nimport { readStudyAdapter } from '../adapters/helpers.js'\nimport { hashStudyBytes } from '../helpers.js'\nimport { STUDY_CUSTODY_BYTES } from '../stores/constants.js'\nimport { readStudyBytes } from '../stores/helpers.js'\nimport {\n\tisStudyCustodyAttempt,\n\tisStudyCustodyEvidence,\n\tisStudyCustodyManifest,\n} from '../stores/validators.js'\nimport { STUDY_FRAME_BYTES } from './constants.js'\nimport {\n\tcollectStudyEntries,\n\tcomputeStudyInstrumentDigest,\n\tresolveStudyInstrument,\n\tvalidateStudyRuntime,\n\tvalueToWire,\n} from './helpers.js'\n\n/** Evaluates only admitted instrumentation in a disposable native child. */\nexport class StudyTaskWorker {\n\t/** Processes exactly one inherited request and returns a bounded response. */\n\tasync execute(): Promise<void> {\n\t\tif (process.send === undefined || !process.connected)\n\t\t\tthrow new StudyError('CONFIG', 'Adapter worker requires inherited IPC')\n\t\tprocess.channel?.ref()\n\t\tconst value: unknown = await new Promise((resolve) => process.once('message', resolve))\n\t\tconst outcome = await this.#execute(value).catch((error: unknown): JSONValue => ({\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\tcode: isStudyError(error) ? error.code : 'FAULT',\n\t\t}))\n\t\tconst response: JSONValue =\n\t\t\tBuffer.byteLength(JSON.stringify(outcome)) > STUDY_FRAME_BYTES\n\t\t\t\t? { error: 'Adapter result exceeds the frame allowance', code: 'FAULT' }\n\t\t\t\t: outcome\n\t\tawait new Promise<void>((resolve, reject) =>\n\t\t\tprocess.send?.(response, (error: Error | null) =>\n\t\t\t\terror === null ? resolve() : reject(error),\n\t\t\t),\n\t\t)\n\t}\n\tasync #execute(value: unknown): Promise<JSONValue> {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\tBuffer.byteLength(JSON.stringify(value)) > STUDY_FRAME_BYTES ||\n\t\t\ttypeof value.adapter !== 'string' ||\n\t\t\ttypeof value.entry !== 'string' ||\n\t\t\t!arrayOf(isString)(value.roots) ||\n\t\t\t!isRecord(value.input)\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Adapter request is malformed')\n\t\tif (value.closure !== undefined && !isStudyClosure(value.closure))\n\t\t\tthrow new StudyError('CONFIG', 'Adapter closure selection is malformed')\n\t\tconst closure = value.closure\n\t\tif (closure !== undefined) verifyArtifactClosure(closure.closure, true)\n\t\tconst runtime = resolveStudyInstrument(value.entry)\n\t\tconst roots = [...new Set([...value.roots, runtime])]\n\t\tvalidateStudyRuntime(runtime, roots)\n\t\t// Validation precedes agent, subject and provider evaluation, so their selected entries stay\n\t\t// unreachable from every adapter import edge while shared admitted packages still load.\n\t\tconst profile =\n\t\t\tvalue.operation === 'validate' ? parseStudyProfile(value.input.profile) : undefined\n\t\tconst loader = new ArtifactLoader({\n\t\t\tentries: [],\n\t\t\troots,\n\t\t\tinstrument: runtime,\n\t\t\tsource: { root: dirname(value.adapter), entry: value.adapter },\n\t\t\t...(profile === undefined ? {} : { excluded: collectStudyEntries(profile) }),\n\t\t})\n\t\tconst instrument = computeStudyInstrumentDigest(\n\t\t\thashStudyBytes(await readStudyBytes(value.entry, STUDY_CUSTODY_BYTES)),\n\t\t\tloader.inspect().digest,\n\t\t)\n\t\tconst adapter = readStudyAdapter(await loader.load(value.adapter))\n\t\tif (profile === undefined && value.operation !== 'grade')\n\t\t\tthrow new StudyError('CONFIG', 'Unknown adapter operation')\n\t\tconst output: unknown =\n\t\t\tprofile === undefined\n\t\t\t\t? this.#grade(adapter, value.input)\n\t\t\t\t: this.#validate(adapter, value.input, profile)\n\t\tloader.verify()\n\t\tif (closure !== undefined) verifyArtifactClosure(closure.closure, true)\n\t\treturn valueToWire({ instrument, value: output })\n\t}\n\n\t#validate(\n\t\tadapter: StudyAdapterInterface,\n\t\tinput: Readonly<Record<string, unknown>>,\n\t\tprofile: StudyProfile,\n\t): true {\n\t\tif (!isArray(input.scenarios)) throw new StudyError('CONFIG', 'Adapter scenarios are invalid')\n\t\tadapter.validate({\n\t\t\tdefinition: parseStudyDefinition(input.definition),\n\t\t\tscenarios: input.scenarios.map(parseStudyScenario),\n\t\t\trubric: parseStudyRubric(input.rubric),\n\t\t\tprofile,\n\t\t})\n\t\treturn true\n\t}\n\n\t#grade(adapter: StudyAdapterInterface, input: Readonly<Record<string, unknown>>): unknown {\n\t\tif (\n\t\t\t!isStudyCustodyManifest(input.manifest) ||\n\t\t\t!isArray(input.attempts) ||\n\t\t\t!isRecord(input.evidence)\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Adapter grading input is invalid')\n\t\tconst manifest = input.manifest\n\t\tconst attempts: readonly unknown[] = input.attempts\n\t\tif (\n\t\t\t!attempts.every((retained): retained is StudyAttempt =>\n\t\t\t\tisStudyCustodyAttempt(retained, manifest),\n\t\t\t)\n\t\t)\n\t\t\tthrow new StudyError('CONFIG', 'Adapter attempts are invalid')\n\t\tconst evidence: Record<string, readonly StudyEvidence[]> = Object.fromEntries(\n\t\t\tObject.entries(input.evidence).map(([trial, records]) => {\n\t\t\t\tif (!isArray(records) || !records.every(isStudyCustodyEvidence))\n\t\t\t\t\tthrow new StudyError('CONFIG', 'Adapter evidence is invalid')\n\t\t\t\treturn [trial, records]\n\t\t\t}),\n\t\t)\n\t\tconst output = adapter.grade({\n\t\t\tmanifest,\n\t\t\tattempts,\n\t\t\trubric: parseStudyRubric(input.rubric),\n\t\t\tevidence,\n\t\t})\n\t\tif (!isArray(output) || !output.every(isStudyJudgment))\n\t\t\tthrow new StudyError('FAULT', 'Adapter returned invalid judgments')\n\t\treturn output\n\t}\n}\n","/** Bounds each supervised operation other than execution to 60 seconds. */\nexport const STUDY_LAUNCH_DURATION = 60000\n\n/** Extends supervised execution beyond its declared series duration for cleanup. */\nexport const STUDY_LAUNCH_CLEANUP = 15000\n\n/** Bounds combined supervised command output to 16 MiB before terminating the tree. */\nexport const STUDY_LAUNCH_BYTES = 16 * 1024 * 1024\n","import type { ChildProcess } from 'node:child_process'\nimport type { StudyLaunchResult } from './types.js'\nimport { StudyError } from '@src/core'\nimport { terminateStudyChild } from '../processes/helpers.js'\nimport { STUDY_LAUNCH_BYTES } from './constants.js'\n\n/** Supervises one launched command child until it closes under its output allowance and deadline. */\nexport class StudyLaunchChild {\n\treadonly #child: ChildProcess\n\treadonly #duration: number\n\treadonly #forward: boolean\n\treadonly #signal: AbortSignal\n\treadonly #chunks: Buffer[] = []\n\t#bytes = 0\n\t#failure: Error | undefined\n\t#expired = false\n\t#executed = false\n\n\t/** Binds one spawned child to its deadline, output route and the launcher's interruption.\n\t * @param child - The spawned child; `execute` subscribes before any of its events can fire.\n\t * @param duration - The deadline in milliseconds.\n\t * @param forward - If `true`, stdout is forwarded to this process; if `false`, it is captured as the result output.\n\t * @param signal - The launcher's interruption; an abort terminates the child and reports 130.\n\t */\n\tconstructor(child: ChildProcess, duration: number, forward: boolean, signal: AbortSignal) {\n\t\tthis.#child = child\n\t\tthis.#duration = duration\n\t\tthis.#forward = forward\n\t\tthis.#signal = signal\n\t}\n\n\t/** Waits for the child to close and reports its exit code and captured output.\n\t * @returns The child's code, 130 after interruption or 124 after the deadline, with captured stdout.\n\t * @throws StudyError - Thrown with code `CONFIG` when this child is already supervised.\n\t */\n\texecute(): Promise<StudyLaunchResult> {\n\t\tif (this.#executed) throw new StudyError('CONFIG', 'Study launch can execute only once')\n\t\tthis.#executed = true\n\t\tconst child = this.#child\n\t\tconst signal = this.#signal\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst listeners = new AbortController()\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.#expired = true\n\t\t\t\tterminateStudyChild(child)\n\t\t\t}, this.#duration)\n\t\t\tsignal.addEventListener('abort', () => terminateStudyChild(child), {\n\t\t\t\tonce: true,\n\t\t\t\tsignal: listeners.signal,\n\t\t\t})\n\t\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\t\tif (!this.#measure(chunk)) return\n\t\t\t\tif (this.#forward) process.stdout.write(chunk)\n\t\t\t\telse this.#chunks.push(chunk)\n\t\t\t})\n\t\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\t\tif (this.#measure(chunk)) process.stderr.write(chunk)\n\t\t\t})\n\t\t\tchild.once('error', (error) => {\n\t\t\t\tthis.#failure ??= error\n\t\t\t})\n\t\t\tchild.once('close', (code) => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tlisteners.abort()\n\t\t\t\tif (this.#failure !== undefined) {\n\t\t\t\t\treject(this.#failure)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (this.#expired)\n\t\t\t\t\tprocess.stderr.write(\n\t\t\t\t\t\t`study: DEADLINE: Process tree exceeded its ${this.#duration} ms deadline\\n`,\n\t\t\t\t\t)\n\t\t\t\tresolve({\n\t\t\t\t\tcode: signal.aborted ? 130 : this.#expired ? 124 : (code ?? 1),\n\t\t\t\t\toutput: Buffer.concat(this.#chunks).toString('utf8'),\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (signal.aborted) terminateStudyChild(child)\n\t\t})\n\t}\n\n\t// Counts a chunk against the shared stdout and stderr allowance; an overflow retains the failure and terminates the tree.\n\t#measure(chunk: Buffer): boolean {\n\t\tthis.#bytes += chunk.byteLength\n\t\tif (this.#bytes <= STUDY_LAUNCH_BYTES) return true\n\t\tthis.#failure ??= new Error('Study command output exceeds the 16 MiB host allowance')\n\t\tterminateStudyChild(this.#child)\n\t\treturn false\n\t}\n}\n","import type { StudyLaunchOptions, StudyLaunchResult } from './types.js'\nimport { StudyError, isStudyBounds, isStudyDigest } from '@src/core'\nimport { isRecord } from '@orkestrel/contract'\nimport { spawn } from 'node:child_process'\nimport { STUDY_COMMAND_DURATION } from '../commands/constants.js'\nimport { parseStudyArguments } from '../commands/parsers.js'\nimport { STUDY_COMMAND_OPERATION } from '../processes/constants.js'\nimport { STUDY_LAUNCH_CLEANUP, STUDY_LAUNCH_DURATION } from './constants.js'\nimport { StudyLaunchChild } from './StudyLaunchChild.js'\n\n/** Supervises finite command trees and binds offline check to execution. */\nexport class StudyLauncher {\n\treadonly #root: string\n\treadonly #entry: string\n\treadonly #interruption = new AbortController()\n\treadonly #signal: () => void\n\n\t/** Owns the trusted runtime entry and caller working directory.\n\t * @param options - Native entry and consumer root.\n\t */\n\tconstructor(options: StudyLaunchOptions) {\n\t\tthis.#root = options.root\n\t\tthis.#entry = options.entry\n\t\tthis.#signal = this.#interruption.abort.bind(this.#interruption)\n\t}\n\n\t/** Checks and supervises the requested command under its finite native allowance.\n\t * @param arguments_ - Public command tokens.\n\t * @returns The exact operational or supervisor exit code.\n\t */\n\tasync execute(arguments_: readonly string[]): Promise<number> {\n\t\tconst entry = this.#entry\n\t\tconst request = parseStudyArguments(arguments_)\n\t\tprocess.on('SIGINT', this.#signal)\n\t\tprocess.on('SIGTERM', this.#signal)\n\t\ttry {\n\t\t\tif (request.command !== 'execute') {\n\t\t\t\tif (this.#interruption.signal.aborted) return 130\n\t\t\t\treturn (await this.#launch(entry, arguments_, STUDY_LAUNCH_DURATION, true)).code\n\t\t\t}\n\t\t\tconst check = [\n\t\t\t\t'check',\n\t\t\t\trequest.target,\n\t\t\t\t'--profile',\n\t\t\t\trequest.profile,\n\t\t\t\t...(request.closure === undefined ? [] : ['--closure', request.closure]),\n\t\t\t]\n\t\t\tconst reading = await this.#launch(entry, check, STUDY_LAUNCH_DURATION, false)\n\t\t\tif (reading.code !== 0) {\n\t\t\t\tprocess.stdout.write(reading.output)\n\t\t\t\treturn reading.code\n\t\t\t}\n\t\t\tconst value: unknown = JSON.parse(reading.output)\n\t\t\tif (\n\t\t\t\t!isRecord(value) ||\n\t\t\t\t!isStudyBounds(value.bounds) ||\n\t\t\t\tvalue.bounds.series.duration > STUDY_COMMAND_DURATION\n\t\t\t)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Study execution requires a validated series duration within the 24-hour host ceiling',\n\t\t\t\t)\n\t\t\tif (!isStudyDigest(value.fingerprint))\n\t\t\t\tthrow new Error('Study check did not return an execution fingerprint')\n\t\t\tconst duration = value.bounds.series.duration + STUDY_LAUNCH_CLEANUP\n\t\t\tif (request.expected !== undefined && request.expected !== value.fingerprint)\n\t\t\t\tthrow new StudyError('CONFIG', 'Validated execution differs from the requested fingerprint')\n\t\t\tconst execution = [\n\t\t\t\t'execute',\n\t\t\t\trequest.target,\n\t\t\t\t'--profile',\n\t\t\t\trequest.profile,\n\t\t\t\t...(request.out === undefined ? [] : ['--out', request.out]),\n\t\t\t\t...(request.closure === undefined ? [] : ['--closure', request.closure]),\n\t\t\t\t...(request.replay === undefined\n\t\t\t\t\t? []\n\t\t\t\t\t: [\n\t\t\t\t\t\t\t'--replay',\n\t\t\t\t\t\t\trequest.replay.result,\n\t\t\t\t\t\t\t'--prefix',\n\t\t\t\t\t\t\tJSON.stringify(request.replay.prefix),\n\t\t\t\t\t\t\t'--offline',\n\t\t\t\t\t\t\tString(request.replay.offline),\n\t\t\t\t\t\t]),\n\t\t\t\t'--expected',\n\t\t\t\tvalue.fingerprint,\n\t\t\t]\n\t\t\tif (this.#interruption.signal.aborted) return 130\n\t\t\treturn (await this.#launch(entry, execution, duration, true)).code\n\t\t} finally {\n\t\t\tprocess.removeListener('SIGINT', this.#signal)\n\t\t\tprocess.removeListener('SIGTERM', this.#signal)\n\t\t}\n\t}\n\n\t// Spawns one command child; its own entity supervises the deadline, output allowance and interruption.\n\t#launch(\n\t\tentry: string,\n\t\targuments_: readonly string[],\n\t\tduration: number,\n\t\tforward: boolean,\n\t): Promise<StudyLaunchResult> {\n\t\tconst child = spawn(\n\t\t\tprocess.execPath,\n\t\t\t[...process.execArgv, entry, STUDY_COMMAND_OPERATION, ...arguments_],\n\t\t\t{\n\t\t\t\tcwd: this.#root,\n\t\t\t\tshell: false,\n\t\t\t\twindowsHide: true,\n\t\t\t\tdetached: process.platform !== 'win32',\n\t\t\t\tstdio: ['ignore', 'pipe', 'pipe', 'ipc'],\n\t\t\t},\n\t\t)\n\t\treturn new StudyLaunchChild(child, duration, forward, this.#interruption.signal).execute()\n\t}\n}\n","import type { StudyLaunchOptions } from './types.js'\nimport { StudyError } from '@src/core'\nimport { isRecord } from '@orkestrel/contract'\nimport { StudyCommand } from '../commands/StudyCommand.js'\nimport { STUDY_COMMAND_HELP } from '../commands/constants.js'\nimport {\n\tSTUDY_COMMAND_OPERATION,\n\tSTUDY_TASK_OPERATION,\n\tSTUDY_WORKER_OPERATION,\n} from '../processes/constants.js'\nimport { StudyTaskWorker } from '../processes/StudyTaskWorker.js'\nimport { StudyWorker } from '../processes/StudyWorker.js'\nimport { readStudyVersion } from '../processes/helpers.js'\nimport { StudyLauncher } from './StudyLauncher.js'\n\n/** Dispatches private child routes before the public native supervisor. */\nexport class StudyCLI {\n\t#options: StudyLaunchOptions\n\t/** Owns the installed executable path and consumer working directory.\n\t * @param options - Exact runtime entry and consumer root, snapshotted at construction.\n\t */\n\tconstructor(options: StudyLaunchOptions) {\n\t\tthis.#options = { ...options }\n\t}\n\t/** Executes one route with truthful public exit semantics.\n\t * @param arguments_ - Native command arguments.\n\t * @returns The command, deadline, interruption, or invalid-input exit code.\n\t */\n\tasync execute(arguments_: readonly string[]): Promise<number> {\n\t\ttry {\n\t\t\tif (\n\t\t\t\t[STUDY_COMMAND_OPERATION, STUDY_WORKER_OPERATION, STUDY_TASK_OPERATION].includes(\n\t\t\t\t\targuments_[0] ?? '',\n\t\t\t\t) &&\n\t\t\t\t(process.send === undefined || !process.connected)\n\t\t\t)\n\t\t\t\tthrow new StudyError(\n\t\t\t\t\t'CONFIG',\n\t\t\t\t\t`Private route ${JSON.stringify(arguments_[0])} requires supervised native IPC; use study check, execute, grade, label, or report. Use study --help for grammar.`,\n\t\t\t\t)\n\t\t\tif (arguments_[0] === STUDY_WORKER_OPERATION) {\n\t\t\t\tawait new StudyWorker().execute()\n\t\t\t\treturn 0\n\t\t\t}\n\t\t\tif (arguments_[0] === STUDY_TASK_OPERATION) {\n\t\t\t\tawait new StudyTaskWorker().execute()\n\t\t\t\treturn 0\n\t\t\t}\n\t\t\tif (arguments_[0] !== STUDY_COMMAND_OPERATION) {\n\t\t\t\tif (arguments_.includes('--help')) {\n\t\t\t\t\tprocess.stdout.write(STUDY_COMMAND_HELP)\n\t\t\t\t\treturn 0\n\t\t\t\t}\n\t\t\t\tif (arguments_.length === 1 && arguments_[0] === '--version') {\n\t\t\t\t\tprocess.stdout.write(`${readStudyVersion(this.#options.entry)}\\n`)\n\t\t\t\t\treturn 0\n\t\t\t\t}\n\t\t\t\tif (arguments_.length === 0) {\n\t\t\t\t\tprocess.stderr.write(STUDY_COMMAND_HELP)\n\t\t\t\t\treturn 64\n\t\t\t\t}\n\t\t\t\treturn await new StudyLauncher(this.#options).execute(arguments_)\n\t\t\t}\n\t\t\tconst controller = new AbortController()\n\t\t\tconst listener = controller.abort.bind(controller)\n\t\t\tprocess.once('SIGINT', listener)\n\t\t\tprocess.once('SIGTERM', listener)\n\t\t\ttry {\n\t\t\t\tconst result = await new StudyCommand(this.#options).execute(\n\t\t\t\t\targuments_.slice(1),\n\t\t\t\t\tcontroller.signal,\n\t\t\t\t)\n\t\t\t\tprocess.stdout.write(`${JSON.stringify(result)}\\n`)\n\t\t\t\treturn controller.signal.aborted\n\t\t\t\t\t? 130\n\t\t\t\t\t: isRecord(result) && result.status === 'operational-failure'\n\t\t\t\t\t\t? 1\n\t\t\t\t\t\t: 0\n\t\t\t} finally {\n\t\t\t\tprocess.removeListener('SIGINT', listener)\n\t\t\t\tprocess.removeListener('SIGTERM', listener)\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code =\n\t\t\t\terror instanceof Error && 'code' in error && typeof error.code === 'string'\n\t\t\t\t\t? error.code\n\t\t\t\t\t: 'FAULT'\n\t\t\tprocess.stderr.write(\n\t\t\t\t`study: ${code}: ${error instanceof Error ? error.message : String(error)}\\n`,\n\t\t\t)\n\t\t\treturn error instanceof StudyError\n\t\t\t\t? error.code === 'CONFIG'\n\t\t\t\t\t? 64\n\t\t\t\t\t: error.failure?.cause === 'deadline'\n\t\t\t\t\t\t? 124\n\t\t\t\t\t\t: error.failure?.cause === 'interrupted'\n\t\t\t\t\t\t\t? 130\n\t\t\t\t\t\t\t: 1\n\t\t\t\t: 1\n\t\t}\n\t}\n}\n","import type { ProviderDelta, ProviderRequest, ProviderResult } from '@orkestrel/agent'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type { ToolCall } from '@orkestrel/tool'\nimport type { StudyAgentResponse } from './types.js'\nimport { StudyError } from '@src/core'\nimport {\n\tattempt,\n\tcanonicalStringify,\n\tcloneJSONValue,\n\tisArray,\n\tisObject,\n\tisRecord,\n} from '@orkestrel/contract'\nimport { isToolCall } from '@orkestrel/tool'\nimport { hashStudyBytes } from '../helpers.js'\n\n/**\n * Reads an Agent tool call into a validated envelope from one read of each foreign field.\n * @remarks The returned envelope owns its fields; arguments retain their original record identity.\n * JSON validation and copying belong to the executed-result projection.\n * @param call - The call received from the admitted Agent\n * @returns A fresh ToolCall envelope with the original arguments record\n * @throws StudyError - Thrown with code `FAULT` when a field cannot be read or the envelope is malformed\n * @example Read an Agent tool call\n * ```ts\n * import { readStudyAgentToolCall } from '@orkestrel/study/server'\n *\n * const call = readStudyAgentToolCall({ id: 'c1', name: 'write', arguments: { path: 'note.txt' } })\n * // { id: 'c1', name: 'write', arguments: { path: 'note.txt' } }\n * ```\n */\nexport function readStudyAgentToolCall(call: unknown): ToolCall {\n\tconst observed = attempt(() =>\n\t\tisRecord(call)\n\t\t\t? {\n\t\t\t\t\tid: 'id' in call ? call.id : undefined,\n\t\t\t\t\tname: 'name' in call ? call.name : undefined,\n\t\t\t\t\targuments: 'arguments' in call ? call.arguments : undefined,\n\t\t\t\t}\n\t\t\t: undefined,\n\t)\n\tif (!observed.success || !isToolCall(observed.value))\n\t\tthrow new StudyError('FAULT', 'Admitted Agent supplied invalid tool observation')\n\treturn observed.value\n}\n\n/**\n * Builds the JSON evidence form of an Agent tool call and its executed result.\n * @param call - The call received from the admitted Agent\n * @param result - The executed tool result\n * @returns The call identity, owned arguments, success, and owned value or error text\n * @throws StudyError - Thrown with code `FAULT` when the call, result, arguments, or value is malformed\n * @example\n * ```ts\n * buildStudyAgentToolResult(call, { success: true, value: 'stored' })\n * ```\n */\nexport function buildStudyAgentToolResult(call: unknown, result: unknown): JSONValue {\n\tconst { id, name, arguments: arguments_ } = readStudyAgentToolCall(call)\n\tconst returned = attempt(() => {\n\t\tif (!isObject(result)) return undefined\n\t\tconst success = 'success' in result ? result.success : undefined\n\t\tif (typeof success !== 'boolean') return undefined\n\t\treturn success\n\t\t\t? { success, value: 'value' in result ? result.value : undefined }\n\t\t\t: { success, error: 'error' in result ? result.error : undefined }\n\t})\n\tif (!returned.success || returned.value === undefined)\n\t\tthrow new StudyError('FAULT', 'Admitted Agent supplied invalid tool result')\n\tconst argumentsCopy = attempt(() => cloneJSONValue(arguments_))\n\tif (!argumentsCopy.success)\n\t\tthrow new StudyError('FAULT', 'Admitted Agent supplied non-JSON tool arguments')\n\tconst outcome = returned.value\n\tif (outcome.success) {\n\t\tconst valueCopy = attempt(() => cloneJSONValue(outcome.value))\n\t\tif (!valueCopy.success)\n\t\t\tthrow new StudyError('FAULT', 'Admitted Agent supplied non-JSON tool value')\n\t\treturn {\n\t\t\tid,\n\t\t\tname,\n\t\t\targuments: argumentsCopy.value,\n\t\t\tsuccess: true,\n\t\t\tvalue: valueCopy.value,\n\t\t}\n\t}\n\tif (typeof outcome.error !== 'string')\n\t\tthrow new StudyError('FAULT', 'Admitted Agent supplied invalid tool error')\n\treturn {\n\t\tid,\n\t\tname,\n\t\targuments: argumentsCopy.value,\n\t\tsuccess: false,\n\t\terror: outcome.error,\n\t}\n}\n\n/**\n * Builds the JSON evidence form of an Agent tool call the Agent denied before dispatch.\n * @param call - The call received from the admitted Agent\n * @param reason - The denial reason, retained only when it is a string\n * @returns The call identity with the optional string reason\n * @throws StudyError - Thrown with code `FAULT` when the call is malformed\n * @example\n * ```ts\n * buildStudyAgentToolDenial(call, 'refused')\n * ```\n */\nexport function buildStudyAgentToolDenial(call: unknown, reason: unknown): JSONValue {\n\tconst { id, name } = readStudyAgentToolCall(call)\n\treturn { id, name, ...(typeof reason === 'string' ? { reason } : {}) }\n}\n\n/**\n * Builds a request revision by hashing its canonical rendering exactly as rendered.\n * @remarks\n * The request is rendered once with key-sorted canonical JSON and hashed as rendered; no\n * newline or JSON round trip is added. Any change to content, order, ids, tools, or options\n * changes the revision.\n * @param request - The exact pre-encoding request\n * @returns The lowercase SHA-256 digest, or undefined when the request cannot be canonically rendered; a rendering failure never throws\n */\nexport function buildStudyAgentRevision(request: ProviderRequest): string | undefined {\n\tconst rendered = attempt(() => canonicalStringify(request))\n\tif (!rendered.success || rendered.value === undefined) return undefined\n\treturn hashStudyBytes(rendered.value)\n}\n\n/**\n * Builds the JSON evidence form of a Ledger result's logical classifier readings.\n * @param result - Value returned by the Ledger\n * @returns Null when the result carries no readings array, else one entry per well-formed reading in asking order, each with its duration or null\n */\nexport function buildStudyAgentReadings(result: unknown): JSONValue {\n\tif (!isObject(result) || !('readings' in result) || !isArray(result.readings)) return null\n\treturn result.readings.flatMap((entry): JSONValue[] =>\n\t\t!isObject(entry) ||\n\t\t!('key' in entry) ||\n\t\ttypeof entry.key !== 'string' ||\n\t\t!('phase' in entry) ||\n\t\ttypeof entry.phase !== 'string' ||\n\t\t!('outcome' in entry) ||\n\t\ttypeof entry.outcome !== 'string'\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t{\n\t\t\t\t\t\tkey: entry.key,\n\t\t\t\t\t\tphase: entry.phase,\n\t\t\t\t\t\toutcome: entry.outcome,\n\t\t\t\t\t\tduration:\n\t\t\t\t\t\t\t'duration' in entry && typeof entry.duration === 'number' ? entry.duration : null,\n\t\t\t\t\t},\n\t\t\t\t],\n\t)\n}\n\n/**\n * Resolves the content a scripted response serves, from its declaration or from a prior tool message.\n * @param request - The projected actual request messages\n * @param response - The declared response being served\n * @returns The declared content, or the content of the actual tool message the response consumes\n * @throws StudyError - Thrown when a consuming response has no actual referenced tool result\n */\nexport function resolveStudyAgentContent(\n\trequest: readonly JSONValue[],\n\tresponse: StudyAgentResponse,\n): string {\n\tif (response.consume === undefined) return response.content\n\tconst prior = request.findLast(\n\t\t(message) => isRecord(message) && message.role === 'tool' && message.call === response.consume,\n\t)\n\tif (!isRecord(prior) || typeof prior.content !== 'string')\n\t\tthrow new StudyError('FAULT', 'Continuation has no actual referenced tool result')\n\treturn prior.content\n}\n\n/**\n * Drains a scripted provider stream into its assembled result.\n * @param stream - The provider stream to consume to its end\n * @returns The result the stream returns after its last delta\n */\nexport async function readStudyAgentResult(\n\tstream: AsyncGenerator<ProviderDelta, ProviderResult>,\n): Promise<ProviderResult> {\n\tfor (;;) {\n\t\tconst next = await stream.next()\n\t\tif (next.done) return next.value\n\t}\n}\n\n/**\n * Projects foreign provider messages onto the exact fields the workload reads.\n * @param value - The foreign provider message collection\n * @returns Owned JSON message readings in original order\n * @throws StudyError - Thrown when a dereferenced foreign member is malformed\n * @example\n * ```ts\n * readStudyAgentMessages([{ id: 'm1', role: 'user', content: 'Hi' }]) // [{ role: 'user', content: 'Hi' }]\n * ```\n */\nexport function readStudyAgentMessages(value: unknown): readonly JSONValue[] {\n\tif (!isArray(value)) throw new StudyError('FAULT', 'Provider messages are not an array')\n\treturn Object.freeze(\n\t\tArray.from(value).map((message): JSONValue => {\n\t\t\tif (!isObject(message)) throw new StudyError('FAULT', 'Provider message fields are invalid')\n\t\t\tconst role = 'role' in message ? message.role : undefined\n\t\t\tconst content = 'content' in message ? message.content : undefined\n\t\t\tconst call = 'call' in message ? message.call : undefined\n\t\t\tif (\n\t\t\t\ttypeof role !== 'string' ||\n\t\t\t\ttypeof content !== 'string' ||\n\t\t\t\t(call !== undefined && typeof call !== 'string')\n\t\t\t)\n\t\t\t\tthrow new StudyError('FAULT', 'Provider message fields are invalid')\n\t\t\treturn Object.freeze({\n\t\t\t\trole,\n\t\t\t\tcontent,\n\t\t\t\t...(call === undefined ? {} : { call }),\n\t\t\t})\n\t\t}),\n\t)\n}\n","import type { StudyAgentResponse } from './types.js'\nimport { matchesStudyKeys } from '@src/core'\nimport { holds, isArray, isJSONValue, isRecord } from '@orkestrel/contract'\nimport { isToolCall } from '@orkestrel/tool'\n\n/**\n * Checks whether a scripted response has JSON calls and workload controls.\n * @remarks\n * The guard accepts exact own data keys: `content` and `calls` are required; `consume`, `abort`,\n * `tokens`, `bytes` and `truncated` are optional. Each call must satisfy the Tool package's call\n * guard and carry JSON arguments. The guard sets no size limit on content, calls or `consume`; a\n * consumer composes its own workload bounds. A throwing accessor returns false.\n * @param value - The candidate response\n * @returns True if every declared response member is valid; false otherwise\n * @example\n * ```ts\n * isStudyAgentResponse({ content: 'done', calls: [] }) // true\n * ```\n */\nexport function isStudyAgentResponse(value: unknown): value is StudyAgentResponse {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) &&\n\t\t\tmatchesStudyKeys(\n\t\t\t\tvalue,\n\t\t\t\t['content', 'calls'],\n\t\t\t\t['consume', 'abort', 'tokens', 'bytes', 'truncated'],\n\t\t\t) &&\n\t\t\ttypeof value.content === 'string' &&\n\t\t\tisArray(value.calls) &&\n\t\t\tvalue.calls.every(isToolCall) &&\n\t\t\tisJSONValue(value.calls) &&\n\t\t\t(value.consume === undefined ||\n\t\t\t\t(typeof value.consume === 'string' && value.consume.length > 0)) &&\n\t\t\t(value.abort === undefined || typeof value.abort === 'boolean') &&\n\t\t\t(value.truncated === undefined || typeof value.truncated === 'boolean') &&\n\t\t\t['tokens', 'bytes'].every(\n\t\t\t\t(key) =>\n\t\t\t\t\tvalue[key] === undefined ||\n\t\t\t\t\t(typeof value[key] === 'number' && Number.isSafeInteger(value[key]) && value[key] >= 0),\n\t\t\t),\n\t)\n}\n","import type { StudyEvidence } from '@src/core'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type { StudyAgentStamp } from './types.js'\n\n/** Holds one goal's retained trace rows, its latest admission and its last refused identity. */\nexport class StudyAgentTraceGoal {\n\treadonly #goal: string\n\treadonly #rows: StudyEvidence[] = []\n\t#admission: StudyAgentStamp | undefined\n\t#refused: unknown\n\n\t/** Binds the rows that follow to one goal.\n\t * @param goal - The goal whose rows follow.\n\t */\n\tconstructor(goal: string) {\n\t\tthis.#goal = goal\n\t}\n\n\t/** Reports the goal the rows belong to. */\n\tget goal(): string {\n\t\treturn this.#goal\n\t}\n\n\t/** Reports every row retained so far; the same live view for the goal's whole life, which sees each row retained later. */\n\tget rows(): readonly StudyEvidence[] {\n\t\treturn this.#rows\n\t}\n\n\t/** Reports the goal's latest admission stamp; undefined before one, or when the latest was not observed. */\n\tget admission(): StudyAgentStamp | undefined {\n\t\treturn this.#admission\n\t}\n\n\t/** Retains one row for the goal.\n\t * @param event - The evidence event name.\n\t * @param value - The JSON evidence value.\n\t */\n\tappend(event: string, value: JSONValue): void {\n\t\tthis.#rows.push({ event, goal: this.#goal, value })\n\t}\n\n\t/** Retains the goal's latest admission stamp.\n\t * @param stamp - The admission measurement's stamp; undefined when it was not observed.\n\t */\n\tadmit(stamp: StudyAgentStamp | undefined): void {\n\t\tthis.#admission = stamp\n\t}\n\n\t/** Latches a refused failure identity.\n\t * @param error - The refused value.\n\t * @returns True if it differs from the last refused identity; false otherwise.\n\t */\n\trefuse(error: unknown): boolean {\n\t\tif (this.#refused === error) return false\n\t\tthis.#refused = error\n\t\treturn true\n\t}\n}\n","import type { StudySinkInterface, StudyAgentDispatch, StudyAgentReading } from '@src/core'\nimport type { LedgerGauge, ProviderRequest } from '@orkestrel/agent'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type {\n\tStudyAgentRole,\n\tStudyAgentStage,\n\tStudyAgentStamp,\n\tStudyAgentTraceOptions,\n} from './types.js'\nimport {\n\tbuildStudyAgentParts,\n\tprojectStudyAgentRequest,\n\ttranslateStudyAgentError,\n\tStudyError,\n} from '@src/core'\nimport { buildStudyAgentRevision } from './helpers.js'\nimport { StudyAgentTraceGoal } from './StudyAgentTraceGoal.js'\n\n/** Correlates measured Agent requests and retains their evidence across a trial's goals. */\nexport class StudyAgentTrace {\n\treadonly #options: StudyAgentTraceOptions\n\t// Dispatch identities per role; one current dispatch cannot be overtaken by another of its role\n\t// because the consumer awaits each request before the next of that role.\n\t// Each dispatch replaces the map, so a reader never sees one change in place.\n\t#slots: ReadonlyMap<StudyAgentRole, StudyAgentDispatch> = new Map()\n\t// The goal in flight; `start` binds it and its flush releases it when it settles.\n\t#goal: StudyAgentTraceGoal | undefined\n\t// The goals being flushed; a goal joins when its flush starts and leaves when the flush settles.\n\treadonly #flushes = new Set<StudyAgentTraceGoal>()\n\t#ordinal = 0\n\t#dispatches = 0\n\n\t/** Binds the measuring runtime, the failure owner and the consumer origin join.\n\t * @param options - Runtime, latch, observation switch and origin handler.\n\t */\n\tconstructor(options: StudyAgentTraceOptions) {\n\t\tthis.#options = { ...options }\n\t}\n\n\t/** Reports the active goal; undefined between goals. */\n\tget goal(): string | undefined {\n\t\treturn this.#goal?.goal\n\t}\n\n\t/** Begins a goal's rows. Ordinals, dispatch numbers and role identities continue from earlier goals.\n\t * @param goal - The goal whose rows follow.\n\t * @throws StudyError - Thrown with code `CONFIG` when a goal is already active; the active goal and its rows stay unchanged.\n\t */\n\tstart(goal: string): void {\n\t\tif (this.#goal !== undefined) throw new StudyError('CONFIG', 'Trace goal is already active')\n\t\tthis.#goal = new StudyAgentTraceGoal(goal)\n\t}\n\n\t/** Retains one domain row for the active goal, whether or not observation is enabled; a row outside a goal is dropped.\n\t * @param event - The evidence event name.\n\t * @param value - The JSON evidence value.\n\t */\n\tappend(event: string, value: JSONValue): void {\n\t\tthis.#goal?.append(event, value)\n\t}\n\n\t/** Appends the retained rows in order, including rows added during the flush, and ends the goal even when custody refuses a row.\n\t * @param evidence - The sink that takes custody of each row.\n\t * @returns Completion after every row is appended; immediately when no goal is active.\n\t * @throws StudyError - Thrown with code `CONFIG` when another flush is pending; the pending flush is untouched.\n\t */\n\tasync flush(evidence: StudySinkInterface): Promise<void> {\n\t\tconst running = this.#goal\n\t\tif (running === undefined) return\n\t\tif (this.#flushes.size !== 0) throw new StudyError('CONFIG', 'Trace flush is already pending')\n\t\t// The goal joins the registry before the sink can run, so a sink that re-enters `flush` meets it.\n\t\tthis.#flushes.add(running)\n\t\ttry {\n\t\t\tfor (const row of running.rows) await evidence.append(row)\n\t\t} finally {\n\t\t\tthis.#goal = undefined\n\t\t\tthis.#flushes.delete(running)\n\t\t}\n\t}\n\n\t/** Prices a window measurement and, when observing, retains it as the goal's admission.\n\t * @param request - The measured request.\n\t * @param gauge - The explicit gauge pricing the estimate.\n\t * @returns The projected prompt tokens.\n\t */\n\tadmit(request: ProviderRequest, gauge: LedgerGauge): number {\n\t\tconst estimate = this.#options.runtime.estimateRequest(request)\n\t\tconst projected = projectStudyAgentRequest(gauge, estimate)\n\t\tconst stamp = this.measure('admission', 'agent', request, { estimate, projected }, undefined)\n\t\tthis.#goal?.admit(stamp)\n\t\treturn projected\n\t}\n\n\t/** Retains a dispatching agent request's reading, names it for the wire request that follows, and records its estimate.\n\t * @param reading - The explicit size reading.\n\t * @param request - The exact pre-encoding request.\n\t */\n\trecord(reading: StudyAgentReading, request: ProviderRequest): void {\n\t\tconst goal = this.#observed()\n\t\tif (goal === undefined) return\n\t\tconst dispatch = this.#number('agent', request, reading)\n\t\tgoal.append('estimate', {\n\t\t\testimate: reading.estimate,\n\t\t\tprojected: reading.projected ?? null,\n\t\t\trevision: dispatch.revision ?? null,\n\t\t\tdispatch: dispatch.id,\n\t\t})\n\t}\n\n\t/** Takes one synchronous measurement row; the goal's flush appends it, failure included.\n\t * @param stage - Where the measurement was taken.\n\t * @param role - The responsibility whose request was measured.\n\t * @param request - The exact pre-encoding request.\n\t * @param reading - The explicit size reading.\n\t * @param dispatch - The dispatch number the request received; undefined for an admission.\n\t * @returns The ordinal and revision; undefined when not observing.\n\t */\n\tmeasure(\n\t\tstage: StudyAgentStage,\n\t\trole: StudyAgentRole,\n\t\trequest: ProviderRequest,\n\t\treading: StudyAgentReading,\n\t\tdispatch: number | undefined,\n\t): StudyAgentStamp | undefined {\n\t\tconst goal = this.#observed()\n\t\tif (goal === undefined) return undefined\n\t\tconst ordinal = ++this.#ordinal\n\t\tconst revision = buildStudyAgentRevision(request) ?? null\n\t\tgoal.append('context', {\n\t\t\tstage,\n\t\t\trole,\n\t\t\tordinal,\n\t\t\trevision,\n\t\t\testimate: reading.estimate,\n\t\t\tprojected: reading.projected ?? null,\n\t\t\t...(dispatch === undefined ? {} : { dispatch }),\n\t\t\tparts: buildStudyAgentParts(this.#options.runtime.measureRequest(request)),\n\t\t\torigins: this.#options.origins(request.messages),\n\t\t})\n\t\treturn { ordinal, revision }\n\t}\n\n\t/** Numbers a request about to be dispatched and retains it as its role's current dispatch; does nothing unless observing.\n\t * @param role - The responsibility dispatching.\n\t * @param request - The exact pre-encoding request.\n\t * @param reading - The explicit size reading.\n\t */\n\tdispatch(role: StudyAgentRole, request: ProviderRequest, reading: StudyAgentReading): void {\n\t\tif (this.#observed() === undefined) return\n\t\tthis.#number(role, request, reading)\n\t}\n\n\t/** Reads the role's current dispatch identity for the wire request that follows it.\n\t * @param role - The responsibility dispatching.\n\t * @returns The dispatch id and revision; undefined before any observed dispatch of the role.\n\t */\n\tcanonical(role: StudyAgentRole): StudyAgentDispatch | undefined {\n\t\treturn this.#slots.get(role)\n\t}\n\n\t/** Latches the study-level reading of a failure before an enclosing runtime can swallow it and retains one refusal row per refused identity in a goal.\n\t * @param error - The caught or reported value.\n\t * @returns The translated failure, or the same value when it is not an Agent window refusal.\n\t */\n\ttranslate(error: unknown): unknown {\n\t\tconst translated = translateStudyAgentError(error, this.#options.runtime)\n\t\tthis.#refuse(error, translated)\n\t\tthis.#options.latch.fail(translated)\n\t\treturn translated\n\t}\n\n\t// Reads the active goal only while observation is enabled.\n\t#observed(): StudyAgentTraceGoal | undefined {\n\t\treturn this.#options.observe ? this.#goal : undefined\n\t}\n\n\t// Numbers the dispatch, retains its context row and makes it the role's current identity.\n\t#number(\n\t\trole: StudyAgentRole,\n\t\trequest: ProviderRequest,\n\t\treading: StudyAgentReading,\n\t): StudyAgentDispatch {\n\t\tconst id = ++this.#dispatches\n\t\tconst stamp = this.measure('dispatch', role, request, reading, id)\n\t\tconst dispatch = Object.freeze({ id, revision: stamp?.revision ?? undefined })\n\t\tthis.#slots = new Map([...this.#slots, [role, dispatch]])\n\t\treturn dispatch\n\t}\n\n\t// Retains one refusal row per refused error identity in a goal, however many callbacks it traverses.\n\t#refuse(error: unknown, translated: unknown): void {\n\t\tconst goal = this.#observed()\n\t\tif (translated === error || goal === undefined || !goal.refuse(error)) return\n\t\tconst context = this.#options.runtime.isAgentError(error) ? error.context : undefined\n\t\tgoal.append('refusal', {\n\t\t\tcause: 'capacity',\n\t\t\trole: 'agent',\n\t\t\tordinal: goal.admission?.ordinal ?? null,\n\t\t\trevision: goal.admission?.revision ?? null,\n\t\t\tconsumed: typeof context?.consumed === 'number' ? context.consumed : null,\n\t\t\tmax: typeof context?.max === 'number' ? context.max : null,\n\t\t})\n\t}\n}\n","import type { Message, ProviderRequest } from '@orkestrel/agent'\nimport type { StudyAgentSummaryOptions } from './types.js'\nimport {\n\tStudyError,\n\tisStudyAgentGauge,\n\tprojectStudyAgentRequest,\n\tvalidateStudyAgentUsage,\n} from '@src/core'\nimport { cloneJSONValue, isJSONValue } from '@orkestrel/contract'\n\n/** Folds a conversation through the real provider under an explicit gauge and prompt limit. */\nexport class StudyAgentSummary {\n\treadonly #options: StudyAgentSummaryOptions\n\n\t/** Binds the provider, the measuring trace, the gauge, the limit and the consumer's instruction.\n\t * @param options - Delegate, measurement seam, limits and cancellation.\n\t * @throws StudyError - Thrown with code `CONFIG` when the limit is not a positive safe integer, or the gauge scale is not finite and greater than 0 or its overhead is not finite and at least 0.\n\t */\n\tconstructor(options: StudyAgentSummaryOptions) {\n\t\t// Validate the owned readings so later caller mutation cannot change the bound.\n\t\tconst { limit } = options\n\t\tconst { scale, overhead } = options.gauge\n\t\tconst gauge = { scale, overhead }\n\t\tif (!Number.isSafeInteger(limit) || limit <= 0)\n\t\t\tthrow new StudyError('CONFIG', 'Summary limit must be a positive safe integer')\n\t\tif (!isStudyAgentGauge(gauge))\n\t\t\tthrow new StudyError(\n\t\t\t\t'CONFIG',\n\t\t\t\t'Summary gauge scale must be finite and positive and its overhead finite and nonnegative',\n\t\t\t)\n\t\tthis.#options = { ...options, limit, gauge }\n\t}\n\n\t/** Measures one canonical request, refuses it at the limit, and sends the very same array to the provider.\n\t * @param messages - The conversation to fold; the instruction follows as the final user turn.\n\t * @param signal - Bounds the request; the options' signal bounds it when omitted.\n\t * @returns The summary content, retained as evidence before a blank result is refused.\n\t * @throws StudyError - Thrown with code `CAPACITY` when the projection reaches the limit, and with code `FAULT` when usage is unusable, no goal is active, or the content is blank.\n\t */\n\tasync summarize(messages: readonly Message[], signal: AbortSignal | undefined): Promise<string> {\n\t\tconst { provider, runtime, trace, latch, gauge, limit, instruction } = this.#options\n\t\tconst bound = signal ?? this.#options.signal\n\t\tbound.throwIfAborted()\n\t\tlatch.check()\n\t\t// One canonical array: measured once, admitted or refused, then sent as the very same array. The\n\t\t// instruction is the final user turn, so the chat template opens a fresh reply instead of\n\t\t// continuing the last folded assistant message.\n\t\tconst canonical: readonly Message[] = [...messages, instruction]\n\t\tconst request: ProviderRequest = { messages: canonical }\n\t\tconst estimate = runtime.estimateRequest(request)\n\t\tconst projected = projectStudyAgentRequest(gauge, estimate)\n\t\tconst reading = { estimate, projected }\n\t\tif (projected >= limit) {\n\t\t\tconst message = 'Summary request projection reaches the summary room'\n\t\t\t// The refusal keeps its own admission, so the Agent's admission stays the one a later window refusal names.\n\t\t\tconst stamp = trace.measure('admission', 'summary', request, reading, undefined)\n\t\t\tif (stamp !== undefined)\n\t\t\t\ttrace.append('refusal', {\n\t\t\t\t\tcause: 'capacity',\n\t\t\t\t\trole: 'summary',\n\t\t\t\t\tordinal: stamp.ordinal,\n\t\t\t\t\trevision: stamp.revision,\n\t\t\t\t\tconsumed: projected,\n\t\t\t\t\tmax: limit,\n\t\t\t\t})\n\t\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\t\tcause: 'capacity',\n\t\t\t\tmessage,\n\t\t\t\trole: 'summary',\n\t\t\t\tstop: { layer: 'window', id: 'Summary room', max: limit, consumed: projected },\n\t\t\t})\n\t\t}\n\t\ttrace.dispatch('summary', request, reading)\n\t\tconst result = await provider.generate(canonical, bound)\n\t\tif (!bound.aborted) validateStudyAgentUsage(result.usage, 'summary')\n\t\tlatch.check()\n\t\tif (trace.goal === undefined || typeof result.content !== 'string')\n\t\t\tthrow new StudyError('FAULT', 'Summary outside an active goal or invalid content')\n\t\tconst value: unknown = {\n\t\t\tsources: messages.map((message) => message.id),\n\t\t\tcontent: result.content,\n\t\t}\n\t\tif (!isJSONValue(value)) throw new StudyError('FAULT', 'Summary evidence is not JSON')\n\t\ttrace.append('summary', cloneJSONValue(value))\n\t\tif (result.content.trim() === '') {\n\t\t\tconst message = 'Summary returned no usable content'\n\t\t\tthrow new StudyError('FAULT', message, {\n\t\t\t\tcause: 'content',\n\t\t\t\tmessage,\n\t\t\t\trole: 'summary',\n\t\t\t\tstop: undefined,\n\t\t\t})\n\t\t}\n\t\treturn result.content\n\t}\n}\n","import type { StudyAgentPlan, StudyAgentResponse } from './types.js'\n\n/** Serves one goal's owned response sequence in declared order. */\nexport class StudyAgentScriptGoal {\n\treadonly #plan: StudyAgentPlan\n\t#cursor = 0\n\n\t/** Binds one goal's owned plan.\n\t * @param plan - The validated plan whose response snapshot the provider owns.\n\t */\n\tconstructor(plan: StudyAgentPlan) {\n\t\tthis.#plan = plan\n\t}\n\n\t/** Reports the goal's owned plan. */\n\tget plan(): StudyAgentPlan {\n\t\treturn this.#plan\n\t}\n\n\t/** Takes the next declared response and advances past it.\n\t * @returns The response; undefined after the sequence is exhausted, which it then stays.\n\t */\n\ttake(): StudyAgentResponse | undefined {\n\t\tconst response = this.#plan.responses[this.#cursor]\n\t\tif (response !== undefined) this.#cursor++\n\t\treturn response\n\t}\n}\n","import type { StudyTicket } from '@src/core'\nimport type { Message, ProviderDelta, ProviderInterface, ProviderResult } from '@orkestrel/agent'\nimport type { StudyAgentPlan, StudyAgentResponse, StudyAgentScriptOptions } from './types.js'\nimport { StudyError, failStudyTicket } from '@src/core'\nimport { isBudgetError } from '@orkestrel/budget'\nimport { cloneJSONValue, isArray } from '@orkestrel/contract'\nimport { randomUUID } from 'node:crypto'\nimport { encodeStudyJSON } from '../helpers.js'\nimport {\n\tresolveStudyAgentContent,\n\treadStudyAgentMessages,\n\treadStudyAgentResult,\n} from './helpers.js'\nimport { isStudyAgentResponse } from './validators.js'\nimport { StudyAgentScriptGoal } from './StudyAgentScriptGoal.js'\n\n/** Serves declared inert responses through the actual Agent provider boundary. */\nexport class StudyAgentScript implements ProviderInterface {\n\treadonly id = randomUUID()\n\treadonly name = 'scripted-study'\n\treadonly #bytes: number\n\t// The prepared goal; `prepare` binds it and `clear` releases it. A running stream keeps the goal it took its response from.\n\t#goal: StudyAgentScriptGoal | undefined\n\t// The responses being served; a response joins when its stream starts and leaves when the stream settles.\n\treadonly #serving = new Set<StudyAgentResponse>()\n\n\t/**\n\t * Binds the encoded byte bound every served request and response must fit.\n\t * @param options - The explicit encoded bound; it is also each response's default admitted bytes\n\t * @throws StudyError - Thrown when the bound is not a nonnegative safe integer\n\t */\n\tconstructor(options: StudyAgentScriptOptions) {\n\t\tif (!Number.isSafeInteger(options.bytes) || options.bytes < 0)\n\t\t\tthrow new StudyError('CONFIG', 'Scripted byte bound must be a nonnegative safe integer')\n\t\tthis.#bytes = options.bytes\n\t}\n\n\t/**\n\t * Prepares one goal's declared response sequence and metered operational boundary until `clear` ends the goal.\n\t * @param plan - The workload's responses and its operational context\n\t * @returns Nothing when the provider is ready\n\t * @throws StudyError - Thrown with code `CONFIG` when a response is still running, a goal is already prepared, or a declared response is invalid; a prepared goal stays prepared\n\t */\n\tprepare(plan: StudyAgentPlan): void {\n\t\tif (this.#serving.size !== 0)\n\t\t\tthrow new StudyError('CONFIG', 'Cannot replace a running scripted workload')\n\t\tif (this.#goal !== undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Scripted goal is already prepared')\n\t\tif (!isArray(plan.responses) || !plan.responses.every(isStudyAgentResponse))\n\t\t\tthrow new StudyError('CONFIG', 'Scripted response sequence is invalid')\n\t\t// Own the declared calls so later caller mutation cannot change a served response; the\n\t\t// clone is re-narrowed through the guard rather than asserted.\n\t\tconst owned: unknown = plan.responses.map((response) => ({\n\t\t\t...response,\n\t\t\tcalls: cloneJSONValue(response.calls),\n\t\t}))\n\t\tif (!isArray(owned) || !owned.every(isStudyAgentResponse))\n\t\t\tthrow new StudyError('CONFIG', 'Scripted response sequence is invalid')\n\t\tthis.#goal = new StudyAgentScriptGoal({ ...plan, responses: Object.freeze(owned) })\n\t}\n\n\t/**\n\t * Ends the prepared goal so another goal can be prepared; a stream already running keeps serving its own goal.\n\t * @returns Nothing; a provider with no prepared goal stays unprepared\n\t */\n\tclear(): void {\n\t\tthis.#goal = undefined\n\t}\n\n\t/**\n\t * Consumes the same streaming response into its assembled provider result.\n\t * @param messages - The actual Agent conversation\n\t * @param signal - The enclosing Agent run signal\n\t * @returns The assembled declared response\n\t */\n\tasync generate(messages: readonly Message[], signal: AbortSignal): Promise<ProviderResult> {\n\t\treturn readStudyAgentResult(this.stream(messages, signal))\n\t}\n\n\t/**\n\t * Streams a declared response after authoritative admission and retains actual request bytes.\n\t * @param messages - The actual Agent conversation\n\t * @param signal - The enclosing Agent run signal\n\t * @returns The declared response, optionally consuming an actual prior tool message\n\t * @remarks\n\t * A stream abandoned after admission accounts for an Agent budget cut without latching a failure.\n\t * Other abandoned streams fail the admitted request with the run signal's reason, or a `FAULT`\n\t * when the signal carries none.\n\t * @throws StudyError - Thrown with code `CONFIG` when no goal is prepared, another response is running, or the responses are exhausted; thrown with the meter's refusal when admission fails\n\t */\n\tasync *stream(\n\t\tmessages: readonly Message[],\n\t\tsignal: AbortSignal,\n\t): AsyncGenerator<ProviderDelta, ProviderResult> {\n\t\tconst goal = this.#goal\n\t\tif (goal === undefined || this.#serving.size !== 0)\n\t\t\tthrow new StudyError('CONFIG', 'Scripted provider is unavailable')\n\t\tconst response = goal.take()\n\t\tif (response === undefined)\n\t\t\tthrow new StudyError('CONFIG', 'Scripted provider response sequence is exhausted')\n\t\tconst plan = goal.plan\n\t\tthis.#serving.add(response)\n\t\tconst started = performance.now()\n\t\ttry {\n\t\t\tconst request = readStudyAgentMessages(messages)\n\t\t\tconst content = resolveStudyAgentContent(request, response)\n\t\t\tconst result: ProviderResult = {\n\t\t\t\tcontent,\n\t\t\t\t...(response.calls.length === 0 ? {} : { tools: response.calls }),\n\t\t\t\t...(response.truncated === true ? { truncated: true } : {}),\n\t\t\t}\n\t\t\tconst bytes = encodeStudyJSON({ request, response: result }).byteLength\n\t\t\tif (bytes > this.#bytes) {\n\t\t\t\tconst message = 'Scripted request exceeds its encoded workload bound'\n\t\t\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\t\t\tcause: 'capacity',\n\t\t\t\t\tmessage,\n\t\t\t\t\trole: undefined,\n\t\t\t\t\tstop: { layer: 'scope', id: 'Scripted bytes', max: this.#bytes, consumed: bytes },\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst ticket = await this.#admit(plan, response)\n\t\t\ttry {\n\t\t\t\tconst bounded = AbortSignal.any([\n\t\t\t\t\tsignal,\n\t\t\t\t\tplan.context.signal,\n\t\t\t\t\tplan.context.meter.signal,\n\t\t\t\t\tticket.signal,\n\t\t\t\t])\n\t\t\t\tbounded.throwIfAborted()\n\t\t\t\tawait plan.context.evidence.append({\n\t\t\t\t\tevent: 'provider',\n\t\t\t\t\tgoal: plan.goal,\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\tcalls: response.calls.map((call) => ({\n\t\t\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\t\t\tname: call.name,\n\t\t\t\t\t\t\t\targuments: cloneJSONValue(call.arguments),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tif (content.length > 0) yield { channel: 'content', text: content }\n\t\t\t\tbounded.throwIfAborted()\n\t\t\t\tticket.finish({\n\t\t\t\t\trole: 'agent',\n\t\t\t\t\tcalls: 1,\n\t\t\t\t\ttokens: undefined,\n\t\t\t\t\tbytes,\n\t\t\t\t\tduration: Math.ceil(performance.now() - started),\n\t\t\t\t})\n\t\t\t\tif (response.abort === true) {\n\t\t\t\t\tawait plan.context.evidence.append({\n\t\t\t\t\t\tevent: 'workload',\n\t\t\t\t\t\tgoal: plan.goal,\n\t\t\t\t\t\tvalue: { aborted: true },\n\t\t\t\t\t})\n\t\t\t\t\tplan.workload.abort(new Error('Declared workload cancellation'))\n\t\t\t\t}\n\t\t\t\treturn result\n\t\t\t} catch (error) {\n\t\t\t\t// An Agent budget's cut is Agent's own stop, so the request is accounted and the layer stays in Agent's record.\n\t\t\t\tif (isBudgetError(error)) this.#cut(ticket, bytes, started)\n\t\t\t\telse failStudyTicket(ticket, error, 'agent')\n\t\t\t\tthrow error\n\t\t\t} finally {\n\t\t\t\t// Generator return skips the catch, before Agent publishes the stop's layer.\n\t\t\t\tif (isBudgetError(signal.reason)) this.#cut(ticket, bytes, started)\n\t\t\t\telse\n\t\t\t\t\tfailStudyTicket(\n\t\t\t\t\t\tticket,\n\t\t\t\t\t\tsignal.reason ??\n\t\t\t\t\t\t\tnew StudyError('FAULT', 'Scripted response was abandoned before completion'),\n\t\t\t\t\t\t'agent',\n\t\t\t\t\t)\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.#serving.delete(response)\n\t\t}\n\t}\n\n\t// Finishes an unsettled request that an Agent budget cut, with unknown tokens; a settled or aborted ticket is left untouched.\n\t#cut(ticket: StudyTicket, bytes: number, started: number): void {\n\t\tif (ticket.settled || ticket.signal.aborted) return\n\t\tticket.finish({\n\t\t\trole: 'agent',\n\t\t\tcalls: 1,\n\t\t\ttokens: undefined,\n\t\t\tbytes,\n\t\t\tduration: Math.ceil(performance.now() - started),\n\t\t})\n\t}\n\n\t// Admits the response's ceiling, retaining a refused admission as evidence before rethrowing it.\n\tasync #admit(plan: StudyAgentPlan, response: StudyAgentResponse): Promise<StudyTicket> {\n\t\ttry {\n\t\t\treturn await plan.context.meter.admit({\n\t\t\t\trole: 'agent',\n\t\t\t\ttokens: response.tokens ?? 1,\n\t\t\t\tbytes: response.bytes ?? this.#bytes,\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tawait plan.context.evidence.append({\n\t\t\t\tevent: 'admission',\n\t\t\t\tgoal: plan.goal,\n\t\t\t\tvalue: { role: 'agent', refused: true },\n\t\t\t})\n\t\t\tthrow error\n\t\t}\n\t}\n}\n","import type { StudyAgentDispatch } from '@src/core'\nimport type {\n\tStudyOllamaModel,\n\tStudyOllamaPolicy,\n\tStudyOllamaRole,\n\tStudyOllamaSnapshot,\n\tStudyOllamaTransportOptions,\n} from './types.js'\nimport { StudyError } from '@src/core'\n\n/**\n * Builds a frozen owned copy of transport configuration that later caller mutation cannot reach.\n * @remarks\n * Every caller member is read once, outer fields before nested data. Every nested data object is\n * copied and frozen; the caller's objects are never frozen. The cancellation signal, timing\n * extractor, and fetch collaborator keep their live identity.\n * @param options - The caller's transport configuration\n * @returns The owned configuration, not yet validated\n */\nexport function buildStudyOllamaTransportOptions(\n\toptions: StudyOllamaTransportOptions,\n): StudyOllamaTransportOptions {\n\tconst {\n\t\turl,\n\t\troom,\n\t\tlimit,\n\t\tmodels,\n\t\troles,\n\t\tsignal,\n\t\tobserve,\n\t\ttiming,\n\t\tfetch,\n\t\tmetadata,\n\t\tversion,\n\t\tprocedure,\n\t\texchanges,\n\t} = options\n\tif (Object.hasOwn(roles, 'maintenance'))\n\t\tthrow new StudyError('CONFIG', 'Maintenance cannot declare a generation policy')\n\tconst owned: Record<string, StudyOllamaModel> = Object.fromEntries(\n\t\tObject.entries(models).map(([label, { name, digest }]) => [\n\t\t\tlabel,\n\t\t\tObject.freeze({ name, digest }),\n\t\t]),\n\t)\n\tconst policies: Partial<Record<StudyOllamaRole, StudyOllamaPolicy>> = Object.fromEntries(\n\t\t(['agent', 'summary', 'judge'] as const).flatMap((role) => {\n\t\t\tconst policy = roles[role]\n\t\t\tif (policy === undefined) return []\n\t\t\tconst { model, options: wire, think, strict, length } = policy\n\t\t\treturn [\n\t\t\t\t[\n\t\t\t\t\trole,\n\t\t\t\t\tObject.freeze({ model, options: Object.freeze({ ...wire }), think, strict, length }),\n\t\t\t\t] as const,\n\t\t\t]\n\t\t}),\n\t)\n\tconst { context, safety } = room\n\tconst { duration, bytes } = limit\n\treturn Object.freeze({\n\t\turl,\n\t\troom: Object.freeze({ context, safety }),\n\t\tlimit: Object.freeze({ duration, bytes }),\n\t\tmodels: Object.freeze(owned),\n\t\troles: Object.freeze(policies),\n\t\tsignal,\n\t\tobserve,\n\t\ttiming,\n\t\tmetadata: Object.freeze({ ...metadata }),\n\t\t...(version === undefined ? {} : { version }),\n\t\t...(procedure === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tprocedure: Object.freeze(\n\t\t\t\t\t\tprocedure.map((step) => {\n\t\t\t\t\t\t\tconst { policy, ...identity } = step\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t(identity.admission === 'exact' && Object.hasOwn(step, 'bytes')) ||\n\t\t\t\t\t\t\t\t(identity.admission === 'capture' &&\n\t\t\t\t\t\t\t\t\t(Object.hasOwn(step, 'body') || Object.hasOwn(step, 'input')))\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tthrow new StudyError('CONFIG', 'Conflicting model-step admission declarations')\n\t\t\t\t\t\t\tconst { options: wire, ...settings } = policy\n\t\t\t\t\t\t\treturn Object.freeze({\n\t\t\t\t\t\t\t\t...identity,\n\t\t\t\t\t\t\t\tpolicy: Object.freeze({ ...settings, options: Object.freeze({ ...wire }) }),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\t...(exchanges === undefined ? {} : { exchanges }),\n\t\t...(fetch === undefined ? {} : { fetch }),\n\t})\n}\n\n/**\n * Builds an owned snapshot of one outbound request before anything is awaited.\n * @remarks\n * The URL spelling, accepted settings, headers, and dispatch are copied at the call, each caller\n * member read once; headers are cloned from the copied settings. The settings' `signal` keeps its\n * live identity so caller cancellation still reaches the request.\n * @param input - The requested URL\n * @param init - The native fetch settings\n * @param dispatch - The canonical dispatch the caller measured\n * @returns The owned request facts\n * @throws StudyError - Thrown with code `CONFIG` when the input is a `Request`\n */\nexport function buildStudyOllamaSnapshot(\n\tinput: string | URL | Request,\n\tinit: RequestInit | undefined,\n\tdispatch: StudyAgentDispatch | undefined,\n): StudyOllamaSnapshot {\n\tif (input instanceof Request)\n\t\tthrow new StudyError('CONFIG', 'Ollama transport requires explicit URL requests')\n\tconst copy = init === undefined ? undefined : { ...init }\n\treturn {\n\t\turl: typeof input === 'string' ? input : input.href,\n\t\tinit:\n\t\t\tcopy === undefined || copy.headers === undefined\n\t\t\t\t? copy\n\t\t\t\t: { ...copy, headers: new Headers(copy.headers) },\n\t\tdispatch: dispatch === undefined ? undefined : { id: dispatch.id, revision: dispatch.revision },\n\t}\n}\n","import type { OllamaTiming } from '@orkestrel/ollama'\nimport type { StudyOllamaTerminal, StudyOllamaWire } from './types.js'\nimport type { StudyExchangeReply } from '../stores/types.js'\nimport { StudyError } from '@src/core'\nimport { buildStudyOllamaBytes } from './helpers.js'\n\n/** Tracks one owned HTTP response through its counted bytes, decoded rows, terminal and settlement. */\nexport class StudyOllamaExchange implements StudyOllamaWire {\n\treadonly slot: StudyOllamaWire['slot']\n\treadonly identity: StudyOllamaWire['identity']\n\treadonly headers: StudyOllamaWire['headers']\n\treadonly ceiling: number\n\treadonly activity: StudyOllamaWire['activity']\n\treadonly request: StudyOllamaWire['request']\n\treadonly ticket: StudyOllamaWire['ticket']\n\treadonly signal: StudyOllamaWire['signal']\n\treadonly reader: StudyOllamaWire['reader']\n\treadonly decoder: StudyOllamaWire['decoder']\n\treadonly status: StudyOllamaWire['status']\n\treadonly started: StudyOllamaWire['started']\n\treadonly id: StudyOllamaWire['id']\n\treadonly sent: StudyOllamaWire['sent']\n\treadonly dispatch: StudyOllamaWire['dispatch']\n\t#bytes: number\n\t#text = ''\n\t#terminal: StudyOllamaTerminal | undefined\n\t#timing: OllamaTiming | undefined\n\t#settled = false\n\t#chunks: readonly Uint8Array[] = []\n\t#recorded = false\n\n\t/** Binds the facts of one dispatched request and its open response.\n\t * @param wire - The request, accounting boundary, reader and identities; its byte count starts the tally.\n\t */\n\tconstructor(\n\t\twire: Pick<\n\t\t\tStudyOllamaWire,\n\t\t\t| 'activity'\n\t\t\t| 'request'\n\t\t\t| 'ticket'\n\t\t\t| 'signal'\n\t\t\t| 'reader'\n\t\t\t| 'decoder'\n\t\t\t| 'status'\n\t\t\t| 'started'\n\t\t\t| 'id'\n\t\t\t| 'sent'\n\t\t\t| 'dispatch'\n\t\t\t| 'bytes'\n\t\t\t| 'slot'\n\t\t\t| 'identity'\n\t\t\t| 'headers'\n\t\t\t| 'ceiling'\n\t\t>,\n\t) {\n\t\tthis.slot = wire.slot\n\t\tthis.identity = wire.identity\n\t\tthis.headers = wire.headers\n\t\tthis.ceiling = wire.ceiling\n\t\tthis.activity = wire.activity\n\t\tthis.request = wire.request\n\t\tthis.ticket = wire.ticket\n\t\tthis.signal = wire.signal\n\t\tthis.reader = wire.reader\n\t\tthis.decoder = wire.decoder\n\t\tthis.status = wire.status\n\t\tthis.started = wire.started\n\t\tthis.id = wire.id\n\t\tthis.sent = wire.sent\n\t\tthis.dispatch = wire.dispatch\n\t\tthis.#bytes = wire.bytes\n\t}\n\n\t/** Holds the encoded request bytes plus every response byte counted so far. */\n\tget bytes(): number {\n\t\treturn this.#bytes\n\t}\n\n\t/** Holds the decoded response text not yet consumed as complete rows. */\n\tget text(): string {\n\t\treturn this.#text\n\t}\n\n\t/** Holds the validated terminal row once observed. */\n\tget terminal(): StudyOllamaTerminal | undefined {\n\t\treturn this.#terminal\n\t}\n\n\t/** Holds the daemon timing of the terminal row once observed. */\n\tget timing(): OllamaTiming | undefined {\n\t\treturn this.#timing\n\t}\n\n\t/** Reports whether the request was accounted, finished or failed. */\n\tget settled(): boolean {\n\t\treturn this.#settled\n\t}\n\n\t/** Reports whether a sidecar terminal has already been admitted. */\n\tget recorded(): boolean {\n\t\treturn this.#recorded\n\t}\n\n\t/** Holds the exact bounded bytes and native chunk lengths observed so far. */\n\tget reply(): StudyExchangeReply {\n\t\treturn {\n\t\t\tstatus: this.status,\n\t\t\theaders: this.headers,\n\t\t\t...buildStudyOllamaBytes(Buffer.concat(this.#chunks)),\n\t\t\tchunks: this.#chunks.map((chunk) => chunk.byteLength),\n\t\t}\n\t}\n\n\t/** Retains one bounded chunk before decoding changes its representation.\n\t * @param chunk - The native response bytes already counted under the ceiling.\n\t */\n\tretain(chunk: Uint8Array): void {\n\t\tif (this.identity !== undefined && chunk.byteLength > 0)\n\t\t\tthis.#chunks = [...this.#chunks, Buffer.from(chunk)]\n\t}\n\n\t/** Marks a sidecar terminal admitted so failure cleanup cannot append another. */\n\trecord(): void {\n\t\tthis.#recorded = true\n\t}\n\n\t/** Adds a response chunk's bytes to the tally and refuses a tally beyond the allowance.\n\t * @param length - The chunk's byte length.\n\t * @param limit - The response byte allowance.\n\t * @throws StudyError - Thrown with code `CAPACITY` and the request's role when the tally exceeds the allowance.\n\t */\n\tcount(length: number, limit: number): void {\n\t\tthis.#bytes += length\n\t\tif (this.#bytes <= limit) return\n\t\tconst message = 'Ollama wire byte allowance exceeded'\n\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\tcause: 'capacity',\n\t\t\tmessage,\n\t\t\trole: this.request.role,\n\t\t\tstop: { layer: 'scope', id: 'Wire bytes', max: limit, consumed: this.#bytes },\n\t\t})\n\t}\n\n\t/** Appends a chunk to the retained text through the strict decoder.\n\t * @param chunk - The next response bytes.\n\t * @throws TypeError - Thrown when the bytes are not valid UTF-8.\n\t */\n\tdecode(chunk: Uint8Array): void {\n\t\tthis.#text += this.decoder.decode(chunk, { stream: true })\n\t}\n\n\t/** Appends what the strict decoder still holds after the last chunk.\n\t * @throws TypeError - Thrown when the bytes ended inside a UTF-8 sequence.\n\t */\n\tflush(): void {\n\t\tthis.#text += this.decoder.decode()\n\t}\n\n\t/** Takes the complete lines of the retained text and keeps the unfinished tail.\n\t * @param final - If `true`, the whole text is consumed and nothing is kept; if `false`, the last line is kept as an unfinished tail.\n\t * @returns The lines in arrival order.\n\t */\n\ttake(final: boolean): readonly string[] {\n\t\tconst lines = this.#text.split(/\\r\\n|\\n/)\n\t\tthis.#text = final ? '' : (lines.at(-1) ?? '')\n\t\treturn final ? lines : lines.slice(0, -1)\n\t}\n\n\t/** Retains what a row read as its terminal and its daemon timing.\n\t * @param terminal - The terminal the row validated as, or undefined when the row is not terminal.\n\t * @param timing - The daemon timing of that row, or undefined when it is not observed.\n\t */\n\tobserve(terminal: StudyOllamaTerminal | undefined, timing: OllamaTiming | undefined): void {\n\t\tthis.#terminal = terminal\n\t\tthis.#timing = timing\n\t}\n\n\t/** Marks the request accounted, finished or failed. */\n\tsettle(): void {\n\t\tthis.#settled = true\n\t}\n}\n","import type { JSONValue } from '@orkestrel/contract'\nimport type { StudyOllamaActivity } from './types.js'\n\n/** Holds one goal's accounting boundary and whether its checkpoint has joined a dispatch row. */\nexport class StudyOllamaGoal {\n\treadonly #activity: StudyOllamaActivity\n\t#attached = false\n\n\t/** Binds one goal's accounting boundary.\n\t * @param activity - The goal's admitted activity; it is held by reference.\n\t */\n\tconstructor(activity: StudyOllamaActivity) {\n\t\tthis.#activity = activity\n\t}\n\n\t/** Reports the goal's accounting boundary. */\n\tget activity(): StudyOllamaActivity {\n\t\treturn this.#activity\n\t}\n\n\t/** Hands out the goal's checkpoint for its first observed dispatch.\n\t * @returns The checkpoint the first time it is asked for; undefined afterwards and whenever the goal has none.\n\t */\n\tattach(): JSONValue | undefined {\n\t\tconst checkpoint = this.#activity.checkpoint\n\t\tif (checkpoint === undefined || this.#attached) return undefined\n\t\tthis.#attached = true\n\t\treturn checkpoint\n\t}\n}\n","import type { StudyRole, StudyTicket, StudyAgentDispatch, StudyLatchInterface } from '@src/core'\nimport type { BudgetError } from '@orkestrel/budget'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type { OllamaTiming } from '@orkestrel/ollama'\nimport type { ReadableStreamReadResult } from 'node:stream/web'\nimport type {\n\tStudyOllamaActivity,\n\tStudyOllamaFetchFunction,\n\tStudyOllamaRequest,\n\tStudyOllamaSnapshot,\n\tStudyOllamaTerminal,\n\tStudyOllamaTransportOptions,\n} from './types.js'\nimport type { StudyExchangeIdentity } from '../stores/types.js'\nimport {\n\tStudyError,\n\tisStudyError,\n\tStudyControl,\n\tStudyScope,\n\tStudyMeter,\n\treadStudyFailure,\n\tbuildStudyAgentDispatch,\n\tstudyStopToJSON,\n} from '@src/core'\nimport { Abort } from '@orkestrel/abort'\nimport { isBudgetError } from '@orkestrel/budget'\nimport { isFunction, isRecord, parseJSON } from '@orkestrel/contract'\nimport { MAX_TIMEOUT_MS } from '@orkestrel/timeout'\nimport { buildStudyOllamaSnapshot, buildStudyOllamaTransportOptions } from './cloners.js'\nimport { StudyOllamaExchange } from './StudyOllamaExchange.js'\nimport { StudyOllamaGoal } from './StudyOllamaGoal.js'\nimport {\n\tbuildStudyOllamaRaw,\n\tbuildStudyOllamaTiming,\n\treadStudyOllamaDigest,\n\treadStudyOllamaFailure,\n\treadStudyOllamaRequest,\n\treadStudyOllamaSupport,\n\treadStudyOllamaTerminal,\n\treadStudyOllamaTiming,\n\tvalidateStudyOllamaCompletion,\n\tvalidateStudyOllamaInventory,\n\tvalidateStudyOllamaRoles,\n\tvalidateStudyOllamaRecording,\n\tvalidateStudyOllamaStep,\n\tbuildStudyOllamaBytes,\n} from './helpers.js'\n\n/** Admits and accounts Ollama wire requests under declared policies and latches failure. */\nexport class StudyOllamaTransport implements StudyLatchInterface {\n\treadonly #options: StudyOllamaTransportOptions\n\treadonly #abort = new AbortController()\n\treadonly #sends = new Set<Promise<StudyOllamaExchange>>()\n\treadonly #wires = new Set<StudyOllamaExchange>()\n\treadonly #requests = new Set<symbol>()\n\treadonly #verifications = new Set<symbol>()\n\treadonly #metadataControl: StudyControl\n\treadonly #metadataScope: StudyScope\n\treadonly #metadataMeter: StudyMeter\n\t#passes = 0\n\t#step = 0\n\t// The bound goal; `prepare` binds it and `clear` or `close` releases it. An admitted request keeps the goal it was admitted under.\n\t#goal: StudyOllamaGoal | undefined\n\t// Wraps the first retained failure so a thrown undefined or null is still a presence.\n\t#fault: { readonly error: unknown } | undefined\n\t#count = 0\n\t// The model of the preceding model dispatch; it spans goals, so the next goal's first dispatch reports a switch.\n\t#previous: string | undefined\n\n\t/** Records immutable transport bounds and refuses a role policy the inventory cannot serve.\n\t * @param options - Origin, room, request limit, pinned inventory, role policies, and cancellation.\n\t */\n\tconstructor(options: StudyOllamaTransportOptions) {\n\t\tconst owned = buildStudyOllamaTransportOptions(options)\n\t\tif (owned.fetch !== undefined && !isFunction(owned.fetch))\n\t\t\tthrow new StudyError('CONFIG', 'Ollama fetch collaborator must be callable')\n\t\tvalidateStudyOllamaRoles(owned.roles, owned.models)\n\t\tvalidateStudyOllamaRecording(owned)\n\t\tthis.#options = owned\n\t\tthis.#metadataControl = new StudyControl(owned.signal)\n\t\tconst duration = Math.min(MAX_TIMEOUT_MS, Math.ceil(owned.metadata.duration))\n\t\tthis.#metadataScope = new StudyScope({\n\t\t\tlimit: { ...owned.metadata, duration: MAX_TIMEOUT_MS, tokens: 1 },\n\t\t\tcontrol: this.#metadataControl,\n\t\t\tlabel: 'Metadata',\n\t\t})\n\t\tthis.#metadataMeter = new StudyMeter({\n\t\t\trequest: {\n\t\t\t\tduration: Math.min(duration, owned.limit.duration),\n\t\t\t\tcalls: 1,\n\t\t\t\ttokens: 1,\n\t\t\t\tbytes: owned.metadata.bytes,\n\t\t\t},\n\t\t\tscopes: [this.#metadataScope],\n\t\t\tcontrol: this.#metadataControl,\n\t\t})\n\t}\n\n\t/** Binds subsequent wire requests to one live goal until `clear` or `close` ends it.\n\t * @param activity - The goal's accounting boundary.\n\t * @throws StudyError - Thrown with code `FAULT` when a model response is still open or a goal is still bound; the bound goal stays bound.\n\t * @throws unknown - Thrown with the retained failure or the cancellation reason, as `check` throws it.\n\t */\n\tprepare(activity: StudyOllamaActivity): void {\n\t\tthis.check()\n\t\tif (this.#wires.size !== 0)\n\t\t\tthrow new StudyError('FAULT', 'Previous model response is still open')\n\t\tif (this.#goal !== undefined) throw new StudyError('FAULT', 'Previous goal is still bound')\n\t\tthis.#goal = new StudyOllamaGoal(activity)\n\t}\n\n\t/** Ends the bound goal so another goal can be prepared; a request already admitted keeps its own goal.\n\t * @returns Nothing; a transport with no bound goal stays unbound, and a closed transport stays closed.\n\t */\n\tclear(): void {\n\t\tthis.#goal = undefined\n\t}\n\n\t/** Refuses work after any retained failure or cancellation.\n\t * @returns Nothing when work may continue.\n\t */\n\tcheck(): void {\n\t\tif (this.#fault !== undefined) throw this.#fault.error\n\t\tthis.#options.signal.throwIfAborted()\n\t\tthis.#abort.signal.throwIfAborted()\n\t}\n\n\t/** Retains an operational failure even when an inner runtime catches it.\n\t * @param error - The observed failure; the first retained failure keeps its identity, and a branded `BudgetError` retains nothing because Agent reports that stop in its own result.\n\t */\n\tfail(error: unknown): void {\n\t\t// An Agent budget's cut is reported by Agent's own result, so nothing is retained to re-raise.\n\t\tif (!isBudgetError(error)) this.#fault ??= { error }\n\t}\n\n\t/** Checks every pinned serving identity through admitted inventory and metadata requests.\n\t * @returns Completion after inventory validation and support evidence.\n\t * @throws StudyError - Thrown with code `FAULT` when no goal is bound; the transport retains this refusal as its failure, as it retains every verification failure.\n\t */\n\tasync verify(): Promise<void> {\n\t\tconst verification = Symbol('verification')\n\t\ttry {\n\t\t\tthis.check()\n\t\t\tif (this.#requests.size !== 0 || this.#verifications.size !== 0)\n\t\t\t\tthrow new StudyError('FAULT', 'Verification cannot overlap an admitted request')\n\t\t\tif (this.#goal === undefined)\n\t\t\t\tthrow new StudyError('FAULT', 'Model dispatch outside an active goal')\n\t\t\tif (\n\t\t\t\tthis.#options.procedure !== undefined &&\n\t\t\t\t(this.#passes > 1 || (this.#passes === 1 && this.#step !== this.#options.procedure.length))\n\t\t\t)\n\t\t\t\tthrow new StudyError('FAULT', 'Postflight requires the complete model procedure')\n\t\t\tthis.#verifications.add(verification)\n\t\t\tif (this.#options.version !== undefined) {\n\t\t\t\tconst version = await this.fetch('metadata', new URL('/api/version', this.#options.url), {\n\t\t\t\t\tmethod: 'GET',\n\t\t\t\t})\n\t\t\t\tawait version.text()\n\t\t\t}\n\t\t\tconst response = await this.fetch('metadata', new URL('/api/tags', this.#options.url), {\n\t\t\t\tmethod: 'GET',\n\t\t\t})\n\t\t\tconst value: unknown = await response.json()\n\t\t\tvalidateStudyOllamaInventory(value, this.#options.models)\n\t\t\tconst goal = this.#goal\n\t\t\tif (goal === undefined) throw new StudyError('FAULT', 'Inventory has no goal attribution')\n\t\t\tconst activity = goal.activity\n\t\t\tconst models = Object.values(this.#options.models)\n\t\t\tfor (const model of new Set(models.map((entry) => entry.name))) {\n\t\t\t\tconst support = await this.fetch('metadata', new URL('/api/show', this.#options.url), {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tbody: JSON.stringify({ model }),\n\t\t\t\t\theaders: { 'content-type': 'application/json' },\n\t\t\t\t})\n\t\t\t\tconst metadata: unknown = await support.json()\n\t\t\t\tconst ceiling = readStudyOllamaSupport(metadata, this.#options.room.context)\n\t\t\t\tawait activity.context.evidence.append({\n\t\t\t\t\tevent: 'support',\n\t\t\t\t\tgoal: activity.goal,\n\t\t\t\t\tvalue: { model, ceiling, requested: this.#options.room.context },\n\t\t\t\t})\n\t\t\t}\n\t\t\tawait activity.context.evidence.append({\n\t\t\t\tevent: 'inventory',\n\t\t\t\tgoal: activity.goal,\n\t\t\t\tvalue: Object.fromEntries(\n\t\t\t\t\tObject.entries(this.#options.models).map(([label, model]) => [label, model.digest]),\n\t\t\t\t),\n\t\t\t})\n\t\t\tthis.check()\n\t\t\tthis.#passes += 1\n\t\t\tif (this.#options.exchanges !== undefined && this.#passes === 2) {\n\t\t\t\tif (this.#requests.size !== 0 || this.#sends.size !== 0 || this.#wires.size !== 0)\n\t\t\t\t\tthrow new StudyError('FAULT', 'Cannot complete while an exchange is pending')\n\t\t\t\tawait this.#options.exchanges.append({\n\t\t\t\t\tphase: 'complete',\n\t\t\t\t\tcount: this.#options.exchanges.next - 1,\n\t\t\t\t})\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.fail(error)\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tthis.#verifications.delete(verification)\n\t\t}\n\t}\n\n\t/** Dispatches exactly one admitted request with bounded streaming reads.\n\t * @param role - The accountable responsibility.\n\t * @param input - The exact configured URL.\n\t * @param init - The native fetch settings.\n\t * @param original - The immutable canonical dispatch the caller measured for this request; it joins the observation rows and never changes the request.\n\t * @returns A validated streaming response.\n\t * @throws StudyError - Thrown with code `FAULT` when no goal is bound, before admission and without retaining a failure.\n\t * @throws StudyError - Thrown with the recognized provider failure or a role-attributed `FAULT` for a non-2xx response, after its bounded body was read and its request accounted once.\n\t */\n\tasync fetch(\n\t\trole: StudyRole,\n\t\tinput: string | URL | Request,\n\t\tinit?: RequestInit,\n\t\toriginal?: StudyAgentDispatch,\n\t): Promise<Response> {\n\t\tthis.check()\n\t\tconst goal = this.#goal\n\t\tif (goal === undefined) throw new StudyError('FAULT', 'Model dispatch outside an active goal')\n\t\tconst activity = goal.activity\n\t\tconst slot = Symbol('request')\n\t\ttry {\n\t\t\tif (this.#requests.size !== 0)\n\t\t\t\tthrow new StudyError('FAULT', 'A previous Ollama request is still in flight')\n\t\t\tif (this.#verifications.size !== 0 && role !== 'metadata')\n\t\t\t\tthrow new StudyError('FAULT', 'Model dispatch cannot overlap verification')\n\t\t\tthis.#requests.add(slot)\n\t\t\t// Everything the request depends on is owned before the first await; the caller's originals are never read again.\n\t\t\tconst snapshot = buildStudyOllamaSnapshot(input, init, original)\n\t\t\tconst settings = snapshot.init\n\t\t\tconst request = readStudyOllamaRequest(this.#options, role, snapshot.url, settings)\n\t\t\tif (this.#options.procedure !== undefined && role !== 'metadata') {\n\t\t\t\tif (this.#passes !== 1)\n\t\t\t\t\tthrow new StudyError(\n\t\t\t\t\t\t'FAULT',\n\t\t\t\t\t\t'Model dispatch requires completed preflight and open execution',\n\t\t\t\t\t)\n\t\t\t\tvalidateStudyOllamaStep(\n\t\t\t\t\tthis.#options.procedure[this.#step],\n\t\t\t\t\tactivity.goal,\n\t\t\t\t\trequest,\n\t\t\t\t\tsettings?.body,\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (\n\t\t\t\tthis.#options.exchanges !== undefined &&\n\t\t\t\trole === 'metadata' &&\n\t\t\t\tthis.#verifications.size === 0\n\t\t\t)\n\t\t\t\tthrow new StudyError('FAULT', 'Recorded metadata requires a verification pass')\n\t\t\treturn await this.#request(slot, role, goal, request, snapshot)\n\t\t} catch (error) {\n\t\t\tthis.#requests.delete(slot)\n\t\t\tthis.fail(error)\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/** Cancels every outstanding native reader and permanently closes the transport.\n\t * @returns Completion after finite native cancellation.\n\t */\n\tasync close(): Promise<void> {\n\t\tthis.#abort.abort(new StudyError('FAULT', 'Ollama transport closed'))\n\t\tawait Promise.all(\n\t\t\t[...this.#sends].map((sending) => sending.catch((error: unknown) => this.fail(error))),\n\t\t)\n\t\tawait Promise.all(\n\t\t\t[...this.#wires].map((wire) => this.#failWire(wire, this.#abort.signal.reason)),\n\t\t)\n\t\tthis.#goal = undefined\n\t\tthis.#metadataMeter.close()\n\t\tthis.#metadataScope.close()\n\t\tthis.#metadataControl.close()\n\t}\n\n\tasync #request(\n\t\tslot: symbol,\n\t\trole: StudyRole,\n\t\tgoal: StudyOllamaGoal,\n\t\trequest: StudyOllamaRequest,\n\t\tsnapshot: StudyOllamaSnapshot,\n\t): Promise<Response> {\n\t\tconst activity = goal.activity\n\t\tconst settings = snapshot.init\n\t\tconst metadata = role === 'metadata'\n\t\tconst available =\n\t\t\tthis.#options.metadata.bytes -\n\t\t\tthis.#metadataMeter.usage.reduce(\n\t\t\t\t(total, usage) => total + (usage.bytes ?? this.#options.metadata.bytes),\n\t\t\t\t0,\n\t\t\t)\n\t\tconst remaining = this.#remaining\n\t\tif (metadata && remaining <= 0)\n\t\t\tthrow new StudyError('DEADLINE', 'Metadata duration allowance exhausted', {\n\t\t\t\tcause: 'deadline',\n\t\t\t\tmessage: 'Metadata duration allowance exhausted',\n\t\t\t\trole,\n\t\t\t\tstop: {\n\t\t\t\t\tlayer: 'scope',\n\t\t\t\t\tid: 'Metadata duration',\n\t\t\t\t\tmax: this.#options.metadata.duration,\n\t\t\t\t\tconsumed: this.#options.metadata.duration - remaining,\n\t\t\t\t},\n\t\t\t})\n\t\tconst limit = {\n\t\t\tduration: metadata\n\t\t\t\t? Math.min(this.#options.limit.duration, Math.ceil(remaining))\n\t\t\t\t: this.#options.limit.duration,\n\t\t\tbytes: metadata ? Math.min(this.#options.limit.bytes, available) : this.#options.limit.bytes,\n\t\t}\n\t\tif (request.bytes >= limit.bytes) {\n\t\t\tconst message = 'Encoded request consumes the response byte allowance'\n\t\t\tthrow new StudyError('CAPACITY', message, {\n\t\t\t\tcause: 'capacity',\n\t\t\t\tmessage,\n\t\t\t\trole,\n\t\t\t\tstop: { layer: 'scope', id: 'Wire bytes', max: limit.bytes, consumed: request.bytes },\n\t\t\t})\n\t\t}\n\t\tconst ticket = await (metadata ? this.#metadataMeter : activity.context.meter).admit({\n\t\t\trole,\n\t\t\ttokens: role === 'metadata' ? 0 : this.#options.room.context - this.#options.room.safety,\n\t\t\tbytes: limit.bytes,\n\t\t})\n\t\tconst id = this.#options.exchanges?.next ?? ++this.#count\n\t\tconst started = performance.now()\n\t\tconst signal = AbortSignal.any([\n\t\t\tthis.#options.signal,\n\t\t\tthis.#abort.signal,\n\t\t\tactivity.context.signal,\n\t\t\t...(metadata ? [this.#metadataMeter.signal] : [activity.context.meter.signal]),\n\t\t\tticket.signal,\n\t\t\tAbortSignal.timeout(limit.duration),\n\t\t\t...(settings?.signal === undefined || settings.signal === null ? [] : [settings.signal]),\n\t\t])\n\t\tconst identity: StudyExchangeIdentity | undefined =\n\t\t\tthis.#options.exchanges === undefined\n\t\t\t\t? undefined\n\t\t\t\t: {\n\t\t\t\t\t\tordinal: id,\n\t\t\t\t\t\tgoal: activity.goal,\n\t\t\t\t\t\trole,\n\t\t\t\t\t\tpath:\n\t\t\t\t\t\t\trole === 'metadata'\n\t\t\t\t\t\t\t\t? request.path === '/api/version'\n\t\t\t\t\t\t\t\t\t? '/api/version'\n\t\t\t\t\t\t\t\t\t: request.path === '/api/tags'\n\t\t\t\t\t\t\t\t\t\t? '/api/tags'\n\t\t\t\t\t\t\t\t\t\t: '/api/show'\n\t\t\t\t\t\t\t\t: role === 'judge'\n\t\t\t\t\t\t\t\t\t? '/api/generate'\n\t\t\t\t\t\t\t\t\t: '/api/chat',\n\t\t\t\t\t\tmethod: settings?.method === 'GET' ? 'GET' : 'POST',\n\t\t\t\t\t\tstage:\n\t\t\t\t\t\t\trole === 'metadata' ? (this.#passes === 0 ? 'preflight' : 'postflight') : 'execution',\n\t\t\t\t\t\t...(role === 'metadata' ? {} : { step: this.#step + 1 }),\n\t\t\t\t\t}\n\t\tconst sending = this.#send(\n\t\t\trole,\n\t\t\tgoal,\n\t\t\tticket,\n\t\t\trequest,\n\t\t\tsnapshot,\n\t\t\tsignal,\n\t\t\tid,\n\t\t\tstarted,\n\t\t\tslot,\n\t\t\tidentity,\n\t\t\tlimit.bytes,\n\t\t)\n\t\tthis.#sends.add(sending)\n\t\tconst wire = await sending.finally(() => this.#sends.delete(sending))\n\t\tif (wire.status < 200 || wire.status > 299) return await this.#refuse(wire)\n\t\treturn new Response(\n\t\t\tnew ReadableStream<Uint8Array>({\n\t\t\t\tpull: (controller) => this.#pull(wire, controller),\n\t\t\t\t// A consumer cancel without a reason is the only absence; any thrown value keeps its identity.\n\t\t\t\tcancel: (reason: unknown) =>\n\t\t\t\t\tisBudgetError(reason)\n\t\t\t\t\t\t? this.#cut(wire, reason)\n\t\t\t\t\t\t: this.#failWire(\n\t\t\t\t\t\t\t\twire,\n\t\t\t\t\t\t\t\treason === undefined\n\t\t\t\t\t\t\t\t\t? new StudyError('FAULT', 'Ollama response cancelled before its end')\n\t\t\t\t\t\t\t\t\t: reason,\n\t\t\t\t\t\t\t),\n\t\t\t}),\n\t\t\t{\n\t\t\t\tstatus: wire.status,\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type':\n\t\t\t\t\t\trole === 'judge' || role === 'metadata' ? 'application/json' : 'application/x-ndjson',\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\n\tget #remaining(): number {\n\t\treturn (\n\t\t\tthis.#options.metadata.duration -\n\t\t\tthis.#metadataMeter.usage.reduce((total, usage) => total + usage.duration, 0)\n\t\t)\n\t}\n\n\t// Buffers a non-2xx body under the wire bounds and parses it once at its end, because an error body is one JSON document, not rows.\n\tasync #refuse(wire: StudyOllamaExchange): Promise<never> {\n\t\tconst failure = await this.#diagnose(wire)\n\t\tawait this.#failWire(wire, failure)\n\t\tthrow failure\n\t}\n\n\t// Reads the refusal body to its end and returns the failure it names, or the error that stopped the read.\n\tasync #diagnose(wire: StudyOllamaExchange): Promise<unknown> {\n\t\t// A lenient decoder: undecodable bytes make the body invalid JSON, which is a generic refusal rather than a decode crash.\n\t\tconst decoder = new TextDecoder()\n\t\tconst parts: string[] = []\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\twire.signal.throwIfAborted()\n\t\t\t\tconst chunk = await this.#read(wire)\n\t\t\t\twire.signal.throwIfAborted()\n\t\t\t\tif (chunk.done) break\n\t\t\t\twire.count(chunk.value.byteLength, wire.ceiling)\n\t\t\t\twire.retain(chunk.value)\n\t\t\t\tparts.push(decoder.decode(chunk.value, { stream: true }))\n\t\t\t}\n\t\t\tconst body: unknown = parseJSON(parts.join('') + decoder.decode())\n\t\t\tconst message = `Ollama HTTP response refused: ${wire.status}`\n\t\t\treturn (\n\t\t\t\treadStudyOllamaFailure(body, wire.request.role, wire.status) ??\n\t\t\t\tnew StudyError('FAULT', message, {\n\t\t\t\t\tcause: 'infrastructure',\n\t\t\t\t\tmessage,\n\t\t\t\t\trole: wire.request.role,\n\t\t\t\t\tstop: undefined,\n\t\t\t\t})\n\t\t\t)\n\t\t} catch (error) {\n\t\t\treturn error\n\t\t}\n\t}\n\n\tasync #pull(\n\t\twire: StudyOllamaExchange,\n\t\tcontroller: ReadableStreamDefaultController<Uint8Array>,\n\t): Promise<void> {\n\t\ttry {\n\t\t\twire.signal.throwIfAborted()\n\t\t\tconst chunk = await this.#read(wire)\n\t\t\twire.signal.throwIfAborted()\n\t\t\tif (!chunk.done) {\n\t\t\t\twire.count(chunk.value.byteLength, wire.ceiling)\n\t\t\t\twire.retain(chunk.value)\n\t\t\t\twire.decode(chunk.value)\n\t\t\t\tif (wire.request.role !== 'metadata' && wire.request.role !== 'judge')\n\t\t\t\t\tthis.#rows(wire, false)\n\t\t\t\tcontroller.enqueue(chunk.value)\n\t\t\t\treturn\n\t\t\t}\n\t\t\twire.flush()\n\t\t\tif (wire.request.role === 'metadata') {\n\t\t\t\tconst value: unknown = JSON.parse(wire.text)\n\t\t\t\tif (wire.request.path === '/api/tags')\n\t\t\t\t\tvalidateStudyOllamaInventory(value, this.#options.models)\n\t\t\t\telse if (wire.request.path === '/api/version') {\n\t\t\t\t\tif (!isRecord(value) || value.version !== this.#options.version)\n\t\t\t\t\t\tthrow new StudyError('FAULT', 'Serving version differs from the declared version')\n\t\t\t\t} else readStudyOllamaSupport(value, this.#options.room.context)\n\t\t\t} else if (wire.request.role === 'judge') {\n\t\t\t\tthis.#observe(wire, JSON.parse(wire.text))\n\t\t\t} else this.#rows(wire, true)\n\t\t\tif (wire.request.role !== 'metadata' && wire.terminal === undefined)\n\t\t\t\tthrow new StudyError('FAULT', 'Ollama response has no terminal row')\n\t\t\tawait this.#finish(wire)\n\t\t\tif (wire.request.role === 'metadata' && this.#remaining < 0) {\n\t\t\t\tconst message = 'Metadata duration allowance exhausted'\n\t\t\t\tthrow new StudyError('DEADLINE', message, {\n\t\t\t\t\tcause: 'deadline',\n\t\t\t\t\tmessage,\n\t\t\t\t\trole: 'metadata',\n\t\t\t\t\tstop: {\n\t\t\t\t\t\tlayer: 'scope',\n\t\t\t\t\t\tid: 'Metadata duration',\n\t\t\t\t\t\tmax: this.#options.metadata.duration,\n\t\t\t\t\t\tconsumed: this.#options.metadata.duration - this.#remaining,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (wire.terminal !== undefined) await this.#judge(wire, wire.terminal)\n\t\t\tif (wire.identity !== undefined) {\n\t\t\t\tthis.check()\n\t\t\t\tawait this.#options.exchanges?.append({\n\t\t\t\t\tphase: 'response',\n\t\t\t\t\t...wire.identity,\n\t\t\t\t\t...wire.reply,\n\t\t\t\t})\n\t\t\t\twire.record()\n\t\t\t\tif (wire.identity.step !== undefined) this.#step += 1\n\t\t\t}\n\t\t\tthis.#requests.delete(wire.slot)\n\t\t\tcontroller.close()\n\t\t} catch (error) {\n\t\t\tthis.fail(error)\n\t\t\ttry {\n\t\t\t\tif (wire.settled) await this.#recordFailure(wire, error)\n\t\t\t\tif (isBudgetError(error)) await this.#cut(wire, error)\n\t\t\t\telse await this.#failWire(wire, error)\n\t\t\t} finally {\n\t\t\t\tthis.#requests.delete(wire.slot)\n\t\t\t\tcontroller.error(error)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Checks the terminal against the wire's declared policy; a refusal that names a stop is retained as one `stop` row before it propagates.\n\tasync #judge(wire: StudyOllamaExchange, terminal: StudyOllamaTerminal): Promise<void> {\n\t\ttry {\n\t\t\tvalidateStudyOllamaCompletion(terminal, this.#options.room, wire.request)\n\t\t} catch (error) {\n\t\t\tconst stop = readStudyFailure(error).stop\n\t\t\tif (stop !== undefined)\n\t\t\t\tawait wire.activity.context.evidence.append({\n\t\t\t\t\tevent: 'stop',\n\t\t\t\t\tgoal: wire.activity.goal,\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\trole: wire.request.role,\n\t\t\t\t\t\tpath: wire.request.path,\n\t\t\t\t\t\tfinish: terminal.reason,\n\t\t\t\t\t\tprompt: terminal.prompt ?? null,\n\t\t\t\t\t\tcompletion: terminal.completion ?? null,\n\t\t\t\t\t\tstop: studyStopToJSON(stop),\n\t\t\t\t\t\t...(this.#options.observe ? this.#timeline(wire) : {}),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t// Consumes the complete rows of the wire's text; each row after the terminal is refused.\n\t#rows(wire: StudyOllamaExchange, final: boolean): void {\n\t\tfor (const line of wire.take(final)) {\n\t\t\tif (line.trim() === '') continue\n\t\t\tif (wire.terminal !== undefined)\n\t\t\t\tthrow new StudyError('FAULT', 'Ollama emitted a row after its terminal')\n\t\t\tthis.#observe(wire, JSON.parse(line))\n\t\t}\n\t}\n\n\t// Validates a row against the wire's request and retains it; the timing extractor runs only on a terminal row.\n\t#observe(wire: StudyOllamaExchange, row: unknown): void {\n\t\tconst terminal = readStudyOllamaTerminal(row, wire.request)\n\t\twire.observe(terminal, terminal === undefined ? undefined : this.#time(row))\n\t}\n\n\t// Reads the daemon timing of a terminal row when timing is observed.\n\t#time(row: unknown): OllamaTiming | undefined {\n\t\treturn this.#options.observe && isRecord(row)\n\t\t\t? readStudyOllamaTiming(this.#options.timing, row)\n\t\t\t: undefined\n\t}\n\n\t// Dispatches one admitted request and owns the wire it opens; a failure before the wire exists fails the request's ticket here.\n\tasync #send(\n\t\trole: StudyRole,\n\t\tgoal: StudyOllamaGoal,\n\t\tticket: StudyTicket,\n\t\trequest: StudyOllamaRequest,\n\t\tsnapshot: StudyOllamaSnapshot,\n\t\tsignal: AbortSignal,\n\t\tid: number,\n\t\tstarted: number,\n\t\tslot: symbol,\n\t\tidentity: StudyExchangeIdentity | undefined,\n\t\tceiling: number,\n\t): Promise<StudyOllamaExchange> {\n\t\tconst { url, init: settings, dispatch } = snapshot\n\t\ttry {\n\t\t\tthis.check()\n\t\t\tsignal.throwIfAborted()\n\t\t\tif (identity !== undefined)\n\t\t\t\tawait this.#options.exchanges?.append({\n\t\t\t\t\tphase: 'attempt',\n\t\t\t\t\t...identity,\n\t\t\t\t\t...buildStudyOllamaBytes(\n\t\t\t\t\t\tnew TextEncoder().encode(typeof settings?.body === 'string' ? settings.body : ''),\n\t\t\t\t\t),\n\t\t\t\t})\n\t\t\tawait goal.activity.context.evidence.append({\n\t\t\t\tevent: 'dispatch',\n\t\t\t\tgoal: goal.activity.goal,\n\t\t\t\tvalue: {\n\t\t\t\t\trole,\n\t\t\t\t\tpath: request.path,\n\t\t\t\t\tmodel: request.model ?? null,\n\t\t\t\t\toptions: { ...request.options },\n\t\t\t\t\tbytes: request.bytes,\n\t\t\t\t\t...(identity === undefined ? {} : { ordinal: identity.ordinal }),\n\t\t\t\t\t...(this.#options.observe ? this.#dispatch(goal, request, id, settings, dispatch) : {}),\n\t\t\t\t},\n\t\t\t})\n\t\t\tsignal.throwIfAborted()\n\t\t\tthis.check()\n\t\t\tconst sent = performance.now()\n\t\t\tconst response =\n\t\t\t\tthis.#options.fetch === undefined\n\t\t\t\t\t? await globalThis.fetch(url, { ...settings, signal, redirect: 'error' })\n\t\t\t\t\t: await this.#fetch(this.#options.fetch, role, url, settings, signal)\n\t\t\tif (signal.aborted) {\n\t\t\t\tvoid response.body?.cancel(signal.reason).catch(() => undefined)\n\t\t\t\tsignal.throwIfAborted()\n\t\t\t}\n\t\t\tif (response.body === null)\n\t\t\t\tthrow new StudyError('FAULT', `Ollama HTTP response refused: ${response.status}`)\n\t\t\tconst wire = new StudyOllamaExchange({\n\t\t\t\tslot,\n\t\t\t\tidentity,\n\t\t\t\tceiling,\n\t\t\t\theaders: [...response.headers.entries()].filter(\n\t\t\t\t\t([name]) => name === 'content-type' || name === 'content-encoding',\n\t\t\t\t),\n\t\t\t\tactivity: goal.activity,\n\t\t\t\trequest,\n\t\t\t\tticket,\n\t\t\t\tsignal,\n\t\t\t\treader: response.body.getReader(),\n\t\t\t\tdecoder: new TextDecoder('utf-8', { fatal: true }),\n\t\t\t\tstatus: response.status,\n\t\t\t\tstarted,\n\t\t\t\tid,\n\t\t\t\tsent,\n\t\t\t\tdispatch,\n\t\t\t\tbytes: request.bytes,\n\t\t\t})\n\t\t\tthis.#wires.add(wire)\n\t\t\treturn wire\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tif (\n\t\t\t\t\tidentity !== undefined &&\n\t\t\t\t\tthis.#options.exchanges !== undefined &&\n\t\t\t\t\tthis.#options.exchanges.next > identity.ordinal\n\t\t\t\t) {\n\t\t\t\t\tthis.#fault ??= { error }\n\t\t\t\t\tawait this.#options.exchanges.append({\n\t\t\t\t\t\tphase: 'failure',\n\t\t\t\t\t\t...identity,\n\t\t\t\t\t\treason: readStudyFailure(error).message.slice(0, 256),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tif (!ticket.settled && !ticket.signal.aborted) {\n\t\t\t\t\t// Agent reports its budget cut; the admitted request still keeps unknown cost.\n\t\t\t\t\tif (isBudgetError(error))\n\t\t\t\t\t\tticket.finish({\n\t\t\t\t\t\t\trole,\n\t\t\t\t\t\t\tcalls: 1,\n\t\t\t\t\t\t\ttokens: undefined,\n\t\t\t\t\t\t\tbytes: undefined,\n\t\t\t\t\t\t\tduration: Math.ceil(performance.now() - started),\n\t\t\t\t\t\t})\n\t\t\t\t\telse ticket.fail({ ...readStudyFailure(error), role })\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t#read(wire: StudyOllamaExchange): Promise<ReadableStreamReadResult<Uint8Array>> {\n\t\tconst listeners = new Abort()\n\t\treturn new Promise<ReadableStreamReadResult<Uint8Array>>((resolve, reject) => {\n\t\t\twire.signal.addEventListener('abort', () => reject(wire.signal.reason), {\n\t\t\t\tonce: true,\n\t\t\t\tsignal: listeners.signal,\n\t\t\t})\n\t\t\twire.signal.throwIfAborted()\n\t\t\twire.reader.read().then(resolve, reject)\n\t\t}).finally(() => listeners.abort())\n\t}\n\n\tasync #recordFailure(wire: StudyOllamaExchange, error: unknown): Promise<void> {\n\t\tif (wire.identity === undefined || wire.recorded) return\n\t\tthis.#fault ??= { error }\n\t\tconst reason = readStudyFailure(error).message\n\t\ttry {\n\t\t\tawait this.#options.exchanges?.append({\n\t\t\t\tphase: 'failure',\n\t\t\t\t...wire.identity,\n\t\t\t\treason: reason.slice(0, 256),\n\t\t\t\tresponse: wire.reply,\n\t\t\t})\n\t\t} catch (failure) {\n\t\t\tif (!isStudyError(failure) || failure.code !== 'CAPACITY') throw failure\n\t\t\tawait this.#options.exchanges?.append({\n\t\t\t\tphase: 'failure',\n\t\t\t\t...wire.identity,\n\t\t\t\treason: `The reply was not retained because it exceeded the sidecar allowance; ${reason.slice(0, 128)}`,\n\t\t\t})\n\t\t}\n\t\twire.record()\n\t}\n\n\t// Bounds the collaborator independently of its cooperation and releases a response that arrives after cancellation.\n\t#fetch(\n\t\tfetch: StudyOllamaFetchFunction,\n\t\trole: StudyRole,\n\t\turl: string,\n\t\tsettings: RequestInit | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<Response> {\n\t\tconst listeners = new Abort()\n\t\treturn new Promise<Response>((resolve, reject) => {\n\t\t\tsignal.addEventListener('abort', () => reject(signal.reason), {\n\t\t\t\tonce: true,\n\t\t\t\tsignal: listeners.signal,\n\t\t\t})\n\t\t\tsignal.throwIfAborted()\n\t\t\tfetch(role, url, { ...settings, signal, redirect: 'error' }).then((response) => {\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tvoid response.body?.cancel(signal.reason).catch(() => undefined)\n\t\t\t\t\treject(signal.reason)\n\t\t\t\t} else resolve(response)\n\t\t\t}, reject)\n\t\t}).finally(() => listeners.abort())\n\t}\n\n\t#dispatch(\n\t\tgoal: StudyOllamaGoal,\n\t\trequest: StudyOllamaRequest,\n\t\tid: number,\n\t\tinit: RequestInit | undefined,\n\t\tdispatch: StudyAgentDispatch | undefined,\n\t): Readonly<Record<string, JSONValue>> {\n\t\tconst previous = this.#previous\n\t\tconst model = request.role !== 'metadata'\n\t\tif (model) this.#previous = request.model\n\t\tconst checkpoint = goal.activity.checkpoint\n\t\tconst snapshot = goal.attach()\n\t\tconst raw = buildStudyOllamaRaw(init?.body)\n\t\treturn {\n\t\t\tid,\n\t\t\t...buildStudyAgentDispatch(dispatch),\n\t\t\t...(raw === undefined ? {} : { raw }),\n\t\t\tdigest: readStudyOllamaDigest(this.#options.models, request) ?? null,\n\t\t\tprevious: previous ?? null,\n\t\t\tchanged: model && previous !== undefined && previous !== request.model,\n\t\t\t...(request.strict ? { strict: true } : {}),\n\t\t\t...(checkpoint === undefined\n\t\t\t\t? {}\n\t\t\t\t: { body: typeof init?.body === 'string' ? init.body : null }),\n\t\t\t...(snapshot === undefined ? {} : { snapshot }),\n\t\t}\n\t}\n\n\t#timeline(wire: StudyOllamaExchange): Readonly<Record<string, JSONValue>> {\n\t\treturn {\n\t\t\tid: wire.id,\n\t\t\t...buildStudyAgentDispatch(wire.dispatch),\n\t\t\tstarted: wire.started,\n\t\t\tsent: wire.sent,\n\t\t\telapsed: performance.now() - wire.sent,\n\t\t}\n\t}\n\n\tasync #finish(wire: StudyOllamaExchange): Promise<void> {\n\t\tif (wire.settled) throw new StudyError('FAULT', 'Duplicate wire accounting')\n\t\tconst terminal = wire.terminal\n\t\tconst observation = this.#options.observe\n\t\t\t? { ...this.#timeline(wire), timing: buildStudyOllamaTiming(wire.timing) }\n\t\t\t: {}\n\t\tawait wire.activity.context.evidence.append({\n\t\t\tevent: 'wire',\n\t\t\tgoal: wire.activity.goal,\n\t\t\tvalue: {\n\t\t\t\trole: wire.request.role,\n\t\t\t\tpath: wire.request.path,\n\t\t\t\tmodel: wire.request.model ?? null,\n\t\t\t\toptions: { ...wire.request.options },\n\t\t\t\tfinish: terminal?.reason ?? null,\n\t\t\t\tprompt: terminal?.prompt ?? null,\n\t\t\t\tcompletion: terminal?.completion ?? null,\n\t\t\t\tbytes: wire.bytes,\n\t\t\t\t...(wire.identity === undefined ? {} : { ordinal: wire.identity.ordinal }),\n\t\t\t\t...observation,\n\t\t\t},\n\t\t})\n\t\twire.settle()\n\t\ttry {\n\t\t\twire.ticket.finish({\n\t\t\t\trole: wire.request.role,\n\t\t\t\tcalls: 1,\n\t\t\t\ttokens:\n\t\t\t\t\twire.request.role === 'metadata'\n\t\t\t\t\t\t? 0\n\t\t\t\t\t\t: terminal?.prompt !== undefined && terminal.completion !== undefined\n\t\t\t\t\t\t\t? terminal.prompt + terminal.completion\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\tbytes: wire.bytes,\n\t\t\t\tduration: Math.ceil(performance.now() - wire.started),\n\t\t\t})\n\t\t} finally {\n\t\t\tthis.#wires.delete(wire)\n\t\t\twire.reader.releaseLock()\n\t\t}\n\t}\n\n\t// Accounts a request an Agent budget cut: the wire settles, the cut is retained as one `cut` row, and the request finishes with unknown tokens.\n\tasync #cut(wire: StudyOllamaExchange, error: BudgetError): Promise<void> {\n\t\tif (wire.settled) return\n\t\twire.settle()\n\t\tconst observation = this.#options.observe ? this.#timeline(wire) : {}\n\t\tconst stop = readStudyFailure(error).stop\n\t\ttry {\n\t\t\tawait this.#recordFailure(wire, error)\n\t\t\tawait wire.activity.context.evidence.append({\n\t\t\t\tevent: 'cut',\n\t\t\t\tgoal: wire.activity.goal,\n\t\t\t\tvalue: {\n\t\t\t\t\trole: wire.request.role,\n\t\t\t\t\tpath: wire.request.path,\n\t\t\t\t\tbytes: wire.bytes,\n\t\t\t\t\tstatus: wire.status,\n\t\t\t\t\tbudget:\n\t\t\t\t\t\tstop === undefined\n\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t: { id: stop.id, max: stop.max ?? null, consumed: stop.consumed ?? null },\n\t\t\t\t\t...observation,\n\t\t\t\t},\n\t\t\t})\n\t\t\tif (!wire.ticket.signal.aborted)\n\t\t\t\twire.ticket.finish({\n\t\t\t\t\trole: wire.request.role,\n\t\t\t\t\tcalls: 1,\n\t\t\t\t\ttokens: undefined,\n\t\t\t\t\tbytes: wire.bytes,\n\t\t\t\t\tduration: Math.ceil(performance.now() - wire.started),\n\t\t\t\t})\n\t\t} catch (failure) {\n\t\t\tthis.fail(failure)\n\t\t\tif (!wire.ticket.settled && !wire.ticket.signal.aborted)\n\t\t\t\twire.ticket.fail({ ...readStudyFailure(failure), role: wire.request.role })\n\t\t\tthrow failure\n\t\t} finally {\n\t\t\tthis.#requests.delete(wire.slot)\n\t\t\tthis.#wires.delete(wire)\n\t\t\tawait wire.reader.cancel(error).catch(() => undefined)\n\t\t\twire.reader.releaseLock()\n\t\t}\n\t}\n\n\tasync #failWire(wire: StudyOllamaExchange, error: unknown): Promise<void> {\n\t\tif (wire.settled) return\n\t\tthis.fail(error)\n\t\twire.settle()\n\t\tconst observation = this.#options.observe ? this.#timeline(wire) : {}\n\t\tconst failure = readStudyFailure(this.#fault?.error)\n\t\ttry {\n\t\t\tif (!wire.ticket.signal.aborted) wire.ticket.fail({ ...failure, role: wire.request.role })\n\t\t\tawait this.#recordFailure(wire, error)\n\t\t\tawait wire.activity.context.evidence.append({\n\t\t\t\tevent: 'failure',\n\t\t\t\tgoal: wire.activity.goal,\n\t\t\t\tvalue: {\n\t\t\t\t\trole: wire.request.role,\n\t\t\t\t\tpath: wire.request.path,\n\t\t\t\t\tbytes: wire.bytes,\n\t\t\t\t\tstatus: wire.status,\n\t\t\t\t\t// Bounded so a daemon-supplied message cannot grow the retained row.\n\t\t\t\t\treason: failure.message.slice(0, 256),\n\t\t\t\t\t...observation,\n\t\t\t\t},\n\t\t\t})\n\t\t} finally {\n\t\t\tthis.#requests.delete(wire.slot)\n\t\t\tthis.#wires.delete(wire)\n\t\t\tawait wire.reader.cancel(error).catch(() => undefined)\n\t\t\twire.reader.releaseLock()\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,mBAAmB,OAAgB,MAAuB;CACzE,QAAA,GAAOA,oBAAAA,MAAAA,QAAAA,GAAYC,oBAAAA,QAAAA,CAAQ,KAAK,KAAK,UAAU,SAAS,MAAM,SAAS,IAAI;AAC5E;;;;;;AAOA,SAAgB,iBAAiB,MAAc,MAAuB;CACrE,MAAM,YAAA,GAAWC,UAAAA,SAAAA,CAAS,MAAM,IAAI;CACpC,OACC,aAAa,MACb,aAAa,QACb,CAAC,SAAS,WAAW,KAAKC,UAAAA,KAAK,KAC/B,EAAA,GAACC,UAAAA,WAAAA,CAAW,QAAQ;AAEtB;;;;;;;;;;;;AAaA,SAAgB,eAAe,OAAoC;CAClE,QAAA,GAAOC,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACvD;;;;;;;;;;;;;AAcA,SAAgB,gBAAgB,OAA4B;CAC3D,MAAM,OAAO,KAAK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