fascicle 0.12.3 → 0.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["throw_if_aborted","e"],"sources":["../src/core/flow-schema.json","../src/core/step_kinds.ts","../src/composites/adversarial.ts","../src/composites/consensus.ts","../src/composites/ensemble.ts","../src/composites/ensemble_step.ts","../src/composites/gate.ts","../src/composites/improve.ts","../src/composites/learn.ts","../src/composites/tournament.ts","../src/composites/errors.ts","../src/composites/bench.ts","../src/composites/judges.ts","../src/composites/regression.ts","../src/model_call.ts","../src/forward_standard_env.ts"],"sourcesContent":["","/**\n * Closed registry of every `Step.kind` produced by the composition layer.\n *\n * Studio (and any other consumer that needs to enumerate primitives: palette,\n * docs, code generation) can rely on this being the exhaustive set. New\n * primitives must add their kind here. `step_kinds.test.ts` pins the list\n * against the kinds core actually constructs, and\n * `composites/__tests__/coverage.test.ts` covers the four composite kinds\n * whose factories live outside core.\n */\n\nexport const STEP_KINDS = [\n 'step',\n 'sequence',\n 'parallel',\n 'branch',\n 'map',\n 'pipe',\n 'retry',\n 'fallback',\n 'timeout',\n 'loop',\n 'compose',\n 'adversarial',\n 'ensemble',\n 'tournament',\n 'consensus',\n 'checkpoint',\n 'suspend',\n 'scope',\n 'stash',\n 'use',\n 'chain',\n] as const\n\nexport type StepKind = (typeof STEP_KINDS)[number]\n\n/**\n * Check whether a value is one of the registered `Step.kind` strings.\n */\nexport function is_step_kind(value: unknown): value is StepKind {\n return typeof value === 'string' && (STEP_KINDS as readonly string[]).includes(value)\n}\n","/**\n * adversarial: build-and-critique loop.\n *\n * This file is the canonical example of how a user-built composite is\n * structured: the entire implementation is a composition of core\n * primitives. Read it as documentation.\n */\n\nimport { compose, loop, scope, stash, step, use } from '#core'\nimport type { Step } from '#core'\n\nexport type AdversarialBuildInput<input, candidate> = {\n readonly input: input\n readonly prior?: candidate\n readonly critique?: string\n}\n\nexport type AdversarialCritiqueResult = { readonly notes: string } & Record<string, unknown>\n\nexport type AdversarialResult<candidate> = {\n readonly candidate: candidate\n readonly converged: boolean\n readonly rounds: number\n}\n\nexport type AdversarialConfig<input, candidate, projected = AdversarialResult<candidate>> = {\n readonly name?: string\n readonly build: Step<AdversarialBuildInput<input, candidate>, candidate>\n readonly critique: Step<candidate, AdversarialCritiqueResult>\n readonly accept: (critique_result: AdversarialCritiqueResult) => boolean\n readonly max_rounds: number\n readonly project?: (r: AdversarialResult<candidate>) => projected\n}\n\ntype AdversarialState<input, candidate> = {\n readonly input: input\n readonly candidate?: candidate\n readonly critique_notes?: string\n readonly last_critique?: AdversarialCritiqueResult\n}\n\n/**\n * Projects loop state into the build step's input.\n *\n * Omits `prior` and `critique` until they exist, so the first round's build\n * sees only the original input and later rounds see what came before.\n */\nfunction build_input_from_state<i, c>(\n s: AdversarialState<i, c>,\n): AdversarialBuildInput<i, c> {\n if (s.candidate === undefined) return { input: s.input }\n if (s.critique_notes === undefined) return { input: s.input, prior: s.candidate }\n return { input: s.input, prior: s.candidate, critique: s.critique_notes }\n}\n\n/**\n * Builds a Step that runs up to `max_rounds` iterations of build ->\n * critique -> accept.\n *\n * Each round builds a candidate (receiving the prior candidate and critique\n * notes when available), critiques it, then checks `accept(critique_result)`.\n * Returns `{ candidate, converged, rounds }`. Does not throw on\n * non-convergence; `converged: false` reports it instead. `project` maps\n * that envelope into the step's output (for example, `(r) => r.candidate`); omitted,\n * the envelope itself is the output.\n *\n * Implemented as a `compose`d `loop` whose body builds a new candidate and\n * whose guard runs the critique step and checks `accept`. State is threaded\n * through `scope`/`stash`/`use` so the build and critique steps remain\n * unmodified user-supplied `Step` values.\n */\nexport function adversarial<input, candidate, projected = AdversarialResult<candidate>>(\n config: AdversarialConfig<input, candidate, projected>,\n): Step<input, projected> {\n const { build, critique, accept, max_rounds } = config\n // When `project` is omitted, `projected` defaults to the envelope type, which is\n // what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = config.project ?? ((r: AdversarialResult<candidate>) => r as unknown as projected)\n\n type S = AdversarialState<input, candidate>\n\n const body: Step<S, S> = scope([\n stash('state', step('snapshot', (s: S) => s)),\n step('to_build_input', (s: S) => build_input_from_state(s)),\n build,\n use(['state'], (vars, candidate: candidate) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars['state'] as S\n return { ...prior, candidate }\n }),\n ])\n\n const guard: Step<S, { stop: boolean; state: S }> = scope([\n stash('state', step('snapshot', (s: S) => s)),\n step('extract_candidate', (s: S) => {\n if (s.candidate === undefined) {\n throw new Error('adversarial: guard reached without a candidate')\n }\n return s.candidate\n }),\n critique,\n use(['state'], (vars, critique_result: AdversarialCritiqueResult) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars['state'] as S\n return {\n stop: accept(critique_result),\n state: {\n ...prior,\n last_critique: critique_result,\n critique_notes: critique_result.notes,\n },\n }\n }),\n ])\n\n const inner = loop<input, S, projected>({\n init: (input) => ({ input }),\n body,\n guard,\n finish: (s, { converged, rounds }) => {\n if (s.candidate === undefined) {\n throw new Error('adversarial: finished without a candidate')\n }\n return project({ candidate: s.candidate, converged, rounds })\n },\n max_rounds,\n })\n\n return compose(inner, { name: config.name ?? 'adversarial' })\n}\n","/**\n * consensus: run-until-agreement composite over concurrent members.\n */\n\nimport { compose, loop, parallel, scope, stash, step, use } from '#core'\nimport type { Step } from '#core'\n\nexport type ConsensusConfig<i, o, projected = ConsensusResult<o>> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly agree: (results: Record<string, o>) => boolean\n readonly max_rounds: number\n readonly project?: (r: ConsensusResult<o>) => projected\n}\n\nexport type ConsensusResult<o> = {\n readonly result: Record<string, o>\n readonly converged: boolean\n}\n\ntype ConsensusState<i, o> = {\n readonly input: i\n readonly results: Record<string, o>\n}\n\n/**\n * Builds a Step that runs every member concurrently with the same input\n * until `agree(results)` accepts a round.\n *\n * On agreement, returns the round's results with `converged: true`.\n * Otherwise re-runs all members up to `max_rounds` times and returns the\n * last results with `converged: false` if no agreement is reached.\n * `project` maps the `{ result, converged }` envelope into the step's output\n * (for example, `(r) => r.converged`); omitted, the envelope itself is the output.\n *\n * Implemented as a `compose`d `loop` whose body runs `parallel(members)` and\n * whose guard evaluates `agree`. State carries the original input alongside\n * the most recent results so each round receives the same input.\n */\nexport function consensus<i, o, projected = ConsensusResult<o>>(\n config: ConsensusConfig<i, o, projected>,\n): Step<i, projected> {\n const { members, agree, max_rounds } = config\n // When `project` is omitted, `projected` defaults to the envelope type, which is\n // what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = config.project ?? ((r: ConsensusResult<o>) => r as unknown as projected)\n\n type S = ConsensusState<i, o>\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const round_step = parallel(members) as Step<i, Record<string, o>>\n\n const body: Step<S, S> = scope([\n stash('state', step('snapshot', (s: S) => s)),\n step('extract_input', (s: S) => s.input),\n round_step,\n use(['state'], (vars, results: Record<string, o>) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars['state'] as S\n return { ...prior, results }\n }),\n ])\n\n const guard: Step<S, { stop: boolean; state: S }> = step('agree', (s: S) => ({\n stop: agree(s.results),\n state: s,\n }))\n\n const inner = loop<i, S, projected>({\n init: (input) => ({ input, results: {} }),\n body,\n guard,\n finish: (s, { converged }) => project({ result: s.results, converged }),\n max_rounds,\n })\n\n return compose(inner, { name: config.name ?? 'consensus' })\n}\n","/**\n * ensemble: N-of-M pick-best with a plain-function scorer.\n */\n\nimport { compose, parallel, sequence, step } from '#core'\nimport type { Step } from '#core'\n\nexport type EnsembleConfig<i, o, projected = EnsembleResult<o>> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly score: (result: o, member_id: string) => number | Promise<number>\n readonly select?: 'max' | 'min'\n readonly project?: (r: EnsembleResult<o>) => projected\n}\n\nexport type EnsembleResult<o> = {\n readonly winner: o\n readonly scores: Record<string, number>\n}\n\n/**\n * Builds a Step that runs every member concurrently with the same input,\n * scores each result, and returns the winner plus the complete score map.\n *\n * `select` picks the highest (`'max'`, the default) or lowest (`'min'`)\n * score. Tie-breaking is \"any tied result is acceptable\": the first member\n * (in `members` key order) holding the best score wins. `project` maps the\n * `{ winner, scores }` envelope into the step's output (for example, `(r) =>\n * r.winner`); omitted, the envelope itself is the output.\n *\n * Implemented as a `compose`d `sequence` of `parallel(members)` followed by\n * a single picking step. Cancellation, fan-out, and abort propagation come\n * from `parallel`'s own contract.\n */\nexport function ensemble<i, o, projected = EnsembleResult<o>>(\n config: EnsembleConfig<i, o, projected>,\n): Step<i, projected> {\n const select: 'max' | 'min' = config.select ?? 'max'\n const score_fn = config.score\n const keys = Object.keys(config.members)\n // When `project` is omitted, `projected` defaults to the envelope type, which is\n // what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = config.project ?? ((r: EnsembleResult<o>) => r as unknown as projected)\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const fan_out = parallel(config.members) as Step<i, Record<string, o>>\n\n const pick = step('pick_winner', async (results: Record<string, o>) => {\n const scores: Record<string, number> = {}\n for (const k of keys) {\n const value = results[k]\n if (value === undefined) continue\n scores[k] = await score_fn(value, k)\n }\n \n let winner_key: string | undefined = undefined\n let winner_score: number | undefined = undefined\n for (const k of keys) {\n const current = scores[k]\n if (current === undefined) continue\n if (winner_score === undefined) {\n winner_key = k\n winner_score = current\n continue\n }\n const better = select === 'max' ? current > winner_score : current < winner_score\n if (better) {\n winner_key = k\n winner_score = current\n }\n }\n \n if (winner_key === undefined) {\n throw new Error('ensemble: no members produced a result')\n }\n const winner = results[winner_key]\n if (winner === undefined) {\n throw new Error('ensemble: winner missing from results')\n }\n return project({ winner, scores })\n })\n\n const inner = sequence([fan_out, pick])\n\n return compose(inner, { name: config.name ?? 'ensemble' })\n}\n","/**\n * ensemble_step: N-of-M pick-best with a Step-based scorer.\n */\n\nimport { compose, map, parallel, scope, stash, step, use } from '#core'\nimport type { Step } from '#core'\n\nexport type EnsembleStepConfig<i, o, ranked, projected = EnsembleStepResult<o, ranked>> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly score: Step<o, ranked>\n readonly rank_by: (r: ranked) => number\n readonly select?: 'max' | 'min'\n readonly project?: (r: EnsembleStepResult<o, ranked>) => projected\n}\n\nexport type EnsembleStepResult<o, ranked> = {\n readonly winner_id: string\n readonly winner: o\n readonly winner_scored: ranked\n readonly scored: Record<string, ranked>\n}\n\n// Scope variable keys, underscore-prefixed to avoid colliding with any\n// stashes a user-supplied step might set in the same scope chain.\nconst RESULTS_KEY = '__ensemble_step_results'\nconst ITEM_KEY = '__ensemble_step_item'\n\ntype Pair<o> = { readonly id: string; readonly value: o }\ntype ScoredPair<ranked> = { readonly id: string; readonly scored: ranked }\n\n/**\n * Builds a Step that runs every member concurrently, scores each result via\n * a scoring `Step`, and returns the best-ranking winner.\n *\n * Sibling of `ensemble` for the case where scoring is itself a `Step` (for\n * example, a separate model call, a sub-flow, anything that wants its own\n * trajectory span and abort routing). The `score` step is dispatched once per\n * member result; `rank_by` projects a number out of the structured scored output;\n * `select` picks the highest (`'max'`, default) or lowest (`'min'`) rank.\n *\n * The result carries `winner_scored`, the structured output from the round's\n * scoring run preserved verbatim, so callers never pay to re-score the\n * winner. `scored` holds the structured score for every member. `project`\n * maps that envelope into the step's output (for example, `(r) => r.winner`);\n * omitted, the envelope itself is the output.\n *\n * Implemented as a `compose`d `scope` over (`stash(parallel(members))` ->\n * `to_pairs` -> `map(score per result, threading id)` -> `use` to pick the\n * winner). Cancellation, fan-out, and abort propagation come from the\n * underlying `parallel` and `map` contracts.\n */\nexport function ensemble_step<i, o, ranked, projected = EnsembleStepResult<o, ranked>>(\n config: EnsembleStepConfig<i, o, ranked, projected>,\n): Step<i, projected> {\n const { members, score, rank_by } = config\n const select: 'max' | 'min' = config.select ?? 'max'\n const keys = Object.keys(members)\n // When `project` is omitted, `projected` defaults to the envelope type, which is\n // what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = config.project ?? ((r: EnsembleStepResult<o, ranked>) => r as unknown as projected)\n\n if (keys.length === 0) {\n throw new Error('ensemble_step: at least one member required')\n }\n\n const fan_out = parallel(members)\n\n const score_one = scope([\n stash(ITEM_KEY, step('ensemble_step_item_snapshot', (item: Pair<o>) => item)),\n step('ensemble_step_extract_value', (item: Pair<o>) => item.value),\n score,\n use([ITEM_KEY], (vars, scored: ranked): ScoredPair<ranked> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const item = vars[ITEM_KEY] as Pair<o>\n return { id: item.id, scored }\n }),\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<Pair<o>, ScoredPair<ranked>>\n\n const to_pairs = step(\n 'ensemble_step_to_pairs',\n (results: Record<string, o>): ReadonlyArray<Pair<o>> => {\n const out: Pair<o>[] = []\n for (const id of keys) {\n if (id in results) {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n out.push({ id, value: results[id] as o })\n }\n }\n return out\n },\n )\n\n const score_each = map<ReadonlyArray<Pair<o>>, Pair<o>, ScoredPair<ranked>>({\n items: (pairs) => pairs,\n do: score_one,\n })\n\n const pick = use(\n [RESULTS_KEY],\n (vars, scored_pairs: ReadonlyArray<ScoredPair<ranked>>): projected => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const results = vars[RESULTS_KEY] as Record<string, o>\n const scored: Record<string, ranked> = {}\n let winner_id: string | undefined\n let winner_rank: number | undefined\n let winner_scored: ranked | undefined\n for (const pair of scored_pairs) {\n scored[pair.id] = pair.scored\n const rank = rank_by(pair.scored)\n const better =\n winner_rank === undefined\n ? true\n : select === 'max'\n ? rank > winner_rank\n : rank < winner_rank\n if (better) {\n winner_id = pair.id\n winner_rank = rank\n winner_scored = pair.scored\n }\n }\n if (winner_id === undefined || winner_scored === undefined) {\n throw new Error('ensemble_step: no members produced a result')\n }\n const winner = results[winner_id]\n if (winner === undefined) {\n throw new Error('ensemble_step: winner missing from results')\n }\n return project({ winner_id, winner, winner_scored, scored })\n },\n )\n\n const inner = scope([\n stash(RESULTS_KEY, fan_out),\n to_pairs,\n score_each,\n pick,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<i, projected>\n\n return compose(inner, { name: config.name ?? 'ensemble_step' })\n}\n","/**\n * gate: persist paid work before a human gate, never re-bill on resume.\n *\n * `gate(inner, config)` runs `inner`, checkpoints its result, then suspends\n * so a human can approve what was produced. The checkpoint write lands before\n * the suspend unwinds the run, so the expensive work (typically a paid model\n * call) survives the pause: a resume, or a fresh run after a process restart,\n * replays the result from the store instead of buying it again.\n *\n * Decisions this composite fixes, and why:\n *\n * - Checkpoint key: `gate:<config.id>`. Derived only from the user-supplied\n * id, with no construction-time counters, so a flow rebuilt in a new\n * process maps to the same stored result. The key is fixed per gate, which\n * assumes a store scoped per logical job (the same assumption the\n * checkpoint and resume docs make for fixed string keys). Inherited from\n * `checkpoint`: a stored `null`/`undefined` counts as a miss, and the inner\n * step must be named.\n * - Suspend payload: follows the library's suspend contract, which raises\n * `{ input }` on the `suspended_error`. Here that `input` is\n * `format(result)` when `format` is given and the raw result otherwise, so\n * `run.until_suspended` surfaces `{ input: <approver view> }` as the\n * outcome payload. A `format` return value is used verbatim (even\n * `undefined`): the approver view is the format's business. The store\n * always holds the raw result; `format` shapes only the view.\n * - Resumed value: the inner result passes through unchanged. The resume\n * decision is the approval signal only and is discarded, so any defined\n * value counts as approval arriving (the schema accepts everything). A\n * flow that needs decision-dependent output (approve vs reject branches)\n * should use `suspend` directly, whose `combine` exists for exactly that.\n * - `store` is optional. Absent, the checkpoint falls back to the run's\n * `checkpoint_store`; with neither, the gate still suspends and resumes\n * in-process but a restart re-executes `inner`. Present, the gate-local\n * store wins over the run-level one, because an explicit argument beats\n * ambient configuration.\n * - The suspend's `on` hook is a noop: notification is the driver's job, and\n * `run.until_suspended` already hands it the payload to render.\n */\n\nimport { checkpoint, compose, scope, stash, step, suspend, use } from '#core'\nimport type { CheckpointStore, RunContext, Step } from '#core'\n\nexport type GateConfig<o> = {\n readonly id: string\n readonly name?: string\n readonly store?: CheckpointStore\n readonly format?: (result: o) => unknown\n}\n\n// The gate has no opinion about the decision's shape, so its resume schema is\n// the always-accepting Standard Schema, written inline because composites\n// depend only on the public core surface.\nconst approval_schema = {\n '~standard': {\n version: 1,\n vendor: 'fascicle',\n validate: (value: unknown) => ({ value }),\n },\n} as const\n\n/**\n * Bind a gate-local store over the run context for the checkpoint beneath.\n *\n * `checkpoint` reads `ctx.checkpoint_store`, so scoping a store to one gate\n * means forking the context above it; contexts are plain spread-copied\n * values, which is what makes this possible with public primitives only. The\n * wrapper adopts the checkpointed step as its child so `describe` still shows\n * the persistence layer and the inner step beneath it.\n */\nfunction bind_store<i, o>(persisted: Step<i, o>, store: CheckpointStore): Step<i, o> {\n const wrapper = step('bind_store', (input: i, ctx: RunContext) => {\n const forked: RunContext = { ...ctx, checkpoint_store: store }\n return forked.call(persisted, input)\n })\n return { ...wrapper, children: [persisted] }\n}\n\n/**\n * Build a Step that runs `inner`, checkpoints its result at `gate:<id>`, and\n * suspends with that result as the payload awaiting approval.\n *\n * On resume (any defined resume value) the gate resolves to the inner result\n * unchanged; the decision itself is discarded. On a re-run against the same\n * store, the checkpoint absorbs the replay so `inner` never re-executes.\n * Throws at construction time when `inner` is anonymous, because the cached\n * result must map back to a stable step.\n *\n * Implemented as a `compose`d `scope`: the checkpointed result is stashed,\n * projected into the approver's view, and handed to `suspend`; the suspend's\n * `combine` returns a `use` step that restores the stashed result, which is\n * how the decision stays signal-only.\n */\nexport function gate<i, o>(inner: Step<i, o>, config: GateConfig<o>): Step<i, o> {\n if (inner.anonymous === true) {\n throw new Error(\n \"gate requires a named inner step, got anonymous — give the inner step an id with step('id', fn)\",\n )\n }\n const { id, store, format } = config\n\n const checkpointed = checkpoint(inner, { key: `gate:${id}` })\n const persisted = store === undefined ? checkpointed : bind_store(checkpointed, store)\n\n const restore = use(['result'], (vars) => {\n // The stash below wrote the checkpointed inner result under this key, so\n // the read-back re-asserts its type.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return vars['result'] as o\n })\n\n const approval = suspend<unknown, o, unknown>({\n id,\n on: () => {},\n resume_schema: approval_schema,\n combine: () => restore,\n })\n\n const body: Step<i, o> = scope([\n stash('result', persisted),\n step('project_payload', (result: o) => (format === undefined ? result : format(result))),\n approval,\n ])\n\n return compose(body, { name: config.name ?? 'gate' })\n}\n","/**\n * improve: bounded online self-improvement loop.\n *\n * The *online* counterpart to `learn`: where `learn` reflects on recorded\n * trajectories offline, `improve` runs a propose/score loop live inside a\n * single run. The amplify example is a domain-specific consumer of this\n * same pattern (filesystem mutation, test-suite gates, subprocess\n * research); `improve` strips those opinions out so any domain can plug in\n * its own `propose` and `score` steps.\n */\n\nimport { compose, loop, scope, step, stash, use } from '#core'\nimport type { Step } from '#core'\nimport { ensemble_step } from './ensemble_step.js'\n\nexport type Candidate<c> = {\n readonly content: c\n readonly proposer_id: string\n readonly rationale?: string\n}\n\nexport type ScoredCandidate<c> = {\n readonly candidate: Candidate<c>\n readonly score: number\n readonly accepted: boolean\n readonly reason?: string\n}\n\nexport type Lesson = {\n readonly round: number\n readonly proposer_id: string\n readonly reason: string\n}\n\nexport type ImproveRoundInput<c> = {\n readonly parent: c\n readonly parent_score: number\n readonly round: number\n readonly lessons: ReadonlyArray<Lesson>\n}\n\nexport type ImproveBudget = {\n readonly max_rounds: number\n readonly max_wallclock_ms?: number\n readonly patience: number\n}\n\nexport type ImproveConfig<i, c, projected = ImproveResult<c>> = {\n readonly name?: string\n readonly seed: Step<i, { readonly content: c; readonly score: number }>\n readonly propose: Step<ImproveRoundInput<c>, Candidate<c>>\n readonly score: Step<Candidate<c>, ScoredCandidate<c>>\n readonly budget: ImproveBudget\n readonly epsilon?: number\n readonly proposers_per_round?: number\n readonly lessons_capacity?: number\n readonly project?: (r: ImproveResult<c>) => projected\n}\n\nexport type HistoryEntry<c> = {\n readonly round: number\n readonly winner: ScoredCandidate<c>\n readonly accepted: boolean\n}\n\nexport type ImproveResult<c> = {\n readonly best: { readonly content: c; readonly score: number }\n readonly rounds_used: number\n readonly stopped_by: 'budget' | 'plateau'\n readonly history: ReadonlyArray<HistoryEntry<c>>\n}\n\n// Scope variable key for the pre-round state snapshot, underscore-prefixed\n// to avoid colliding with stashes set by user-supplied steps.\nconst PRIOR_KEY = '__improve_prior'\n\ntype ImproveState<c> = {\n readonly parent: c\n readonly parent_score: number\n readonly round: number\n readonly rounds_since_progress: number\n readonly started_at_ms: number\n readonly history: ReadonlyArray<HistoryEntry<c>>\n readonly lessons: ReadonlyArray<Lesson>\n readonly stopped_by?: 'budget' | 'plateau'\n}\n\n/**\n * Builds a Step that runs a round-bounded loop threading a `parent`\n * candidate through repeated propose -> score -> accept/reject cycles.\n *\n * Acceptance requires both a hard gate (`scored.accepted`) and an\n * epsilon-improvement test (`scored.score > parent_score + epsilon`).\n * Rejected rounds with a `reason` feed a bounded lessons list back into the\n * next round's input. Plateau detection stops the loop early when no\n * progress has been made for `patience` rounds; an optional wall-clock\n * budget caps total runtime. `project` maps the result envelope into the\n * step's output (for example, `(r) => r.best.content`); omitted, the envelope\n * itself is the output.\n *\n * Implemented as a `compose`d `scope` of (seed) -> (init state) -> (loop) ->\n * (unwrap). The loop body is itself a small `scope` that snapshots prior\n * state, builds a round input, dispatches the proposers + scorer via\n * `ensemble_step`, and merges the outcome back into state via `use`.\n * State threading is the entire job.\n */\nexport function improve<i, c, projected = ImproveResult<c>>(\n config: ImproveConfig<i, c, projected>,\n): Step<i, projected> {\n const { seed, propose, score, budget } = config\n // When `project` is omitted, `projected` defaults to the envelope type, which is\n // what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = config.project ?? ((r: ImproveResult<c>) => r as unknown as projected)\n const epsilon = config.epsilon ?? 0\n const proposers_per_round = Math.max(1, config.proposers_per_round ?? 1)\n const lessons_capacity = Math.max(0, config.lessons_capacity ?? 5)\n const { max_rounds, max_wallclock_ms, patience } = budget\n\n const proposers: Record<string, Step<ImproveRoundInput<c>, Candidate<c>>> = {}\n for (let i = 0; i < proposers_per_round; i += 1) {\n proposers[`p${String(i)}`] = propose\n }\n\n const round_ensemble = ensemble_step<\n ImproveRoundInput<c>,\n Candidate<c>,\n ScoredCandidate<c>\n >({\n name: 'improve_round',\n members: proposers,\n score,\n rank_by: (s) => s.score,\n })\n\n type RoundResult = {\n readonly winner_id: string\n readonly winner: Candidate<c>\n readonly winner_scored: ScoredCandidate<c>\n readonly scored: Record<string, ScoredCandidate<c>>\n }\n\n const project_round = use(\n [PRIOR_KEY],\n (vars, ensemble_result: RoundResult, ctx): ScoredCandidate<c> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars[PRIOR_KEY] as ImproveState<c>\n const round = prior.round + 1\n for (const slot_id of Object.keys(ensemble_result.scored)) {\n const scored = ensemble_result.scored[slot_id]\n if (scored === undefined) continue\n ctx.trajectory.record({\n kind: 'improve.candidate',\n round,\n proposer_id: slot_id,\n score: scored.score,\n accepted: scored.accepted,\n ...(scored.reason === undefined ? {} : { reason: scored.reason }),\n })\n }\n const w = ensemble_result.winner_scored\n return {\n ...w,\n candidate: { ...w.candidate, proposer_id: ensemble_result.winner_id },\n }\n },\n )\n\n const init_state = step(\n 'improve_init_state',\n (seed_result: { content: c; score: number }): ImproveState<c> => ({\n parent: seed_result.content,\n parent_score: seed_result.score,\n round: 0,\n rounds_since_progress: 0,\n started_at_ms: Date.now(),\n history: [],\n lessons: [],\n }),\n )\n\n const to_round_input = step(\n 'improve_to_round_input',\n (s: ImproveState<c>, ctx): ImproveRoundInput<c> => {\n const round = s.round + 1\n ctx.trajectory.record({\n kind: 'improve.round_start',\n round,\n parent_score: s.parent_score,\n lessons_count: s.lessons.length,\n })\n return {\n parent: s.parent,\n parent_score: s.parent_score,\n round,\n lessons: s.lessons,\n }\n },\n )\n\n const merge_outcome = use(\n [PRIOR_KEY],\n (vars, scored: ScoredCandidate<c>, ctx): ImproveState<c> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars[PRIOR_KEY] as ImproveState<c>\n const next_round = prior.round + 1\n const better = scored.score > prior.parent_score + epsilon\n const accepted = scored.accepted && better\n const next_lessons = !accepted && scored.reason !== undefined\n ? [\n ...prior.lessons,\n {\n round: next_round,\n proposer_id: scored.candidate.proposer_id,\n reason: scored.reason,\n },\n ].slice(-lessons_capacity)\n : prior.lessons\n ctx.trajectory.record({\n kind: accepted ? 'improve.accept' : 'improve.reject',\n round: next_round,\n proposer_id: scored.candidate.proposer_id,\n score: scored.score,\n prior_score: prior.parent_score,\n ...(accepted ? { delta: scored.score - prior.parent_score } : {}),\n ...(scored.reason === undefined ? {} : { reason: scored.reason }),\n })\n return {\n parent: accepted ? scored.candidate.content : prior.parent,\n parent_score: accepted ? scored.score : prior.parent_score,\n round: next_round,\n rounds_since_progress: accepted ? 0 : prior.rounds_since_progress + 1,\n started_at_ms: prior.started_at_ms,\n history: [\n ...prior.history,\n { round: next_round, winner: scored, accepted },\n ],\n lessons: next_lessons,\n }\n },\n )\n\n const body = scope([\n stash(PRIOR_KEY, step('improve_snapshot', (s: ImproveState<c>) => s)),\n to_round_input,\n round_ensemble,\n project_round,\n merge_outcome,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<ImproveState<c>, ImproveState<c>>\n\n const guard = step(\n 'improve_guard',\n (s: ImproveState<c>): { stop: boolean; state: ImproveState<c> } => {\n if (s.rounds_since_progress >= patience) {\n return { stop: true, state: { ...s, stopped_by: 'plateau' } }\n }\n if (\n max_wallclock_ms !== undefined &&\n Date.now() - s.started_at_ms >= max_wallclock_ms\n ) {\n return { stop: true, state: { ...s, stopped_by: 'budget' } }\n }\n return { stop: false, state: s }\n },\n )\n\n const round_loop = loop<ImproveState<c>, ImproveState<c>, ImproveResult<c>>({\n init: (s) => s,\n body,\n guard,\n finish: (s): ImproveResult<c> => ({\n best: { content: s.parent, score: s.parent_score },\n rounds_used: s.round,\n stopped_by: s.stopped_by ?? 'budget',\n history: s.history,\n }),\n max_rounds,\n })\n\n const record_stop = step(\n 'improve_stop',\n (result: ImproveResult<c>, ctx): projected => {\n ctx.trajectory.record({\n kind: 'improve.stop',\n stopped_by: result.stopped_by,\n rounds_used: result.rounds_used,\n final_score: result.best.score,\n })\n return project(result)\n },\n )\n\n const inner = scope([\n seed,\n init_state,\n round_loop,\n record_stop,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<i, projected>\n\n return compose(inner, { name: config.name ?? 'improve' })\n}\n","/**\n * learn: offline self-improvement composer.\n *\n * `learn({ flow, source, analyzer })` reads recorded trajectory events from\n * past runs of `flow`, hands them to a user-supplied `analyzer` step alongside\n * `describe(flow)`, and returns the analyzer's proposals plus summary metadata\n * (events considered, distinct run ids).\n *\n * The amplify example is the *online* counterpart of this pattern: propose →\n * score → accept/reject inside a single run. `learn` is the *offline*\n * counterpart: reflect on what already happened across one or many recorded\n * runs without an evaluator in the loop.\n *\n * Implemented as a `compose`d `scope` of (compute meta) → (build LearnInput) →\n * (analyzer) → (wrap result with meta). No engine dependency; the analyzer\n * decides how to use the events.\n *\n * Three source kinds: `events` (in-memory), `paths` (explicit JSONL files),\n * `dir` (recursive *.jsonl walk). File reads honor `ctx.abort` at file-level\n * granularity; malformed lines are skipped and surface as `learn.parse_error`\n * trajectory events with 1-indexed line offsets. When `max_events` clips the\n * filtered set, a `learn.truncated` event records `available`, `kept`, and the\n * configured cap.\n */\n\nimport { readFile, readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport {\n aborted_error,\n compose,\n describe,\n parse_trajectory_event,\n scope,\n stash,\n step,\n use,\n} from '#core'\nimport type { AnyStep, RunContext, Step, TrajectoryEvent } from '#core'\n\nexport type TrajectorySource =\n | { readonly kind: 'events'; readonly events: ReadonlyArray<TrajectoryEvent> }\n | { readonly kind: 'paths'; readonly paths: ReadonlyArray<string> }\n | { readonly kind: 'dir'; readonly dir: string }\n\nexport type LearnInput = {\n readonly flow_description: string\n readonly events: ReadonlyArray<TrajectoryEvent>\n readonly prior?: unknown\n}\n\nexport type Improvement = {\n readonly target: string\n readonly kind: 'prompt' | 'config' | 'structure' | 'note'\n readonly rationale: string\n readonly suggestion: string\n}\n\nexport type LearnConfig<i extends LearnInput, o> = {\n readonly name?: string\n readonly flow: AnyStep\n readonly source: TrajectorySource\n readonly analyzer: Step<i, o>\n readonly filter?: (event: TrajectoryEvent) => boolean\n readonly max_events?: number\n}\n\nexport type LearnResult<o> = {\n readonly proposals: o\n readonly events_considered: number\n readonly run_ids: ReadonlyArray<string>\n}\n\nconst DEFAULT_MAX_EVENTS = 10_000\nconst META_KEY = '__learn_meta'\n\ntype LearnMeta = {\n readonly events_considered: number\n readonly run_ids: ReadonlyArray<string>\n}\n\ntype MetaPlus = LearnMeta & {\n readonly events: ReadonlyArray<TrajectoryEvent>\n readonly prior: unknown\n}\n\n/**\n * Recursively collect every `.jsonl` file path under a directory.\n */\nasync function walk_jsonl(dir: string): Promise<string[]> {\n const out: string[] = []\n const entries = await readdir(dir, { withFileTypes: true })\n for (const entry of entries) {\n const full = join(dir, entry.name)\n if (entry.isDirectory()) {\n out.push(...(await walk_jsonl(full)))\n } else if (entry.isFile() && entry.name.endsWith('.jsonl')) {\n out.push(full)\n }\n }\n return out\n}\n\n/**\n * Parse one JSONL file into validated trajectory events.\n *\n * Malformed JSON lines and lines that fail schema validation are skipped,\n * each recorded as a `learn.parse_error` event with a 1-indexed line number,\n * so a single corrupt line never sinks an analysis run.\n */\nasync function read_jsonl(file_path: string, ctx: RunContext): Promise<TrajectoryEvent[]> {\n const content = await readFile(file_path, 'utf8')\n const lines = content.split('\\n')\n const events: TrajectoryEvent[] = []\n for (let i = 0; i < lines.length; i += 1) {\n const raw = lines[i]\n if (raw === undefined || raw.trim() === '') continue\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n ctx.trajectory.record({ kind: 'learn.parse_error', path: file_path, line: i + 1 })\n continue\n }\n const result = parse_trajectory_event(parsed)\n if (result.success) {\n events.push(result.data)\n } else {\n ctx.trajectory.record({ kind: 'learn.parse_error', path: file_path, line: i + 1 })\n }\n }\n return events\n}\n\n/**\n * Throw the abort reason (wrapped in `aborted_error` if needed) when the run\n * has been cancelled.\n */\nfunction throw_if_aborted(ctx: RunContext): void {\n if (!ctx.abort.aborted) return\n const reason = ctx.abort.reason\n if (reason instanceof aborted_error) throw reason\n throw new aborted_error('aborted', reason === undefined ? {} : { reason })\n}\n\n/**\n * Materialize a `TrajectorySource` into an event array.\n *\n * `dir` sources walk recursively and sort paths for deterministic order.\n * File-backed sources check `ctx.abort` between files, so cancellation lands\n * at file-level granularity.\n */\nasync function resolve_events(\n source: TrajectorySource,\n ctx: RunContext,\n): Promise<ReadonlyArray<TrajectoryEvent>> {\n if (source.kind === 'events') return source.events\n\n const file_paths =\n source.kind === 'paths' ? [...source.paths] : (await walk_jsonl(source.dir)).toSorted()\n\n const all: TrajectoryEvent[] = []\n for (const p of file_paths) {\n throw_if_aborted(ctx)\n const events = await read_jsonl(p, ctx)\n all.push(...events)\n }\n return all\n}\n\n/**\n * List the distinct `run_id` values in the events, in first-seen order.\n */\nfunction collect_run_ids(events: ReadonlyArray<TrajectoryEvent>): ReadonlyArray<string> {\n const seen = new Set<string>()\n const out: string[] = []\n for (const event of events) {\n const id = event['run_id']\n if (typeof id === 'string' && !seen.has(id)) {\n seen.add(id)\n out.push(id)\n }\n }\n return out\n}\n\n/**\n * Build the offline self-improvement step.\n *\n * Composes a scope that resolves and caps the recorded events, builds the\n * `LearnInput` (including `describe(flow)`), runs the user's analyzer, and\n * wraps its proposals with the stashed meta (event count, run ids) into a\n * `LearnResult`.\n */\nexport function learn<i extends LearnInput, o>(\n config: LearnConfig<i, o>,\n): Step<unknown, LearnResult<o>> {\n const { flow, source, analyzer, filter } = config\n const max = config.max_events ?? DEFAULT_MAX_EVENTS\n\n const compute_meta = step(\n 'learn_compute_meta',\n async (prior: unknown, ctx): Promise<MetaPlus> => {\n const all = await resolve_events(source, ctx)\n const filtered = filter ? all.filter(filter) : all\n const truncated = filtered.length > max\n const capped = truncated ? filtered.slice(0, max) : filtered\n if (truncated) {\n ctx.trajectory.record({\n kind: 'learn.truncated',\n available: filtered.length,\n kept: capped.length,\n max_events: max,\n })\n }\n return {\n events_considered: capped.length,\n run_ids: collect_run_ids(capped),\n events: capped,\n prior,\n }\n },\n )\n\n const build_input = step(\n 'learn_build_input',\n (meta: MetaPlus): LearnInput => ({\n flow_description: describe(flow),\n events: meta.events,\n prior: meta.prior,\n }),\n )\n\n const wrap_result = use(\n [META_KEY],\n (vars, proposals: o, ctx): LearnResult<o> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const meta = vars[META_KEY] as LearnMeta\n ctx.trajectory.record({\n kind: 'learn.summary',\n events_considered: meta.events_considered,\n run_ids: meta.run_ids,\n })\n return {\n proposals,\n events_considered: meta.events_considered,\n run_ids: meta.run_ids,\n }\n },\n )\n\n const inner = scope([\n stash(META_KEY, compute_meta),\n build_input,\n analyzer,\n wrap_result,\n ])\n\n return compose(inner, { name: config.name ?? 'learn' })\n}\n","/**\n * tournament: pairwise bracket.\n *\n * `tournament({ members, compare })` runs every member, then pairs them off\n * in a single-elimination bracket. `compare(a, b)` returns which result\n * advances. An odd member count yields one bye per affected round. Returns\n * `{ winner, bracket }` where `bracket` lists every match record.\n *\n * Implemented as a `compose`d `sequence` of `parallel(members)` followed\n * by a single bracket-reduction step. Cancellation, fan-out, and abort\n * propagation come from `parallel`'s contract; the bracket step only runs\n * after all members settle.\n */\n\nimport { compose, parallel, sequence, step } from '#core'\nimport type { Step } from '#core'\n\nexport type BracketRecord = {\n readonly round: number\n readonly a_id: string\n readonly b_id: string\n readonly winner_id: string\n}\n\nexport type TournamentConfig<i, o, projected = TournamentResult<o>> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly compare: (a: o, b: o) => Promise<'a' | 'b'> | 'a' | 'b'\n readonly project?: (r: TournamentResult<o>) => projected\n}\n\nexport type TournamentResult<o> = {\n readonly winner: o\n readonly bracket: ReadonlyArray<BracketRecord>\n}\n\n/**\n * Build a single-elimination bracket step over named members.\n *\n * All members run concurrently via `parallel`; the bracket step then reduces\n * survivors round by round with `compare`, recording every match. Requires at\n * least one member so a winner always exists. `project` maps the `{ winner,\n * bracket }` envelope into the step's output (for example, `(r) => r.winner`);\n * omitted, the envelope itself is the output.\n */\nexport function tournament<i, o, projected = TournamentResult<o>>(\n config: TournamentConfig<i, o, projected>,\n): Step<i, projected> {\n const compare_fn = config.compare\n const keys = Object.keys(config.members)\n // When `project` is omitted, `projected` defaults to the envelope type, which is\n // what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = config.project ?? ((r: TournamentResult<o>) => r as unknown as projected)\n\n if (keys.length === 0) {\n throw new Error('tournament: at least one member required')\n }\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const fan_out = parallel(config.members) as Step<i, Record<string, o>>\n\n const bracket_step = step('bracket', async (results: Record<string, o>) => {\n let current: string[] = [...keys]\n const bracket: BracketRecord[] = []\n let round = 0\n\n while (current.length > 1) {\n round += 1\n current = await play_round(current, results, compare_fn, round, bracket)\n }\n\n return project({ winner: winner_of(current, results), bracket })\n })\n\n const inner = sequence([fan_out, bracket_step])\n\n return compose(inner, { name: config.name ?? 'tournament' })\n}\n\n/**\n * Plays one bracket round: pairs survivors two at a time, comparing each pair\n * and recording a `BracketRecord`, and returns the ids advancing. An unpaired\n * trailing survivor takes a bye. Every paired id must have a settled result.\n */\nasync function play_round<o>(\n current: ReadonlyArray<string>,\n results: Record<string, o>,\n compare: (a: o, b: o) => Promise<'a' | 'b'> | 'a' | 'b',\n round: number,\n bracket: BracketRecord[],\n): Promise<string[]> {\n const next_round: string[] = []\n for (let i = 0; i < current.length; i += 2) {\n const a_id = current[i]\n const b_id = current[i + 1]\n if (a_id === undefined) continue\n if (b_id === undefined) {\n next_round.push(a_id)\n continue\n }\n const a_val = results[a_id]\n const b_val = results[b_id]\n if (a_val === undefined || b_val === undefined) {\n throw new Error('tournament: missing result for match')\n }\n const pick = await compare(a_val, b_val)\n const winner_id = pick === 'a' ? a_id : b_id\n bracket.push({ round, a_id, b_id, winner_id })\n next_round.push(winner_id)\n }\n return next_round\n}\n\n/**\n * Extracts the tournament winner from the single surviving id, throwing when\n * no survivor remains or its result is missing.\n */\nfunction winner_of<o>(current: ReadonlyArray<string>, results: Record<string, o>): o {\n const final_id = current[0]\n if (final_id === undefined) {\n throw new Error('tournament: no winner')\n }\n const winner = results[final_id]\n if (winner === undefined) {\n throw new Error('tournament: winner missing from results')\n }\n return winner\n}\n","/**\n * Typed errors for the composites layer.\n *\n * Listed alongside src/core/errors.ts, src/engine/errors.ts, and\n * src/mcp/errors.ts in the `no-class` rule ignores: `instanceof` branching is\n * how a caller tells a benched flow's usage error apart from a case failure.\n */\n\nexport class bench_suspend_error extends Error {\n readonly kind = 'bench_suspend_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly case_id: string;\n readonly suspend_id: string;\n constructor(case_id: string, suspend_id: string, message?: string) {\n super(\n message ??\n `bench: case ${case_id} suspended at ${suspend_id}; bench cannot resume a suspended flow`,\n )\n this.name = 'bench_suspend_error'\n this.case_id = case_id\n this.suspend_id = suspend_id\n }\n}\n","/**\n * bench: run a flow against a fixture set, score each result, return a report.\n *\n * Online counterpart to `learn`: where `learn` reflects on past trajectories\n * after the fact, `bench` runs the flow live against fresh cases and judges\n * each output.\n */\n\nimport { mkdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { aborted_error, resolve_display_name, run, suspended_error } from '#core'\nimport type { Step, TrajectoryEvent, TrajectoryLogger } from '#core'\nimport { filesystem_logger, http_logger, tee_logger } from '#adapters'\nimport { bench_suspend_error } from './errors.js'\n\nexport type Score = { readonly score: number; readonly reason?: string }\n\nexport type BenchCase<I> = {\n readonly id: string\n readonly input: I\n readonly meta?: Readonly<Record<string, unknown>>\n}\n\nexport type JudgeArgs<I, O> = {\n readonly input: I\n readonly output: O\n readonly meta?: Readonly<Record<string, unknown>>\n}\n\nexport type Judge<I, O, S = Score> = Step<JudgeArgs<I, O>, S | undefined>\n\nexport type CaseResult<I = unknown, O = unknown, S = Score> = {\n readonly case_id: string\n readonly ok: boolean\n readonly output?: O\n readonly error?: string\n readonly scores: Record<string, S>\n readonly duration_ms: number\n readonly cost_usd: number\n readonly trajectory_path?: string\n readonly _input?: I\n}\n\nexport type BenchSummary = {\n readonly pass_rate: number\n readonly mean_scores: Record<string, number>\n readonly total_duration_ms: number\n readonly total_cost_usd: number\n readonly mean_cost_usd: number\n}\n\nexport type BenchReport<I = unknown, O = unknown, S = Score> = {\n readonly flow_name: string\n readonly run_id: string\n readonly cases: ReadonlyArray<CaseResult<I, O, S>>\n readonly summary: BenchSummary\n}\n\nexport type BenchOptions = {\n readonly concurrency?: number\n readonly on_case?: (result: CaseResult) => void\n readonly trajectory_dir?: string\n readonly live_url?: string\n readonly run_id?: string\n readonly install_signal_handlers?: boolean\n readonly abort?: AbortSignal\n}\n\n/**\n * Runs `flow` against every case, judges each output, and produces a\n * `BenchReport` you can compare against a committed baseline via\n * `regression_compare`.\n *\n * Each case becomes one `run(flow, case.input, ...)`. Per-case observability:\n * - `trajectory_dir` writes `${dir}/${case.id}.jsonl` via `filesystem_logger`\n * - `live_url` POSTs each event via `http_logger` to a viewer's /api/ingest\n * - both can be combined; bench tees them with an internal cost tracker\n *\n * Cost is tracked per-case in-process by intercepting `kind: 'cost'` events\n * on the trajectory pipeline, so the cost number matches what would be on\n * disk even when no `trajectory_dir` is set.\n *\n * Judges run as Steps after each case, with the same trajectory logger so\n * judge spans land in the case's trajectory file (or push). A judge that\n * throws or returns undefined abstains: the entry is omitted from\n * `case.scores` and the case does not contribute to that judge's mean.\n *\n * Control-flow signals are not case failures and never reach a `CaseResult`.\n * `abort` forwards to every per-case `run` and is re-checked before each case\n * is claimed, so cancelling rejects the whole bench rather than returning a\n * report that silently covers fewer cases than it was given. A\n * `suspended_error` from an approval gate rejects with `bench_suspend_error`:\n * `bench` has no resume path, so a suspend is a usage error, not a zero score.\n */\nexport async function bench<I, O, S = Score>(\n flow: Step<I, O>,\n cases: ReadonlyArray<BenchCase<I>>,\n judges: Record<string, Judge<I, O, S>>,\n options: BenchOptions = {},\n): Promise<BenchReport<I, O, S>> {\n const run_id = options.run_id ?? `bench-${String(Date.now())}-${random_suffix()}`\n const flow_name = describe_flow_name(flow)\n const concurrency = resolve_concurrency(options.concurrency, cases.length)\n const install_signal_handlers = options.install_signal_handlers ?? false\n const run_options = options.abort === undefined ? {} : { abort: options.abort }\n\n throw_if_aborted(options.abort)\n\n if (options.trajectory_dir !== undefined) {\n await mkdir(options.trajectory_dir, { recursive: true })\n }\n\n const judge_entries = Object.entries(judges)\n\n const run_one = async (bc: BenchCase<I>): Promise<CaseResult<I, O, S>> => {\n const { trajectory_path, case_logger, cost_tracker } = build_case_logging(options, bc.id)\n const ctx: CaseRunContext = { case_logger, install_signal_handlers, run_options }\n\n const start = Date.now()\n let output: O | undefined\n let error: string | undefined\n let ok = false\n try {\n output = await run(flow, bc.input, {\n trajectory: case_logger,\n install_signal_handlers,\n ...run_options,\n })\n ok = true\n } catch (err) {\n rethrow_control_flow(err, bc.id)\n error = err instanceof Error ? err.message : String(err)\n ok = false\n }\n\n const scores: Record<string, S> =\n ok && output !== undefined\n ? await run_judges(judge_entries, build_judge_input(bc, output), ctx, bc.id)\n : {}\n\n const duration_ms = Date.now() - start\n const result: CaseResult<I, O, S> = {\n case_id: bc.id,\n ok,\n ...(output !== undefined ? { output } : {}),\n ...(error !== undefined ? { error } : {}),\n scores,\n duration_ms,\n cost_usd: cost_tracker.total(),\n ...(trajectory_path !== undefined ? { trajectory_path } : {}),\n }\n if (options.on_case) {\n // The on_case callback receives the lossy-typed shape: bench's S is\n // generic but the callback hook is a single concrete signature.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n options.on_case(result as unknown as CaseResult)\n }\n return result\n }\n\n const cases_out = await run_with_concurrency(cases, concurrency, run_one, options.abort)\n\n // An abort that fires while every case is already in flight has no queue to\n // halt, and a flow that never checks `ctx.abort` finishes regardless. Both\n // would otherwise yield a full report for a cancelled run.\n throw_if_aborted(options.abort)\n\n const summary = summarize(cases_out, judge_entries.map(([n]) => n))\n\n return {\n flow_name,\n run_id,\n cases: cases_out,\n summary,\n }\n}\n\n/**\n * Per-case run context shared by the flow run and every judge run: the tee'd\n * trajectory logger, the signal-handler flag, and the optional abort forward.\n */\ntype CaseRunContext = {\n readonly case_logger: TrajectoryLogger\n readonly install_signal_handlers: boolean\n readonly run_options: { readonly abort?: AbortSignal }\n}\n\n/**\n * Builds the per-case trajectory pipeline: an optional filesystem sink when\n * `trajectory_dir` is set, an optional HTTP sink when `live_url` is set, and\n * always an in-process cost tracker, all tee'd together. Returns the resolved\n * trajectory path (undefined when no dir is set) alongside the logger and\n * tracker.\n */\nfunction build_case_logging(\n options: BenchOptions,\n case_id: string,\n): {\n readonly trajectory_path: string | undefined\n readonly case_logger: TrajectoryLogger\n readonly cost_tracker: ReturnType<typeof create_cost_tracker>\n} {\n const trajectory_path =\n options.trajectory_dir === undefined\n ? undefined\n : join(options.trajectory_dir, `${case_id}.jsonl`)\n const sinks: TrajectoryLogger[] = []\n if (trajectory_path !== undefined) {\n sinks.push(filesystem_logger({ output_path: trajectory_path }))\n }\n if (options.live_url !== undefined) {\n sinks.push(http_logger({ url: options.live_url }))\n }\n const cost_tracker = create_cost_tracker()\n const case_logger: TrajectoryLogger =\n sinks.length === 0 ? cost_tracker.logger : tee_logger(...sinks, cost_tracker.logger)\n return { trajectory_path, case_logger, cost_tracker }\n}\n\n/**\n * Assembles the judge input triple, including `meta` only when the case\n * carries it so the optional field stays absent rather than `undefined`.\n */\nfunction build_judge_input<I, O>(bc: BenchCase<I>, output: O): JudgeArgs<I, O> {\n return bc.meta === undefined\n ? { input: bc.input, output }\n : { input: bc.input, output, meta: bc.meta }\n}\n\n/**\n * Runs each judge as a Step over the case's input/output, collecting the\n * normalized scores. A judge that throws a control-flow signal rethrows via\n * `rethrow_control_flow`; any other throw, or an abstaining `undefined`,\n * omits that judge from the scores rather than failing the case.\n */\nasync function run_judges<I, O, S>(\n judge_entries: ReadonlyArray<readonly [string, Judge<I, O, S>]>,\n judge_input: JudgeArgs<I, O>,\n ctx: CaseRunContext,\n case_id: string,\n): Promise<Record<string, S>> {\n const scores: Record<string, S> = {}\n for (const [name, judge] of judge_entries) {\n let raw: unknown\n try {\n // oxlint-disable-next-line no-await-in-loop\n raw = await run(judge, judge_input, {\n trajectory: ctx.case_logger,\n install_signal_handlers: ctx.install_signal_handlers,\n ...ctx.run_options,\n })\n } catch (err) {\n rethrow_control_flow(err, case_id)\n continue\n }\n const normalized = normalize_score(raw)\n if (normalized === undefined) continue\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n scores[name] = normalized as S\n }\n return scores\n}\n\n/**\n * Rethrows the control-flow signals that must never become a `CaseResult`.\n *\n * An `aborted_error` cancels the whole bench: a report claiming every\n * remaining case failed is worse than no report. A `suspended_error` becomes\n * `bench_suspend_error` naming the case, because `bench` cannot resume an\n * approval gate and scoring the paused case as a failure corrupts the\n * benchmark. Anything else returns, and the caller records it as a failure.\n */\nfunction rethrow_control_flow(err: unknown, case_id: string): void {\n if (err instanceof aborted_error) throw err\n if (err instanceof suspended_error) throw new bench_suspend_error(case_id, err.suspend_id)\n}\n\n/**\n * Rejects once `signal` has fired, so an abort stops the bench claiming\n * further cases instead of running the queue to completion.\n *\n * Mirrors core's abort shape: an `Error` reason propagates verbatim, anything\n * else is wrapped, so a caller aborting with its own `aborted_error` sees that\n * instance rather than a copy.\n */\nfunction throw_if_aborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted !== true) return\n const reason: unknown = signal.reason\n throw reason instanceof Error ? reason : new aborted_error('aborted', { reason })\n}\n\n/**\n * Aggregates per-case results into the report summary.\n *\n * A judge's mean only averages the cases where that judge produced a score;\n * abstained cases do not drag the mean down, and a judge that never scored\n * is omitted from `mean_scores` entirely.\n */\nfunction summarize<I, O, S>(\n cases: ReadonlyArray<CaseResult<I, O, S>>,\n judge_names: ReadonlyArray<string>,\n): BenchSummary {\n const total_duration_ms = cases.reduce((acc, c) => acc + c.duration_ms, 0)\n const total_cost_usd = cases.reduce((acc, c) => acc + c.cost_usd, 0)\n const ok_count = cases.filter((c) => c.ok).length\n const pass_rate = cases.length === 0 ? 0 : ok_count / cases.length\n const mean_cost_usd = cases.length === 0 ? 0 : total_cost_usd / cases.length\n\n const mean_scores: Record<string, number> = {}\n for (const name of judge_names) {\n let sum = 0\n let count = 0\n for (const c of cases) {\n const n = score_value_of(c.scores[name])\n if (n === undefined) continue\n sum += n\n count += 1\n }\n if (count > 0) mean_scores[name] = sum / count\n }\n\n return {\n pass_rate,\n mean_scores,\n total_duration_ms,\n total_cost_usd,\n mean_cost_usd,\n }\n}\n\n/**\n * Coerces a raw judge return value into a `Score`.\n *\n * Accepts a bare finite number or an object with a finite numeric `score`\n * and optional string `reason`. Anything else (including NaN/Infinity, or a\n * non-string `reason`, which is dropped) normalizes toward `undefined` or a\n * reason-less score; `undefined` means the judge abstained.\n */\nexport function normalize_score(raw: unknown): Score | undefined {\n if (raw === undefined || raw === null) return undefined\n if (typeof raw === 'number') {\n return Number.isFinite(raw) ? { score: raw } : undefined\n }\n if (typeof raw === 'object' && 'score' in raw) {\n const r = raw as { score: unknown; reason?: unknown }\n if (typeof r.score !== 'number' || !Number.isFinite(r.score)) return undefined\n if (r.reason !== undefined && typeof r.reason !== 'string') {\n return { score: r.score }\n }\n return r.reason === undefined ? { score: r.score } : { score: r.score, reason: r.reason }\n }\n return undefined\n}\n\n/**\n * Extracts the numeric value from a score-shaped entry, tolerating both bare\n * numbers and `{ score }` objects since `S` is caller-defined.\n */\nfunction score_value_of(s: unknown): number | undefined {\n if (s === undefined || s === null) return undefined\n if (typeof s === 'number') return Number.isFinite(s) ? s : undefined\n if (typeof s === 'object' && 'score' in s) {\n const raw = (s as Record<string, unknown>)['score']\n return typeof raw === 'number' && Number.isFinite(raw) ? raw : undefined\n }\n return undefined\n}\n\n/**\n * Builds a minimal `TrajectoryLogger` that ignores everything except\n * `kind: 'cost'` events and accumulates their `total_usd` into a running\n * total, read back via `total()` after the case finishes.\n */\nfunction create_cost_tracker(): {\n readonly logger: TrajectoryLogger\n readonly total: () => number\n} {\n let total = 0\n return {\n total: () => total,\n logger: {\n record: (event: TrajectoryEvent) => {\n if (event.kind !== 'cost') return\n const e: Record<string, unknown> = event\n const value = e['total_usd']\n if (typeof value === 'number' && Number.isFinite(value)) total += value\n },\n start_span: (name) => `cost-tracker:${name}`,\n end_span: () => {},\n },\n }\n}\n\n/**\n * Runs `fn` over `items` with at most `limit` calls in flight, preserving\n * input order in the results.\n *\n * Uses a shared-index worker pool: each of the `limit` workers claims the\n * next unclaimed index and writes its result into that slot, so completion\n * order never reorders the output.\n *\n * `abort` is re-checked before each claim, so a signal that fires mid-run\n * halts scheduling at the queue rather than only cancelling work already in\n * flight. The full fan-out path has no queue to halt: every item is already\n * running, so the caller re-checks the signal before reading the results.\n */\nasync function run_with_concurrency<t, r>(\n items: ReadonlyArray<t>,\n limit: number,\n fn: (item: t) => Promise<r>,\n abort?: AbortSignal,\n): Promise<r[]> {\n if (items.length === 0) return []\n if (limit >= items.length) {\n return Promise.all(items.map((it) => fn(it)))\n }\n const results: r[] = Array.from({ length: items.length })\n let next = 0\n const worker = async (): Promise<void> => {\n while (true) {\n throw_if_aborted(abort)\n const idx = next\n next += 1\n if (idx >= items.length) return\n const item = items[idx]\n if (item === undefined) continue\n // oxlint-disable-next-line no-await-in-loop\n results[idx] = await fn(item)\n }\n }\n const workers: Promise<void>[] = []\n for (let i = 0; i < limit; i += 1) workers.push(worker())\n await Promise.all(workers)\n return results\n}\n\n/**\n * Clamps the requested concurrency to a positive integer, defaulting to full\n * fan-out (one worker per case) when unset or invalid.\n */\nfunction resolve_concurrency(value: number | undefined, n_cases: number): number {\n if (value === undefined) return Math.max(1, n_cases)\n if (!Number.isFinite(value) || value <= 0) return Math.max(1, n_cases)\n return Math.max(1, Math.floor(value))\n}\n\n/**\n * Picks a human-readable name for the report, resolving the display channels\n * the same way spans and `describe` do, then falling back to identity.\n */\nfunction describe_flow_name<I, O>(flow: Step<I, O>): string {\n return resolve_display_name(flow, flow.id ?? flow.kind ?? 'flow')\n}\n\n/**\n * Short random base36 suffix to keep default run ids unique across\n * same-millisecond starts.\n */\nfunction random_suffix(): string {\n return Math.random().toString(36).slice(2, 8)\n}\n","/**\n * Stock judges for `bench`.\n *\n * A `Judge<I, O, S>` is a `Step<{ input, output, meta }, S>`: just a step\n * that scores a flow's input/output/metadata triple. Returning `undefined`\n * (or throwing) means the judge abstains; bench records the absence as a\n * missing key in `case.scores` and excludes the case from that judge's\n * `mean_scores` denominator.\n *\n * judge_equals: strict equality vs. `meta.expected`\n * judge_with: wrap a user-supplied scoring function\n * judge_llm: prompt a model + parse the rubric score out of the reply\n *\n * `judge_llm` is engine-agnostic: callers pass their already-configured\n * model_call step (`Step<string, string>`), which keeps composites decoupled\n * from engine. The user-facing wiring lives in their own code.\n */\n\nimport { compose, sequence, step } from '#core'\nimport type { Step } from '#core'\nimport { normalize_score } from './bench.js'\nimport type { Judge, JudgeArgs, Score } from './bench.js'\n\n/**\n * Narrows an unknown value to a plain string-keyed record (non-null object,\n * not an array).\n */\nexport function is_record(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === 'object' && !Array.isArray(v)\n}\n\n/**\n * Structural equality over JSON-shaped values: primitives by `===`, arrays\n * element-wise, records key-by-key with sorted keys. Anything else (class\n * instances, functions) only compares equal by reference.\n */\nexport function deep_equal(a: unknown, b: unknown): boolean {\n if (a === b) return true\n // null, primitives, and array/record mismatches all fall through to the\n // Array.isArray and is_record guards below, so no separate null/typeof\n // pre-checks are needed.\n if (Array.isArray(a) || Array.isArray(b)) return arrays_equal(a, b)\n if (!is_record(a) || !is_record(b)) return false\n return records_equal(a, b)\n}\n\n/**\n * Element-wise deep equality once at least one side is an array: both must be\n * arrays of the same length with every index equal.\n */\nfunction arrays_equal(a: unknown, b: unknown): boolean {\n if (!Array.isArray(a) || !Array.isArray(b)) return false\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i += 1) {\n if (!deep_equal(a[i], b[i])) return false\n }\n return true\n}\n\n/**\n * Key-by-key deep equality over two records: same sorted key sets, and each\n * value deep-equal under the shared key.\n */\nfunction records_equal(a: Record<string, unknown>, b: Record<string, unknown>): boolean {\n const ak = Object.keys(a).toSorted()\n const bk = Object.keys(b).toSorted()\n if (ak.length !== bk.length) return false\n for (let i = 0; i < ak.length; i += 1) {\n const ka = ak[i]\n const kb = bk[i]\n if (ka === undefined || kb === undefined || ka !== kb) return false\n if (!deep_equal(a[ka], b[kb])) return false\n }\n return true\n}\n\n/**\n * Judge that scores 1 when the output deep-equals `meta.expected`, 0\n * otherwise. Abstains when the case has no `meta` or no `expected` key.\n */\nexport function judge_equals<O>(): Judge<unknown, O> {\n return step('judge_equals', (args: JudgeArgs<unknown, O>): Score | undefined => {\n if (args.meta === undefined) return undefined\n if (!('expected' in args.meta)) return undefined\n const expected = args.meta['expected']\n const matches = deep_equal(args.output, expected)\n return { score: matches ? 1 : 0, reason: matches ? 'match' : 'mismatch' }\n })\n}\n\nexport type JudgeWithFn<I, O> = (\n args: JudgeArgs<I, O>,\n) => number | Score | undefined | Promise<number | Score | undefined>\n\n/**\n * Wraps a plain scoring function as a Judge. The function may return a bare\n * number, a `Score`, or `undefined` to abstain; the result is normalized\n * via `normalize_score`.\n */\nexport function judge_with<I, O>(fn: JudgeWithFn<I, O>): Judge<I, O> {\n return step('judge_with', async (args: JudgeArgs<I, O>): Promise<Score | undefined> => {\n const raw = await fn(args)\n return normalize_score(raw)\n })\n}\n\nexport type JudgeLlmConfig = {\n readonly model: Step<string, string>\n readonly rubric: string\n readonly scale?: { readonly min: number; readonly max: number }\n}\n\n/**\n * Judge that prompts a model with a rubric and parses the score out of the\n * reply.\n *\n * Built as a three-step sequence: render the rubric prompt, run the\n * caller-supplied model step, parse the JSON score from the reply. An\n * unparseable reply makes the judge abstain rather than fail the case.\n */\nexport function judge_llm<I, O>(config: JudgeLlmConfig): Judge<I, O> {\n const scale = config.scale ?? { min: 0, max: 1 }\n const build_prompt = step('judge_llm_build_prompt', (args: JudgeArgs<I, O>): string =>\n render_prompt(config.rubric, scale, args),\n )\n const parse = step('judge_llm_parse', (reply: string): Score | undefined =>\n parse_score(reply, scale),\n )\n const inner = sequence([build_prompt, config.model, parse])\n return compose(inner, { name: 'judge_llm' })\n}\n\n/**\n * Renders the evaluator prompt: rubric, required JSON reply shape with the\n * score scale, and the case's input/output serialized as JSON.\n */\nexport function render_prompt<I, O>(\n rubric: string,\n scale: { min: number; max: number },\n args: JudgeArgs<I, O>,\n): string {\n return [\n `You are an evaluator. Score the model output against the rubric below.`,\n ``,\n `Rubric:`,\n rubric,\n ``,\n `Return a single line of JSON with exactly two keys: {\"score\": <number ${String(scale.min)}..${String(scale.max)}>, \"reason\": \"<short>\"}.`,\n `Do not include prose outside the JSON.`,\n ``,\n `Input:`,\n JSON.stringify(args.input),\n ``,\n `Output:`,\n JSON.stringify(args.output),\n ].join('\\n')\n}\n\n/**\n * Parses a model reply into a `Score`, or `undefined` (abstain) when no\n * valid JSON object with a finite numeric `score` can be extracted.\n *\n * Tolerates prose around the JSON via `extract_json_object` and clamps the\n * score into the configured scale rather than rejecting out-of-range values.\n */\nexport function parse_score(\n reply: string,\n scale: { min: number; max: number },\n): Score | undefined {\n const trimmed = reply.trim()\n const candidate = extract_json_object(trimmed)\n if (candidate === undefined) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(candidate)\n } catch {\n return undefined\n }\n if (!is_record(parsed)) return undefined\n const raw_score = parsed['score']\n if (typeof raw_score !== 'number' || !Number.isFinite(raw_score)) return undefined\n const clamped = Math.max(scale.min, Math.min(scale.max, raw_score))\n const raw_reason = parsed['reason']\n const reason = typeof raw_reason === 'string' ? raw_reason : undefined\n return reason === undefined ? { score: clamped } : { score: clamped, reason }\n}\n\n/**\n * Pulls the outermost `{...}` slice out of a reply that may wrap the JSON\n * in prose or code fences. Returns the text as-is when it already starts\n * with `{`.\n */\nexport function extract_json_object(text: string): string | undefined {\n if (text.startsWith('{')) return text\n const start = text.indexOf('{')\n const end = text.lastIndexOf('}')\n if (start === -1 || end === -1 || end < start) return undefined\n return text.slice(start, end + 1)\n}\n","/**\n * regression_compare: diff two BenchReports for regressions.\n *\n * The contract: given a `current` report and a `baseline` report, produce a\n * `RegressionReport` whose `ok` flag is false when any tracked metric got\n * worse beyond a threshold. The function does NOT short-circuit on first\n * failure; every metric and every per-case delta is computed so callers can\n * print or assert against the whole report.\n *\n * Tracked metrics:\n * - pass_rate (any drop is a regression by default)\n * - mean_scores.<name> (per judge; any drop is a regression by default)\n * - total_cost_usd (a relative cost increase above cost_threshold\n * counts as a regression; default 10%)\n *\n * Baselines are plain JSON, written via `write_baseline` and read via\n * `read_baseline`. They live wherever the caller decides, typically\n * `bench/<flow>/baseline.json` checked into git.\n */\n\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\nimport type { BenchReport, CaseResult } from './bench.js'\n\nexport type RegressionDelta = {\n readonly metric: string\n readonly baseline: number\n readonly current: number\n readonly delta: number\n readonly is_regression: boolean\n}\n\nexport type PerCaseDelta = {\n readonly case_id: string\n readonly baseline?: CaseResult\n readonly current?: CaseResult\n readonly score_deltas: Record<string, number>\n readonly cost_delta: number\n readonly is_regression: boolean\n}\n\nexport type RegressionReport = {\n readonly ok: boolean\n readonly deltas: ReadonlyArray<RegressionDelta>\n readonly per_case: ReadonlyArray<PerCaseDelta>\n}\n\nexport type RegressionCompareOptions = {\n readonly score_threshold?: number\n readonly cost_threshold?: number\n}\n\n/**\n * Diff a current `BenchReport` against a baseline.\n *\n * Compares `pass_rate`, each judge's mean score, and total cost, then every\n * individual case. Score metrics regress on any drop beyond\n * `score_threshold` (default 0); cost regresses on a relative increase above\n * `cost_threshold` (default 10%).\n */\nexport function regression_compare(\n current: BenchReport,\n baseline: BenchReport,\n options: RegressionCompareOptions = {},\n): RegressionReport {\n const score_threshold = options.score_threshold ?? 0\n const cost_threshold = options.cost_threshold ?? 0.1\n\n const deltas: RegressionDelta[] = []\n\n const pass_delta = current.summary.pass_rate - baseline.summary.pass_rate\n deltas.push({\n metric: 'pass_rate',\n baseline: baseline.summary.pass_rate,\n current: current.summary.pass_rate,\n delta: pass_delta,\n is_regression: pass_delta < -score_threshold,\n })\n\n const judge_names = collect_judge_names(current, baseline)\n for (const name of judge_names) {\n const c = current.summary.mean_scores[name] ?? 0\n const b = baseline.summary.mean_scores[name] ?? 0\n const d = c - b\n deltas.push({\n metric: `mean_scores.${name}`,\n baseline: b,\n current: c,\n delta: d,\n is_regression: d < -score_threshold,\n })\n }\n\n const cb = baseline.summary.total_cost_usd\n const cc = current.summary.total_cost_usd\n const cost_delta = cc - cb\n const cost_ratio = cb === 0 ? (cc > 0 ? Infinity : 0) : cost_delta / cb\n deltas.push({\n metric: 'total_cost_usd',\n baseline: cb,\n current: cc,\n delta: cost_delta,\n is_regression: cost_ratio > cost_threshold,\n })\n\n const per_case = compute_per_case(current, baseline, score_threshold, cost_threshold)\n const ok = !deltas.some((d) => d.is_regression) && !per_case.some((c) => c.is_regression)\n\n return { ok, deltas, per_case }\n}\n\n/**\n * Compute per-case deltas across the union of case ids in both reports.\n *\n * Cases present on only one side still appear (missing side scores count as\n * 0). A case regresses when a judge score drops beyond the threshold, its\n * cost rises beyond the relative threshold, or it flips from ok to failing.\n */\nfunction compute_per_case(\n current: BenchReport,\n baseline: BenchReport,\n score_threshold: number,\n cost_threshold: number,\n): PerCaseDelta[] {\n const by_id_current = index_by_case_id(current.cases)\n const by_id_baseline = index_by_case_id(baseline.cases)\n const all_ids = new Set<string>([...by_id_current.keys(), ...by_id_baseline.keys()])\n\n const out: PerCaseDelta[] = []\n for (const id of all_ids) {\n const c = by_id_current.get(id)\n const b = by_id_baseline.get(id)\n const { score_deltas, any_regression } = compute_score_deltas(c, b, score_threshold)\n const { cost_delta, is_regression: cost_regression } = compute_cost_regression(\n c,\n b,\n cost_threshold,\n )\n const ok_regression = b?.ok === true && c?.ok !== true\n out.push({\n case_id: id,\n ...(b !== undefined ? { baseline: b } : {}),\n ...(c !== undefined ? { current: c } : {}),\n score_deltas,\n cost_delta,\n is_regression: any_regression || cost_regression || ok_regression,\n })\n }\n return out\n}\n\n/**\n * Compute per-judge score deltas for one case pair across the union of judge\n * names on both sides (a missing side scores 0), flagging a regression when\n * any judge's score drops beyond the threshold.\n */\nfunction compute_score_deltas(\n c: CaseResult | undefined,\n b: CaseResult | undefined,\n score_threshold: number,\n): { score_deltas: Record<string, number>; any_regression: boolean } {\n const score_deltas: Record<string, number> = {}\n let any_regression = false\n const judge_names = new Set<string>([\n ...Object.keys(c?.scores ?? {}),\n ...Object.keys(b?.scores ?? {}),\n ])\n for (const name of judge_names) {\n const delta = score_value(c?.scores[name]) - score_value(b?.scores[name])\n score_deltas[name] = delta\n if (delta < -score_threshold) any_regression = true\n }\n return { score_deltas, any_regression }\n}\n\n/**\n * Compute the cost delta for one case pair and whether it regressed. With a\n * positive baseline cost, a relative rise beyond `cost_threshold` regresses;\n * with a zero baseline, any positive current cost regresses (unless the\n * threshold is Infinity). A missing side counts as 0.\n */\nfunction compute_cost_regression(\n c: CaseResult | undefined,\n b: CaseResult | undefined,\n cost_threshold: number,\n): { cost_delta: number; is_regression: boolean } {\n const baseline_cost = b?.cost_usd ?? 0\n const current_cost = c?.cost_usd ?? 0\n const cost_delta = current_cost - baseline_cost\n const is_regression =\n baseline_cost > 0\n ? cost_delta / baseline_cost > cost_threshold\n : current_cost > 0 && baseline_cost === 0 && cost_threshold < Infinity\n return { cost_delta, is_regression }\n}\n\n/**\n * Extract a finite numeric score from a raw score entry.\n *\n * Accepts a bare number or an object with a numeric `score` field; anything\n * else (missing, NaN, non-numeric) counts as 0 so deltas stay well-defined.\n */\nfunction score_value(s: unknown): number {\n if (s === undefined || s === null) return 0\n if (typeof s === 'number') return Number.isFinite(s) ? s : 0\n if (typeof s === 'object' && 'score' in s) {\n const v = (s as Record<string, unknown>)['score']\n return typeof v === 'number' && Number.isFinite(v) ? v : 0\n }\n return 0\n}\n\n/**\n * Index case results by their `case_id` for pairwise lookup.\n */\nfunction index_by_case_id<I, O, S>(\n cases: ReadonlyArray<CaseResult<I, O, S>>,\n): Map<string, CaseResult<I, O, S>> {\n const m = new Map<string, CaseResult<I, O, S>>()\n for (const c of cases) m.set(c.case_id, c)\n return m\n}\n\n/**\n * Union the judge names appearing in either report, sorted for stable output.\n */\nfunction collect_judge_names(a: BenchReport, b: BenchReport): string[] {\n const names = new Set<string>([\n ...Object.keys(a.summary.mean_scores),\n ...Object.keys(b.summary.mean_scores),\n ])\n return [...names].toSorted()\n}\n\n/**\n * Read and validate a baseline `BenchReport` from a JSON file.\n *\n * Validation is structural (required fields present), so a hand-edited or\n * truncated baseline fails loudly with the offending path in the message.\n */\nexport async function read_baseline(path: string): Promise<BenchReport> {\n const text = await readFile(path, 'utf8')\n const parsed: unknown = JSON.parse(text)\n validate_report(parsed, path)\n return parsed\n}\n\n/**\n * Write a `BenchReport` as pretty-printed JSON, creating parent directories.\n */\nexport async function write_baseline(path: string, report: BenchReport): Promise<void> {\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, `${JSON.stringify(report, null, 2)}\\n`, 'utf8')\n}\n\n/**\n * Assert that parsed JSON has the structural shape of a `BenchReport`.\n */\nfunction validate_report(value: unknown, path: string): asserts value is BenchReport {\n if (value === null || typeof value !== 'object') {\n throw new Error(`baseline at ${path} is not an object`)\n }\n const v = value as Partial<BenchReport>\n if (typeof v.flow_name !== 'string' || typeof v.run_id !== 'string') {\n throw new Error(`baseline at ${path} missing flow_name/run_id`)\n }\n if (!Array.isArray(v.cases) || typeof v.summary !== 'object' || v.summary === null) {\n throw new Error(`baseline at ${path} missing cases/summary`)\n }\n}\n","/**\n * model_call: the single sanctioned bridge between the composition and\n * engine layers.\n *\n * This is the only file under `src/` permitted to import value symbols from\n * both `core` and `engine` (enforced by the model-call-is-sole-bridge\n * ast-grep rule in `rules/`).\n *\n * The returned Step auto-threads ctx.abort, ctx.trajectory, and, only when\n * run.stream is driving, an on_chunk forwarder that records each chunk as a\n * `model_chunk` trajectory event. Callers cannot override these: the\n * composition layer owns cancellation and trajectory plumbing. Cost events\n * flow out via ctx.trajectory per the engine's own emission rules.\n */\n\nimport { createHash } from 'node:crypto'\nimport { aborted_error, step } from '#core'\nimport type { RunContext, Step, TrajectoryLogger } from '#core'\nimport type {\n EffortLevel,\n Engine,\n GenerateOptions,\n GenerateResult,\n Message,\n PrepareStepHook,\n RetryPolicy,\n Tool,\n ToolApprovalHandler,\n} from '#engine'\nimport type { ToolSchema } from '#schema'\n\nexport type ModelCallInput = string | ReadonlyArray<Message>\n\nexport type ModelCallConfig<T = string, projected = GenerateResult<T>> = {\n readonly engine: Engine\n /**\n * Model id, sent to the provider verbatim (there is no alias layer).\n * Optional: if omitted, the engine's `defaults.model` is used. Errors at\n * call time if neither is set.\n */\n readonly model?: string\n /**\n * Transport for the model: `anthropic` | `claude_cli` | `openrouter` | ...\n * Optional: if omitted, the engine's `defaults.provider` (or its sole\n * configured provider) is used.\n */\n readonly provider?: string\n readonly id?: string\n readonly system?: string\n readonly tools?: ReadonlyArray<Tool>\n readonly schema?: ToolSchema<T>\n readonly effort?: EffortLevel\n readonly temperature?: number\n readonly max_tokens?: number\n readonly top_p?: number\n readonly max_steps?: number\n /**\n * Per-turn wall-clock budget in milliseconds, forwarded to the engine.\n * See `GenerateOptions.turn_timeout_ms`.\n */\n readonly turn_timeout_ms?: number\n /**\n * Per-turn message hook, forwarded to the engine. See\n * `GenerateOptions.prepare_step`.\n */\n readonly prepare_step?: PrepareStepHook\n readonly provider_options?: Record<string, unknown>\n readonly retry_policy?: RetryPolicy\n readonly tool_error_policy?: 'feed_back' | 'throw'\n readonly schema_repair_attempts?: number\n readonly tool_call_repair_attempts?: number\n readonly max_tool_calls_per_step?: number\n readonly on_tool_approval?: ToolApprovalHandler\n /**\n * Map the `GenerateResult` envelope into the step's output at the source.\n * The projection runs inside the model_call step itself, so `describe` and\n * the trajectory gain no wrapper node. Omitted, the envelope is the output.\n * `model_step` is this option preset to `(r) => r.content`.\n */\n readonly project?: (r: GenerateResult<T>) => projected\n}\n\n/**\n * Wrap the run's trajectory so the engine's own spans (engine.generate and its\n * step spans) nest under the model_call step rather than floating. The wrapper\n * keeps a private span stack seeded with the model_call step's id, so nesting\n * is correct and concurrency-safe even when several model_calls run together\n * under `parallel`/`map` (each invocation builds its own wrapper). A\n * caller-supplied `parent_span_id` is never overridden.\n */\nfunction engine_trajectory(\n inner: TrajectoryLogger,\n root_parent: string | undefined,\n): TrajectoryLogger {\n const stack: string[] = root_parent !== undefined ? [root_parent] : []\n return {\n record: (event) => {\n inner.record(event)\n },\n start_span: (name, meta) => {\n const has_parent = meta !== undefined && 'parent_span_id' in meta\n const parent = stack.length > 0 ? stack[stack.length - 1] : undefined\n const next_meta =\n has_parent || parent === undefined ? meta : { ...meta, parent_span_id: parent }\n const id = inner.start_span(name, next_meta)\n stack.push(id)\n return id\n },\n end_span: (id, meta) => {\n inner.end_span(id, meta)\n const idx = stack.lastIndexOf(id)\n if (idx !== -1) stack.splice(idx, 1)\n },\n }\n}\n\n/**\n * Derive a short, stable hash from the call's model, provider, system\n * prompt, and tool/schema shape.\n *\n * Used to build a default step id when the caller doesn't supply `cfg.id`.\n */\nfunction stable_signature(input: {\n model: string | undefined\n provider: string | undefined\n system: string | undefined\n has_tools: boolean\n has_schema: boolean\n}): string {\n const payload = JSON.stringify({\n model: input.model ?? null,\n provider: input.provider ?? null,\n system: input.system ?? null,\n has_tools: input.has_tools,\n has_schema: input.has_schema,\n })\n return createHash('sha256').update(payload).digest('hex').slice(0, 8)\n}\n\nlet model_call_counter = 0\n\n/**\n * Build the default step id: `model_call_<hash>_<n>`. The instance counter\n * keeps two leaves built from identical configs distinguishable in describe\n * and the trajectory; the hash still identifies the call's shape.\n *\n * Underscore-separated rather than colon-separated because every id in the\n * system is identifier-shaped, generated ones included.\n */\nfunction next_auto_id(input: Parameters<typeof stable_signature>[0]): string {\n model_call_counter += 1\n return `model_call_${stable_signature(input)}_${model_call_counter}`\n}\n\n/**\n * Copy `value` onto `target[key]` only when it is defined, so an absent optional\n * config field leaves the key off `GenerateOptions` rather than present-as-undefined.\n */\nfunction assign_if_present<T, K extends keyof T>(target: T, key: K, value: T[K]): void {\n if (value !== undefined) target[key] = value\n}\n\n/**\n * Translate `cfg` into a `GenerateOptions`, folding each supplied optional field\n * in via `assign_if_present`. `tools` (spread to a fresh array) and\n * `retry_policy` (renamed to `retry`) are the two fields that do not copy\n * straight across and stay explicit; the rest map name-for-name.\n */\nfunction build_generate_options<T, projected>(\n cfg: ModelCallConfig<T, projected>,\n prompt: Message[],\n ctx: RunContext,\n): GenerateOptions<T> {\n const opts: GenerateOptions<T> = {\n prompt,\n abort: ctx.abort,\n trajectory: engine_trajectory(ctx.trajectory, ctx.parent_span_id),\n }\n assign_if_present(opts, 'model', cfg.model)\n assign_if_present(opts, 'provider', cfg.provider)\n assign_if_present(opts, 'system', cfg.system)\n if (cfg.tools !== undefined) opts.tools = [...cfg.tools]\n assign_if_present(opts, 'schema', cfg.schema)\n assign_if_present(opts, 'effort', cfg.effort)\n assign_if_present(opts, 'temperature', cfg.temperature)\n assign_if_present(opts, 'max_tokens', cfg.max_tokens)\n assign_if_present(opts, 'top_p', cfg.top_p)\n assign_if_present(opts, 'turn_timeout_ms', cfg.turn_timeout_ms)\n assign_if_present(opts, 'prepare_step', cfg.prepare_step)\n assign_if_present(opts, 'max_steps', cfg.max_steps)\n assign_if_present(opts, 'provider_options', cfg.provider_options)\n if (cfg.retry_policy !== undefined) opts.retry = cfg.retry_policy\n assign_if_present(opts, 'tool_error_policy', cfg.tool_error_policy)\n assign_if_present(opts, 'schema_repair_attempts', cfg.schema_repair_attempts)\n assign_if_present(opts, 'tool_call_repair_attempts', cfg.tool_call_repair_attempts)\n assign_if_present(opts, 'max_tool_calls_per_step', cfg.max_tool_calls_per_step)\n assign_if_present(opts, 'on_tool_approval', cfg.on_tool_approval)\n return opts\n}\n\n/**\n * Build a `Step` that calls `cfg.engine.generate` with `cfg` translated into\n * `GenerateOptions`.\n *\n * Threads `ctx.abort` and `ctx.trajectory` (nested under the model_call\n * step's own span) into every call, and, when `run.stream` is driving,\n * records each chunk as a `model_chunk` trajectory event. `cfg.project`\n * maps the `GenerateResult` envelope into the step's output inside the same\n * step; omitted, the envelope is the output.\n */\nexport function model_call<T = string, projected = GenerateResult<T>>(\n cfg: ModelCallConfig<T, projected>,\n): Step<ModelCallInput, projected> {\n // Guard at construction so a wiring mistake (JS caller, spread gone wrong)\n // surfaces where it was made instead of as a bare property-read crash at\n // dispatch time.\n if (typeof cfg?.engine?.generate !== 'function') {\n throw new TypeError(\n 'model_call: cfg.engine is required (an Engine from create_engine or fascicle/testing)',\n )\n }\n const has_tools = Boolean(cfg.tools && cfg.tools.length > 0)\n const has_schema = cfg.schema !== undefined\n // When `project` is omitted, `projected` defaults to the envelope type, which\n // is what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = cfg.project ?? ((r: GenerateResult<T>) => r as unknown as projected)\n const step_id =\n cfg.id ??\n next_auto_id({\n model: cfg.model,\n provider: cfg.provider,\n system: cfg.system,\n has_tools,\n has_schema,\n })\n\n const describe_config: {\n model?: string\n provider?: string\n has_tools: boolean\n has_schema: boolean\n has_project: boolean\n has_prepare_step: boolean\n system?: string\n effort?: EffortLevel\n temperature?: number\n max_tokens?: number\n top_p?: number\n turn_timeout_ms?: number\n } = {\n has_tools,\n has_schema,\n has_project: cfg.project !== undefined,\n has_prepare_step: cfg.prepare_step !== undefined,\n }\n if (cfg.model !== undefined) describe_config.model = cfg.model\n if (cfg.provider !== undefined) describe_config.provider = cfg.provider\n if (cfg.system !== undefined) describe_config.system = cfg.system\n if (cfg.effort !== undefined) describe_config.effort = cfg.effort\n if (cfg.temperature !== undefined) describe_config.temperature = cfg.temperature\n if (cfg.max_tokens !== undefined) describe_config.max_tokens = cfg.max_tokens\n if (cfg.top_p !== undefined) describe_config.top_p = cfg.top_p\n if (cfg.turn_timeout_ms !== undefined) describe_config.turn_timeout_ms = cfg.turn_timeout_ms\n\n const inner = step<ModelCallInput, projected>(step_id, async (input, ctx) => {\n if (ctx.abort.aborted) {\n throw new aborted_error('aborted before model_call', {\n reason: { signal: 'abort' },\n step_index: 0,\n })\n }\n\n const prompt: Message[] =\n typeof input === 'string'\n ? [{ role: 'user', content: [{ type: 'text', text: input }] }]\n : [...input]\n\n const opts = build_generate_options(cfg, prompt, ctx)\n\n if (ctx.streaming) {\n opts.on_chunk = (chunk) => {\n // Record with kind preserved. ctx.emit would clobber kind to 'emit'\n // and bury the chunk, so stream consumers would have to un-nest a\n // generic event; recording keeps a clean top-level `model_chunk` event\n // (what docs/concepts.md already documents) carrying the StreamChunk.\n ctx.trajectory.record({ kind: 'model_chunk', step_id, chunk })\n }\n }\n\n return project(await cfg.engine.generate(opts))\n })\n\n return {\n id: inner.id,\n kind: inner.kind,\n run: (input, ctx) => inner.run(input, ctx),\n config: Object.freeze({ ...describe_config }),\n }\n}\n\n/**\n * model_step: `model_call` projected to its content.\n *\n * Returns a Step whose output is the model's final content (a `string`, or\n * the schema-validated value when `cfg.schema` is set) instead of the full\n * `GenerateResult` envelope. Use `model_step` when the flow only wants the\n * answer, keeping compositions at the `step, step, model_step, step` cadence;\n * drop to `model_call` when the caller needs usage, cost, tool calls, or\n * finish reason (or its `project` option, when the flow wants a slice of the\n * envelope mapped at the source).\n *\n * Implemented as `model_call` with `project` preset to `(r) => r.content`,\n * so the leaf is a single node in `describe` and the trajectory. Wrapping a\n * primitive into an app-shaped helper of your own is still the extension\n * pattern; this is its smallest instance.\n */\nexport function model_step<T = string>(\n cfg: Omit<ModelCallConfig<T>, 'project'>,\n): Step<ModelCallInput, T> {\n return model_call<T, T>({ ...cfg, project: (r) => r.content })\n}\n","/**\n * Env forwarding allowlist for CLI subprocesses.\n *\n * Useful when passing explicit env to `claude_cli` under api_key mode\n * (oauth mode inherits the parent env automatically), or whenever an\n * explicit, minimal allowlist is preferred over inheriting the full parent\n * env.\n */\nconst STANDARD_KEYS = ['PATH', 'HOME', 'SHELL', 'USER', 'LOGNAME', 'LANG', 'TMPDIR'] as const\n\n/**\n * Return the standard env vars a CLI subprocess needs to reach a user's\n * logged-in session: PATH, HOME, SHELL, USER, LOGNAME, LANG, TMPDIR.\n *\n * Keys absent from `process.env` are skipped.\n *\n * @example\n * provider_options: {\n * claude_cli: { env: forward_standard_env() },\n * }\n */\nexport function forward_standard_env(): Record<string, string> {\n const out: Record<string, string> = {}\n for (const key of STANDARD_KEYS) {\n const v = process.env[key]\n if (typeof v === 'string') out[key] = v\n }\n return out\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACWA,MAAa,aAAa;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;A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,SAAS,CAAC;IAAE,MAAM;IAAQ,MAAM;GAAM,CAAC;EAAE,CAAC,IAC3D,CAAC,GAAG,KAAK,GAEkC,GAAG;EAEpD,IAAI,IAAI,WACN,KAAK,YAAY,UAAU;GAKzB,IAAI,WAAW,OAAO;IAAE,MAAM;IAAe;IAAS;GAAM,CAAC;EAC/D;EAGF,OAAO,QAAQ,MAAM,IAAI,OAAO,SAAS,IAAI,CAAC;CAChD,CAAC;CAED,OAAO;EACL,IAAI,MAAM;EACV,MAAM,MAAM;EACZ,MAAM,OAAO,QAAQ,MAAM,IAAI,OAAO,GAAG;EACzC,QAAQ,OAAO,OAAO,EAAE,GAAG,gBAAgB,CAAC;CAC9C;AACF;;;;;;;;;;;;;;;;;AAkBA,SAAgB,WACd,KACyB;CACzB,OAAO,WAAiB;EAAE,GAAG;EAAK,UAAU,MAAM,EAAE;CAAQ,CAAC;AAC/D;;;;;;;;;;;ACzTA,MAAM,gBAAgB;CAAC;CAAQ;CAAQ;CAAS;CAAQ;CAAW;CAAQ;AAAQ;;;;;;;;;;;;AAanF,SAAgB,uBAA+C;CAC7D,MAAM,MAA8B,CAAC;CACrC,KAAK,MAAM,OAAO,eAAe;EAC/B,MAAM,IAAI,QAAQ,IAAI;EACtB,IAAI,OAAO,MAAM,UAAU,IAAI,OAAO;CACxC;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"index.js","names":["throw_if_aborted","e"],"sources":["../src/core/flow-schema.json","../src/core/step_kinds.ts","../src/composites/adversarial.ts","../src/composites/consensus.ts","../src/composites/ensemble.ts","../src/composites/ensemble_step.ts","../src/composites/gate.ts","../src/composites/improve.ts","../src/composites/learn.ts","../src/composites/tournament.ts","../src/composites/errors.ts","../src/composites/bench.ts","../src/composites/judges.ts","../src/composites/regression.ts","../src/engine/throughput.ts","../src/model_call.ts","../src/forward_standard_env.ts"],"sourcesContent":["","/**\n * Closed registry of every `Step.kind` produced by the composition layer.\n *\n * Studio (and any other consumer that needs to enumerate primitives: palette,\n * docs, code generation) can rely on this being the exhaustive set. New\n * primitives must add their kind here. `step_kinds.test.ts` pins the list\n * against the kinds core actually constructs, and\n * `composites/__tests__/coverage.test.ts` covers the four composite kinds\n * whose factories live outside core.\n */\n\nexport const STEP_KINDS = [\n 'step',\n 'sequence',\n 'parallel',\n 'branch',\n 'map',\n 'pipe',\n 'retry',\n 'fallback',\n 'timeout',\n 'loop',\n 'compose',\n 'adversarial',\n 'ensemble',\n 'tournament',\n 'consensus',\n 'checkpoint',\n 'suspend',\n 'scope',\n 'stash',\n 'use',\n 'chain',\n] as const\n\nexport type StepKind = (typeof STEP_KINDS)[number]\n\n/**\n * Check whether a value is one of the registered `Step.kind` strings.\n */\nexport function is_step_kind(value: unknown): value is StepKind {\n return typeof value === 'string' && (STEP_KINDS as readonly string[]).includes(value)\n}\n","/**\n * adversarial: build-and-critique loop.\n *\n * This file is the canonical example of how a user-built composite is\n * structured: the entire implementation is a composition of core\n * primitives. Read it as documentation.\n */\n\nimport { compose, loop, scope, stash, step, use } from '#core'\nimport type { Step } from '#core'\n\nexport type AdversarialBuildInput<input, candidate> = {\n readonly input: input\n readonly prior?: candidate\n readonly critique?: string\n}\n\nexport type AdversarialCritiqueResult = { readonly notes: string } & Record<string, unknown>\n\nexport type AdversarialResult<candidate> = {\n readonly candidate: candidate\n readonly converged: boolean\n readonly rounds: number\n}\n\nexport type AdversarialConfig<input, candidate, projected = AdversarialResult<candidate>> = {\n readonly name?: string\n readonly build: Step<AdversarialBuildInput<input, candidate>, candidate>\n readonly critique: Step<candidate, AdversarialCritiqueResult>\n readonly accept: (critique_result: AdversarialCritiqueResult) => boolean\n readonly max_rounds: number\n readonly project?: (r: AdversarialResult<candidate>) => projected\n}\n\ntype AdversarialState<input, candidate> = {\n readonly input: input\n readonly candidate?: candidate\n readonly critique_notes?: string\n readonly last_critique?: AdversarialCritiqueResult\n}\n\n/**\n * Projects loop state into the build step's input.\n *\n * Omits `prior` and `critique` until they exist, so the first round's build\n * sees only the original input and later rounds see what came before.\n */\nfunction build_input_from_state<i, c>(\n s: AdversarialState<i, c>,\n): AdversarialBuildInput<i, c> {\n if (s.candidate === undefined) return { input: s.input }\n if (s.critique_notes === undefined) return { input: s.input, prior: s.candidate }\n return { input: s.input, prior: s.candidate, critique: s.critique_notes }\n}\n\n/**\n * Builds a Step that runs up to `max_rounds` iterations of build ->\n * critique -> accept.\n *\n * Each round builds a candidate (receiving the prior candidate and critique\n * notes when available), critiques it, then checks `accept(critique_result)`.\n * Returns `{ candidate, converged, rounds }`. Does not throw on\n * non-convergence; `converged: false` reports it instead. `project` maps\n * that envelope into the step's output (for example, `(r) => r.candidate`); omitted,\n * the envelope itself is the output.\n *\n * Implemented as a `compose`d `loop` whose body builds a new candidate and\n * whose guard runs the critique step and checks `accept`. State is threaded\n * through `scope`/`stash`/`use` so the build and critique steps remain\n * unmodified user-supplied `Step` values.\n */\nexport function adversarial<input, candidate, projected = AdversarialResult<candidate>>(\n config: AdversarialConfig<input, candidate, projected>,\n): Step<input, projected> {\n const { build, critique, accept, max_rounds } = config\n // When `project` is omitted, `projected` defaults to the envelope type, which is\n // what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = config.project ?? ((r: AdversarialResult<candidate>) => r as unknown as projected)\n\n type S = AdversarialState<input, candidate>\n\n const body: Step<S, S> = scope([\n stash('state', step('snapshot', (s: S) => s)),\n step('to_build_input', (s: S) => build_input_from_state(s)),\n build,\n use(['state'], (vars, candidate: candidate) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars['state'] as S\n return { ...prior, candidate }\n }),\n ])\n\n const guard: Step<S, { stop: boolean; state: S }> = scope([\n stash('state', step('snapshot', (s: S) => s)),\n step('extract_candidate', (s: S) => {\n if (s.candidate === undefined) {\n throw new Error('adversarial: guard reached without a candidate')\n }\n return s.candidate\n }),\n critique,\n use(['state'], (vars, critique_result: AdversarialCritiqueResult) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars['state'] as S\n return {\n stop: accept(critique_result),\n state: {\n ...prior,\n last_critique: critique_result,\n critique_notes: critique_result.notes,\n },\n }\n }),\n ])\n\n const inner = loop<input, S, projected>({\n init: (input) => ({ input }),\n body,\n guard,\n finish: (s, { converged, rounds }) => {\n if (s.candidate === undefined) {\n throw new Error('adversarial: finished without a candidate')\n }\n return project({ candidate: s.candidate, converged, rounds })\n },\n max_rounds,\n })\n\n return compose(inner, { name: config.name ?? 'adversarial' })\n}\n","/**\n * consensus: run-until-agreement composite over concurrent members.\n */\n\nimport { compose, loop, parallel, scope, stash, step, use } from '#core'\nimport type { Step } from '#core'\n\nexport type ConsensusConfig<i, o, projected = ConsensusResult<o>> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly agree: (results: Record<string, o>) => boolean\n readonly max_rounds: number\n readonly project?: (r: ConsensusResult<o>) => projected\n}\n\nexport type ConsensusResult<o> = {\n readonly result: Record<string, o>\n readonly converged: boolean\n}\n\ntype ConsensusState<i, o> = {\n readonly input: i\n readonly results: Record<string, o>\n}\n\n/**\n * Builds a Step that runs every member concurrently with the same input\n * until `agree(results)` accepts a round.\n *\n * On agreement, returns the round's results with `converged: true`.\n * Otherwise re-runs all members up to `max_rounds` times and returns the\n * last results with `converged: false` if no agreement is reached.\n * `project` maps the `{ result, converged }` envelope into the step's output\n * (for example, `(r) => r.converged`); omitted, the envelope itself is the output.\n *\n * Implemented as a `compose`d `loop` whose body runs `parallel(members)` and\n * whose guard evaluates `agree`. State carries the original input alongside\n * the most recent results so each round receives the same input.\n */\nexport function consensus<i, o, projected = ConsensusResult<o>>(\n config: ConsensusConfig<i, o, projected>,\n): Step<i, projected> {\n const { members, agree, max_rounds } = config\n // When `project` is omitted, `projected` defaults to the envelope type, which is\n // what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = config.project ?? ((r: ConsensusResult<o>) => r as unknown as projected)\n\n type S = ConsensusState<i, o>\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const round_step = parallel(members) as Step<i, Record<string, o>>\n\n const body: Step<S, S> = scope([\n stash('state', step('snapshot', (s: S) => s)),\n step('extract_input', (s: S) => s.input),\n round_step,\n use(['state'], (vars, results: Record<string, o>) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars['state'] as S\n return { ...prior, results }\n }),\n ])\n\n const guard: Step<S, { stop: boolean; state: S }> = step('agree', (s: S) => ({\n stop: agree(s.results),\n state: s,\n }))\n\n const inner = loop<i, S, projected>({\n init: (input) => ({ input, results: {} }),\n body,\n guard,\n finish: (s, { converged }) => project({ result: s.results, converged }),\n max_rounds,\n })\n\n return compose(inner, { name: config.name ?? 'consensus' })\n}\n","/**\n * ensemble: N-of-M pick-best with a plain-function scorer.\n */\n\nimport { compose, parallel, sequence, step } from '#core'\nimport type { Step } from '#core'\n\nexport type EnsembleConfig<i, o, projected = EnsembleResult<o>> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly score: (result: o, member_id: string) => number | Promise<number>\n readonly select?: 'max' | 'min'\n readonly project?: (r: EnsembleResult<o>) => projected\n}\n\nexport type EnsembleResult<o> = {\n readonly winner: o\n readonly scores: Record<string, number>\n}\n\n/**\n * Builds a Step that runs every member concurrently with the same input,\n * scores each result, and returns the winner plus the complete score map.\n *\n * `select` picks the highest (`'max'`, the default) or lowest (`'min'`)\n * score. Tie-breaking is \"any tied result is acceptable\": the first member\n * (in `members` key order) holding the best score wins. `project` maps the\n * `{ winner, scores }` envelope into the step's output (for example, `(r) =>\n * r.winner`); omitted, the envelope itself is the output.\n *\n * Implemented as a `compose`d `sequence` of `parallel(members)` followed by\n * a single picking step. Cancellation, fan-out, and abort propagation come\n * from `parallel`'s own contract.\n */\nexport function ensemble<i, o, projected = EnsembleResult<o>>(\n config: EnsembleConfig<i, o, projected>,\n): Step<i, projected> {\n const select: 'max' | 'min' = config.select ?? 'max'\n const score_fn = config.score\n const keys = Object.keys(config.members)\n // When `project` is omitted, `projected` defaults to the envelope type, which is\n // what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = config.project ?? ((r: EnsembleResult<o>) => r as unknown as projected)\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const fan_out = parallel(config.members) as Step<i, Record<string, o>>\n\n const pick = step('pick_winner', async (results: Record<string, o>) => {\n const scores: Record<string, number> = {}\n for (const k of keys) {\n const value = results[k]\n if (value === undefined) continue\n scores[k] = await score_fn(value, k)\n }\n \n let winner_key: string | undefined = undefined\n let winner_score: number | undefined = undefined\n for (const k of keys) {\n const current = scores[k]\n if (current === undefined) continue\n if (winner_score === undefined) {\n winner_key = k\n winner_score = current\n continue\n }\n const better = select === 'max' ? current > winner_score : current < winner_score\n if (better) {\n winner_key = k\n winner_score = current\n }\n }\n \n if (winner_key === undefined) {\n throw new Error('ensemble: no members produced a result')\n }\n const winner = results[winner_key]\n if (winner === undefined) {\n throw new Error('ensemble: winner missing from results')\n }\n return project({ winner, scores })\n })\n\n const inner = sequence([fan_out, pick])\n\n return compose(inner, { name: config.name ?? 'ensemble' })\n}\n","/**\n * ensemble_step: N-of-M pick-best with a Step-based scorer.\n */\n\nimport { compose, map, parallel, scope, stash, step, use } from '#core'\nimport type { Step } from '#core'\n\nexport type EnsembleStepConfig<i, o, ranked, projected = EnsembleStepResult<o, ranked>> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly score: Step<o, ranked>\n readonly rank_by: (r: ranked) => number\n readonly select?: 'max' | 'min'\n readonly project?: (r: EnsembleStepResult<o, ranked>) => projected\n}\n\nexport type EnsembleStepResult<o, ranked> = {\n readonly winner_id: string\n readonly winner: o\n readonly winner_scored: ranked\n readonly scored: Record<string, ranked>\n}\n\n// Scope variable keys, underscore-prefixed to avoid colliding with any\n// stashes a user-supplied step might set in the same scope chain.\nconst RESULTS_KEY = '__ensemble_step_results'\nconst ITEM_KEY = '__ensemble_step_item'\n\ntype Pair<o> = { readonly id: string; readonly value: o }\ntype ScoredPair<ranked> = { readonly id: string; readonly scored: ranked }\n\n/**\n * Builds a Step that runs every member concurrently, scores each result via\n * a scoring `Step`, and returns the best-ranking winner.\n *\n * Sibling of `ensemble` for the case where scoring is itself a `Step` (for\n * example, a separate model call, a sub-flow, anything that wants its own\n * trajectory span and abort routing). The `score` step is dispatched once per\n * member result; `rank_by` projects a number out of the structured scored output;\n * `select` picks the highest (`'max'`, default) or lowest (`'min'`) rank.\n *\n * The result carries `winner_scored`, the structured output from the round's\n * scoring run preserved verbatim, so callers never pay to re-score the\n * winner. `scored` holds the structured score for every member. `project`\n * maps that envelope into the step's output (for example, `(r) => r.winner`);\n * omitted, the envelope itself is the output.\n *\n * Implemented as a `compose`d `scope` over (`stash(parallel(members))` ->\n * `to_pairs` -> `map(score per result, threading id)` -> `use` to pick the\n * winner). Cancellation, fan-out, and abort propagation come from the\n * underlying `parallel` and `map` contracts.\n */\nexport function ensemble_step<i, o, ranked, projected = EnsembleStepResult<o, ranked>>(\n config: EnsembleStepConfig<i, o, ranked, projected>,\n): Step<i, projected> {\n const { members, score, rank_by } = config\n const select: 'max' | 'min' = config.select ?? 'max'\n const keys = Object.keys(members)\n // When `project` is omitted, `projected` defaults to the envelope type, which is\n // what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = config.project ?? ((r: EnsembleStepResult<o, ranked>) => r as unknown as projected)\n\n if (keys.length === 0) {\n throw new Error('ensemble_step: at least one member required')\n }\n\n const fan_out = parallel(members)\n\n const score_one = scope([\n stash(ITEM_KEY, step('ensemble_step_item_snapshot', (item: Pair<o>) => item)),\n step('ensemble_step_extract_value', (item: Pair<o>) => item.value),\n score,\n use([ITEM_KEY], (vars, scored: ranked): ScoredPair<ranked> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const item = vars[ITEM_KEY] as Pair<o>\n return { id: item.id, scored }\n }),\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<Pair<o>, ScoredPair<ranked>>\n\n const to_pairs = step(\n 'ensemble_step_to_pairs',\n (results: Record<string, o>): ReadonlyArray<Pair<o>> => {\n const out: Pair<o>[] = []\n for (const id of keys) {\n if (id in results) {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n out.push({ id, value: results[id] as o })\n }\n }\n return out\n },\n )\n\n const score_each = map<ReadonlyArray<Pair<o>>, Pair<o>, ScoredPair<ranked>>({\n items: (pairs) => pairs,\n do: score_one,\n })\n\n const pick = use(\n [RESULTS_KEY],\n (vars, scored_pairs: ReadonlyArray<ScoredPair<ranked>>): projected => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const results = vars[RESULTS_KEY] as Record<string, o>\n const scored: Record<string, ranked> = {}\n let winner_id: string | undefined\n let winner_rank: number | undefined\n let winner_scored: ranked | undefined\n for (const pair of scored_pairs) {\n scored[pair.id] = pair.scored\n const rank = rank_by(pair.scored)\n const better =\n winner_rank === undefined\n ? true\n : select === 'max'\n ? rank > winner_rank\n : rank < winner_rank\n if (better) {\n winner_id = pair.id\n winner_rank = rank\n winner_scored = pair.scored\n }\n }\n if (winner_id === undefined || winner_scored === undefined) {\n throw new Error('ensemble_step: no members produced a result')\n }\n const winner = results[winner_id]\n if (winner === undefined) {\n throw new Error('ensemble_step: winner missing from results')\n }\n return project({ winner_id, winner, winner_scored, scored })\n },\n )\n\n const inner = scope([\n stash(RESULTS_KEY, fan_out),\n to_pairs,\n score_each,\n pick,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<i, projected>\n\n return compose(inner, { name: config.name ?? 'ensemble_step' })\n}\n","/**\n * gate: persist paid work before a human gate, never re-bill on resume.\n *\n * `gate(inner, config)` runs `inner`, checkpoints its result, then suspends\n * so a human can approve what was produced. The checkpoint write lands before\n * the suspend unwinds the run, so the expensive work (typically a paid model\n * call) survives the pause: a resume, or a fresh run after a process restart,\n * replays the result from the store instead of buying it again.\n *\n * Decisions this composite fixes, and why:\n *\n * - Checkpoint key: `gate:<config.id>`. Derived only from the user-supplied\n * id, with no construction-time counters, so a flow rebuilt in a new\n * process maps to the same stored result. The key is fixed per gate, which\n * assumes a store scoped per logical job (the same assumption the\n * checkpoint and resume docs make for fixed string keys). Inherited from\n * `checkpoint`: a stored `null`/`undefined` counts as a miss, and the inner\n * step must be named.\n * - Suspend payload: follows the library's suspend contract, which raises\n * `{ input }` on the `suspended_error`. Here that `input` is\n * `format(result)` when `format` is given and the raw result otherwise, so\n * `run.until_suspended` surfaces `{ input: <approver view> }` as the\n * outcome payload. A `format` return value is used verbatim (even\n * `undefined`): the approver view is the format's business. The store\n * always holds the raw result; `format` shapes only the view.\n * - Resumed value: the inner result passes through unchanged. The resume\n * decision is the approval signal only and is discarded, so any defined\n * value counts as approval arriving (the schema accepts everything). A\n * flow that needs decision-dependent output (approve vs reject branches)\n * should use `suspend` directly, whose `combine` exists for exactly that.\n * - `store` is optional. Absent, the checkpoint falls back to the run's\n * `checkpoint_store`; with neither, the gate still suspends and resumes\n * in-process but a restart re-executes `inner`. Present, the gate-local\n * store wins over the run-level one, because an explicit argument beats\n * ambient configuration.\n * - The suspend's `on` hook is a noop: notification is the driver's job, and\n * `run.until_suspended` already hands it the payload to render.\n */\n\nimport { checkpoint, compose, scope, stash, step, suspend, use } from '#core'\nimport type { CheckpointStore, RunContext, Step } from '#core'\n\nexport type GateConfig<o> = {\n readonly id: string\n readonly name?: string\n readonly store?: CheckpointStore\n readonly format?: (result: o) => unknown\n}\n\n// The gate has no opinion about the decision's shape, so its resume schema is\n// the always-accepting Standard Schema, written inline because composites\n// depend only on the public core surface.\nconst approval_schema = {\n '~standard': {\n version: 1,\n vendor: 'fascicle',\n validate: (value: unknown) => ({ value }),\n },\n} as const\n\n/**\n * Bind a gate-local store over the run context for the checkpoint beneath.\n *\n * `checkpoint` reads `ctx.checkpoint_store`, so scoping a store to one gate\n * means forking the context above it; contexts are plain spread-copied\n * values, which is what makes this possible with public primitives only. The\n * wrapper adopts the checkpointed step as its child so `describe` still shows\n * the persistence layer and the inner step beneath it.\n */\nfunction bind_store<i, o>(persisted: Step<i, o>, store: CheckpointStore): Step<i, o> {\n const wrapper = step('bind_store', (input: i, ctx: RunContext) => {\n const forked: RunContext = { ...ctx, checkpoint_store: store }\n return forked.call(persisted, input)\n })\n return { ...wrapper, children: [persisted] }\n}\n\n/**\n * Build a Step that runs `inner`, checkpoints its result at `gate:<id>`, and\n * suspends with that result as the payload awaiting approval.\n *\n * On resume (any defined resume value) the gate resolves to the inner result\n * unchanged; the decision itself is discarded. On a re-run against the same\n * store, the checkpoint absorbs the replay so `inner` never re-executes.\n * Throws at construction time when `inner` is anonymous, because the cached\n * result must map back to a stable step.\n *\n * Implemented as a `compose`d `scope`: the checkpointed result is stashed,\n * projected into the approver's view, and handed to `suspend`; the suspend's\n * `combine` returns a `use` step that restores the stashed result, which is\n * how the decision stays signal-only.\n */\nexport function gate<i, o>(inner: Step<i, o>, config: GateConfig<o>): Step<i, o> {\n if (inner.anonymous === true) {\n throw new Error(\n \"gate requires a named inner step, got anonymous — give the inner step an id with step('id', fn)\",\n )\n }\n const { id, store, format } = config\n\n const checkpointed = checkpoint(inner, { key: `gate:${id}` })\n const persisted = store === undefined ? checkpointed : bind_store(checkpointed, store)\n\n const restore = use(['result'], (vars) => {\n // The stash below wrote the checkpointed inner result under this key, so\n // the read-back re-asserts its type.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return vars['result'] as o\n })\n\n const approval = suspend<unknown, o, unknown>({\n id,\n on: () => {},\n resume_schema: approval_schema,\n combine: () => restore,\n })\n\n const body: Step<i, o> = scope([\n stash('result', persisted),\n step('project_payload', (result: o) => (format === undefined ? result : format(result))),\n approval,\n ])\n\n return compose(body, { name: config.name ?? 'gate' })\n}\n","/**\n * improve: bounded online self-improvement loop.\n *\n * The *online* counterpart to `learn`: where `learn` reflects on recorded\n * trajectories offline, `improve` runs a propose/score loop live inside a\n * single run. The amplify example is a domain-specific consumer of this\n * same pattern (filesystem mutation, test-suite gates, subprocess\n * research); `improve` strips those opinions out so any domain can plug in\n * its own `propose` and `score` steps.\n */\n\nimport { compose, loop, scope, step, stash, use } from '#core'\nimport type { Step } from '#core'\nimport { ensemble_step } from './ensemble_step.js'\n\nexport type Candidate<c> = {\n readonly content: c\n readonly proposer_id: string\n readonly rationale?: string\n}\n\nexport type ScoredCandidate<c> = {\n readonly candidate: Candidate<c>\n readonly score: number\n readonly accepted: boolean\n readonly reason?: string\n}\n\nexport type Lesson = {\n readonly round: number\n readonly proposer_id: string\n readonly reason: string\n}\n\nexport type ImproveRoundInput<c> = {\n readonly parent: c\n readonly parent_score: number\n readonly round: number\n readonly lessons: ReadonlyArray<Lesson>\n}\n\nexport type ImproveBudget = {\n readonly max_rounds: number\n readonly max_wallclock_ms?: number\n readonly patience: number\n}\n\nexport type ImproveConfig<i, c, projected = ImproveResult<c>> = {\n readonly name?: string\n readonly seed: Step<i, { readonly content: c; readonly score: number }>\n readonly propose: Step<ImproveRoundInput<c>, Candidate<c>>\n readonly score: Step<Candidate<c>, ScoredCandidate<c>>\n readonly budget: ImproveBudget\n readonly epsilon?: number\n readonly proposers_per_round?: number\n readonly lessons_capacity?: number\n readonly project?: (r: ImproveResult<c>) => projected\n}\n\nexport type HistoryEntry<c> = {\n readonly round: number\n readonly winner: ScoredCandidate<c>\n readonly accepted: boolean\n}\n\nexport type ImproveResult<c> = {\n readonly best: { readonly content: c; readonly score: number }\n readonly rounds_used: number\n readonly stopped_by: 'budget' | 'plateau'\n readonly history: ReadonlyArray<HistoryEntry<c>>\n}\n\n// Scope variable key for the pre-round state snapshot, underscore-prefixed\n// to avoid colliding with stashes set by user-supplied steps.\nconst PRIOR_KEY = '__improve_prior'\n\ntype ImproveState<c> = {\n readonly parent: c\n readonly parent_score: number\n readonly round: number\n readonly rounds_since_progress: number\n readonly started_at_ms: number\n readonly history: ReadonlyArray<HistoryEntry<c>>\n readonly lessons: ReadonlyArray<Lesson>\n readonly stopped_by?: 'budget' | 'plateau'\n}\n\n/**\n * Builds a Step that runs a round-bounded loop threading a `parent`\n * candidate through repeated propose -> score -> accept/reject cycles.\n *\n * Acceptance requires both a hard gate (`scored.accepted`) and an\n * epsilon-improvement test (`scored.score > parent_score + epsilon`).\n * Rejected rounds with a `reason` feed a bounded lessons list back into the\n * next round's input. Plateau detection stops the loop early when no\n * progress has been made for `patience` rounds; an optional wall-clock\n * budget caps total runtime. `project` maps the result envelope into the\n * step's output (for example, `(r) => r.best.content`); omitted, the envelope\n * itself is the output.\n *\n * Implemented as a `compose`d `scope` of (seed) -> (init state) -> (loop) ->\n * (unwrap). The loop body is itself a small `scope` that snapshots prior\n * state, builds a round input, dispatches the proposers + scorer via\n * `ensemble_step`, and merges the outcome back into state via `use`.\n * State threading is the entire job.\n */\nexport function improve<i, c, projected = ImproveResult<c>>(\n config: ImproveConfig<i, c, projected>,\n): Step<i, projected> {\n const { seed, propose, score, budget } = config\n // When `project` is omitted, `projected` defaults to the envelope type, which is\n // what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = config.project ?? ((r: ImproveResult<c>) => r as unknown as projected)\n const epsilon = config.epsilon ?? 0\n const proposers_per_round = Math.max(1, config.proposers_per_round ?? 1)\n const lessons_capacity = Math.max(0, config.lessons_capacity ?? 5)\n const { max_rounds, max_wallclock_ms, patience } = budget\n\n const proposers: Record<string, Step<ImproveRoundInput<c>, Candidate<c>>> = {}\n for (let i = 0; i < proposers_per_round; i += 1) {\n proposers[`p${String(i)}`] = propose\n }\n\n const round_ensemble = ensemble_step<\n ImproveRoundInput<c>,\n Candidate<c>,\n ScoredCandidate<c>\n >({\n name: 'improve_round',\n members: proposers,\n score,\n rank_by: (s) => s.score,\n })\n\n type RoundResult = {\n readonly winner_id: string\n readonly winner: Candidate<c>\n readonly winner_scored: ScoredCandidate<c>\n readonly scored: Record<string, ScoredCandidate<c>>\n }\n\n const project_round = use(\n [PRIOR_KEY],\n (vars, ensemble_result: RoundResult, ctx): ScoredCandidate<c> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars[PRIOR_KEY] as ImproveState<c>\n const round = prior.round + 1\n for (const slot_id of Object.keys(ensemble_result.scored)) {\n const scored = ensemble_result.scored[slot_id]\n if (scored === undefined) continue\n ctx.trajectory.record({\n kind: 'improve.candidate',\n round,\n proposer_id: slot_id,\n score: scored.score,\n accepted: scored.accepted,\n ...(scored.reason === undefined ? {} : { reason: scored.reason }),\n })\n }\n const w = ensemble_result.winner_scored\n return {\n ...w,\n candidate: { ...w.candidate, proposer_id: ensemble_result.winner_id },\n }\n },\n )\n\n const init_state = step(\n 'improve_init_state',\n (seed_result: { content: c; score: number }): ImproveState<c> => ({\n parent: seed_result.content,\n parent_score: seed_result.score,\n round: 0,\n rounds_since_progress: 0,\n started_at_ms: Date.now(),\n history: [],\n lessons: [],\n }),\n )\n\n const to_round_input = step(\n 'improve_to_round_input',\n (s: ImproveState<c>, ctx): ImproveRoundInput<c> => {\n const round = s.round + 1\n ctx.trajectory.record({\n kind: 'improve.round_start',\n round,\n parent_score: s.parent_score,\n lessons_count: s.lessons.length,\n })\n return {\n parent: s.parent,\n parent_score: s.parent_score,\n round,\n lessons: s.lessons,\n }\n },\n )\n\n const merge_outcome = use(\n [PRIOR_KEY],\n (vars, scored: ScoredCandidate<c>, ctx): ImproveState<c> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars[PRIOR_KEY] as ImproveState<c>\n const next_round = prior.round + 1\n const better = scored.score > prior.parent_score + epsilon\n const accepted = scored.accepted && better\n const next_lessons = !accepted && scored.reason !== undefined\n ? [\n ...prior.lessons,\n {\n round: next_round,\n proposer_id: scored.candidate.proposer_id,\n reason: scored.reason,\n },\n ].slice(-lessons_capacity)\n : prior.lessons\n ctx.trajectory.record({\n kind: accepted ? 'improve.accept' : 'improve.reject',\n round: next_round,\n proposer_id: scored.candidate.proposer_id,\n score: scored.score,\n prior_score: prior.parent_score,\n ...(accepted ? { delta: scored.score - prior.parent_score } : {}),\n ...(scored.reason === undefined ? {} : { reason: scored.reason }),\n })\n return {\n parent: accepted ? scored.candidate.content : prior.parent,\n parent_score: accepted ? scored.score : prior.parent_score,\n round: next_round,\n rounds_since_progress: accepted ? 0 : prior.rounds_since_progress + 1,\n started_at_ms: prior.started_at_ms,\n history: [\n ...prior.history,\n { round: next_round, winner: scored, accepted },\n ],\n lessons: next_lessons,\n }\n },\n )\n\n const body = scope([\n stash(PRIOR_KEY, step('improve_snapshot', (s: ImproveState<c>) => s)),\n to_round_input,\n round_ensemble,\n project_round,\n merge_outcome,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<ImproveState<c>, ImproveState<c>>\n\n const guard = step(\n 'improve_guard',\n (s: ImproveState<c>): { stop: boolean; state: ImproveState<c> } => {\n if (s.rounds_since_progress >= patience) {\n return { stop: true, state: { ...s, stopped_by: 'plateau' } }\n }\n if (\n max_wallclock_ms !== undefined &&\n Date.now() - s.started_at_ms >= max_wallclock_ms\n ) {\n return { stop: true, state: { ...s, stopped_by: 'budget' } }\n }\n return { stop: false, state: s }\n },\n )\n\n const round_loop = loop<ImproveState<c>, ImproveState<c>, ImproveResult<c>>({\n init: (s) => s,\n body,\n guard,\n finish: (s): ImproveResult<c> => ({\n best: { content: s.parent, score: s.parent_score },\n rounds_used: s.round,\n stopped_by: s.stopped_by ?? 'budget',\n history: s.history,\n }),\n max_rounds,\n })\n\n const record_stop = step(\n 'improve_stop',\n (result: ImproveResult<c>, ctx): projected => {\n ctx.trajectory.record({\n kind: 'improve.stop',\n stopped_by: result.stopped_by,\n rounds_used: result.rounds_used,\n final_score: result.best.score,\n })\n return project(result)\n },\n )\n\n const inner = scope([\n seed,\n init_state,\n round_loop,\n record_stop,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<i, projected>\n\n return compose(inner, { name: config.name ?? 'improve' })\n}\n","/**\n * learn: offline self-improvement composer.\n *\n * `learn({ flow, source, analyzer })` reads recorded trajectory events from\n * past runs of `flow`, hands them to a user-supplied `analyzer` step alongside\n * `describe(flow)`, and returns the analyzer's proposals plus summary metadata\n * (events considered, distinct run ids).\n *\n * The amplify example is the *online* counterpart of this pattern: propose →\n * score → accept/reject inside a single run. `learn` is the *offline*\n * counterpart: reflect on what already happened across one or many recorded\n * runs without an evaluator in the loop.\n *\n * Implemented as a `compose`d `scope` of (compute meta) → (build LearnInput) →\n * (analyzer) → (wrap result with meta). No engine dependency; the analyzer\n * decides how to use the events.\n *\n * Three source kinds: `events` (in-memory), `paths` (explicit JSONL files),\n * `dir` (recursive *.jsonl walk). File reads honor `ctx.abort` at file-level\n * granularity; malformed lines are skipped and surface as `learn.parse_error`\n * trajectory events with 1-indexed line offsets. When `max_events` clips the\n * filtered set, a `learn.truncated` event records `available`, `kept`, and the\n * configured cap.\n */\n\nimport { readFile, readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport {\n aborted_error,\n compose,\n describe,\n parse_trajectory_event,\n scope,\n stash,\n step,\n use,\n} from '#core'\nimport type { AnyStep, RunContext, Step, TrajectoryEvent } from '#core'\n\nexport type TrajectorySource =\n | { readonly kind: 'events'; readonly events: ReadonlyArray<TrajectoryEvent> }\n | { readonly kind: 'paths'; readonly paths: ReadonlyArray<string> }\n | { readonly kind: 'dir'; readonly dir: string }\n\nexport type LearnInput = {\n readonly flow_description: string\n readonly events: ReadonlyArray<TrajectoryEvent>\n readonly prior?: unknown\n}\n\nexport type Improvement = {\n readonly target: string\n readonly kind: 'prompt' | 'config' | 'structure' | 'note'\n readonly rationale: string\n readonly suggestion: string\n}\n\nexport type LearnConfig<i extends LearnInput, o> = {\n readonly name?: string\n readonly flow: AnyStep\n readonly source: TrajectorySource\n readonly analyzer: Step<i, o>\n readonly filter?: (event: TrajectoryEvent) => boolean\n readonly max_events?: number\n}\n\nexport type LearnResult<o> = {\n readonly proposals: o\n readonly events_considered: number\n readonly run_ids: ReadonlyArray<string>\n}\n\nconst DEFAULT_MAX_EVENTS = 10_000\nconst META_KEY = '__learn_meta'\n\ntype LearnMeta = {\n readonly events_considered: number\n readonly run_ids: ReadonlyArray<string>\n}\n\ntype MetaPlus = LearnMeta & {\n readonly events: ReadonlyArray<TrajectoryEvent>\n readonly prior: unknown\n}\n\n/**\n * Recursively collect every `.jsonl` file path under a directory.\n */\nasync function walk_jsonl(dir: string): Promise<string[]> {\n const out: string[] = []\n const entries = await readdir(dir, { withFileTypes: true })\n for (const entry of entries) {\n const full = join(dir, entry.name)\n if (entry.isDirectory()) {\n out.push(...(await walk_jsonl(full)))\n } else if (entry.isFile() && entry.name.endsWith('.jsonl')) {\n out.push(full)\n }\n }\n return out\n}\n\n/**\n * Parse one JSONL file into validated trajectory events.\n *\n * Malformed JSON lines and lines that fail schema validation are skipped,\n * each recorded as a `learn.parse_error` event with a 1-indexed line number,\n * so a single corrupt line never sinks an analysis run.\n */\nasync function read_jsonl(file_path: string, ctx: RunContext): Promise<TrajectoryEvent[]> {\n const content = await readFile(file_path, 'utf8')\n const lines = content.split('\\n')\n const events: TrajectoryEvent[] = []\n for (let i = 0; i < lines.length; i += 1) {\n const raw = lines[i]\n if (raw === undefined || raw.trim() === '') continue\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n ctx.trajectory.record({ kind: 'learn.parse_error', path: file_path, line: i + 1 })\n continue\n }\n const result = parse_trajectory_event(parsed)\n if (result.success) {\n events.push(result.data)\n } else {\n ctx.trajectory.record({ kind: 'learn.parse_error', path: file_path, line: i + 1 })\n }\n }\n return events\n}\n\n/**\n * Throw the abort reason (wrapped in `aborted_error` if needed) when the run\n * has been cancelled.\n */\nfunction throw_if_aborted(ctx: RunContext): void {\n if (!ctx.abort.aborted) return\n const reason = ctx.abort.reason\n if (reason instanceof aborted_error) throw reason\n throw new aborted_error('aborted', reason === undefined ? {} : { reason })\n}\n\n/**\n * Materialize a `TrajectorySource` into an event array.\n *\n * `dir` sources walk recursively and sort paths for deterministic order.\n * File-backed sources check `ctx.abort` between files, so cancellation lands\n * at file-level granularity.\n */\nasync function resolve_events(\n source: TrajectorySource,\n ctx: RunContext,\n): Promise<ReadonlyArray<TrajectoryEvent>> {\n if (source.kind === 'events') return source.events\n\n const file_paths =\n source.kind === 'paths' ? [...source.paths] : (await walk_jsonl(source.dir)).toSorted()\n\n const all: TrajectoryEvent[] = []\n for (const p of file_paths) {\n throw_if_aborted(ctx)\n const events = await read_jsonl(p, ctx)\n all.push(...events)\n }\n return all\n}\n\n/**\n * List the distinct `run_id` values in the events, in first-seen order.\n */\nfunction collect_run_ids(events: ReadonlyArray<TrajectoryEvent>): ReadonlyArray<string> {\n const seen = new Set<string>()\n const out: string[] = []\n for (const event of events) {\n const id = event['run_id']\n if (typeof id === 'string' && !seen.has(id)) {\n seen.add(id)\n out.push(id)\n }\n }\n return out\n}\n\n/**\n * Build the offline self-improvement step.\n *\n * Composes a scope that resolves and caps the recorded events, builds the\n * `LearnInput` (including `describe(flow)`), runs the user's analyzer, and\n * wraps its proposals with the stashed meta (event count, run ids) into a\n * `LearnResult`.\n */\nexport function learn<i extends LearnInput, o>(\n config: LearnConfig<i, o>,\n): Step<unknown, LearnResult<o>> {\n const { flow, source, analyzer, filter } = config\n const max = config.max_events ?? DEFAULT_MAX_EVENTS\n\n const compute_meta = step(\n 'learn_compute_meta',\n async (prior: unknown, ctx): Promise<MetaPlus> => {\n const all = await resolve_events(source, ctx)\n const filtered = filter ? all.filter(filter) : all\n const truncated = filtered.length > max\n const capped = truncated ? filtered.slice(0, max) : filtered\n if (truncated) {\n ctx.trajectory.record({\n kind: 'learn.truncated',\n available: filtered.length,\n kept: capped.length,\n max_events: max,\n })\n }\n return {\n events_considered: capped.length,\n run_ids: collect_run_ids(capped),\n events: capped,\n prior,\n }\n },\n )\n\n const build_input = step(\n 'learn_build_input',\n (meta: MetaPlus): LearnInput => ({\n flow_description: describe(flow),\n events: meta.events,\n prior: meta.prior,\n }),\n )\n\n const wrap_result = use(\n [META_KEY],\n (vars, proposals: o, ctx): LearnResult<o> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const meta = vars[META_KEY] as LearnMeta\n ctx.trajectory.record({\n kind: 'learn.summary',\n events_considered: meta.events_considered,\n run_ids: meta.run_ids,\n })\n return {\n proposals,\n events_considered: meta.events_considered,\n run_ids: meta.run_ids,\n }\n },\n )\n\n const inner = scope([\n stash(META_KEY, compute_meta),\n build_input,\n analyzer,\n wrap_result,\n ])\n\n return compose(inner, { name: config.name ?? 'learn' })\n}\n","/**\n * tournament: pairwise bracket.\n *\n * `tournament({ members, compare })` runs every member, then pairs them off\n * in a single-elimination bracket. `compare(a, b)` returns which result\n * advances. An odd member count yields one bye per affected round. Returns\n * `{ winner, bracket }` where `bracket` lists every match record.\n *\n * Implemented as a `compose`d `sequence` of `parallel(members)` followed\n * by a single bracket-reduction step. Cancellation, fan-out, and abort\n * propagation come from `parallel`'s contract; the bracket step only runs\n * after all members settle.\n */\n\nimport { compose, parallel, sequence, step } from '#core'\nimport type { Step } from '#core'\n\nexport type BracketRecord = {\n readonly round: number\n readonly a_id: string\n readonly b_id: string\n readonly winner_id: string\n}\n\nexport type TournamentConfig<i, o, projected = TournamentResult<o>> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly compare: (a: o, b: o) => Promise<'a' | 'b'> | 'a' | 'b'\n readonly project?: (r: TournamentResult<o>) => projected\n}\n\nexport type TournamentResult<o> = {\n readonly winner: o\n readonly bracket: ReadonlyArray<BracketRecord>\n}\n\n/**\n * Build a single-elimination bracket step over named members.\n *\n * All members run concurrently via `parallel`; the bracket step then reduces\n * survivors round by round with `compare`, recording every match. Requires at\n * least one member so a winner always exists. `project` maps the `{ winner,\n * bracket }` envelope into the step's output (for example, `(r) => r.winner`);\n * omitted, the envelope itself is the output.\n */\nexport function tournament<i, o, projected = TournamentResult<o>>(\n config: TournamentConfig<i, o, projected>,\n): Step<i, projected> {\n const compare_fn = config.compare\n const keys = Object.keys(config.members)\n // When `project` is omitted, `projected` defaults to the envelope type, which is\n // what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = config.project ?? ((r: TournamentResult<o>) => r as unknown as projected)\n\n if (keys.length === 0) {\n throw new Error('tournament: at least one member required')\n }\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const fan_out = parallel(config.members) as Step<i, Record<string, o>>\n\n const bracket_step = step('bracket', async (results: Record<string, o>) => {\n let current: string[] = [...keys]\n const bracket: BracketRecord[] = []\n let round = 0\n\n while (current.length > 1) {\n round += 1\n current = await play_round(current, results, compare_fn, round, bracket)\n }\n\n return project({ winner: winner_of(current, results), bracket })\n })\n\n const inner = sequence([fan_out, bracket_step])\n\n return compose(inner, { name: config.name ?? 'tournament' })\n}\n\n/**\n * Plays one bracket round: pairs survivors two at a time, comparing each pair\n * and recording a `BracketRecord`, and returns the ids advancing. An unpaired\n * trailing survivor takes a bye. Every paired id must have a settled result.\n */\nasync function play_round<o>(\n current: ReadonlyArray<string>,\n results: Record<string, o>,\n compare: (a: o, b: o) => Promise<'a' | 'b'> | 'a' | 'b',\n round: number,\n bracket: BracketRecord[],\n): Promise<string[]> {\n const next_round: string[] = []\n for (let i = 0; i < current.length; i += 2) {\n const a_id = current[i]\n const b_id = current[i + 1]\n if (a_id === undefined) continue\n if (b_id === undefined) {\n next_round.push(a_id)\n continue\n }\n const a_val = results[a_id]\n const b_val = results[b_id]\n if (a_val === undefined || b_val === undefined) {\n throw new Error('tournament: missing result for match')\n }\n const pick = await compare(a_val, b_val)\n const winner_id = pick === 'a' ? a_id : b_id\n bracket.push({ round, a_id, b_id, winner_id })\n next_round.push(winner_id)\n }\n return next_round\n}\n\n/**\n * Extracts the tournament winner from the single surviving id, throwing when\n * no survivor remains or its result is missing.\n */\nfunction winner_of<o>(current: ReadonlyArray<string>, results: Record<string, o>): o {\n const final_id = current[0]\n if (final_id === undefined) {\n throw new Error('tournament: no winner')\n }\n const winner = results[final_id]\n if (winner === undefined) {\n throw new Error('tournament: winner missing from results')\n }\n return winner\n}\n","/**\n * Typed errors for the composites layer.\n *\n * Listed alongside src/core/errors.ts, src/engine/errors.ts, and\n * src/mcp/errors.ts in the `no-class` rule ignores: `instanceof` branching is\n * how a caller tells a benched flow's usage error apart from a case failure.\n */\n\nexport class bench_suspend_error extends Error {\n readonly kind = 'bench_suspend_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly case_id: string;\n readonly suspend_id: string;\n constructor(case_id: string, suspend_id: string, message?: string) {\n super(\n message ??\n `bench: case ${case_id} suspended at ${suspend_id}; bench cannot resume a suspended flow`,\n )\n this.name = 'bench_suspend_error'\n this.case_id = case_id\n this.suspend_id = suspend_id\n }\n}\n","/**\n * bench: run a flow against a fixture set, score each result, return a report.\n *\n * Online counterpart to `learn`: where `learn` reflects on past trajectories\n * after the fact, `bench` runs the flow live against fresh cases and judges\n * each output.\n */\n\nimport { mkdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { aborted_error, resolve_display_name, run, suspended_error } from '#core'\nimport type { Step, TrajectoryEvent, TrajectoryLogger } from '#core'\nimport { filesystem_logger, http_logger, tee_logger } from '#adapters'\nimport { bench_suspend_error } from './errors.js'\n\nexport type Score = { readonly score: number; readonly reason?: string }\n\nexport type BenchCase<I> = {\n readonly id: string\n readonly input: I\n readonly meta?: Readonly<Record<string, unknown>>\n}\n\nexport type JudgeArgs<I, O> = {\n readonly input: I\n readonly output: O\n readonly meta?: Readonly<Record<string, unknown>>\n}\n\nexport type Judge<I, O, S = Score> = Step<JudgeArgs<I, O>, S | undefined>\n\nexport type CaseResult<I = unknown, O = unknown, S = Score> = {\n readonly case_id: string\n readonly ok: boolean\n readonly output?: O\n readonly error?: string\n readonly scores: Record<string, S>\n readonly duration_ms: number\n readonly cost_usd: number\n readonly trajectory_path?: string\n readonly _input?: I\n}\n\nexport type BenchSummary = {\n readonly pass_rate: number\n readonly mean_scores: Record<string, number>\n readonly total_duration_ms: number\n readonly total_cost_usd: number\n readonly mean_cost_usd: number\n}\n\nexport type BenchReport<I = unknown, O = unknown, S = Score> = {\n readonly flow_name: string\n readonly run_id: string\n readonly cases: ReadonlyArray<CaseResult<I, O, S>>\n readonly summary: BenchSummary\n}\n\nexport type BenchOptions = {\n readonly concurrency?: number\n readonly on_case?: (result: CaseResult) => void\n readonly trajectory_dir?: string\n readonly live_url?: string\n readonly run_id?: string\n readonly install_signal_handlers?: boolean\n readonly abort?: AbortSignal\n}\n\n/**\n * Runs `flow` against every case, judges each output, and produces a\n * `BenchReport` you can compare against a committed baseline via\n * `regression_compare`.\n *\n * Each case becomes one `run(flow, case.input, ...)`. Per-case observability:\n * - `trajectory_dir` writes `${dir}/${case.id}.jsonl` via `filesystem_logger`\n * - `live_url` POSTs each event via `http_logger` to a viewer's /api/ingest\n * - both can be combined; bench tees them with an internal cost tracker\n *\n * Cost is tracked per-case in-process by intercepting `kind: 'cost'` events\n * on the trajectory pipeline, so the cost number matches what would be on\n * disk even when no `trajectory_dir` is set.\n *\n * Judges run as Steps after each case, with the same trajectory logger so\n * judge spans land in the case's trajectory file (or push). A judge that\n * throws or returns undefined abstains: the entry is omitted from\n * `case.scores` and the case does not contribute to that judge's mean.\n *\n * Control-flow signals are not case failures and never reach a `CaseResult`.\n * `abort` forwards to every per-case `run` and is re-checked before each case\n * is claimed, so cancelling rejects the whole bench rather than returning a\n * report that silently covers fewer cases than it was given. A\n * `suspended_error` from an approval gate rejects with `bench_suspend_error`:\n * `bench` has no resume path, so a suspend is a usage error, not a zero score.\n */\nexport async function bench<I, O, S = Score>(\n flow: Step<I, O>,\n cases: ReadonlyArray<BenchCase<I>>,\n judges: Record<string, Judge<I, O, S>>,\n options: BenchOptions = {},\n): Promise<BenchReport<I, O, S>> {\n const run_id = options.run_id ?? `bench-${String(Date.now())}-${random_suffix()}`\n const flow_name = describe_flow_name(flow)\n const concurrency = resolve_concurrency(options.concurrency, cases.length)\n const install_signal_handlers = options.install_signal_handlers ?? false\n const run_options = options.abort === undefined ? {} : { abort: options.abort }\n\n throw_if_aborted(options.abort)\n\n if (options.trajectory_dir !== undefined) {\n await mkdir(options.trajectory_dir, { recursive: true })\n }\n\n const judge_entries = Object.entries(judges)\n\n const run_one = async (bc: BenchCase<I>): Promise<CaseResult<I, O, S>> => {\n const { trajectory_path, case_logger, cost_tracker } = build_case_logging(options, bc.id)\n const ctx: CaseRunContext = { case_logger, install_signal_handlers, run_options }\n\n const start = Date.now()\n let output: O | undefined\n let error: string | undefined\n let ok = false\n try {\n output = await run(flow, bc.input, {\n trajectory: case_logger,\n install_signal_handlers,\n ...run_options,\n })\n ok = true\n } catch (err) {\n rethrow_control_flow(err, bc.id)\n error = err instanceof Error ? err.message : String(err)\n ok = false\n }\n\n const scores: Record<string, S> =\n ok && output !== undefined\n ? await run_judges(judge_entries, build_judge_input(bc, output), ctx, bc.id)\n : {}\n\n const duration_ms = Date.now() - start\n const result: CaseResult<I, O, S> = {\n case_id: bc.id,\n ok,\n ...(output !== undefined ? { output } : {}),\n ...(error !== undefined ? { error } : {}),\n scores,\n duration_ms,\n cost_usd: cost_tracker.total(),\n ...(trajectory_path !== undefined ? { trajectory_path } : {}),\n }\n if (options.on_case) {\n // The on_case callback receives the lossy-typed shape: bench's S is\n // generic but the callback hook is a single concrete signature.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n options.on_case(result as unknown as CaseResult)\n }\n return result\n }\n\n const cases_out = await run_with_concurrency(cases, concurrency, run_one, options.abort)\n\n // An abort that fires while every case is already in flight has no queue to\n // halt, and a flow that never checks `ctx.abort` finishes regardless. Both\n // would otherwise yield a full report for a cancelled run.\n throw_if_aborted(options.abort)\n\n const summary = summarize(cases_out, judge_entries.map(([n]) => n))\n\n return {\n flow_name,\n run_id,\n cases: cases_out,\n summary,\n }\n}\n\n/**\n * Per-case run context shared by the flow run and every judge run: the tee'd\n * trajectory logger, the signal-handler flag, and the optional abort forward.\n */\ntype CaseRunContext = {\n readonly case_logger: TrajectoryLogger\n readonly install_signal_handlers: boolean\n readonly run_options: { readonly abort?: AbortSignal }\n}\n\n/**\n * Builds the per-case trajectory pipeline: an optional filesystem sink when\n * `trajectory_dir` is set, an optional HTTP sink when `live_url` is set, and\n * always an in-process cost tracker, all tee'd together. Returns the resolved\n * trajectory path (undefined when no dir is set) alongside the logger and\n * tracker.\n */\nfunction build_case_logging(\n options: BenchOptions,\n case_id: string,\n): {\n readonly trajectory_path: string | undefined\n readonly case_logger: TrajectoryLogger\n readonly cost_tracker: ReturnType<typeof create_cost_tracker>\n} {\n const trajectory_path =\n options.trajectory_dir === undefined\n ? undefined\n : join(options.trajectory_dir, `${case_id}.jsonl`)\n const sinks: TrajectoryLogger[] = []\n if (trajectory_path !== undefined) {\n sinks.push(filesystem_logger({ output_path: trajectory_path }))\n }\n if (options.live_url !== undefined) {\n sinks.push(http_logger({ url: options.live_url }))\n }\n const cost_tracker = create_cost_tracker()\n const case_logger: TrajectoryLogger =\n sinks.length === 0 ? cost_tracker.logger : tee_logger(...sinks, cost_tracker.logger)\n return { trajectory_path, case_logger, cost_tracker }\n}\n\n/**\n * Assembles the judge input triple, including `meta` only when the case\n * carries it so the optional field stays absent rather than `undefined`.\n */\nfunction build_judge_input<I, O>(bc: BenchCase<I>, output: O): JudgeArgs<I, O> {\n return bc.meta === undefined\n ? { input: bc.input, output }\n : { input: bc.input, output, meta: bc.meta }\n}\n\n/**\n * Runs each judge as a Step over the case's input/output, collecting the\n * normalized scores. A judge that throws a control-flow signal rethrows via\n * `rethrow_control_flow`; any other throw, or an abstaining `undefined`,\n * omits that judge from the scores rather than failing the case.\n */\nasync function run_judges<I, O, S>(\n judge_entries: ReadonlyArray<readonly [string, Judge<I, O, S>]>,\n judge_input: JudgeArgs<I, O>,\n ctx: CaseRunContext,\n case_id: string,\n): Promise<Record<string, S>> {\n const scores: Record<string, S> = {}\n for (const [name, judge] of judge_entries) {\n let raw: unknown\n try {\n // oxlint-disable-next-line no-await-in-loop\n raw = await run(judge, judge_input, {\n trajectory: ctx.case_logger,\n install_signal_handlers: ctx.install_signal_handlers,\n ...ctx.run_options,\n })\n } catch (err) {\n rethrow_control_flow(err, case_id)\n continue\n }\n const normalized = normalize_score(raw)\n if (normalized === undefined) continue\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n scores[name] = normalized as S\n }\n return scores\n}\n\n/**\n * Rethrows the control-flow signals that must never become a `CaseResult`.\n *\n * An `aborted_error` cancels the whole bench: a report claiming every\n * remaining case failed is worse than no report. A `suspended_error` becomes\n * `bench_suspend_error` naming the case, because `bench` cannot resume an\n * approval gate and scoring the paused case as a failure corrupts the\n * benchmark. Anything else returns, and the caller records it as a failure.\n */\nfunction rethrow_control_flow(err: unknown, case_id: string): void {\n if (err instanceof aborted_error) throw err\n if (err instanceof suspended_error) throw new bench_suspend_error(case_id, err.suspend_id)\n}\n\n/**\n * Rejects once `signal` has fired, so an abort stops the bench claiming\n * further cases instead of running the queue to completion.\n *\n * Mirrors core's abort shape: an `Error` reason propagates verbatim, anything\n * else is wrapped, so a caller aborting with its own `aborted_error` sees that\n * instance rather than a copy.\n */\nfunction throw_if_aborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted !== true) return\n const reason: unknown = signal.reason\n throw reason instanceof Error ? reason : new aborted_error('aborted', { reason })\n}\n\n/**\n * Aggregates per-case results into the report summary.\n *\n * A judge's mean only averages the cases where that judge produced a score;\n * abstained cases do not drag the mean down, and a judge that never scored\n * is omitted from `mean_scores` entirely.\n */\nfunction summarize<I, O, S>(\n cases: ReadonlyArray<CaseResult<I, O, S>>,\n judge_names: ReadonlyArray<string>,\n): BenchSummary {\n const total_duration_ms = cases.reduce((acc, c) => acc + c.duration_ms, 0)\n const total_cost_usd = cases.reduce((acc, c) => acc + c.cost_usd, 0)\n const ok_count = cases.filter((c) => c.ok).length\n const pass_rate = cases.length === 0 ? 0 : ok_count / cases.length\n const mean_cost_usd = cases.length === 0 ? 0 : total_cost_usd / cases.length\n\n const mean_scores: Record<string, number> = {}\n for (const name of judge_names) {\n let sum = 0\n let count = 0\n for (const c of cases) {\n const n = score_value_of(c.scores[name])\n if (n === undefined) continue\n sum += n\n count += 1\n }\n if (count > 0) mean_scores[name] = sum / count\n }\n\n return {\n pass_rate,\n mean_scores,\n total_duration_ms,\n total_cost_usd,\n mean_cost_usd,\n }\n}\n\n/**\n * Coerces a raw judge return value into a `Score`.\n *\n * Accepts a bare finite number or an object with a finite numeric `score`\n * and optional string `reason`. Anything else (including NaN/Infinity, or a\n * non-string `reason`, which is dropped) normalizes toward `undefined` or a\n * reason-less score; `undefined` means the judge abstained.\n */\nexport function normalize_score(raw: unknown): Score | undefined {\n if (raw === undefined || raw === null) return undefined\n if (typeof raw === 'number') {\n return Number.isFinite(raw) ? { score: raw } : undefined\n }\n if (typeof raw === 'object' && 'score' in raw) {\n const r = raw as { score: unknown; reason?: unknown }\n if (typeof r.score !== 'number' || !Number.isFinite(r.score)) return undefined\n if (r.reason !== undefined && typeof r.reason !== 'string') {\n return { score: r.score }\n }\n return r.reason === undefined ? { score: r.score } : { score: r.score, reason: r.reason }\n }\n return undefined\n}\n\n/**\n * Extracts the numeric value from a score-shaped entry, tolerating both bare\n * numbers and `{ score }` objects since `S` is caller-defined.\n */\nfunction score_value_of(s: unknown): number | undefined {\n if (s === undefined || s === null) return undefined\n if (typeof s === 'number') return Number.isFinite(s) ? s : undefined\n if (typeof s === 'object' && 'score' in s) {\n const raw = (s as Record<string, unknown>)['score']\n return typeof raw === 'number' && Number.isFinite(raw) ? raw : undefined\n }\n return undefined\n}\n\n/**\n * Builds a minimal `TrajectoryLogger` that ignores everything except\n * `kind: 'cost'` events and accumulates their `total_usd` into a running\n * total, read back via `total()` after the case finishes.\n */\nfunction create_cost_tracker(): {\n readonly logger: TrajectoryLogger\n readonly total: () => number\n} {\n let total = 0\n return {\n total: () => total,\n logger: {\n record: (event: TrajectoryEvent) => {\n if (event.kind !== 'cost') return\n const e: Record<string, unknown> = event\n const value = e['total_usd']\n if (typeof value === 'number' && Number.isFinite(value)) total += value\n },\n start_span: (name) => `cost-tracker:${name}`,\n end_span: () => {},\n },\n }\n}\n\n/**\n * Runs `fn` over `items` with at most `limit` calls in flight, preserving\n * input order in the results.\n *\n * Uses a shared-index worker pool: each of the `limit` workers claims the\n * next unclaimed index and writes its result into that slot, so completion\n * order never reorders the output.\n *\n * `abort` is re-checked before each claim, so a signal that fires mid-run\n * halts scheduling at the queue rather than only cancelling work already in\n * flight. The full fan-out path has no queue to halt: every item is already\n * running, so the caller re-checks the signal before reading the results.\n */\nasync function run_with_concurrency<t, r>(\n items: ReadonlyArray<t>,\n limit: number,\n fn: (item: t) => Promise<r>,\n abort?: AbortSignal,\n): Promise<r[]> {\n if (items.length === 0) return []\n if (limit >= items.length) {\n return Promise.all(items.map((it) => fn(it)))\n }\n const results: r[] = Array.from({ length: items.length })\n let next = 0\n const worker = async (): Promise<void> => {\n while (true) {\n throw_if_aborted(abort)\n const idx = next\n next += 1\n if (idx >= items.length) return\n const item = items[idx]\n if (item === undefined) continue\n // oxlint-disable-next-line no-await-in-loop\n results[idx] = await fn(item)\n }\n }\n const workers: Promise<void>[] = []\n for (let i = 0; i < limit; i += 1) workers.push(worker())\n await Promise.all(workers)\n return results\n}\n\n/**\n * Clamps the requested concurrency to a positive integer, defaulting to full\n * fan-out (one worker per case) when unset or invalid.\n */\nfunction resolve_concurrency(value: number | undefined, n_cases: number): number {\n if (value === undefined) return Math.max(1, n_cases)\n if (!Number.isFinite(value) || value <= 0) return Math.max(1, n_cases)\n return Math.max(1, Math.floor(value))\n}\n\n/**\n * Picks a human-readable name for the report, resolving the display channels\n * the same way spans and `describe` do, then falling back to identity.\n */\nfunction describe_flow_name<I, O>(flow: Step<I, O>): string {\n return resolve_display_name(flow, flow.id ?? flow.kind ?? 'flow')\n}\n\n/**\n * Short random base36 suffix to keep default run ids unique across\n * same-millisecond starts.\n */\nfunction random_suffix(): string {\n return Math.random().toString(36).slice(2, 8)\n}\n","/**\n * Stock judges for `bench`.\n *\n * A `Judge<I, O, S>` is a `Step<{ input, output, meta }, S>`: just a step\n * that scores a flow's input/output/metadata triple. Returning `undefined`\n * (or throwing) means the judge abstains; bench records the absence as a\n * missing key in `case.scores` and excludes the case from that judge's\n * `mean_scores` denominator.\n *\n * judge_equals: strict equality vs. `meta.expected`\n * judge_with: wrap a user-supplied scoring function\n * judge_llm: prompt a model + parse the rubric score out of the reply\n *\n * `judge_llm` is engine-agnostic: callers pass their already-configured\n * model_call step (`Step<string, string>`), which keeps composites decoupled\n * from engine. The user-facing wiring lives in their own code.\n */\n\nimport { compose, sequence, step } from '#core'\nimport type { Step } from '#core'\nimport { normalize_score } from './bench.js'\nimport type { Judge, JudgeArgs, Score } from './bench.js'\n\n/**\n * Narrows an unknown value to a plain string-keyed record (non-null object,\n * not an array).\n */\nexport function is_record(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === 'object' && !Array.isArray(v)\n}\n\n/**\n * Structural equality over JSON-shaped values: primitives by `===`, arrays\n * element-wise, records key-by-key with sorted keys. Anything else (class\n * instances, functions) only compares equal by reference.\n */\nexport function deep_equal(a: unknown, b: unknown): boolean {\n if (a === b) return true\n // null, primitives, and array/record mismatches all fall through to the\n // Array.isArray and is_record guards below, so no separate null/typeof\n // pre-checks are needed.\n if (Array.isArray(a) || Array.isArray(b)) return arrays_equal(a, b)\n if (!is_record(a) || !is_record(b)) return false\n return records_equal(a, b)\n}\n\n/**\n * Element-wise deep equality once at least one side is an array: both must be\n * arrays of the same length with every index equal.\n */\nfunction arrays_equal(a: unknown, b: unknown): boolean {\n if (!Array.isArray(a) || !Array.isArray(b)) return false\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i += 1) {\n if (!deep_equal(a[i], b[i])) return false\n }\n return true\n}\n\n/**\n * Key-by-key deep equality over two records: same sorted key sets, and each\n * value deep-equal under the shared key.\n */\nfunction records_equal(a: Record<string, unknown>, b: Record<string, unknown>): boolean {\n const ak = Object.keys(a).toSorted()\n const bk = Object.keys(b).toSorted()\n if (ak.length !== bk.length) return false\n for (let i = 0; i < ak.length; i += 1) {\n const ka = ak[i]\n const kb = bk[i]\n if (ka === undefined || kb === undefined || ka !== kb) return false\n if (!deep_equal(a[ka], b[kb])) return false\n }\n return true\n}\n\n/**\n * Judge that scores 1 when the output deep-equals `meta.expected`, 0\n * otherwise. Abstains when the case has no `meta` or no `expected` key.\n */\nexport function judge_equals<O>(): Judge<unknown, O> {\n return step('judge_equals', (args: JudgeArgs<unknown, O>): Score | undefined => {\n if (args.meta === undefined) return undefined\n if (!('expected' in args.meta)) return undefined\n const expected = args.meta['expected']\n const matches = deep_equal(args.output, expected)\n return { score: matches ? 1 : 0, reason: matches ? 'match' : 'mismatch' }\n })\n}\n\nexport type JudgeWithFn<I, O> = (\n args: JudgeArgs<I, O>,\n) => number | Score | undefined | Promise<number | Score | undefined>\n\n/**\n * Wraps a plain scoring function as a Judge. The function may return a bare\n * number, a `Score`, or `undefined` to abstain; the result is normalized\n * via `normalize_score`.\n */\nexport function judge_with<I, O>(fn: JudgeWithFn<I, O>): Judge<I, O> {\n return step('judge_with', async (args: JudgeArgs<I, O>): Promise<Score | undefined> => {\n const raw = await fn(args)\n return normalize_score(raw)\n })\n}\n\nexport type JudgeLlmConfig = {\n readonly model: Step<string, string>\n readonly rubric: string\n readonly scale?: { readonly min: number; readonly max: number }\n}\n\n/**\n * Judge that prompts a model with a rubric and parses the score out of the\n * reply.\n *\n * Built as a three-step sequence: render the rubric prompt, run the\n * caller-supplied model step, parse the JSON score from the reply. An\n * unparseable reply makes the judge abstain rather than fail the case.\n */\nexport function judge_llm<I, O>(config: JudgeLlmConfig): Judge<I, O> {\n const scale = config.scale ?? { min: 0, max: 1 }\n const build_prompt = step('judge_llm_build_prompt', (args: JudgeArgs<I, O>): string =>\n render_prompt(config.rubric, scale, args),\n )\n const parse = step('judge_llm_parse', (reply: string): Score | undefined =>\n parse_score(reply, scale),\n )\n const inner = sequence([build_prompt, config.model, parse])\n return compose(inner, { name: 'judge_llm' })\n}\n\n/**\n * Renders the evaluator prompt: rubric, required JSON reply shape with the\n * score scale, and the case's input/output serialized as JSON.\n */\nexport function render_prompt<I, O>(\n rubric: string,\n scale: { min: number; max: number },\n args: JudgeArgs<I, O>,\n): string {\n return [\n `You are an evaluator. Score the model output against the rubric below.`,\n ``,\n `Rubric:`,\n rubric,\n ``,\n `Return a single line of JSON with exactly two keys: {\"score\": <number ${String(scale.min)}..${String(scale.max)}>, \"reason\": \"<short>\"}.`,\n `Do not include prose outside the JSON.`,\n ``,\n `Input:`,\n JSON.stringify(args.input),\n ``,\n `Output:`,\n JSON.stringify(args.output),\n ].join('\\n')\n}\n\n/**\n * Parses a model reply into a `Score`, or `undefined` (abstain) when no\n * valid JSON object with a finite numeric `score` can be extracted.\n *\n * Tolerates prose around the JSON via `extract_json_object` and clamps the\n * score into the configured scale rather than rejecting out-of-range values.\n */\nexport function parse_score(\n reply: string,\n scale: { min: number; max: number },\n): Score | undefined {\n const trimmed = reply.trim()\n const candidate = extract_json_object(trimmed)\n if (candidate === undefined) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(candidate)\n } catch {\n return undefined\n }\n if (!is_record(parsed)) return undefined\n const raw_score = parsed['score']\n if (typeof raw_score !== 'number' || !Number.isFinite(raw_score)) return undefined\n const clamped = Math.max(scale.min, Math.min(scale.max, raw_score))\n const raw_reason = parsed['reason']\n const reason = typeof raw_reason === 'string' ? raw_reason : undefined\n return reason === undefined ? { score: clamped } : { score: clamped, reason }\n}\n\n/**\n * Pulls the outermost `{...}` slice out of a reply that may wrap the JSON\n * in prose or code fences. Returns the text as-is when it already starts\n * with `{`.\n */\nexport function extract_json_object(text: string): string | undefined {\n if (text.startsWith('{')) return text\n const start = text.indexOf('{')\n const end = text.lastIndexOf('}')\n if (start === -1 || end === -1 || end < start) return undefined\n return text.slice(start, end + 1)\n}\n","/**\n * regression_compare: diff two BenchReports for regressions.\n *\n * The contract: given a `current` report and a `baseline` report, produce a\n * `RegressionReport` whose `ok` flag is false when any tracked metric got\n * worse beyond a threshold. The function does NOT short-circuit on first\n * failure; every metric and every per-case delta is computed so callers can\n * print or assert against the whole report.\n *\n * Tracked metrics:\n * - pass_rate (any drop is a regression by default)\n * - mean_scores.<name> (per judge; any drop is a regression by default)\n * - total_cost_usd (a relative cost increase above cost_threshold\n * counts as a regression; default 10%)\n *\n * Baselines are plain JSON, written via `write_baseline` and read via\n * `read_baseline`. They live wherever the caller decides, typically\n * `bench/<flow>/baseline.json` checked into git.\n */\n\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\nimport type { BenchReport, CaseResult } from './bench.js'\n\nexport type RegressionDelta = {\n readonly metric: string\n readonly baseline: number\n readonly current: number\n readonly delta: number\n readonly is_regression: boolean\n}\n\nexport type PerCaseDelta = {\n readonly case_id: string\n readonly baseline?: CaseResult\n readonly current?: CaseResult\n readonly score_deltas: Record<string, number>\n readonly cost_delta: number\n readonly is_regression: boolean\n}\n\nexport type RegressionReport = {\n readonly ok: boolean\n readonly deltas: ReadonlyArray<RegressionDelta>\n readonly per_case: ReadonlyArray<PerCaseDelta>\n}\n\nexport type RegressionCompareOptions = {\n readonly score_threshold?: number\n readonly cost_threshold?: number\n}\n\n/**\n * Diff a current `BenchReport` against a baseline.\n *\n * Compares `pass_rate`, each judge's mean score, and total cost, then every\n * individual case. Score metrics regress on any drop beyond\n * `score_threshold` (default 0); cost regresses on a relative increase above\n * `cost_threshold` (default 10%).\n */\nexport function regression_compare(\n current: BenchReport,\n baseline: BenchReport,\n options: RegressionCompareOptions = {},\n): RegressionReport {\n const score_threshold = options.score_threshold ?? 0\n const cost_threshold = options.cost_threshold ?? 0.1\n\n const deltas: RegressionDelta[] = []\n\n const pass_delta = current.summary.pass_rate - baseline.summary.pass_rate\n deltas.push({\n metric: 'pass_rate',\n baseline: baseline.summary.pass_rate,\n current: current.summary.pass_rate,\n delta: pass_delta,\n is_regression: pass_delta < -score_threshold,\n })\n\n const judge_names = collect_judge_names(current, baseline)\n for (const name of judge_names) {\n const c = current.summary.mean_scores[name] ?? 0\n const b = baseline.summary.mean_scores[name] ?? 0\n const d = c - b\n deltas.push({\n metric: `mean_scores.${name}`,\n baseline: b,\n current: c,\n delta: d,\n is_regression: d < -score_threshold,\n })\n }\n\n const cb = baseline.summary.total_cost_usd\n const cc = current.summary.total_cost_usd\n const cost_delta = cc - cb\n const cost_ratio = cb === 0 ? (cc > 0 ? Infinity : 0) : cost_delta / cb\n deltas.push({\n metric: 'total_cost_usd',\n baseline: cb,\n current: cc,\n delta: cost_delta,\n is_regression: cost_ratio > cost_threshold,\n })\n\n const per_case = compute_per_case(current, baseline, score_threshold, cost_threshold)\n const ok = !deltas.some((d) => d.is_regression) && !per_case.some((c) => c.is_regression)\n\n return { ok, deltas, per_case }\n}\n\n/**\n * Compute per-case deltas across the union of case ids in both reports.\n *\n * Cases present on only one side still appear (missing side scores count as\n * 0). A case regresses when a judge score drops beyond the threshold, its\n * cost rises beyond the relative threshold, or it flips from ok to failing.\n */\nfunction compute_per_case(\n current: BenchReport,\n baseline: BenchReport,\n score_threshold: number,\n cost_threshold: number,\n): PerCaseDelta[] {\n const by_id_current = index_by_case_id(current.cases)\n const by_id_baseline = index_by_case_id(baseline.cases)\n const all_ids = new Set<string>([...by_id_current.keys(), ...by_id_baseline.keys()])\n\n const out: PerCaseDelta[] = []\n for (const id of all_ids) {\n const c = by_id_current.get(id)\n const b = by_id_baseline.get(id)\n const { score_deltas, any_regression } = compute_score_deltas(c, b, score_threshold)\n const { cost_delta, is_regression: cost_regression } = compute_cost_regression(\n c,\n b,\n cost_threshold,\n )\n const ok_regression = b?.ok === true && c?.ok !== true\n out.push({\n case_id: id,\n ...(b !== undefined ? { baseline: b } : {}),\n ...(c !== undefined ? { current: c } : {}),\n score_deltas,\n cost_delta,\n is_regression: any_regression || cost_regression || ok_regression,\n })\n }\n return out\n}\n\n/**\n * Compute per-judge score deltas for one case pair across the union of judge\n * names on both sides (a missing side scores 0), flagging a regression when\n * any judge's score drops beyond the threshold.\n */\nfunction compute_score_deltas(\n c: CaseResult | undefined,\n b: CaseResult | undefined,\n score_threshold: number,\n): { score_deltas: Record<string, number>; any_regression: boolean } {\n const score_deltas: Record<string, number> = {}\n let any_regression = false\n const judge_names = new Set<string>([\n ...Object.keys(c?.scores ?? {}),\n ...Object.keys(b?.scores ?? {}),\n ])\n for (const name of judge_names) {\n const delta = score_value(c?.scores[name]) - score_value(b?.scores[name])\n score_deltas[name] = delta\n if (delta < -score_threshold) any_regression = true\n }\n return { score_deltas, any_regression }\n}\n\n/**\n * Compute the cost delta for one case pair and whether it regressed. With a\n * positive baseline cost, a relative rise beyond `cost_threshold` regresses;\n * with a zero baseline, any positive current cost regresses (unless the\n * threshold is Infinity). A missing side counts as 0.\n */\nfunction compute_cost_regression(\n c: CaseResult | undefined,\n b: CaseResult | undefined,\n cost_threshold: number,\n): { cost_delta: number; is_regression: boolean } {\n const baseline_cost = b?.cost_usd ?? 0\n const current_cost = c?.cost_usd ?? 0\n const cost_delta = current_cost - baseline_cost\n const is_regression =\n baseline_cost > 0\n ? cost_delta / baseline_cost > cost_threshold\n : current_cost > 0 && baseline_cost === 0 && cost_threshold < Infinity\n return { cost_delta, is_regression }\n}\n\n/**\n * Extract a finite numeric score from a raw score entry.\n *\n * Accepts a bare number or an object with a numeric `score` field; anything\n * else (missing, NaN, non-numeric) counts as 0 so deltas stay well-defined.\n */\nfunction score_value(s: unknown): number {\n if (s === undefined || s === null) return 0\n if (typeof s === 'number') return Number.isFinite(s) ? s : 0\n if (typeof s === 'object' && 'score' in s) {\n const v = (s as Record<string, unknown>)['score']\n return typeof v === 'number' && Number.isFinite(v) ? v : 0\n }\n return 0\n}\n\n/**\n * Index case results by their `case_id` for pairwise lookup.\n */\nfunction index_by_case_id<I, O, S>(\n cases: ReadonlyArray<CaseResult<I, O, S>>,\n): Map<string, CaseResult<I, O, S>> {\n const m = new Map<string, CaseResult<I, O, S>>()\n for (const c of cases) m.set(c.case_id, c)\n return m\n}\n\n/**\n * Union the judge names appearing in either report, sorted for stable output.\n */\nfunction collect_judge_names(a: BenchReport, b: BenchReport): string[] {\n const names = new Set<string>([\n ...Object.keys(a.summary.mean_scores),\n ...Object.keys(b.summary.mean_scores),\n ])\n return [...names].toSorted()\n}\n\n/**\n * Read and validate a baseline `BenchReport` from a JSON file.\n *\n * Validation is structural (required fields present), so a hand-edited or\n * truncated baseline fails loudly with the offending path in the message.\n */\nexport async function read_baseline(path: string): Promise<BenchReport> {\n const text = await readFile(path, 'utf8')\n const parsed: unknown = JSON.parse(text)\n validate_report(parsed, path)\n return parsed\n}\n\n/**\n * Write a `BenchReport` as pretty-printed JSON, creating parent directories.\n */\nexport async function write_baseline(path: string, report: BenchReport): Promise<void> {\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, `${JSON.stringify(report, null, 2)}\\n`, 'utf8')\n}\n\n/**\n * Assert that parsed JSON has the structural shape of a `BenchReport`.\n */\nfunction validate_report(value: unknown, path: string): asserts value is BenchReport {\n if (value === null || typeof value !== 'object') {\n throw new Error(`baseline at ${path} is not an object`)\n }\n const v = value as Partial<BenchReport>\n if (typeof v.flow_name !== 'string' || typeof v.run_id !== 'string') {\n throw new Error(`baseline at ${path} missing flow_name/run_id`)\n }\n if (!Array.isArray(v.cases) || typeof v.summary !== 'object' || v.summary === null) {\n throw new Error(`baseline at ${path} missing cases/summary`)\n }\n}\n","/**\n * Derived tokens-per-second over step timing.\n *\n * The engine stores timing primitives (StepTiming) and leaves the rate as a\n * derived view, because \"tokens per second\" has two legitimate readings. The\n * quoted-benchmark meaning is decode throughput: output tokens over the time\n * the model spent emitting them, which needs a streamed turn's first-chunk\n * stamp to isolate. Without streaming, the only measurable window is the whole\n * round-trip, which folds in network, provider queueing, and prompt prefill;\n * that blended rate understates the model on long prompts with short answers.\n * The result names which one it is rather than letting the two be confused.\n */\n\nimport type { GenerateResult, StepRecord } from './types.js'\n\nexport type Throughput = {\n /** Output tokens per second over the measured window. Not rounded. */\n tokens_per_second: number\n /**\n * 'decode' when every contributing step streamed, so each window excludes\n * its time-to-first-chunk; 'blended' when any window is a whole round-trip\n * (network + queueing + prefill included).\n */\n basis: 'decode' | 'blended'\n /** Output tokens summed across the contributing steps. */\n output_tokens: number\n /** The measured window in ms, summed across the contributing steps. */\n measured_ms: number\n}\n\n/**\n * Narrow the accepted source union to its array member. A user-defined guard\n * because Array.isArray does not narrow a ReadonlyArray union member on its\n * own.\n */\nfunction is_step_list(\n source: GenerateResult<unknown> | StepRecord | ReadonlyArray<StepRecord>,\n): source is ReadonlyArray<StepRecord> {\n return Array.isArray(source)\n}\n\n/**\n * Compute output throughput from step timing: a whole GenerateResult, a step\n * array, or a single step.\n *\n * Only steps carrying `timing` contribute; tool-execution time between turns\n * never does, since StepTiming brackets the provider round-trip alone. Each\n * step's window is `duration_ms - first_chunk_ms` when the turn streamed and\n * the full `duration_ms` otherwise, with `basis` reporting 'decode' only when\n * no blended window contributed. Returns undefined when nothing is measurable:\n * no step has timing (an external adapter, a test seam), or the summed window\n * is 0 ms (a sub-millisecond stub turn), where a rate would divide by zero.\n */\nexport function throughput(\n source: GenerateResult<unknown> | StepRecord | ReadonlyArray<StepRecord>,\n): Throughput | undefined {\n const steps: ReadonlyArray<StepRecord> = is_step_list(source)\n ? source\n : 'steps' in source\n ? source.steps\n : [source]\n\n let output_tokens = 0\n let measured_ms = 0\n let all_decode = true\n for (const step of steps) {\n if (step.timing === undefined) continue\n output_tokens += step.usage.output_tokens\n if (step.timing.first_chunk_ms !== undefined) {\n measured_ms += step.timing.duration_ms - step.timing.first_chunk_ms\n } else {\n measured_ms += step.timing.duration_ms\n all_decode = false\n }\n }\n if (measured_ms <= 0) return undefined\n return {\n tokens_per_second: (output_tokens * 1000) / measured_ms,\n basis: all_decode ? 'decode' : 'blended',\n output_tokens,\n measured_ms,\n }\n}\n","/**\n * model_call: the single sanctioned bridge between the composition and\n * engine layers.\n *\n * This is the only file under `src/` permitted to import value symbols from\n * both `core` and `engine` (enforced by the model-call-is-sole-bridge\n * ast-grep rule in `rules/`).\n *\n * The returned Step auto-threads ctx.abort, ctx.trajectory, and, only when\n * run.stream is driving, an on_chunk forwarder that records each chunk as a\n * `model_chunk` trajectory event. Callers cannot override these: the\n * composition layer owns cancellation and trajectory plumbing. Cost events\n * flow out via ctx.trajectory per the engine's own emission rules.\n */\n\nimport { createHash } from 'node:crypto'\nimport { aborted_error, step } from '#core'\nimport type { RunContext, Step, TrajectoryLogger } from '#core'\nimport type {\n EffortLevel,\n Engine,\n GenerateOptions,\n GenerateResult,\n Message,\n PrepareStepHook,\n RetryPolicy,\n Tool,\n ToolApprovalHandler,\n} from '#engine'\nimport type { ToolSchema } from '#schema'\n\nexport type ModelCallInput = string | ReadonlyArray<Message>\n\nexport type ModelCallConfig<T = string, projected = GenerateResult<T>> = {\n readonly engine: Engine\n /**\n * Model id, sent to the provider verbatim (there is no alias layer).\n * Optional: if omitted, the engine's `defaults.model` is used. Errors at\n * call time if neither is set.\n */\n readonly model?: string\n /**\n * Transport for the model: `anthropic` | `claude_cli` | `openrouter` | ...\n * Optional: if omitted, the engine's `defaults.provider` (or its sole\n * configured provider) is used.\n */\n readonly provider?: string\n readonly id?: string\n readonly system?: string\n readonly tools?: ReadonlyArray<Tool>\n readonly schema?: ToolSchema<T>\n readonly effort?: EffortLevel\n readonly temperature?: number\n readonly max_tokens?: number\n readonly top_p?: number\n readonly max_steps?: number\n /**\n * Per-turn wall-clock budget in milliseconds, forwarded to the engine.\n * See `GenerateOptions.turn_timeout_ms`.\n */\n readonly turn_timeout_ms?: number\n /**\n * Per-turn message hook, forwarded to the engine. See\n * `GenerateOptions.prepare_step`.\n */\n readonly prepare_step?: PrepareStepHook\n readonly provider_options?: Record<string, unknown>\n readonly retry_policy?: RetryPolicy\n readonly tool_error_policy?: 'feed_back' | 'throw'\n readonly schema_repair_attempts?: number\n readonly tool_call_repair_attempts?: number\n readonly max_tool_calls_per_step?: number\n readonly on_tool_approval?: ToolApprovalHandler\n /**\n * Map the `GenerateResult` envelope into the step's output at the source.\n * The projection runs inside the model_call step itself, so `describe` and\n * the trajectory gain no wrapper node. Omitted, the envelope is the output.\n * `model_step` is this option preset to `(r) => r.content`.\n */\n readonly project?: (r: GenerateResult<T>) => projected\n}\n\n/**\n * Wrap the run's trajectory so the engine's own spans (engine.generate and its\n * step spans) nest under the model_call step rather than floating. The wrapper\n * keeps a private span stack seeded with the model_call step's id, so nesting\n * is correct and concurrency-safe even when several model_calls run together\n * under `parallel`/`map` (each invocation builds its own wrapper). A\n * caller-supplied `parent_span_id` is never overridden.\n */\nfunction engine_trajectory(\n inner: TrajectoryLogger,\n root_parent: string | undefined,\n): TrajectoryLogger {\n const stack: string[] = root_parent !== undefined ? [root_parent] : []\n return {\n record: (event) => {\n inner.record(event)\n },\n start_span: (name, meta) => {\n const has_parent = meta !== undefined && 'parent_span_id' in meta\n const parent = stack.length > 0 ? stack[stack.length - 1] : undefined\n const next_meta =\n has_parent || parent === undefined ? meta : { ...meta, parent_span_id: parent }\n const id = inner.start_span(name, next_meta)\n stack.push(id)\n return id\n },\n end_span: (id, meta) => {\n inner.end_span(id, meta)\n const idx = stack.lastIndexOf(id)\n if (idx !== -1) stack.splice(idx, 1)\n },\n }\n}\n\n/**\n * Derive a short, stable hash from the call's model, provider, system\n * prompt, and tool/schema shape.\n *\n * Used to build a default step id when the caller doesn't supply `cfg.id`.\n */\nfunction stable_signature(input: {\n model: string | undefined\n provider: string | undefined\n system: string | undefined\n has_tools: boolean\n has_schema: boolean\n}): string {\n const payload = JSON.stringify({\n model: input.model ?? null,\n provider: input.provider ?? null,\n system: input.system ?? null,\n has_tools: input.has_tools,\n has_schema: input.has_schema,\n })\n return createHash('sha256').update(payload).digest('hex').slice(0, 8)\n}\n\nlet model_call_counter = 0\n\n/**\n * Build the default step id: `model_call_<hash>_<n>`. The instance counter\n * keeps two leaves built from identical configs distinguishable in describe\n * and the trajectory; the hash still identifies the call's shape.\n *\n * Underscore-separated rather than colon-separated because every id in the\n * system is identifier-shaped, generated ones included.\n */\nfunction next_auto_id(input: Parameters<typeof stable_signature>[0]): string {\n model_call_counter += 1\n return `model_call_${stable_signature(input)}_${model_call_counter}`\n}\n\n/**\n * Copy `value` onto `target[key]` only when it is defined, so an absent optional\n * config field leaves the key off `GenerateOptions` rather than present-as-undefined.\n */\nfunction assign_if_present<T, K extends keyof T>(target: T, key: K, value: T[K]): void {\n if (value !== undefined) target[key] = value\n}\n\n/**\n * Translate `cfg` into a `GenerateOptions`, folding each supplied optional field\n * in via `assign_if_present`. `tools` (spread to a fresh array) and\n * `retry_policy` (renamed to `retry`) are the two fields that do not copy\n * straight across and stay explicit; the rest map name-for-name.\n */\nfunction build_generate_options<T, projected>(\n cfg: ModelCallConfig<T, projected>,\n prompt: Message[],\n ctx: RunContext,\n): GenerateOptions<T> {\n const opts: GenerateOptions<T> = {\n prompt,\n abort: ctx.abort,\n trajectory: engine_trajectory(ctx.trajectory, ctx.parent_span_id),\n }\n assign_if_present(opts, 'model', cfg.model)\n assign_if_present(opts, 'provider', cfg.provider)\n assign_if_present(opts, 'system', cfg.system)\n if (cfg.tools !== undefined) opts.tools = [...cfg.tools]\n assign_if_present(opts, 'schema', cfg.schema)\n assign_if_present(opts, 'effort', cfg.effort)\n assign_if_present(opts, 'temperature', cfg.temperature)\n assign_if_present(opts, 'max_tokens', cfg.max_tokens)\n assign_if_present(opts, 'top_p', cfg.top_p)\n assign_if_present(opts, 'turn_timeout_ms', cfg.turn_timeout_ms)\n assign_if_present(opts, 'prepare_step', cfg.prepare_step)\n assign_if_present(opts, 'max_steps', cfg.max_steps)\n assign_if_present(opts, 'provider_options', cfg.provider_options)\n if (cfg.retry_policy !== undefined) opts.retry = cfg.retry_policy\n assign_if_present(opts, 'tool_error_policy', cfg.tool_error_policy)\n assign_if_present(opts, 'schema_repair_attempts', cfg.schema_repair_attempts)\n assign_if_present(opts, 'tool_call_repair_attempts', cfg.tool_call_repair_attempts)\n assign_if_present(opts, 'max_tool_calls_per_step', cfg.max_tool_calls_per_step)\n assign_if_present(opts, 'on_tool_approval', cfg.on_tool_approval)\n return opts\n}\n\n/**\n * Build a `Step` that calls `cfg.engine.generate` with `cfg` translated into\n * `GenerateOptions`.\n *\n * Threads `ctx.abort` and `ctx.trajectory` (nested under the model_call\n * step's own span) into every call, and, when `run.stream` is driving,\n * records each chunk as a `model_chunk` trajectory event. `cfg.project`\n * maps the `GenerateResult` envelope into the step's output inside the same\n * step; omitted, the envelope is the output.\n */\nexport function model_call<T = string, projected = GenerateResult<T>>(\n cfg: ModelCallConfig<T, projected>,\n): Step<ModelCallInput, projected> {\n // Guard at construction so a wiring mistake (JS caller, spread gone wrong)\n // surfaces where it was made instead of as a bare property-read crash at\n // dispatch time.\n if (typeof cfg?.engine?.generate !== 'function') {\n throw new TypeError(\n 'model_call: cfg.engine is required (an Engine from create_engine or fascicle/testing)',\n )\n }\n const has_tools = Boolean(cfg.tools && cfg.tools.length > 0)\n const has_schema = cfg.schema !== undefined\n // When `project` is omitted, `projected` defaults to the envelope type, which\n // is what the identity fallback's cast records.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const project = cfg.project ?? ((r: GenerateResult<T>) => r as unknown as projected)\n const step_id =\n cfg.id ??\n next_auto_id({\n model: cfg.model,\n provider: cfg.provider,\n system: cfg.system,\n has_tools,\n has_schema,\n })\n\n const describe_config: {\n model?: string\n provider?: string\n has_tools: boolean\n has_schema: boolean\n has_project: boolean\n has_prepare_step: boolean\n system?: string\n effort?: EffortLevel\n temperature?: number\n max_tokens?: number\n top_p?: number\n turn_timeout_ms?: number\n } = {\n has_tools,\n has_schema,\n has_project: cfg.project !== undefined,\n has_prepare_step: cfg.prepare_step !== undefined,\n }\n if (cfg.model !== undefined) describe_config.model = cfg.model\n if (cfg.provider !== undefined) describe_config.provider = cfg.provider\n if (cfg.system !== undefined) describe_config.system = cfg.system\n if (cfg.effort !== undefined) describe_config.effort = cfg.effort\n if (cfg.temperature !== undefined) describe_config.temperature = cfg.temperature\n if (cfg.max_tokens !== undefined) describe_config.max_tokens = cfg.max_tokens\n if (cfg.top_p !== undefined) describe_config.top_p = cfg.top_p\n if (cfg.turn_timeout_ms !== undefined) describe_config.turn_timeout_ms = cfg.turn_timeout_ms\n\n const inner = step<ModelCallInput, projected>(step_id, async (input, ctx) => {\n if (ctx.abort.aborted) {\n throw new aborted_error('aborted before model_call', {\n reason: { signal: 'abort' },\n step_index: 0,\n })\n }\n\n const prompt: Message[] =\n typeof input === 'string'\n ? [{ role: 'user', content: [{ type: 'text', text: input }] }]\n : [...input]\n\n const opts = build_generate_options(cfg, prompt, ctx)\n\n if (ctx.streaming) {\n opts.on_chunk = (chunk) => {\n // Record with kind preserved. ctx.emit would clobber kind to 'emit'\n // and bury the chunk, so stream consumers would have to un-nest a\n // generic event; recording keeps a clean top-level `model_chunk` event\n // (what docs/concepts.md already documents) carrying the StreamChunk.\n ctx.trajectory.record({ kind: 'model_chunk', step_id, chunk })\n }\n }\n\n return project(await cfg.engine.generate(opts))\n })\n\n return {\n id: inner.id,\n kind: inner.kind,\n run: (input, ctx) => inner.run(input, ctx),\n config: Object.freeze({ ...describe_config }),\n }\n}\n\n/**\n * model_step: `model_call` projected to its content.\n *\n * Returns a Step whose output is the model's final content (a `string`, or\n * the schema-validated value when `cfg.schema` is set) instead of the full\n * `GenerateResult` envelope. Use `model_step` when the flow only wants the\n * answer, keeping compositions at the `step, step, model_step, step` cadence;\n * drop to `model_call` when the caller needs usage, cost, tool calls, or\n * finish reason (or its `project` option, when the flow wants a slice of the\n * envelope mapped at the source).\n *\n * Implemented as `model_call` with `project` preset to `(r) => r.content`,\n * so the leaf is a single node in `describe` and the trajectory. Wrapping a\n * primitive into an app-shaped helper of your own is still the extension\n * pattern; this is its smallest instance.\n */\nexport function model_step<T = string>(\n cfg: Omit<ModelCallConfig<T>, 'project'>,\n): Step<ModelCallInput, T> {\n return model_call<T, T>({ ...cfg, project: (r) => r.content })\n}\n","/**\n * Env forwarding allowlist for CLI subprocesses.\n *\n * Useful when passing explicit env to `claude_cli` under api_key mode\n * (oauth mode inherits the parent env automatically), or whenever an\n * explicit, minimal allowlist is preferred over inheriting the full parent\n * env.\n */\nconst STANDARD_KEYS = ['PATH', 'HOME', 'SHELL', 'USER', 'LOGNAME', 'LANG', 'TMPDIR'] as const\n\n/**\n * Return the standard env vars a CLI subprocess needs to reach a user's\n * logged-in session: PATH, HOME, SHELL, USER, LOGNAME, LANG, TMPDIR.\n *\n * Keys absent from `process.env` are skipped.\n *\n * @example\n * provider_options: {\n * claude_cli: { env: forward_standard_env() },\n * }\n */\nexport function forward_standard_env(): Record<string, string> {\n const out: Record<string, string> = {}\n for (const key of STANDARD_KEYS) {\n const v = process.env[key]\n if (typeof v === 'string') out[key] = v\n }\n return out\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACWA,MAAa,aAAa;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;AAOA,SAAgB,aAAa,OAAmC;CAC9D,OAAO,OAAO,UAAU,YAAa,WAAiC,SAAS,KAAK;AACtF;;;;;;;;;;;;;;;;ACKA,SAAS,uBACP,GAC6B;CAC7B,IAAI,EAAE,cAAc,KAAA,GAAW,OAAO,EAAE,OAAO,EAAE,MAAM;CACvD,IAAI,EAAE,mBAAmB,KAAA,GAAW,OAAO;EAAE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