@tangle-network/agent-eval 2.0.15 → 2.0.17
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/CHANGELOG.md +14 -0
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-8S2LfCvs.d.ts → agent-profile-_A7aMA4F.d.ts} +4 -4
- package/dist/{agent-profile-8S2LfCvs.d.ts.map → agent-profile-_A7aMA4F.d.ts.map} +1 -1
- package/dist/analyst/index.d.ts +23 -5
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +3 -3
- package/dist/app-grade/index.d.ts +2 -2
- package/dist/{benchmark-command-DgR1i30h.js → benchmark-command-CZbrh9bS.js} +27 -8
- package/dist/benchmark-command-CZbrh9bS.js.map +1 -0
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/benchmarks/index.js +2 -2
- package/dist/campaign/index.d.ts +7 -7
- package/dist/campaign/index.js +7 -7
- package/dist/{campaign-CaO2k8Jb.js → campaign-CJRlis5N.js} +7 -7
- package/dist/{campaign-CaO2k8Jb.js.map → campaign-CJRlis5N.js.map} +1 -1
- package/dist/{campaign-evidence-DcTgo4ze.d.ts → campaign-evidence-Biq06MQ9.d.ts} +2 -2
- package/dist/{campaign-evidence-DcTgo4ze.d.ts.map → campaign-evidence-Biq06MQ9.d.ts.map} +1 -1
- package/dist/cli.js +11 -7
- package/dist/cli.js.map +1 -1
- package/dist/{client-3sR4_h5q.d.ts → client-B_9qUZi5.d.ts} +2 -2
- package/dist/{client-3sR4_h5q.d.ts.map → client-B_9qUZi5.d.ts.map} +1 -1
- package/dist/contract/index.d.ts +9 -9
- package/dist/contract/index.js +5 -5
- package/dist/{default-registry-CVklg2e-.d.ts → default-registry-BKHpiYiW.d.ts} +2 -2
- package/dist/{default-registry-CVklg2e-.d.ts.map → default-registry-BKHpiYiW.d.ts.map} +1 -1
- package/dist/{define-agent-eval-DZ7wWMHC.d.ts → define-agent-eval-Bh8tJHZI.d.ts} +5 -5
- package/dist/{define-agent-eval-DZ7wWMHC.d.ts.map → define-agent-eval-Bh8tJHZI.d.ts.map} +1 -1
- package/dist/{define-agent-eval-BLHr0_IP.js → define-agent-eval-Dd6hFx0-.js} +3 -3
- package/dist/{define-agent-eval-BLHr0_IP.js.map → define-agent-eval-Dd6hFx0-.js.map} +1 -1
- package/dist/dspy-rlm-engine-DFgGrKzg.js +1613 -0
- package/dist/dspy-rlm-engine-DFgGrKzg.js.map +1 -0
- package/dist/{evaluation-D50Dzyce.d.ts → evaluation-f-UIDwbL.d.ts} +2 -2
- package/dist/{evaluation-D50Dzyce.d.ts.map → evaluation-f-UIDwbL.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/experiment/index.d.ts +76 -7
- package/dist/experiment/index.d.ts.map +1 -1
- package/dist/experiment/index.js +196 -13
- package/dist/experiment/index.js.map +1 -1
- package/dist/{findings-store-Drnjid7m.js → findings-store-DcBkRLDk.js} +2 -2
- package/dist/{findings-store-Drnjid7m.js.map → findings-store-DcBkRLDk.js.map} +1 -1
- package/dist/hosted/index.d.ts +2 -2
- package/dist/hosted/index.js +1 -1
- package/dist/{index-D1ghgNRI.d.ts → index-4khf0Q7g.d.ts} +238 -4
- package/dist/index-4khf0Q7g.d.ts.map +1 -0
- package/dist/{index-Bam453Y5.d.ts → index-C1jQ7qqy.d.ts} +8 -8
- package/dist/{index-Bam453Y5.d.ts.map → index-C1jQ7qqy.d.ts.map} +1 -1
- package/dist/{index-CYrvUGQl.d.ts → index-Cq_5SLfF.d.ts} +17 -247
- package/dist/index-Cq_5SLfF.d.ts.map +1 -0
- package/dist/{index-CxciVDt0.d.ts → index-DH_Jxu9p.d.ts} +2 -2
- package/dist/{index-CxciVDt0.d.ts.map → index-DH_Jxu9p.d.ts.map} +1 -1
- package/dist/index.d.ts +14 -14
- package/dist/index.js +9 -1091
- package/dist/index.js.map +1 -1
- package/dist/{llm-judge-ChGnwj4s.js → llm-judge-Bf3p1WNA.js} +2 -2
- package/dist/{llm-judge-ChGnwj4s.js.map → llm-judge-Bf3p1WNA.js.map} +1 -1
- package/dist/{matrix-CAeyP9m-.d.ts → matrix-BtyN7jpb.d.ts} +2 -2
- package/dist/{matrix-CAeyP9m-.d.ts.map → matrix-BtyN7jpb.d.ts.map} +1 -1
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +6 -6
- package/dist/multishot/index.js +2 -2
- package/dist/openapi.json +1 -1
- package/dist/{optimization-method-D2uCSc2j.js → optimization-method-BO2sb1m4.js} +4 -4
- package/dist/{optimization-method-D2uCSc2j.js.map → optimization-method-BO2sb1m4.js.map} +1 -1
- package/dist/rl.d.ts +1 -1
- package/dist/rollout/index.d.ts +2 -2
- package/dist/{run-improvement-loop-C9z817z_.d.ts → run-improvement-loop-D9IAZviC.d.ts} +7 -7
- package/dist/{run-improvement-loop-C9z817z_.d.ts.map → run-improvement-loop-D9IAZviC.d.ts.map} +1 -1
- package/dist/search/index.d.ts +3 -3
- package/dist/search/index.js +2 -2
- package/dist/{search-kernel-CZmj8gJW.d.ts → search-kernel-C2XOJHvk.d.ts} +3 -3
- package/dist/{search-kernel-CZmj8gJW.d.ts.map → search-kernel-C2XOJHvk.d.ts.map} +1 -1
- package/dist/{search-kernel-B1TEQ9pa.js → search-kernel-D96Eibc_.js} +2 -2
- package/dist/{search-kernel-B1TEQ9pa.js.map → search-kernel-D96Eibc_.js.map} +1 -1
- package/dist/{search-ledger-EjLGVZ4X.js → search-ledger-C7DywY8N.js} +40 -4
- package/dist/search-ledger-C7DywY8N.js.map +1 -0
- package/dist/{search-ledger-types-D4FsvPP9.d.ts → search-ledger-types-DF-f031V.d.ts} +19 -5
- package/dist/search-ledger-types-DF-f031V.d.ts.map +1 -0
- package/dist/{search-shipper-DtSnRfOJ.js → search-shipper-l6wUUWtc.js} +2 -2
- package/dist/{search-shipper-DtSnRfOJ.js.map → search-shipper-l6wUUWtc.js.map} +1 -1
- package/dist/{search-summary-C5fewoUi.js → search-summary-DjgKz7B1.js} +2 -2
- package/dist/{search-summary-C5fewoUi.js.map → search-summary-DjgKz7B1.js.map} +1 -1
- package/dist/{self-improve-CQM7hIL_.js → self-improve-BiTuylQQ.js} +3 -3
- package/dist/{self-improve-CQM7hIL_.js.map → self-improve-BiTuylQQ.js.map} +1 -1
- package/dist/{self-improve-Eo-EAWL8.d.ts → self-improve-DZ8W-QY-.d.ts} +7 -7
- package/dist/{self-improve-Eo-EAWL8.d.ts.map → self-improve-DZ8W-QY-.d.ts.map} +1 -1
- package/dist/{skillopt-optimization-method-DQ4urRij.js → skillopt-optimization-method-CJkejuSP.js} +3 -3
- package/dist/{skillopt-optimization-method-DQ4urRij.js.map → skillopt-optimization-method-CJkejuSP.js.map} +1 -1
- package/dist/{store-tool-spans-BD5Z304_.d.ts → store-tool-spans-wH8y7InB.d.ts} +2 -2
- package/dist/{store-tool-spans-BD5Z304_.d.ts.map → store-tool-spans-wH8y7InB.d.ts.map} +1 -1
- package/dist/{systemone-D7FQ7n00.d.ts → systemone-CpW1U2Uy.d.ts} +3 -3
- package/dist/{systemone-D7FQ7n00.d.ts.map → systemone-CpW1U2Uy.d.ts.map} +1 -1
- package/dist/systemone.d.ts +2 -2
- package/dist/traces.d.ts +1 -1
- package/dist/{tree-CljLPWVm.js → tree-lU9KWuxr.js} +3 -3
- package/dist/{tree-CljLPWVm.js.map → tree-lU9KWuxr.js.map} +1 -1
- package/dist/{types-BtWzceBY.d.ts → types-BpIAnRCe.d.ts} +12 -2
- package/dist/types-BpIAnRCe.d.ts.map +1 -0
- package/dist/{types-XxFZ2IAT.d.ts → types-DSU3qb_o.d.ts} +2 -2
- package/dist/{types-XxFZ2IAT.d.ts.map → types-DSU3qb_o.d.ts.map} +1 -1
- package/docs/experiment.md +31 -1
- package/docs/search-ledger.md +1 -0
- package/docs/trace-contracts.md +23 -0
- package/package.json +1 -1
- package/dist/benchmark-command-DgR1i30h.js.map +0 -1
- package/dist/dspy-rlm-engine-CR5MSL2k.js +0 -463
- package/dist/dspy-rlm-engine-CR5MSL2k.js.map +0 -1
- package/dist/index-CYrvUGQl.d.ts.map +0 -1
- package/dist/index-D1ghgNRI.d.ts.map +0 -1
- package/dist/search-ledger-EjLGVZ4X.js.map +0 -1
- package/dist/search-ledger-types-D4FsvPP9.d.ts.map +0 -1
- package/dist/types-BtWzceBY.d.ts.map +0 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":["FORMATS","USAGE","PROCESS_IO","parseArgs","NOTES","FORMATS","USAGE","PROCESS_IO","parseArgs","parseArgs"],"sources":["../src/cli-config.ts","../src/skill-usage/command.ts","../src/intent-record/derive.ts","../src/intent-record/contract.ts","../src/intent-record/report.ts","../src/procedure-registry/change-outcome.ts","../src/procedure-registry/registry.ts","../src/procedure-registry/render.ts","../src/procedure-registry/command.ts","../src/search-command.ts","../src/supervisor-run/rollouts-command.ts","../src/supervisor-run/report-command.ts","../src/cli.ts"],"sourcesContent":["/**\n * Provider configuration for the `agent-eval` binary.\n *\n * The binary reads endpoint and credential values from its environment.\n * TypeScript library callers bind a transport explicitly. The maintained\n * HTTP transport accepts their credential and sends provider requests.\n */\n\nimport { type ChatClient, createChatClient } from './analyst/chat-client'\n\ninterface CliLlmConfig {\n /** Judge transport for the wire handlers. Absent when no provider is configured. */\n chat?: ChatClient\n model?: string\n}\n\n/** The endpoint the binary resolved from its environment. */\ninterface CliProviderRoute {\n baseUrl: string\n apiKey: string\n model?: string\n}\n\n/**\n * Environment precedence for the binary's provider route, with no client built.\n *\n * Both halves are required: a base URL without a key, or a key without an\n * endpoint, is a half-configured server. `/v1/judge` then refuses with\n * `llm_not_configured` instead of calling an unintended endpoint.\n */\nfunction resolveCliProviderRoute(\n env: NodeJS.ProcessEnv = process.env,\n): CliProviderRoute | undefined {\n const explicitBaseUrl = nonEmpty(env.AGENT_EVAL_LLM_BASE_URL)\n const explicitApiKey = nonEmpty(env.AGENT_EVAL_LLM_API_KEY)\n const openAiApiKey = nonEmpty(env.OPENAI_API_KEY)\n const tangleApiKey = nonEmpty(env.TANGLE_API_KEY)\n const baseUrl =\n explicitBaseUrl ??\n nonEmpty(env.OPENAI_BASE_URL) ??\n nonEmpty(env.TANGLE_ROUTER_URL) ??\n (openAiApiKey ? 'https://api.openai.com/v1' : undefined) ??\n (tangleApiKey ? 'https://router.tangle.tools/v1' : undefined)\n const apiKey = explicitApiKey ?? openAiApiKey ?? tangleApiKey\n const model =\n nonEmpty(env.AGENT_EVAL_LLM_MODEL) ?? nonEmpty(env.OPENAI_MODEL) ?? nonEmpty(env.TANGLE_MODEL)\n\n if (!baseUrl || !apiKey) return undefined\n return { baseUrl, apiKey, ...(model ? { model } : {}) }\n}\n\nexport function resolveCliLlmConfig(env: NodeJS.ProcessEnv = process.env): CliLlmConfig {\n const route = resolveCliProviderRoute(env)\n if (!route) return {}\n return {\n chat: cliChatClient({ baseUrl: route.baseUrl, apiKey: route.apiKey }, route.model),\n ...(route.model ? { model: route.model } : {}),\n }\n}\n\n/**\n * The binary's transport IS the published one — `createChatClient({ transport:\n * 'openai-compatible' })` — so the server and a library consumer cannot drift\n * onto two different clients for the same endpoint.\n *\n * The one thing kept local is the error text. A generic \"no model on the\n * request\" tells a server operator nothing; this names the variable to set.\n */\nfunction cliChatClient(\n route: { baseUrl: string; apiKey: string },\n defaultModel: string | undefined,\n): ChatClient {\n const client = createChatClient({\n transport: 'openai-compatible',\n baseUrl: route.baseUrl,\n apiKey: route.apiKey,\n ...(defaultModel ? { defaultModel } : {}),\n })\n return {\n ...client,\n chat: (req, callOpts) => {\n if (!req.model && !defaultModel) {\n throw new Error(\n 'agent-eval: no model on the request and no AGENT_EVAL_LLM_MODEL configured',\n )\n }\n return client.chat(req, callOpts)\n },\n }\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n const trimmed = value?.trim()\n return trimmed ? trimmed : undefined\n}\n","/**\n * `agent-eval skill-usage <sessions-dir>` reads a directory of Claude Code\n * transcripts (or, with `--harness codex`, Codex rollouts) and prints the\n * skill-usage report.\n *\n * By default the JSON report goes to stdout and the short table to stderr, so\n * `> report.json` keeps the report while the table stays on the terminal.\n *\n * `--pricing <file>` names a JSON object of per-million rates by model id, for a\n * model the cost ledger has no rate for or prices too coarsely (its table has no\n * cache-read rate).\n *\n * Exit codes follow the other self-parsing subcommands: 2 for a usage error, 1\n * when the directory cannot be read, 0 after the report was written.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport type { CustomTokenPricing } from '../cost-ledger/contract'\nimport { costForTokenPricing } from '../cost-ledger/pricing'\nimport { errorMessage } from '../errors'\nimport { claudeCodeSkillSessions } from './claude-code'\nimport { codexSkillSessions } from './codex'\nimport { buildSkillUsageReport, renderSkillUsageTable } from './report'\nimport type { SkillSessionSource } from './session-record'\nimport { readSkillFile } from './skill-file'\n\ntype SkillUsageFormat = 'both' | 'json' | 'table'\n\nconst FORMATS: readonly SkillUsageFormat[] = ['both', 'json', 'table']\n\nconst USAGE =\n 'usage: agent-eval skill-usage <sessions-dir> [--harness claude-code|codex] [--since <7d|36h|90m|ISO time>] [--format both|json|table] [--limit <rows>] [--pricing <rates.json>]'\n\n/** Output sinks, injectable so a test reads the exact bytes a terminal would. */\nexport interface SkillUsageCommandIo {\n readonly stdout: (text: string) => void\n readonly stderr: (text: string) => void\n /** The instant `--since 7d` counts back from. */\n readonly now?: () => number\n}\n\nconst PROCESS_IO: SkillUsageCommandIo = {\n stdout: (text) => {\n process.stdout.write(text)\n },\n stderr: (text) => {\n process.stderr.write(text)\n },\n}\n\n/** The harnesses whose session stores the commands read. */\nexport const SESSION_HARNESSES = ['claude-code', 'codex'] as const\nexport type SessionHarness = (typeof SESSION_HARNESSES)[number]\n\n/** The sessions under a harness's store: Claude Code's projects directory, or Codex's sessions directory. */\nexport function harnessSkillSessions(\n harness: SessionHarness,\n directory: string,\n options: { sinceMs?: number },\n): SkillSessionSource {\n return harness === 'codex'\n ? codexSkillSessions(directory, options)\n : claudeCodeSkillSessions(directory, options)\n}\n\n/** The value of `--harness`, checked. */\nexport function parseHarness(raw: string): SessionHarness {\n if (!(SESSION_HARNESSES as readonly string[]).includes(raw)) {\n throw new Error(\n `--harness expects one of ${SESSION_HARNESSES.join('|')}, got ${JSON.stringify(raw)}`,\n )\n }\n return raw as SessionHarness\n}\n\ninterface SkillUsageArgs {\n directory: string\n harness: SessionHarness\n since: string | null\n format: SkillUsageFormat\n limit: number\n pricing: string | null\n}\n\nconst DURATION = /^(\\d+(?:\\.\\d+)?)([dhm])$/\nconst UNIT_MS = { d: 86_400_000, h: 3_600_000, m: 60_000 } as const\n\n/** `7d`, `36h` or `90m` back from `nowMs`, or an ISO instant. */\nexport function parseSince(raw: string, nowMs: number): number {\n const duration = DURATION.exec(raw)\n if (duration !== null) {\n return nowMs - Number(duration[1]) * UNIT_MS[duration[2] as keyof typeof UNIT_MS]\n }\n const at = Date.parse(raw)\n if (!Number.isFinite(at)) {\n throw new Error(\n `--since expects a duration such as 7d or an ISO time, got ${JSON.stringify(raw)}`,\n )\n }\n return at\n}\n\nfunction parseArgs(argv: readonly string[]): SkillUsageArgs {\n const args: SkillUsageArgs = {\n directory: '',\n harness: 'claude-code',\n since: null,\n format: 'both',\n limit: 30,\n pricing: null,\n }\n const value = (flag: string, index: number): string => {\n const raw = argv[index]\n if (raw === undefined) throw new Error(`${flag} expects a value`)\n return raw\n }\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i] as string\n if (arg === '--harness') {\n args.harness = parseHarness(value(arg, ++i))\n } else if (arg === '--since') {\n args.since = value(arg, ++i)\n } else if (arg === '--format') {\n const raw = value(arg, ++i)\n if (!(FORMATS as readonly string[]).includes(raw)) {\n throw new Error(`--format expects one of ${FORMATS.join('|')}, got ${JSON.stringify(raw)}`)\n }\n args.format = raw as SkillUsageFormat\n } else if (arg === '--limit') {\n const raw = Number(value(arg, ++i))\n if (!Number.isInteger(raw) || raw < 1) throw new Error('--limit expects a positive integer')\n args.limit = raw\n } else if (arg === '--pricing') {\n args.pricing = value(arg, ++i)\n } else if (arg.startsWith('--')) {\n throw new Error(`unknown flag \"${arg}\"`)\n } else if (args.directory === '') {\n args.directory = arg\n } else {\n throw new Error(`unexpected argument \"${arg}\"`)\n }\n }\n if (args.directory === '') throw new Error('a transcripts directory is required')\n return args\n}\n\nconst RATE_FIELDS = [\n 'inputUsdPerMillion',\n 'cachedInputUsdPerMillion',\n 'cacheWriteUsdPerMillion',\n 'outputUsdPerMillion',\n] as const\n\n/** A rates file: `{ \"<model id>\": { inputUsdPerMillion, outputUsdPerMillion, ... } }`. */\nexport function readPricingFile(path: string): Map<string, CustomTokenPricing> {\n const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error(`--pricing ${path}: expected a JSON object of rates by model id`)\n }\n const rates = new Map<string, CustomTokenPricing>()\n for (const [model, value] of Object.entries(parsed)) {\n const fields = typeof value === 'object' && value !== null ? value : {}\n for (const field of RATE_FIELDS) {\n const rate = (fields as Record<string, unknown>)[field]\n const required = field === 'inputUsdPerMillion' || field === 'outputUsdPerMillion'\n if (typeof rate !== 'number' && (required || rate !== undefined)) {\n throw new Error(`--pricing ${path}: ${JSON.stringify(model)}.${field} must be a number`)\n }\n }\n const pricing = fields as CustomTokenPricing\n // The cost ledger owns what a valid rate is; price nothing to have it check these.\n costForTokenPricing(pricing, { inputTokens: 0, outputTokens: 0 })\n rates.set(model, pricing)\n }\n return rates\n}\n\nexport async function runSkillUsageCommand(\n argv: readonly string[],\n io: SkillUsageCommandIo = PROCESS_IO,\n): Promise<number> {\n if (argv.includes('--help') || argv.includes('-h')) {\n io.stdout(`${USAGE}\\n`)\n return 0\n }\n let args: SkillUsageArgs\n let sinceMs: number | undefined\n let rates: Map<string, CustomTokenPricing> | undefined\n try {\n args = parseArgs(argv)\n rates = args.pricing === null ? undefined : readPricingFile(resolve(args.pricing))\n sinceMs = args.since === null ? undefined : parseSince(args.since, (io.now ?? Date.now)())\n } catch (error) {\n io.stderr(`${errorMessage(error)}\\n${USAGE}\\n`)\n return 2\n }\n try {\n const report = await buildSkillUsageReport(\n harnessSkillSessions(\n args.harness,\n resolve(args.directory),\n sinceMs === undefined ? {} : { sinceMs },\n ),\n {\n ...(sinceMs === undefined ? {} : { sinceMs }),\n ...(rates === undefined ? {} : { pricing: (model: string) => rates?.get(model) }),\n readSkillFile,\n },\n )\n const table = renderSkillUsageTable(report, args.limit)\n if (args.format === 'table') {\n io.stdout(table)\n } else {\n io.stdout(`${JSON.stringify(report, null, 2)}\\n`)\n if (args.format === 'both') io.stderr(table)\n }\n return 0\n } catch (error) {\n io.stderr(`agent-eval skill-usage: ${errorMessage(error)}\\n`)\n return 1\n }\n}\n","/**\n * Intent records from recorded sessions.\n *\n * A session's typed turns are cut into intents. A turn that a labeler calls a\n * correction or a re-ask attaches to the intent already open; any other turn\n * opens a new one and closes the open one. A turn nobody labeled opens a new\n * intent, and the intent it closes then cannot say how many corrections it\n * drew. The span of an intent runs from its opening turn to the turn that\n * closes it, or to the session's end, and its cost and procedures are those of\n * the events in that span.\n */\n\nimport { createHash } from 'node:crypto'\nimport type { InvocationChanges } from '../procedure-registry/change-outcome'\nimport type { SessionChange, SkillSessionRecord, SkillUsageReportOptions } from '../skill-usage'\nimport { afterInvocation, instant } from '../skill-usage/report'\nimport type {\n IntentCost,\n IntentLabeler,\n IntentRecord,\n IntentTurn,\n IntentTurnLabel,\n} from './contract'\n\ninterface Thread {\n openedAtIndex: number\n startEvent: number\n startAt: string | null\n promptSha256: string\n promptChars: number\n turnId: string\n label: IntentTurnLabel | null\n userTurns: number\n corrections: number\n reasks: number\n correctionsKnown: boolean\n reasksKnown: boolean\n endEvent: number\n endAt: string | null\n closedBy: 'next-intent' | 'session-end'\n}\n\n/** An intent before its procedures and outcomes are joined. */\nexport interface IntentDraft {\n record: Omit<IntentRecord, 'procedures' | 'changes' | 'end'> & {\n end: Omit<IntentRecord['end'], 'reachedDone' | 'abandoned' | 'evidence'>\n }\n /** Events [from, to) of the session. */\n span: { from: number; to: number }\n /** The span's instants, for work done in subagents. `to` null: open. */\n window: { from: string | null; to: string | null }\n /** Changes whose tool call is in the span. undefined: the reader records none. */\n changeRefs: string[] | undefined\n}\n\nconst sha256 = (text: string): string => createHash('sha256').update(text).digest('hex')\n\nfunction isCorrection(label: IntentTurnLabel | null): boolean | null {\n if (label === null) return null\n if (label.kind === 'correction') return true\n return label.correction\n}\n\nfunction cost(\n session: SkillSessionRecord,\n thread: Thread,\n options: SkillUsageReportOptions,\n): IntentCost {\n const after = afterInvocation(session, thread.startEvent - 1, thread.startAt, options, {\n eventIndex: thread.endEvent,\n at: thread.endAt,\n })\n return {\n tokens: after.modelCalls > 0 && after.modelCallsWithoutUsage === 0 ? after.tokens.total : null,\n usd: after.pricedModelCalls > 0 && after.unpricedModelCalls === 0 ? after.costUsd : null,\n wallMs: after.wallMs,\n modelCalls: after.modelCalls,\n }\n}\n\nfunction refsInSpan(session: SkillSessionRecord, from: number, to: number): string[] | undefined {\n if (session.changes === undefined) return undefined\n const position = new Map<string, number>()\n session.events.forEach((event, index) => {\n if (event.kind === 'tool') position.set(event.id, index)\n else if (event.kind === 'skill') position.set(event.callId, index)\n })\n const refs = new Set<string>()\n for (const change of session.changes as SessionChange[]) {\n const index = position.get(change.callId)\n if (index !== undefined && index >= from && index < to) refs.add(change.ref)\n }\n return [...refs].sort()\n}\n\n/**\n * Cut one session's typed turns into intents. Returns none when the reader\n * records no typed turns, and the caller counts that session apart.\n */\nexport async function deriveSessionIntents(\n session: SkillSessionRecord,\n labeler: IntentLabeler | undefined,\n options: SkillUsageReportOptions,\n /** True for a typed turn that is no intent: another agent's relay, a harness probe. Such a turn is skipped whole. */\n ignore?: (turn: IntentTurn) => boolean,\n): Promise<IntentDraft[] | null> {\n if (session.turns === undefined) return null\n const threads: Thread[] = []\n let open: Thread | null = null\n let previousText: string | null = null\n\n const close = (\n thread: Thread,\n by: 'next-intent' | 'session-end',\n at: string | null,\n event: number,\n ): void => {\n thread.closedBy = by\n thread.endAt = at\n thread.endEvent = event\n }\n\n for (const [index, turn] of session.turns.entries()) {\n if (options.sinceMs !== undefined) {\n const at = instant(turn.at)\n if (at === null || at < options.sinceMs) continue\n }\n const context: IntentTurn = {\n harness: session.harness,\n sessionId: session.sessionId,\n index,\n at: turn.at,\n text: turn.text,\n previousText,\n }\n if (ignore?.(context) === true) continue\n const label = labeler === undefined ? null : await labeler(context)\n previousText = turn.text\n const correction = isCorrection(label)\n const reask = label === null ? null : label.reask\n const attaches = open !== null && (correction === true || reask === true)\n if (open !== null) {\n // Every turn after an intent says whether it corrected or re-asked it.\n if (correction === null) open.correctionsKnown = false\n else if (correction) open.corrections += 1\n if (reask === null) open.reasksKnown = false\n else if (reask) open.reasks += 1\n }\n if (attaches && open !== null) {\n open.userTurns += 1\n continue\n }\n if (open !== null) close(open, 'next-intent', turn.at, turn.eventIndex)\n open = {\n openedAtIndex: index,\n startEvent: turn.eventIndex,\n startAt: turn.at,\n promptSha256: sha256(turn.text),\n promptChars: turn.text.length,\n turnId: turn.id,\n label,\n userTurns: 1,\n corrections: 0,\n reasks: 0,\n correctionsKnown: true,\n reasksKnown: true,\n endEvent: session.events.length,\n endAt: session.endedAt,\n closedBy: 'session-end',\n }\n threads.push(open)\n }\n\n return threads.map((thread) => {\n const intentId = sha256(`${session.harness}\\u0000${session.sessionId}\\u0000${thread.turnId}`)\n return {\n record: {\n intentId,\n harness: session.harness,\n sessionId: session.sessionId,\n at: thread.startAt,\n prompt: { sha256: thread.promptSha256, chars: thread.promptChars },\n label:\n thread.label === null\n ? null\n : { source: thread.label.source, kind: thread.label.kind, done: thread.label.done },\n cost: cost(session, thread, options),\n end: {\n userTurns: thread.userTurns,\n corrections: thread.correctionsKnown ? thread.corrections : null,\n reasks: thread.reasksKnown ? thread.reasks : null,\n closedBy: thread.closedBy,\n },\n },\n span: { from: thread.startEvent, to: thread.endEvent },\n window: { from: thread.startAt, to: thread.closedBy === 'next-intent' ? thread.endAt : null },\n changeRefs: refsInSpan(session, thread.startEvent, thread.endEvent),\n }\n })\n}\n\n/** Whether a change reading says the change reached its done line: merged and not fixed within the window. */\nexport function changesReachedDone(changes: InvocationChanges): {\n reachedDone: boolean | null\n abandoned: boolean | null\n} {\n if (changes.status !== 'joined' || changes.outcomes.length === 0) {\n return { reachedDone: null, abandoned: null }\n }\n const outcomes = changes.outcomes\n const unmerged = outcomes.some((outcome) => outcome.merged === false)\n const fixed = outcomes.some((outcome) => outcome.merged === true && outcome.hotfixed === true)\n const clean = outcomes.every((outcome) => outcome.merged === true && outcome.hotfixed === false)\n return {\n reachedDone: unmerged || fixed ? false : clean ? true : null,\n abandoned: unmerged ? true : outcomes.every((o) => o.merged === true) ? false : null,\n }\n}\n","/**\n * The intent record: what a person asked for, what served it, what it cost and\n * how it ended.\n *\n * An intent is the input to everything else. Any prompt counts: a task, a\n * problem, a project, information the person shares, or a correction. The\n * record holds the prompt's digest and length, never its text, so a record can\n * be kept and shared where the words cannot.\n *\n * Three things are kept apart from zero throughout: a label nobody gave, a\n * measure no event reported, and a change whose outcome nobody supplied. A\n * correction is counted after the fact as an outcome. Nothing here predicts one.\n */\n\nimport type { InvocationChanges } from '../procedure-registry/change-outcome'\n\nexport type IntentKind = 'task' | 'problem' | 'project' | 'information' | 'correction'\n\nexport const INTENT_KINDS: readonly IntentKind[] = [\n 'task',\n 'problem',\n 'project',\n 'information',\n 'correction',\n]\n\n/**\n * How a prompt says when it is finished. `stated`: the prompt names a done\n * line. `inferred`: it names none and the labeler supplied one. `none`: the\n * labeler found none to state or infer.\n */\nexport type IntentDoneBasis = 'stated' | 'inferred' | 'none'\n\n/**\n * What a labeler says of one typed turn. Each field is the labeler's or null:\n * a labeler that did not look says null, and null is never read as `false`.\n */\nexport interface IntentTurnLabel {\n /** Who labeled: a model, a lexical rule, a person. Carried onto the record. */\n source: string\n kind: IntentKind | null\n done: IntentDoneBasis | null\n /** The turn tells the agent its last work was wrong. */\n correction: boolean | null\n /** The turn asks again for what an open intent already asked. */\n reask: boolean | null\n}\n\n/** One typed turn, as a labeler reads it. The text is private: do not keep it. */\nexport interface IntentTurn {\n harness: string\n sessionId: string\n /** Position among the session's typed turns, from 0. */\n index: number\n at: string | null\n text: string\n /** The turn before this one in the session, when there is one. */\n previousText: string | null\n}\n\n/** The labeler is the caller's: a model pass, a lexical rule, a person's labels looked up by turn. */\nexport type IntentLabeler = (\n turn: IntentTurn,\n) => IntentTurnLabel | null | Promise<IntentTurnLabel | null>\n\nexport interface IntentCost {\n /** Tokens of the model calls in the intent's span; null where any call recorded no usage, or there was none. */\n tokens: number | null\n /** null where any call could not be priced: unknown, not free. */\n usd: number | null\n /** From the intent's turn to the turn that closed it, or the session's end. */\n wallMs: number | null\n modelCalls: number\n}\n\nexport type IntentClosedBy = 'next-intent' | 'session-end'\n\n/** What the evidence for `reachedDone` is. `none`: nothing says. */\nexport type IntentEndEvidence = 'change-outcome' | 'moved-on' | 'none'\n\nexport interface IntentEnd {\n /** The opening turn and every turn attached to it. */\n userTurns: number\n /** Corrections after the opening turn. null when a following turn's label did not say. */\n corrections: number | null\n reasks: number | null\n closedBy: IntentClosedBy\n /**\n * The intent reached its done line. From the outcome of its changes when they\n * have one (merged, and no fix within the window); else true when the person\n * moved on to another intent; else null. A session that simply ends says nothing.\n */\n reachedDone: boolean | null\n /** The change the intent produced did not merge. Never inferred from silence. */\n abandoned: boolean | null\n evidence: IntentEndEvidence\n}\n\nexport interface IntentRecord {\n /** sha256 of the harness, session and the opening turn's id. */\n intentId: string\n harness: string\n sessionId: string\n at: string | null\n prompt: { sha256: string; chars: number }\n /** The opening turn's label; null when no labeler said anything of it. */\n label: Pick<IntentTurnLabel, 'source' | 'kind' | 'done'> | null\n /** Registry keys of the procedure versions invoked in the intent's span, in this session and in the subagents it spawned. */\n procedures: string[]\n cost: IntentCost\n end: IntentEnd\n /** The changes produced in the intent's span, in this session, with the outcomes supplied for them. */\n changes: InvocationChanges\n}\n\nexport interface IntentKindSummary {\n /** null: intents no labeler gave a kind. */\n kind: IntentKind | null\n intents: number\n /** `reachedDone` is known. */\n knownEnd: number\n knownEndShare: number | null\n /** The correction count is known. */\n knownCorrections: number\n joinedToChange: number\n withChangeOutcome: number\n}\n\nexport interface IntentReport {\n intents: IntentRecord[]\n summary: {\n intents: number\n sessionsWithTurns: number\n /** Sessions whose reader does not tell a person's turn from other messages. */\n sessionsWithoutTurns: number\n /** Intents whose opening turn a labeler labeled. */\n labeled: number\n knownEnd: number\n knownEndShare: number | null\n byKind: IntentKindSummary[]\n }\n notes: string[]\n}\n","/** Join intent drafts to the procedure versions that served them and the outcomes of their changes. */\n\nimport type { ChangeOutcomeIndex, InvocationChanges } from '../procedure-registry/change-outcome'\nimport { instant } from '../skill-usage/report'\nimport { INTENT_KINDS, type IntentKind, type IntentRecord, type IntentReport } from './contract'\nimport { changesReachedDone, type IntentDraft } from './derive'\n\n/** One counted procedure invocation, placed in its session. */\nexport interface SessionInvocation {\n /** The event's position in the session. */\n index: number\n at: string | null\n /** The registry key of the version that ran. */\n key: string\n}\n\nexport interface SessionIntents {\n sessionId: string\n parentSessionId: string | null\n /** null: the reader records no typed turns. */\n drafts: IntentDraft[] | null\n invocations: SessionInvocation[]\n}\n\nconst NOTES = [\n 'Intents are cut from typed turns: a turn a labeler calls a correction or a re-ask attaches to the open intent, and any other turn, labeled or not, opens a new one. Without labels every turn is its own intent and no intent knows its corrections.',\n 'An intent joins the changes whose tool call lies in its span, in its own session only. Work and changes in subagents count toward the procedures that served it, by time, and not toward its cost or changes.',\n 'reachedDone comes from the outcome of the intent’s changes when they have one, else is true when the person moved on to another intent, else unknown. A session that ends says nothing.',\n]\n\nfunction joinChanges(refs: string[] | undefined, outcomes: ChangeOutcomeIndex): InvocationChanges {\n if (refs === undefined) return { status: 'not-recorded' }\n if (refs.length === 0) return { status: 'none' }\n return {\n status: 'joined',\n refs,\n outcomes: refs.flatMap((ref) => {\n const reading = outcomes.byRef.get(ref)\n return reading === undefined ? [] : [reading]\n }),\n }\n}\n\nexport function buildIntentReport(\n sessions: readonly SessionIntents[],\n outcomes: ChangeOutcomeIndex,\n): IntentReport {\n const byId = new Map(sessions.map((session) => [session.sessionId, session]))\n // Work in a subagent belongs to the intents of the sessions that spawned it, when it ran inside their span.\n const inherited = new Map<IntentDraft, Set<string>>()\n for (const session of sessions) {\n for (\n let parent = session.parentSessionId, hops = 0;\n parent !== null && hops < 64;\n parent = byId.get(parent)?.parentSessionId ?? null, hops++\n ) {\n for (const draft of byId.get(parent)?.drafts ?? []) {\n const from = instant(draft.window.from)\n const to = instant(draft.window.to)\n if (from === null) continue\n for (const invocation of session.invocations) {\n const at = instant(invocation.at)\n if (at === null || at < from || (to !== null && at >= to)) continue\n const keys = inherited.get(draft) ?? new Set<string>()\n keys.add(invocation.key)\n inherited.set(draft, keys)\n }\n }\n }\n }\n\n const intents: IntentRecord[] = []\n let sessionsWithTurns = 0\n let sessionsWithoutTurns = 0\n for (const session of sessions) {\n if (session.drafts === null) {\n sessionsWithoutTurns += 1\n continue\n }\n sessionsWithTurns += 1\n for (const draft of session.drafts) {\n const keys = new Set(inherited.get(draft))\n for (const invocation of session.invocations) {\n if (invocation.index >= draft.span.from && invocation.index < draft.span.to) {\n keys.add(invocation.key)\n }\n }\n const changes = joinChanges(draft.changeRefs, outcomes)\n const fromChanges = changesReachedDone(changes)\n const movedOn = draft.record.end.closedBy === 'next-intent'\n const evidence =\n fromChanges.reachedDone !== null ? 'change-outcome' : movedOn ? 'moved-on' : 'none'\n intents.push({\n ...draft.record,\n procedures: [...keys].sort(),\n end: {\n ...draft.record.end,\n reachedDone: fromChanges.reachedDone ?? (movedOn ? true : null),\n abandoned: fromChanges.abandoned,\n evidence,\n },\n changes,\n })\n }\n }\n\n const kinds: Array<IntentKind | null> = [...INTENT_KINDS, null]\n const share = (part: number, whole: number): number | null => (whole === 0 ? null : part / whole)\n const known = (record: IntentRecord): boolean => record.end.reachedDone !== null\n return {\n intents,\n summary: {\n intents: intents.length,\n sessionsWithTurns,\n sessionsWithoutTurns,\n labeled: intents.filter((record) => record.label !== null).length,\n knownEnd: intents.filter(known).length,\n knownEndShare: share(intents.filter(known).length, intents.length),\n byKind: kinds.map((kind) => {\n const of = intents.filter((record) => (record.label?.kind ?? null) === kind)\n return {\n kind,\n intents: of.length,\n knownEnd: of.filter(known).length,\n knownEndShare: share(of.filter(known).length, of.length),\n knownCorrections: of.filter((record) => record.end.corrections !== null).length,\n joinedToChange: of.filter((record) => record.changes.status === 'joined').length,\n withChangeOutcome: of.filter(\n (record) => record.changes.status === 'joined' && record.changes.outcomes.length > 0,\n ).length,\n }\n }),\n },\n notes: [...NOTES],\n }\n}\n","/**\n * What happened to a change, supplied by the caller, and the join that attaches\n * it to the procedure invocations of the session that produced the change.\n *\n * A turn-level signal predicts an operator's correction poorly; a change is the\n * unit that has an outcome. The caller says, per change (a commit or a pull\n * request, named by one reference string), whether it merged, whether its gate\n * passed on the first try, and whether a fix to it followed. Any of the three\n * can be unknown, and unknown is never read as `false`.\n */\n\nimport { ValidationError } from '../errors'\n\n/** A later merged change that fixes this one lands within this many days. */\nexport const HOTFIX_WINDOW_DAYS = 7\n\nexport interface ChangeOutcome {\n /** The change's reference, as the session reader names it: `owner/repo#123` for a pull request. */\n ref: string\n /** null: not known. */\n merged: boolean | null\n /** The gate passed on its first run. null: no gate result, or not known. */\n gateGreenFirstTry: boolean | null\n /**\n * A later merged change fixed this one within `hotfixWindowDays`. `false`\n * asserts the whole window was observed with no such fix; null means the\n * window was still open or the fixes were not searched.\n */\n hotfixed: boolean | null\n /** The window `hotfixed` was judged over. Must be {@link HOTFIX_WINDOW_DAYS}. */\n hotfixWindowDays: number\n}\n\n/** A change's outcome as the registry reads it: each field is the caller's, or unknown. */\nexport interface ChangeOutcomeReading {\n ref: string\n merged: boolean | null\n gateGreenFirstTry: boolean | null\n hotfixed: boolean | null\n}\n\nexport interface ChangeOutcomeIndex {\n byRef: ReadonlyMap<string, ChangeOutcomeReading>\n /** Outcomes whose window is not the 7-day one: their `hotfixed` is read as unknown. */\n otherWindow: number\n duplicates: number\n}\n\n/**\n * Index outcomes by change reference. An outcome judged over another window\n * keeps `merged` and `gateGreenFirstTry` and loses `hotfixed`: a 3-day and a\n * 14-day \"no fix\" are different claims, and the registry has one definition.\n * Two outcomes for one reference must agree; a reference given twice with\n * different readings throws.\n */\nexport function indexChangeOutcomes(outcomes: Iterable<ChangeOutcome>): ChangeOutcomeIndex {\n const byRef = new Map<string, ChangeOutcomeReading>()\n let otherWindow = 0\n let duplicates = 0\n for (const outcome of outcomes) {\n if (typeof outcome.ref !== 'string' || outcome.ref === '') {\n throw new ValidationError('a change outcome needs a non-empty ref')\n }\n const sameWindow = outcome.hotfixWindowDays === HOTFIX_WINDOW_DAYS\n if (!sameWindow) otherWindow += 1\n const reading: ChangeOutcomeReading = {\n ref: outcome.ref,\n merged: outcome.merged,\n gateGreenFirstTry: outcome.gateGreenFirstTry,\n hotfixed: sameWindow ? outcome.hotfixed : null,\n }\n const known = byRef.get(outcome.ref)\n if (known !== undefined) {\n duplicates += 1\n if (JSON.stringify(known) !== JSON.stringify(reading)) {\n throw new ValidationError(`change ${outcome.ref} has two different outcomes`)\n }\n continue\n }\n byRef.set(outcome.ref, reading)\n }\n return { byRef, otherWindow, duplicates }\n}\n\n/** One invocation's changes with their outcomes. */\nexport type InvocationChanges =\n /** The session reader does not record changes: the join has no evidence either way. */\n | { status: 'not-recorded' }\n /** The reader looked, and neither the session nor an ancestor produced a change. */\n | { status: 'none' }\n | {\n status: 'joined'\n /** Changes of the invocation's own session and of the sessions that spawned it. */\n refs: string[]\n /** Outcomes the caller supplied for those changes; a change absent here has none. */\n outcomes: ChangeOutcomeReading[]\n }\n\nexport interface SessionChanges {\n parentSessionId: string | null\n /** undefined: the reader does not record changes. */\n refs: readonly string[] | undefined\n}\n\n/**\n * The changes an invocation produced: those of its session, and of every\n * session that spawned it, since a subagent's work belongs to the change its\n * parent shipped. A session absent from `sessions` ends the walk, and a cycle\n * in the parent links is cut where it repeats.\n */\nexport function joinInvocationToChanges(\n sessionId: string,\n sessions: ReadonlyMap<string, SessionChanges>,\n outcomes: ChangeOutcomeIndex,\n): InvocationChanges {\n const refs = new Set<string>()\n let recorded = false\n const visited = new Set<string>()\n for (\n let current: string | null = sessionId;\n current !== null && !visited.has(current);\n current = sessions.get(current)?.parentSessionId ?? null\n ) {\n visited.add(current)\n const session = sessions.get(current)\n if (session?.refs === undefined) continue\n recorded = true\n for (const ref of session.refs) refs.add(ref)\n }\n if (!recorded) return { status: 'not-recorded' }\n if (refs.size === 0) return { status: 'none' }\n const sorted = [...refs].sort()\n return {\n status: 'joined',\n refs: sorted,\n outcomes: sorted.flatMap((ref) => {\n const reading = outcomes.byRef.get(ref)\n return reading === undefined ? [] : [reading]\n }),\n }\n}\n","/**\n * The procedure registry: a projection, not a service.\n *\n * A procedure is anything an agent can be given and have taken away: a skill, a\n * workflow, a workflow whose steps are workflows, or a skill whose object is\n * other procedures. A version of it is named by the sha256 of its materialized\n * files. This module reads search ledgers and recorded sessions and answers,\n * for each version: where it came from, every time it ran, what that cost, what\n * came of the change it was part of, and every decision taken on it.\n *\n * Nothing here writes. The search ledger stays the one record of a search and\n * the session records stay the one record of a session; the registry is the\n * join of the two on the version digest, rebuilt from them on demand.\n *\n * Three things are kept apart from zero throughout, as in the sources: a\n * measure no execution reported, a change whose outcome the caller did not\n * supply, and a session whose reader does not record changes.\n */\n\nimport type { SearchEdgeAttribution, SearchEdgeOperator } from '../campaign/search-ledger-types'\nimport type { SearchStateView } from '../campaign/search-state'\nimport type { SearchNode } from '../campaign/search-state-types'\nimport { ValidationError } from '../errors'\nimport type { IntentLabeler, IntentReport, IntentTurn } from '../intent-record/contract'\nimport { deriveSessionIntents } from '../intent-record/derive'\nimport { buildIntentReport, type SessionIntents } from '../intent-record/report'\nimport type {\n SkillInvocationEvent,\n SkillInvoker,\n SkillSessionSource,\n SkillUsageReportOptions,\n} from '../skill-usage'\nimport { afterInvocation, instant } from '../skill-usage/report'\nimport {\n type ChangeOutcome,\n type ChangeOutcomeIndex,\n type ChangeOutcomeReading,\n HOTFIX_WINDOW_DAYS,\n type InvocationChanges,\n indexChangeOutcomes,\n joinInvocationToChanges,\n type SessionChanges,\n} from './change-outcome'\n\n/** What a procedure is. The registry never infers it; the caller classifies, and an unclassified version says so. */\nexport type ProcedureKind = 'skill' | 'workflow' | 'higher-order-workflow' | 'operator-skill'\n\nexport interface ProcedureNodeIdentity {\n /** The version digest when the node's artifact is not the procedure's own bytes, for example a profile that mounts a skill. */\n digest?: string\n kind?: ProcedureKind\n name?: string\n}\n\nexport interface ProcedureRegistryInput {\n searches?: Iterable<SearchStateView>\n sessions?: SkillSessionSource\n outcomes?: Iterable<ChangeOutcome>\n}\n\nexport interface ProcedureRegistryOptions extends SkillUsageReportOptions {\n /** Which procedure a search node is. Default: the node's own artifact digest, unclassified. */\n procedureOfNode?: (node: SearchNode, search: SearchStateView) => ProcedureNodeIdentity | null\n /** What kind of procedure a session's skill is. Default: `skill`. */\n kindOfSkill?: (skill: string) => ProcedureKind\n /**\n * Cut each session's typed turns into intents and join them to the versions\n * and outcomes. Absent: no intents are derived. A labeler is the caller's;\n * without one every turn is an unlabeled intent.\n */\n intents?: { labeler?: IntentLabeler; ignore?: (turn: IntentTurn) => boolean }\n}\n\n/** A measure summed over the executions that reported it. */\nexport interface MeasureTotal {\n sum: number\n /** Executions that reported it. */\n measured: number\n /** Executions that did not: they are not in `sum`, and are not zero. */\n unmeasured: number\n}\n\nexport interface ExecutionMeasures {\n tokens: number | null\n /** null where no model call could be priced: unknown, not free. */\n usd: number | null\n wallMs: number | null\n}\n\nexport interface CellExecution extends ExecutionMeasures {\n source: 'search-cell'\n searchId: string\n nodeId: string\n cellId: string\n split: string\n stage: string\n /** `passed`, `failed` or `errored`; null for a cell never settled. */\n outcome: string | null\n score: number | null\n /**\n * How the cell's dollars are known. `measured`: `usd` is the charge. `subscription`: every\n * attempt ran on a seat that bills nothing per call, so there is no dollar figure and `usd`\n * is null by design, neither unknown nor a measured zero. `unknown`: no charge was read.\n */\n costBasis: 'measured' | 'subscription' | 'unknown'\n}\n\nexport interface SessionExecution extends ExecutionMeasures {\n source: 'session'\n harness: string\n sessionId: string\n callId: string\n skill: string\n invoker: SkillInvoker\n at: string | null\n /** The harness refused the call; null when no result is recorded. */\n failed: boolean | null\n /** What the invocation's changes came to. Tokens, cost and wall time run from the invocation to the session's end. */\n changes: InvocationChanges\n}\n\nexport type ProcedureExecution = CellExecution | SessionExecution\n\nexport interface ProcedureEdge {\n searchId: string\n edgeId: string\n operator: SearchEdgeOperator\n attribution: SearchEdgeAttribution\n proposer: { kind: string; name: string } | null\n parents: Array<{ searchId: string; nodeId: string; digest: string | null }>\n /** A later edge into a node that already existed: the same content proposed again. */\n reproposal: boolean\n}\n\nexport interface ProcedureDecision {\n searchId: string\n nodeId: string\n source: 'node-decided' | 'claim'\n /** `advanced`, `pruned`, `invalid`, `finalist`, `selected`, `rejected`; or the claim's `ship`, `hold`, `test-cannot-resolve`. */\n status: string\n rung: number | null\n rule: string | null\n reason: string\n /** The node's latest decision in its search; earlier ones are history. */\n current: boolean\n}\n\nexport interface SearchAppearance {\n searchId: string\n nodeId: string\n subject: string\n closed: boolean\n /** The node's latest decision, or null while undecided. */\n status: string | null\n}\n\nexport interface ChangeCounts {\n yes: number\n no: number\n /** No outcome supplied, or that field unknown. */\n unknown: number\n}\n\nexport interface ProcedureChanges {\n /** Counted invocations in sessions. */\n invocations: number\n joined: number\n none: number\n notRecorded: number\n /** Changes the joined invocations are part of, each counted once. */\n distinctChanges: number\n /** Of those, the changes the caller supplied an outcome for. */\n withOutcome: number\n merged: ChangeCounts\n gateGreenFirstTry: ChangeCounts\n hotfixed: ChangeCounts\n}\n\nexport interface ProcedureVersion {\n /** `sha256:<hex>`, or `unversioned:<skill>` when no invocation recorded the text it loaded. */\n key: string\n digest: string | null\n names: string[]\n /** null: unclassified, never guessed. */\n kind: ProcedureKind | null\n /** Digests of the lineage parents. A parent whose digest is unknown is absent here and null in its edge. */\n parents: string[]\n edges: ProcedureEdge[]\n searches: SearchAppearance[]\n decisions: ProcedureDecision[]\n cells: {\n count: number\n passed: number\n failed: number\n errored: number\n /** Cells whose dollars are a subscription seat's: a known basis with no figure, counted in neither `usd.measured` nor `usd.unmeasured`. */\n subscription: number\n tokens: MeasureTotal\n usd: MeasureTotal\n wallMs: MeasureTotal\n }\n sessions: {\n invocations: number\n tokens: MeasureTotal\n usd: MeasureTotal\n wallMs: MeasureTotal\n changes: ProcedureChanges\n }\n executions: ProcedureExecution[]\n}\n\nexport interface ChangeJoinSummary {\n /** The definition of \"needed a hot-fix\" every outcome was held to. */\n hotfixWindowDays: number\n invocations: number\n joined: number\n none: number\n notRecorded: number\n /** joined / invocations; null when there are none. This is the share the program's first check reads. */\n joinedShare: number | null\n /** Joined invocations with an outcome for at least one of their changes. */\n withOutcome: number\n withOutcomeShare: number | null\n distinctChanges: number\n outcomesSupplied: number\n outcomesInWrongWindow: number\n}\n\nexport interface ProcedureRegistry {\n searches: { read: number; closed: number }\n sessions: { read: number; unreadable: number; withInvocation: number }\n invocations: number\n changeJoin: ChangeJoinSummary\n versions: ProcedureVersion[]\n /** Present when the options asked for intents. */\n intents: IntentReport | null\n unreadable: Array<{ source: string; error: string }>\n notes: string[]\n}\n\nconst NOTES = [\n 'Session executions measure from the invocation to the end of its session, as `skill-usage` does, so a session that invokes several procedures counts its later work under each and the totals overlap across versions.',\n 'Search-cell and session measures are different quantities (a cell is one task, a session is open-ended) and are never added together.',\n 'An invocation joins the changes of its own session and of the sessions that spawned it. It joins every change the session produced, before and after the invocation.',\n]\n\ninterface Builder {\n key: string\n digest: string | null\n names: Set<string>\n kind: ProcedureKind | null\n parents: Set<string>\n edges: ProcedureEdge[]\n searches: SearchAppearance[]\n decisions: ProcedureDecision[]\n executions: ProcedureExecution[]\n}\n\nfunction normalizeDigest(value: string): string {\n const hex = value.startsWith('sha256:') ? value.slice('sha256:'.length) : value\n if (!/^[0-9a-f]{64}$/.test(hex)) {\n throw new ValidationError(`a procedure digest is a sha256, got ${JSON.stringify(value)}`)\n }\n return `sha256:${hex}`\n}\n\nfunction compareText(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0\n}\n\nfunction emptyMeasure(): MeasureTotal {\n return { sum: 0, measured: 0, unmeasured: 0 }\n}\n\nfunction addMeasure(total: MeasureTotal, value: number | null): void {\n if (value === null) {\n total.unmeasured += 1\n } else {\n total.sum += value\n total.measured += 1\n }\n}\n\nfunction emptyCounts(): ChangeCounts {\n return { yes: 0, no: 0, unknown: 0 }\n}\n\nfunction count(counts: ChangeCounts, value: boolean | null): void {\n if (value === null) counts.unknown += 1\n else if (value) counts.yes += 1\n else counts.no += 1\n}\n\n/** The caller's reading of one change field, across the readings of every outcome the change has. */\nfunction pick(\n readings: ChangeOutcomeReading | undefined,\n field: 'merged' | 'gateGreenFirstTry' | 'hotfixed',\n): boolean | null {\n return readings === undefined ? null : readings[field]\n}\n\nfunction summarizeChanges(executions: readonly SessionExecution[], index: ChangeOutcomeIndex) {\n const changes: ProcedureChanges = {\n invocations: executions.length,\n joined: 0,\n none: 0,\n notRecorded: 0,\n distinctChanges: 0,\n withOutcome: 0,\n merged: emptyCounts(),\n gateGreenFirstTry: emptyCounts(),\n hotfixed: emptyCounts(),\n }\n const refs = new Set<string>()\n for (const execution of executions) {\n const joined = execution.changes\n if (joined.status === 'joined') {\n changes.joined += 1\n for (const ref of joined.refs) refs.add(ref)\n } else if (joined.status === 'none') {\n changes.none += 1\n } else {\n changes.notRecorded += 1\n }\n }\n changes.distinctChanges = refs.size\n for (const ref of [...refs].sort(compareText)) {\n const reading = index.byRef.get(ref)\n if (reading !== undefined) changes.withOutcome += 1\n count(changes.merged, pick(reading, 'merged'))\n count(changes.gateGreenFirstTry, pick(reading, 'gateGreenFirstTry'))\n count(changes.hotfixed, pick(reading, 'hotfixed'))\n }\n return changes\n}\n\nclass Registry {\n private readonly builders = new Map<string, Builder>()\n\n builder(key: string): Builder {\n let builder = this.builders.get(key)\n if (builder === undefined) {\n builder = {\n key,\n digest: key.startsWith('sha256:') ? key : null,\n names: new Set(),\n kind: null,\n parents: new Set(),\n edges: [],\n searches: [],\n decisions: [],\n executions: [],\n }\n this.builders.set(key, builder)\n }\n return builder\n }\n\n all(): Builder[] {\n return [...this.builders.values()]\n }\n}\n\ninterface NodeRef {\n searchId: string\n nodeId: string\n}\n\nconst nodeKey = (searchId: string, nodeId: string): string => `${searchId}\\u0000${nodeId}`\n\nfunction addSearch(\n registry: Registry,\n search: SearchStateView,\n keys: ReadonlyMap<string, string>,\n options: ProcedureRegistryOptions,\n): void {\n const subject = search.header?.subject ?? ''\n const closed = search.closed !== null\n const claim = search.closed?.claim ?? null\n const rootNodeId = search.rootNodeId\n\n for (const node of search.nodes()) {\n const key = keys.get(nodeKey(search.searchId, node.nodeId)) as string\n const identity = options.procedureOfNode?.(node, search) ?? null\n const builder = registry.builder(key)\n if (identity?.kind !== undefined) builder.kind = identity.kind\n if (identity?.name !== undefined) builder.names.add(identity.name)\n const latest = node.decisions.at(-1)\n builder.searches.push({\n searchId: search.searchId,\n nodeId: node.nodeId,\n subject,\n closed,\n status: latest === undefined ? null : latest.decision.status,\n })\n\n const resolve = (ref: NodeRef): string | null => {\n const parentKey = keys.get(nodeKey(ref.searchId, ref.nodeId))\n return parentKey?.startsWith('sha256:') ? parentKey : null\n }\n for (const parent of node.parents) {\n const digest = resolve(parent)\n if (digest !== null) builder.parents.add(digest)\n }\n node.edgeIds.forEach((edgeId, position) => {\n const edge = search.edge(edgeId)\n if (edge === undefined) return\n builder.edges.push({\n searchId: search.searchId,\n edgeId,\n operator: edge.operator,\n attribution: edge.attribution,\n proposer:\n edge.proposer === null ? null : { kind: edge.proposer.kind, name: edge.proposer.name },\n parents: edge.parents.map((parent) => ({\n searchId: parent.searchId,\n nodeId: parent.nodeId,\n digest: resolve(parent),\n })),\n reproposal: position > 0,\n })\n })\n\n node.decisions.forEach((record, position) => {\n builder.decisions.push({\n searchId: search.searchId,\n nodeId: node.nodeId,\n source: 'node-decided',\n status: record.decision.status,\n rung: record.decision.status === 'advanced' ? record.decision.rung : null,\n rule: record.rule,\n reason: record.reason,\n current: position === node.decisions.length - 1,\n })\n })\n\n for (const cell of search.cells({ nodeId: node.nodeId })) {\n // A cell that never ran, or never settled, is not an execution.\n if (cell.attempts === 0) continue\n const onSeat = cell.subscriptionAttempts === cell.attempts\n builder.executions.push({\n source: 'search-cell',\n searchId: search.searchId,\n nodeId: node.nodeId,\n cellId: cell.cellId,\n split: cell.split,\n stage: cell.stage,\n outcome: cell.outcome,\n score: cell.score,\n tokens: cell.tokensKnown\n ? cell.tokens.inputTokens + cell.tokens.outputTokens + cell.tokens.cachedTokens\n : null,\n usd: cell.costKnown && !onSeat ? cell.spentUsd : null,\n costBasis: !cell.costKnown ? 'unknown' : onSeat ? 'subscription' : 'measured',\n wallMs: cell.wallKnown ? cell.wallMs : null,\n })\n }\n }\n\n // The claim is the search's own ship-or-hold decision. A hold or an\n // unresolved test keeps the root, so that is the node it is about.\n if (claim !== null) {\n const nodeId = claim.selected ?? rootNodeId\n const key = nodeId === null ? undefined : keys.get(nodeKey(search.searchId, nodeId))\n if (nodeId !== null && key !== undefined) {\n registry.builder(key).decisions.push({\n searchId: search.searchId,\n nodeId,\n source: 'claim',\n status: claim.decision,\n rung: null,\n rule: claim.rule.uri,\n reason: claim.reason,\n current: true,\n })\n }\n }\n}\n\ninterface PendingInvocation {\n builderKey: string\n sessionId: string\n harness: string\n event: SkillInvocationEvent\n measures: ExecutionMeasures\n}\n\n/**\n * Build the registry from search ledgers, recorded sessions and the outcomes of\n * the changes those sessions produced. Any of the three may be absent.\n *\n * An invocation is counted once per call id across the whole source, and with\n * `sinceMs` only invocations at or after it count, exactly as `skill-usage`\n * counts them; an undated invocation cannot be placed in the window and is\n * left out. Versions are ordered by executions, most first, then by key.\n */\nexport async function buildProcedureRegistry(\n input: ProcedureRegistryInput,\n options: ProcedureRegistryOptions = {},\n): Promise<ProcedureRegistry> {\n if (options.sinceMs !== undefined && !Number.isFinite(options.sinceMs)) {\n throw new ValidationError(\n `buildProcedureRegistry: sinceMs must be finite, got ${options.sinceMs}`,\n )\n }\n const outcomes = indexChangeOutcomes(input.outcomes ?? [])\n const registry = new Registry()\n\n const searches = [...(input.searches ?? [])]\n const keys = new Map<string, string>()\n for (const search of searches) {\n for (const node of search.nodes()) {\n const identity = options.procedureOfNode?.(node, search) ?? null\n keys.set(\n nodeKey(search.searchId, node.nodeId),\n normalizeDigest(identity?.digest ?? node.artifactDigest),\n )\n }\n }\n for (const search of searches) addSearch(registry, search, keys, options)\n\n const sessionChanges = new Map<string, SessionChanges>()\n const pending: PendingInvocation[] = []\n const unreadable: Array<{ source: string; error: string }> = []\n const seenCalls = new Set<string>()\n const sessions = { read: 0, unreadable: 0, withInvocation: 0 }\n const intentSessions: SessionIntents[] = []\n\n const versionDigest = (event: SkillInvocationEvent): string | null => {\n if (event.version !== null) return event.version.bodySha256\n if (event.skillFile === null || options.readSkillFile === undefined) return null\n const file = options.readSkillFile(event.skillFile)\n return file.succeeded ? file.bodySha256 : null\n }\n\n for await (const read of input.sessions ?? []) {\n if (!read.succeeded) {\n sessions.unreadable += 1\n unreadable.push({ source: read.source, error: read.error })\n continue\n }\n const session = read.value\n sessions.read += 1\n sessionChanges.set(session.sessionId, {\n parentSessionId: session.parentSessionId,\n refs: session.changes?.map((change) => change.ref),\n })\n let counted = false\n const placed: SessionIntents['invocations'] = []\n session.events.forEach((event, position) => {\n if (event.kind !== 'skill') return\n if (seenCalls.has(event.callId)) return\n seenCalls.add(event.callId)\n if (options.sinceMs !== undefined) {\n const at = instant(event.at)\n if (at === null || at < options.sinceMs) return\n }\n counted = true\n const hex = versionDigest(event)\n const key = hex === null ? `unversioned:${event.skill}` : normalizeDigest(hex)\n const builder = registry.builder(key)\n builder.names.add(event.skill)\n builder.kind ??= options.kindOfSkill?.(event.skill) ?? 'skill'\n placed.push({ index: position, at: event.at, key })\n const after = afterInvocation(session, position, event.at, options)\n pending.push({\n builderKey: key,\n sessionId: session.sessionId,\n harness: session.harness,\n event,\n measures: {\n tokens:\n after.modelCalls > 0 && after.modelCallsWithoutUsage === 0 ? after.tokens.total : null,\n usd: after.pricedModelCalls > 0 && after.unpricedModelCalls === 0 ? after.costUsd : null,\n wallMs: after.wallMs,\n },\n })\n })\n if (counted) sessions.withInvocation += 1\n if (options.intents !== undefined) {\n intentSessions.push({\n sessionId: session.sessionId,\n parentSessionId: session.parentSessionId,\n drafts: await deriveSessionIntents(\n session,\n options.intents.labeler,\n options,\n options.intents.ignore,\n ),\n invocations: placed,\n })\n }\n }\n\n const joins = { joined: 0, none: 0, notRecorded: 0, withOutcome: 0 }\n const joinedRefs = new Set<string>()\n for (const invocation of pending) {\n const { event } = invocation\n const changes = joinInvocationToChanges(invocation.sessionId, sessionChanges, outcomes)\n if (changes.status === 'joined') {\n joins.joined += 1\n for (const ref of changes.refs) joinedRefs.add(ref)\n if (changes.outcomes.length > 0) joins.withOutcome += 1\n } else if (changes.status === 'none') {\n joins.none += 1\n } else {\n joins.notRecorded += 1\n }\n registry.builder(invocation.builderKey).executions.push({\n source: 'session',\n harness: invocation.harness,\n sessionId: invocation.sessionId,\n callId: event.callId,\n skill: event.skill,\n invoker: event.invoker,\n at: event.at,\n failed: event.failed,\n ...invocation.measures,\n changes,\n })\n }\n\n const versions = registry.all().map((builder): ProcedureVersion => {\n const cells = {\n count: 0,\n passed: 0,\n failed: 0,\n errored: 0,\n subscription: 0,\n tokens: emptyMeasure(),\n usd: emptyMeasure(),\n wallMs: emptyMeasure(),\n }\n const sessionRuns = {\n invocations: 0,\n tokens: emptyMeasure(),\n usd: emptyMeasure(),\n wallMs: emptyMeasure(),\n }\n const runs: SessionExecution[] = []\n for (const execution of builder.executions) {\n if (execution.source === 'search-cell') {\n cells.count += 1\n if (execution.outcome === 'passed') cells.passed += 1\n else if (execution.outcome === 'failed') cells.failed += 1\n else if (execution.outcome === 'errored') cells.errored += 1\n addMeasure(cells.tokens, execution.tokens)\n if (execution.costBasis === 'subscription') cells.subscription += 1\n else addMeasure(cells.usd, execution.usd)\n addMeasure(cells.wallMs, execution.wallMs)\n } else {\n sessionRuns.invocations += 1\n addMeasure(sessionRuns.tokens, execution.tokens)\n addMeasure(sessionRuns.usd, execution.usd)\n addMeasure(sessionRuns.wallMs, execution.wallMs)\n runs.push(execution)\n }\n }\n return {\n key: builder.key,\n digest: builder.digest,\n names: [...builder.names].sort(compareText),\n kind: builder.kind,\n parents: [...builder.parents].sort(compareText),\n edges: builder.edges,\n searches: builder.searches,\n decisions: builder.decisions,\n cells,\n sessions: { ...sessionRuns, changes: summarizeChanges(runs, outcomes) },\n executions: builder.executions,\n }\n })\n versions.sort((a, b) => {\n const left = a.cells.count + a.sessions.invocations\n const right = b.cells.count + b.sessions.invocations\n return left !== right ? right - left : compareText(a.key, b.key)\n })\n\n const share = (part: number): number | null =>\n pending.length === 0 ? null : part / pending.length\n\n return {\n searches: { read: searches.length, closed: searches.filter((s) => s.closed !== null).length },\n sessions,\n invocations: pending.length,\n changeJoin: {\n hotfixWindowDays: HOTFIX_WINDOW_DAYS,\n invocations: pending.length,\n ...joins,\n joinedShare: share(joins.joined),\n withOutcomeShare: share(joins.withOutcome),\n distinctChanges: joinedRefs.size,\n outcomesSupplied: outcomes.byRef.size,\n outcomesInWrongWindow: outcomes.otherWindow,\n },\n versions,\n intents: options.intents === undefined ? null : buildIntentReport(intentSessions, outcomes),\n unreadable,\n notes: [...NOTES],\n }\n}\n","/** The registry as a short table: one row per procedure version. */\n\nimport type { MeasureTotal, ProcedureRegistry, ProcedureVersion } from './registry'\n\nfunction percent(share: number | null): string {\n return share === null ? 'n/a' : `${(share * 100).toFixed(1)}%`\n}\n\n/** A measure's sum, with how many executions did not report it. */\nfunction measure(total: MeasureTotal, digits = 0): string {\n if (total.measured === 0) return total.unmeasured === 0 ? '-' : 'unknown'\n const text = total.sum.toFixed(digits)\n return total.unmeasured === 0 ? text : `${text}+${total.unmeasured}?`\n}\n\nfunction digest(version: ProcedureVersion): string {\n return version.digest === null ? '(no version)' : version.digest.slice(7, 19)\n}\n\nfunction decided(version: ProcedureVersion): string {\n const latest = version.decisions.filter((decision) => decision.current)\n return latest.length === 0 ? '-' : [...new Set(latest.map((d) => d.status))].join(',')\n}\n\nexport function renderProcedureRegistryTable(registry: ProcedureRegistry, limit = 30): string {\n const join = registry.changeJoin\n const lines = [\n `${registry.versions.length} procedure versions; ${registry.invocations} invocations in ${registry.sessions.read} sessions (${registry.sessions.unreadable} unreadable); ${registry.searches.read} searches`,\n `joined to a change: ${join.joined} of ${join.invocations} invocations (${percent(join.joinedShare)}); none ${join.none}, not recorded ${join.notRecorded}`,\n `with an outcome for a change: ${join.withOutcome} (${percent(join.withOutcomeShare)}); ${join.distinctChanges} distinct changes, ${join.outcomesSupplied} outcomes supplied (hot-fix window ${join.hotfixWindowDays} days)`,\n `cells on a subscription seat (a known basis with no dollar figure): ${registry.versions.reduce((n, v) => n + v.cells.subscription, 0)}`,\n '',\n 'version kind names cells runs chg-joined merged y/n/? hotfix y/n/? tokens(runs) decided',\n ]\n for (const version of registry.versions.slice(0, limit)) {\n const changes = version.sessions.changes\n const counts = (c: { yes: number; no: number; unknown: number }): string =>\n `${c.yes}/${c.no}/${c.unknown}`\n lines.push(\n [\n digest(version).padEnd(13),\n (version.kind ?? 'unclassified').padEnd(11),\n version.names.join(',').slice(0, 30).padEnd(30),\n String(version.cells.count).padStart(5),\n String(version.sessions.invocations).padStart(5),\n String(changes.joined).padStart(10),\n counts(changes.merged).padStart(13),\n counts(changes.hotfixed).padStart(13),\n measure(version.sessions.tokens).padStart(13),\n decided(version),\n ].join(' '),\n )\n }\n if (registry.versions.length > limit) {\n lines.push(`... ${registry.versions.length - limit} more versions in the JSON`)\n }\n const intents = registry.intents\n if (intents !== null) {\n const summary = intents.summary\n lines.push(\n '',\n `${summary.intents} intents in ${summary.sessionsWithTurns} sessions (${summary.sessionsWithoutTurns} record no typed turns); ${summary.labeled} labeled; known end ${summary.knownEnd} (${percent(summary.knownEndShare)})`,\n 'kind intents known-end share corrections-known joined-to-change with-outcome',\n )\n for (const row of summary.byKind) {\n if (row.intents === 0) continue\n lines.push(\n [\n (row.kind ?? 'unlabeled').padEnd(12),\n String(row.intents).padStart(8),\n String(row.knownEnd).padStart(10),\n percent(row.knownEndShare).padStart(7),\n String(row.knownCorrections).padStart(18),\n String(row.joinedToChange).padStart(17),\n String(row.withChangeOutcome).padStart(13),\n ].join(' '),\n )\n }\n for (const note of intents.notes) lines.push('', `note: ${note}`)\n }\n for (const note of registry.notes) lines.push('', `note: ${note}`)\n return `${lines.join('\\n')}\\n`\n}\n","/**\n * `agent-eval procedure-registry <sessions-dir>` prints the procedure registry\n * for a directory of Claude Code transcripts (or, with `--harness codex`, Codex\n * rollouts) and any number of search ledgers.\n *\n * `--change-ledger <file>` (repeatable) names a change ledger, the harness's own\n * record of each commit and pull request a session made (see\n * `src/skill-usage/change-ledger.ts`). A session the ledger observed has exactly\n * the changes it lists; a session it never saw has only what its transcript\n * shows, and none recorded when the transcript shows none.\n *\n * `--outcomes <file>` names a JSON array of {@link ChangeOutcome}: what the\n * caller knows of each change the sessions produced. Without it every change is\n * joined and none has an outcome. The JSON registry goes to stdout and the\n * short table to stderr, as `skill-usage` does.\n *\n * Exit codes: 2 for a usage error, 1 when a directory or ledger cannot be\n * read, 0 after the registry was written.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { replaySearchLedgerText } from '../campaign/search-ledger'\nimport type { SearchStateView } from '../campaign/search-state'\nimport type { CustomTokenPricing } from '../cost-ledger/contract'\nimport { errorMessage } from '../errors'\nimport type { IntentLabeler, IntentTurn } from '../intent-record/contract'\nimport { readChangeLedger, withChangeLedger } from '../skill-usage/change-ledger'\nimport {\n harnessSkillSessions,\n parseHarness,\n parseSince,\n readPricingFile,\n type SessionHarness,\n} from '../skill-usage/command'\nimport { readSkillFile } from '../skill-usage/skill-file'\nimport type { ChangeOutcome } from './change-outcome'\nimport { buildProcedureRegistry } from './registry'\nimport { renderProcedureRegistryTable } from './render'\n\ntype Format = 'both' | 'json' | 'table'\nconst FORMATS: readonly Format[] = ['both', 'json', 'table']\n\nconst USAGE =\n 'usage: agent-eval procedure-registry <sessions-dir> [--harness claude-code|codex] [--ledger <search-ledger.jsonl>]... [--since <7d|36h|90m|ISO time>] [--outcomes <changes.json>] [--change-ledger <changes.jsonl>]... [--intents [<labeler.mjs>]] [--format both|json|table] [--limit <rows>] [--pricing <rates.json>]'\n\nexport interface ProcedureRegistryCommandIo {\n readonly stdout: (text: string) => void\n readonly stderr: (text: string) => void\n /** The instant `--since 30d` counts back from. */\n readonly now?: () => number\n}\n\nconst PROCESS_IO: ProcedureRegistryCommandIo = {\n stdout: (text) => {\n process.stdout.write(text)\n },\n stderr: (text) => {\n process.stderr.write(text)\n },\n}\n\ninterface Args {\n directory: string\n harness: SessionHarness\n ledgers: string[]\n since: string | null\n outcomes: string | null\n changeLedgers: string[]\n intents: { labeler: string | null } | null\n format: Format\n limit: number\n pricing: string | null\n}\n\nfunction parseArgs(argv: readonly string[]): Args {\n const args: Args = {\n directory: '',\n harness: 'claude-code',\n ledgers: [],\n since: null,\n outcomes: null,\n changeLedgers: [],\n intents: null,\n format: 'both',\n limit: 30,\n pricing: null,\n }\n const value = (flag: string, index: number): string => {\n const raw = argv[index]\n if (raw === undefined) throw new Error(`${flag} expects a value`)\n return raw\n }\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i] as string\n if (arg === '--harness') args.harness = parseHarness(value(arg, ++i))\n else if (arg === '--ledger') args.ledgers.push(value(arg, ++i))\n else if (arg === '--since') args.since = value(arg, ++i)\n else if (arg === '--outcomes') args.outcomes = value(arg, ++i)\n else if (arg === '--change-ledger') args.changeLedgers.push(value(arg, ++i))\n else if (arg === '--intents') {\n // The labeler module is optional: a value that is not a flag.\n const next = argv[i + 1]\n const labeler = next !== undefined && !next.startsWith('--') ? next : null\n if (labeler !== null) i += 1\n args.intents = { labeler }\n } else if (arg === '--pricing') args.pricing = value(arg, ++i)\n else if (arg === '--format') {\n const raw = value(arg, ++i)\n if (!(FORMATS as readonly string[]).includes(raw)) {\n throw new Error(`--format expects one of ${FORMATS.join('|')}, got ${JSON.stringify(raw)}`)\n }\n args.format = raw as Format\n } else if (arg === '--limit') {\n const raw = Number(value(arg, ++i))\n if (!Number.isInteger(raw) || raw < 1) throw new Error('--limit expects a positive integer')\n args.limit = raw\n } else if (arg.startsWith('--')) {\n throw new Error(`unknown flag \"${arg}\"`)\n } else if (args.directory === '') {\n args.directory = arg\n } else {\n throw new Error(`unexpected argument \"${arg}\"`)\n }\n }\n if (args.directory === '') throw new Error('a sessions directory is required')\n return args\n}\n\n/** An outcomes file: a JSON array of change outcomes; each field is checked, so a typo is not read as unknown. */\nfunction readOutcomes(path: string): ChangeOutcome[] {\n const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))\n if (!Array.isArray(parsed)) throw new Error(`--outcomes ${path}: expected a JSON array`)\n const tri = (item: Record<string, unknown>, field: string, index: number): boolean | null => {\n const raw = item[field]\n if (raw === null || typeof raw === 'boolean') return raw\n throw new Error(`--outcomes ${path}: entry ${index} ${field} must be true, false or null`)\n }\n return parsed.map((entry: unknown, index) => {\n const item = (typeof entry === 'object' && entry !== null ? entry : {}) as Record<\n string,\n unknown\n >\n if (typeof item.ref !== 'string' || item.ref === '') {\n throw new Error(`--outcomes ${path}: entry ${index} needs a ref`)\n }\n if (typeof item.hotfixWindowDays !== 'number') {\n throw new Error(`--outcomes ${path}: entry ${index} needs hotfixWindowDays`)\n }\n return {\n ref: item.ref,\n merged: tri(item, 'merged', index),\n gateGreenFirstTry: tri(item, 'gateGreenFirstTry', index),\n hotfixed: tri(item, 'hotfixed', index),\n hotfixWindowDays: item.hotfixWindowDays,\n }\n })\n}\n\n/** A labeler module: its default export is an {@link IntentLabeler}. It lives with the caller, where the labels and the words they read do. */\nasync function loadLabeler(\n path: string,\n): Promise<{ labeler: IntentLabeler; ignore?: (turn: IntentTurn) => boolean }> {\n const loaded = (await import(pathToFileURL(resolve(path)).href)) as {\n default?: unknown\n ignore?: unknown\n }\n if (typeof loaded.default !== 'function') {\n throw new Error(`--intents ${path}: the module must export a labeler function as its default`)\n }\n return {\n labeler: loaded.default as IntentLabeler,\n ...(typeof loaded.ignore === 'function'\n ? { ignore: loaded.ignore as (turn: IntentTurn) => boolean }\n : {}),\n }\n}\n\nasync function readLedger(path: string): Promise<SearchStateView> {\n const text = await readFile(path, 'utf8')\n const first = JSON.parse(text.slice(0, Math.max(0, text.indexOf('\\n')))) as { searchId?: unknown }\n if (typeof first.searchId !== 'string') throw new Error(`${path} line 1 names no searchId`)\n return replaySearchLedgerText(text, first.searchId, path)\n}\n\nexport async function runProcedureRegistryCommand(\n argv: readonly string[],\n io: ProcedureRegistryCommandIo = PROCESS_IO,\n): Promise<number> {\n if (argv.includes('--help') || argv.includes('-h')) {\n io.stdout(`${USAGE}\\n`)\n return 0\n }\n let args: Args\n let sinceMs: number | undefined\n let rates: Map<string, CustomTokenPricing> | undefined\n let outcomes: ChangeOutcome[] = []\n try {\n args = parseArgs(argv)\n rates = args.pricing === null ? undefined : readPricingFile(resolve(args.pricing))\n sinceMs = args.since === null ? undefined : parseSince(args.since, (io.now ?? Date.now)())\n if (args.outcomes !== null) outcomes = readOutcomes(resolve(args.outcomes))\n } catch (error) {\n io.stderr(`${errorMessage(error)}\\n${USAGE}\\n`)\n return 2\n }\n try {\n const labeler =\n args.intents?.labeler == null ? undefined : await loadLabeler(args.intents.labeler)\n const searches = await Promise.all(args.ledgers.map((path) => readLedger(resolve(path))))\n const changeLedger =\n args.changeLedgers.length === 0\n ? undefined\n : await readChangeLedger(args.changeLedgers.map((path) => resolve(path)))\n if (changeLedger !== undefined && changeLedger.malformed > 0) {\n io.stderr(`change ledger: ${changeLedger.malformed} lines are not rows and were not read\\n`)\n }\n const transcripts = harnessSkillSessions(\n args.harness,\n resolve(args.directory),\n sinceMs === undefined ? {} : { sinceMs },\n )\n const registry = await buildProcedureRegistry(\n {\n searches,\n sessions:\n changeLedger === undefined ? transcripts : withChangeLedger(transcripts, changeLedger),\n outcomes,\n },\n {\n ...(sinceMs === undefined ? {} : { sinceMs }),\n ...(rates === undefined ? {} : { pricing: (model: string) => rates?.get(model) }),\n readSkillFile,\n ...(args.intents === null ? {} : { intents: { ...labeler } }),\n },\n )\n const table = renderProcedureRegistryTable(registry, args.limit)\n if (args.format === 'table') {\n io.stdout(table)\n } else {\n io.stdout(`${JSON.stringify(registry, null, 2)}\\n`)\n if (args.format === 'both') io.stderr(table)\n }\n return 0\n } catch (error) {\n io.stderr(`agent-eval procedure-registry: ${errorMessage(error)}\\n`)\n return 1\n }\n}\n","/**\n * `agent-eval search <subcommand>`: work with a search ledger from a terminal.\n *\n * agent-eval search ship <search-ledger.jsonl> --run-kind optimization|eval [--content full|digests]\n * agent-eval search show <search-ledger.jsonl> [--tree] [--operator-yield] [--front] [--task-matrix]\n * [--edit-credit] [--landscape] [--skill-manifold] [--json]\n * agent-eval search show <search-ledger.jsonl> [<search-ledger.jsonl> ...] --meta [--objective <key>] [--json]\n *\n * `ship` sends the ledger to the hosted store named by `TANGLE_INGEST_URL`,\n * `TANGLE_INGEST_API_KEY` and `TANGLE_TENANT_ID`, starting from the store's\n * head, so it finishes or resumes a ship that a loop could not complete.\n *\n * `show` verifies the ledger and prints `renderSearchSummary`: the same\n * compact text a proposer reads, on the search's own ranking split (the\n * selection split when the search declares one, else train). There is no\n * local HTML renderer; the hosted store's page is the visual view (§5 of the\n * search-tree design). A lens flag adds that lens's text form after the\n * summary, so an agent reads what a person sees; `--json` prints the lens\n * results as JSON instead, the shape a view renders.\n *\n * `show --meta` reads every ledger it is given and prints the `metaSearch`\n * lens over them instead of one search's summary: each search as one node\n * scored by its held-out lift per known dollar, the configurations best first,\n * and the searches arranged by derivation and containment.\n */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { open, readFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { replaySearchLedgerText } from './campaign/search-ledger'\nimport type { SearchArtifactRef } from './campaign/search-ledger-types'\nimport type { SearchStateView } from './campaign/search-state'\nimport { renderSearchSummary } from './campaign/search-summary'\nimport { hostedTenantFromEnv } from './hosted/client'\nimport { SEARCH_LEDGER_BATCH_MAX_BYTES, SearchRunKindSchema } from './hosted/search-ledger-wire'\nimport { SearchShipConflictError, shipSearchLedger } from './hosted/search-shipper'\nimport { editCredit, editCreditText } from './search/lenses/edit-credit'\nimport { type FrontData, front } from './search/lenses/front'\nimport { formatLandscape, landscape, surfaceTextEdits } from './search/lenses/landscape'\nimport { metaSearch } from './search/lenses/meta-search'\nimport { renderMetaSearchText } from './search/lenses/meta-search-text'\nimport { type OperatorYieldData, operatorYield } from './search/lenses/operator-yield'\nimport { INSUFFICIENT_FROM } from './search/lenses/shared'\nimport { formatSkillManifold, skillManifold } from './search/lenses/skill-manifold'\nimport { type TaskMatrixData, taskMatrix } from './search/lenses/task-matrix'\nimport { type TreeData, type TreeNode, tree } from './search/lenses/tree'\n\nconst USAGE = `usage: agent-eval search <subcommand> ...\n\n ship <search-ledger.jsonl> --run-kind optimization|eval [--content full|digests]\n Ships the ledger's entries, and the blobs they name, to the hosted store in\n TANGLE_INGEST_URL (or TANGLE_ORCHESTRATOR_URL) as tenant TANGLE_TENANT_ID with\n TANGLE_INGEST_API_KEY (or TANGLE_API_KEY). It starts from the store's head, so\n running it again sends only what the store lacks. Prints the result as JSON.\n Exits 1 when the store holds a different chain for the search.\n\n show <search-ledger.jsonl> [--tree] [--operator-yield] [--front] [--task-matrix]\n [--edit-credit] [--landscape] [--skill-manifold] [--json]\n Verifies the ledger and prints its search summary: the leading nodes\n against the root, the most recently discarded nodes and why, and a log\n of recent proposals. The same text a proposer reads as context, on the\n search's own ranking split. Each lens flag adds that lens's text form\n (search-tree-design §12) below the summary — the same JSON\n Intelligence, discovery lab, VerticalBench and agent-runtime read.\n --tree the tidy tree of nodes and edges.\n --operator-yield outcome counts and yield per known dollar, by edge operator.\n --front the Pareto front over score and known cost per cell.\n --task-matrix nodes × units, clustered, with specialist gain per cluster.\n --edit-credit every edit as a gene followed down the lineage, its\n credit, interacting pairs, and skill candidates. It\n reads node artifacts from the blobs the ledger names,\n verified by digest.\n --landscape nodes placed by line edits between their profile\n surfaces (read from the blobs, verified by digest), the\n kriged score surface, its basins, and the plateau score\n a policy drafts on.\n --skill-manifold the node × unit score matrix factored into skill axes,\n its cross-validated intrinsic dimension, and the unit\n that best separates the leaders.\n --json prints the requested lenses as JSON instead of text.\n\n show <search-ledger.jsonl> [<search-ledger.jsonl> ...] --meta [--objective <key>] [--json]\n Verifies every ledger and prints the meta-search lens over them: each\n search as one node, scored by its claim's held-out lift per known\n dollar (unscored searches say why), configurations best first with\n their interval, method and n, and the searches arranged by derivation\n and containment. --objective names the objective the best\n configuration is chosen within when the searches span several.`\n\nexport async function runSearchCommand(argv: string[]): Promise<number> {\n const [subcommand, ...rest] = argv\n if (subcommand === undefined || subcommand === '--help' || subcommand === '-h') {\n process.stdout.write(`${USAGE}\\n`)\n return 0\n }\n if (subcommand === 'show') return await runShowCommand(rest)\n if (subcommand !== 'ship') {\n process.stderr.write(`unknown search subcommand: ${subcommand}\\n${USAGE}\\n`)\n return 1\n }\n if (rest.some((arg) => arg === undefined || arg === '--help' || arg === '-h')) {\n process.stdout.write(`${USAGE}\\n`)\n return 0\n }\n const { path, flags } = parseShipArgs(rest)\n const runKind = SearchRunKindSchema.safeParse(flags['run-kind'])\n if (!runKind.success) throw new Error(`--run-kind must be optimization or eval\\n${USAGE}`)\n const content = flags.content ?? 'full'\n if (content !== 'full' && content !== 'digests') {\n throw new Error(`--content must be full or digests\\n${USAGE}`)\n }\n const tenant = hostedTenantFromEnv()\n if (!tenant) {\n throw new Error(\n 'set TANGLE_INGEST_URL, TANGLE_INGEST_API_KEY and TANGLE_TENANT_ID to name the store',\n )\n }\n const searchId = await firstLineSearchId(path)\n try {\n const shipped = await shipSearchLedger({\n tenant,\n ledger: { path, searchId },\n runKind: runKind.data,\n content,\n })\n process.stdout.write(`${JSON.stringify(shipped, null, 2)}\\n`)\n return shipped.head.nextSequence === shipped.localLines ? 0 : 1\n } catch (error) {\n if (!(error instanceof SearchShipConflictError)) throw error\n process.stderr.write(`${error.message}\\n`)\n return 1\n }\n}\n\nasync function runShowCommand(argv: string[]): Promise<number> {\n if (argv.includes('--help') || argv.includes('-h')) {\n process.stdout.write(`${USAGE}\\n`)\n return 0\n }\n if (argv.includes('--meta')) return await runShowMetaCommand(argv)\n const positional = argv.filter((arg) => !arg.startsWith('--'))\n const flags = new Set(argv.filter((arg) => arg.startsWith('--')))\n const unknown = [...flags].filter((flag) => !SHOW_FLAGS.has(flag))\n if (positional.length !== 1 || unknown.length > 0) {\n if (unknown.length > 0) process.stderr.write(`unknown flag ${unknown.join(', ')}\\n`)\n process.stdout.write(`${USAGE}\\n`)\n return 1\n }\n const path = positional[0]!\n const searchId = await firstLineSearchId(path)\n const text = await readFile(path, 'utf8')\n const state = replaySearchLedgerText(text, searchId, path)\n const split =\n state.header && state.header.splits.selection.tasks.length > 0 ? 'selection' : 'train'\n const lenses = showLenses(state, path, flags)\n if (flags.has('--json')) {\n if (lenses.length === 0) {\n process.stderr.write('--json needs a lens flag\\n')\n return 1\n }\n const json = Object.fromEntries(lenses.map((lens) => [lens.name, lens.result]))\n process.stdout.write(`${JSON.stringify(json, null, 2)}\\n`)\n return 0\n }\n const sections = [renderSearchSummary(state, { split }), ...lenses.map((lens) => lens.text)]\n process.stdout.write(`${sections.join('\\n\\n')}\\n`)\n return 0\n}\n\nasync function runShowMetaCommand(argv: string[]): Promise<number> {\n const paths: string[] = []\n let objective: string | undefined\n let json = false\n for (let index = 0; index < argv.length; index++) {\n const token = argv[index]!\n if (token === '--meta') continue\n if (token === '--json') {\n json = true\n continue\n }\n if (token === '--objective') {\n objective = argv[++index]\n if (objective === undefined) throw new Error(`--objective needs a value\\n${USAGE}`)\n continue\n }\n if (token.startsWith('--')) throw new Error(`unknown flag ${token}\\n${USAGE}`)\n paths.push(token)\n }\n if (paths.length === 0) throw new Error(`show --meta needs at least one ledger\\n${USAGE}`)\n const states = []\n for (const path of paths) {\n const searchId = await firstLineSearchId(path)\n states.push(replaySearchLedgerText(await readFile(path, 'utf8'), searchId, path))\n }\n const lens = metaSearch(states, objective === undefined ? {} : { objective })\n process.stdout.write(\n json ? `${JSON.stringify({ metaSearch: lens }, null, 2)}\\n` : `${renderMetaSearchText(lens)}\\n`,\n )\n return 0\n}\n\nconst SHOW_FLAGS = new Set([\n '--edit-credit',\n '--json',\n '--tree',\n '--operator-yield',\n '--front',\n '--task-matrix',\n '--landscape',\n '--skill-manifold',\n])\n\nfunction showLenses(\n state: SearchStateView,\n ledgerPath: string,\n flags: ReadonlySet<string>,\n): Array<{ name: string; result: unknown; text: string }> {\n const lenses: Array<{ name: string; result: unknown; text: string }> = []\n if (flags.has('--tree')) {\n const result = tree(state)\n lenses.push({ name: 'tree', result, text: renderTreeText(result.data) })\n }\n if (flags.has('--operator-yield')) {\n const result = operatorYield(state)\n lenses.push({ name: 'operatorYield', result, text: renderOperatorYieldText(result.data) })\n }\n if (flags.has('--front')) {\n const result = front(state)\n lenses.push({ name: 'front', result, text: renderFrontText(result.data) })\n }\n if (flags.has('--task-matrix')) {\n const result = taskMatrix(state)\n lenses.push({ name: 'taskMatrix', result, text: renderTaskMatrixText(result.data) })\n }\n if (flags.has('--edit-credit')) {\n const result = editCredit(state, { readArtifact: ledgerBlobReader(ledgerPath) })\n lenses.push({ name: 'editCredit', result, text: editCreditText(result) })\n }\n if (flags.has('--landscape')) {\n const read = ledgerBlobReader(ledgerPath)\n const result = landscape(\n state,\n surfaceTextEdits((surface) => read(surface.artifact) ?? null),\n )\n lenses.push({ name: 'landscape', result, text: formatLandscape(result) })\n }\n if (flags.has('--skill-manifold')) {\n const result = skillManifold(state)\n lenses.push({ name: 'skillManifold', result, text: formatSkillManifold(result) })\n }\n return lenses\n}\n\n/**\n * Reads a blob a ledger names: at its `file:` URI, else under `blobs/` beside\n * the ledger, where `SearchRecorder` writes them. Bytes that do not hash to the\n * reference's digest and length read as unavailable, never as content.\n */\nfunction ledgerBlobReader(ledgerPath: string): (ref: SearchArtifactRef) => unknown | undefined {\n const cache = new Map<string, unknown>()\n return (ref) => {\n if (cache.has(ref.sha256)) return cache.get(ref.sha256)\n const hex = ref.sha256.slice('sha256:'.length)\n const candidates = [join(dirname(ledgerPath), 'blobs', `${hex}.json`)]\n if (ref.uri.startsWith('file:')) candidates.unshift(fileURLToPath(ref.uri))\n let value: unknown\n for (const candidate of candidates) {\n if (!existsSync(candidate)) continue\n const bytes = readFileSync(candidate)\n const digest = createHash('sha256').update(bytes).digest('hex')\n if (digest !== hex || bytes.byteLength !== ref.byteLength) continue\n try {\n value = JSON.parse(bytes.toString('utf8'))\n } catch {\n // Verified bytes that are not JSON are not content a lens can read.\n }\n break\n }\n cache.set(ref.sha256, value)\n return value\n }\n}\n\nfunction renderTreeText(data: TreeData): string {\n const lines = [\n `tree: ${data.nodeCount} node${data.nodeCount === 1 ? '' : 's'}, ${data.edgeCount} edge${data.edgeCount === 1 ? '' : 's'}`,\n ]\n const walk = (node: TreeNode, prefix: string, isLast: boolean): void => {\n const branch = prefix === '' ? '' : isLast ? '└─ ' : '├─ '\n const op = node.operator ? `${node.operator} → ` : ''\n const rung = node.rung === null ? '' : ` rung ${node.rung}`\n const depth = node.depth === null ? ' depth unknown' : ''\n const cost =\n node.unknownCostCells === 0\n ? `$${node.knownCostUsd.toFixed(2)}`\n : `$${node.knownCostUsd.toFixed(2)} known + at least $${node.floorUsd.toFixed(2)} over ${node.unknownCostCells} unknown-cost cell${node.unknownCostCells === 1 ? '' : 's'}`\n lines.push(\n `${prefix}${branch}${op}${node.nodeId} (${node.status ?? 'undecided'}${rung}${depth}) ${cost}`,\n )\n const childPrefix = prefix + (prefix === '' ? '' : isLast ? ' ' : '│ ')\n node.children.forEach((child, index) => {\n walk(child, childPrefix, index === node.children.length - 1)\n })\n }\n data.roots.forEach((root, index) => {\n walk(root, '', index === data.roots.length - 1)\n })\n return lines.join('\\n')\n}\n\nfunction renderOperatorYieldText(data: OperatorYieldData): string {\n const lines = [`operator yield (${data.split} split, gain per known $ of proposal + screen):`]\n if (data.rows.length === 0) lines.push(' no edges yet')\n for (const row of data.rows) {\n const y = row.yield\n const outcomes = Object.entries(row.outcomes)\n .filter(([, count]) => count > 0)\n .map(([status, count]) => `${status}=${count}`)\n .join(' ')\n const yieldText =\n y.method === 'none'\n ? y.n === 0\n ? 'yield: no measured children'\n : `yield unknown (${y.n} of ${INSUFFICIENT_FROM}, none)`\n : y.method === 'insufficient'\n ? `yield≈${y.mean!.toFixed(4)}/$ (${y.n} of ${INSUFFICIENT_FROM}, insufficient)`\n : `yield≈${y.mean!.toFixed(4)}/$ [${y.interval![0].toFixed(4)}, ${y.interval![1].toFixed(4)}] (${y.method}, ${y.intervalMethod}, n=${y.n})`\n const nodes = Object.values(row.outcomes).reduce((sum, count) => sum + count, 0)\n const reproposals = row.reproposals > 0 ? `, ${row.reproposals} re-proposals` : ''\n lines.push(\n ` ${row.operator}: ${row.proposals} proposals${reproposals} → ${nodes} node${nodes === 1 ? '' : 's'} (${outcomes || 'no decisions yet'}); ${yieldText}; ${row.excluded} excluded`,\n )\n }\n return lines.join('\\n')\n}\n\nfunction renderFrontText(data: FrontData): string {\n const onFront = data.rows.filter((row) => row.onFront)\n const reasons = Object.entries(data.exclusions)\n .filter(([, count]) => count > 0)\n .map(([reason, count]) => `${reason} ${count}`)\n .join(', ')\n const lines = [\n `front (${data.split} split, axes: ${data.axes.join(', ')}): ${data.frontierSize} of ${data.rows.length} node(s) on the frontier, ${data.excludedCount} excluded${reasons ? ` (${reasons})` : ''}`,\n ]\n for (const row of onFront) {\n lines.push(\n ` ${row.nodeId}: score=${row.score!.toFixed(4)} on ${row.units} units (${row.method}) costPerCell=$${row.costPerCellUsd!.toFixed(4)}`,\n )\n }\n return lines.join('\\n')\n}\n\nfunction renderTaskMatrixText(data: TaskMatrixData): string {\n const lines = [\n `task matrix (${data.split} split, ${data.direction}): ${data.nodeIds.length} node(s) × ${data.unitIds.length} unit(s), ${data.nodeClusters.length} node cluster(s), ${data.unitClusters.length} unit cluster(s)`,\n ]\n if (data.sampling) {\n lines.push(\n ` clustered ${data.sampling.nodesClustered} of ${data.sampling.nodesTotal} nodes (cap ${data.sampling.cap}), evenly sampled in registration order; unit clusters and specialist gains use the same nodes`,\n )\n }\n for (const row of data.specialistGain) {\n const gain =\n row.gain === null\n ? `insufficient (${row.insufficient})`\n : `${row.gain.toFixed(4)} (best ${row.bestNodeId}, ${row.nodesContributing} nodes on ${row.unitIds.length} units)`\n lines.push(` cluster ${row.clusterId} [${row.unitIds.join(', ')}]: specialist gain ${gain}`)\n }\n return lines.join('\\n')\n}\n\nfunction parseShipArgs(argv: string[]): { path: string; flags: Record<string, string> } {\n const flags: Record<string, string> = {}\n const positional: string[] = []\n for (let index = 0; index < argv.length; index++) {\n const token = argv[index]!\n if (!token.startsWith('--')) {\n positional.push(token)\n continue\n }\n const [name, inline] = token.slice(2).split('=', 2) as [string, string | undefined]\n if (name !== 'run-kind' && name !== 'content') throw new Error(`unknown flag --${name}`)\n const value = inline ?? argv[++index]\n if (value === undefined) throw new Error(`--${name} needs a value`)\n flags[name] = value\n }\n if (positional.length !== 1) throw new Error(USAGE)\n return { path: positional[0]!, flags }\n}\n\n/** The ledger names its search on every line; read the first. */\nasync function firstLineSearchId(path: string): Promise<string> {\n const handle = await open(path, 'r')\n try {\n // A line longer than one request's limit cannot ship anyway.\n const bytes = Buffer.alloc(SEARCH_LEDGER_BATCH_MAX_BYTES + 1)\n const { bytesRead } = await handle.read(bytes, 0, bytes.byteLength, 0)\n const newline = bytes.subarray(0, bytesRead).indexOf(0x0a)\n if (newline < 0) throw new Error(`${path} holds no complete ledger line`)\n const first = JSON.parse(bytes.toString('utf8', 0, newline)) as { searchId?: unknown }\n if (typeof first.searchId !== 'string') throw new Error(`${path} line 1 names no searchId`)\n return first.searchId\n } finally {\n await handle.close()\n }\n}\n","/**\n * `agent-eval supervisor-run rollouts` writes one rollout ledger from the\n * places the fleet's work is recorded:\n *\n * <runDir...> Runtime run directories (`runtimeRunRolloutLines`)\n * --sessions [<harness>:]<path> a HOME, store directory, session file or OpenCode .db;\n * the prefix limits a directory to one harness and names a file's\n * --since <ISO> limit --sessions to stores changed since then\n * --gate-receipts <file> beelink-gate receipts.jsonl, as verifiable labels\n * --denylist <file> literal private terms, one per line\n * --otlp <file> also write each kept run row's session as OTLP spans\n *\n * Every row passes the privacy screen before it is written: a row with any\n * secret or private detail is dropped whole and counted by rule, so the\n * ledger never holds one. Rows are written under the write policy and read\n * back with `readRolloutJournal`; their rewards are unscreened.\n */\n\nimport { appendFile, readFile, rm } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { errorMessage } from '../errors'\nimport { appendRolloutLines } from '../rollout/ledger'\nimport { gateReceiptRolloutLines } from '../rollout/readers/gate-receipts'\nimport {\n harnessSessionRefs,\n harnessSessionRolloutLines,\n} from '../rollout/readers/harness-session-lines'\nimport { PRIVACY_RULE_NAMES, privacyHit } from '../rollout/release/scrub'\nimport type { RolloutLine } from '../rollout/schema'\nimport type { SupervisorRunCommandIo } from './report-command'\nimport { runtimeRunRolloutLines } from './runtime-rollouts'\n\nexport const ROLLOUTS_USAGE =\n 'usage: agent-eval supervisor-run rollouts [<runDir>...] [--sessions [<harness>:]<path>]... [--since <ISO>] [--gate-receipts <file>]... [--denylist <file>] [--otlp <file>] --out <ledger.jsonl>'\n\ninterface RolloutsArgs {\n runDirs: string[]\n sessions: Array<{ path: string; harness?: string }>\n sinceMs?: number\n gateReceipts: string[]\n denylist: string | null\n otlp: string | null\n out: string\n}\n\nfunction parseArgs(argv: readonly string[]): RolloutsArgs {\n const args: RolloutsArgs = {\n runDirs: [],\n sessions: [],\n gateReceipts: [],\n denylist: null,\n otlp: null,\n out: '',\n }\n const value = (i: number, flag: string): string => {\n const v = argv[i]\n if (v === undefined || v.startsWith('--')) throw new Error(`${flag} expects a value`)\n return v\n }\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i] as string\n if (arg === '--out') args.out = value(++i, arg)\n else if (arg === '--sessions') {\n const raw = value(++i, arg)\n const prefixed = /^([a-z][a-z-]*):(.+)$/u.exec(raw)\n args.sessions.push(prefixed ? { harness: prefixed[1]!, path: prefixed[2]! } : { path: raw })\n } else if (arg === '--since') {\n const ms = Date.parse(value(++i, arg))\n if (Number.isNaN(ms)) throw new Error(`--since expects an ISO time, got ${argv[i]}`)\n args.sinceMs = ms\n } else if (arg === '--gate-receipts') args.gateReceipts.push(value(++i, arg))\n else if (arg === '--denylist') args.denylist = value(++i, arg)\n else if (arg === '--otlp') args.otlp = value(++i, arg)\n else if (arg.startsWith('--')) throw new Error(`unknown flag \"${arg}\"`)\n else args.runDirs.push(arg)\n }\n if (!args.out) throw new Error(ROLLOUTS_USAGE)\n if (args.runDirs.length + args.sessions.length + args.gateReceipts.length === 0) {\n throw new Error(`no sources given\\n${ROLLOUTS_USAGE}`)\n }\n return args\n}\n\nexport interface RolloutsSummary {\n out: string\n written: number\n dropped: Record<string, number>\n sources: Array<{ source: string; kind: string; read: number; written: number; errors: string[] }>\n}\n\nexport async function runRolloutsCommand(\n argv: readonly string[],\n io: SupervisorRunCommandIo,\n): Promise<number> {\n let args: RolloutsArgs\n try {\n args = parseArgs(argv)\n } catch (error) {\n io.stderr(`${errorMessage(error)}\\n`)\n return 2\n }\n const out = resolve(args.out)\n const denylist =\n args.denylist === null\n ? []\n : (await readFile(args.denylist, 'utf8'))\n .split('\\n')\n .map((line) => line.replace(/#.*/u, '').trim())\n .filter(Boolean)\n const capturedAt = new Date().toISOString()\n const summary: RolloutsSummary = {\n out,\n written: 0,\n dropped: Object.fromEntries(PRIVACY_RULE_NAMES.map((name) => [name, 0])),\n sources: [],\n }\n await rm(out, { force: true })\n if (args.otlp !== null) await rm(args.otlp, { force: true })\n\n const write = async (source: RolloutsSummary['sources'][number], lines: RolloutLine[]) => {\n source.read += lines.length\n const kept = lines.filter((line) => {\n const hit = privacyHit(line, denylist)\n if (hit !== null) summary.dropped[hit] = (summary.dropped[hit] ?? 0) + 1\n return hit === null\n })\n await appendRolloutLines(out, kept)\n source.written += kept.length\n summary.written += kept.length\n return kept\n }\n\n for (const runDir of args.runDirs) {\n const source = { source: runDir, kind: 'run-dir', read: 0, written: 0, errors: [] as string[] }\n summary.sources.push(source)\n try {\n const run = await runtimeRunRolloutLines(resolve(runDir), { capturedAt })\n source.errors.push(...run.gaps.map((gap) => `${gap.code}: ${gap.message}`))\n const kept = await write(source, run.lines)\n const spans = kept.map((line) => run.otlp.get(line.rollout_id) ?? '')\n if (args.otlp !== null) await appendFile(args.otlp, spans.join(''))\n } catch (error) {\n source.errors.push(errorMessage(error))\n }\n }\n for (const target of args.sessions) {\n const source = {\n source: target.path,\n kind: `sessions:${target.harness ?? 'all'}`,\n read: 0,\n written: 0,\n errors: [] as string[],\n }\n summary.sources.push(source)\n try {\n const refs = await harnessSessionRefs(resolve(target.path), {\n ...(target.harness === undefined ? {} : { harness: target.harness }),\n ...(args.sinceMs === undefined ? {} : { sinceMs: args.sinceMs }),\n })\n let batch: RolloutLine[] = []\n for await (const item of harnessSessionRolloutLines(refs, capturedAt)) {\n if (item.line) batch.push(item.line)\n else source.errors.push(`${item.ref.path}: ${item.error}`)\n if (batch.length >= 100) {\n await write(source, batch)\n batch = []\n }\n }\n await write(source, batch)\n } catch (error) {\n source.errors.push(errorMessage(error))\n }\n }\n for (const path of args.gateReceipts) {\n const source = {\n source: path,\n kind: 'gate-receipts',\n read: 0,\n written: 0,\n errors: [] as string[],\n }\n summary.sources.push(source)\n try {\n const { lines, skipped } = await gateReceiptRolloutLines(path, capturedAt)\n if (skipped > 0) source.errors.push(`${skipped} receipts carried no verdict`)\n await write(source, lines)\n } catch (error) {\n source.errors.push(errorMessage(error))\n }\n }\n io.stdout(`${JSON.stringify(summary, null, 2)}\\n`)\n return summary.sources.some((s) => s.read === 0 && s.errors.length > 0) ? 1 : 0\n}\n","/**\n * `agent-eval supervisor-run report <runDir>` takes one run directory and\n * prints the report the module already renders. The command reads through\n * `analyzeSupervisorRun`, so a Runtime run directory takes the\n * same path and the status comes from the record `terminal-record.ts` names.\n *\n * Exit codes follow the other self-parsing subcommands: 2 for a usage error,\n * 1 when the directory cannot be read (missing, not a directory, or a corrupt\n * journal or terminal record), 0 after the report was written to stdout.\n */\n\nimport { stat } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { errorMessage } from '../errors'\nimport { analyzeSupervisorRun } from './reader'\nimport { renderSupervisorRunHeadline, renderSupervisorRunMarkdown } from './render'\nimport { ROLLOUTS_USAGE, runRolloutsCommand } from './rollouts-command'\n\nexport type SupervisorRunReportFormat = 'headline' | 'markdown' | 'json'\n\nconst FORMATS: readonly SupervisorRunReportFormat[] = ['headline', 'markdown', 'json']\n\nconst SUPERVISOR_RUN_USAGE = `usage: agent-eval supervisor-run report <runDir> [--format headline|markdown|json]\n ${ROLLOUTS_USAGE.replace('usage: ', '')}`\n\n/** Output sinks, injectable so tests read the exact bytes a terminal would. */\nexport interface SupervisorRunCommandIo {\n readonly stdout: (text: string) => void\n readonly stderr: (text: string) => void\n}\n\nconst PROCESS_IO: SupervisorRunCommandIo = {\n stdout: (text) => {\n process.stdout.write(text)\n },\n stderr: (text) => {\n process.stderr.write(text)\n },\n}\n\ninterface ReportArgs {\n readonly runDir: string\n readonly format: SupervisorRunReportFormat\n}\n\nfunction isFormat(value: string): value is SupervisorRunReportFormat {\n return (FORMATS as readonly string[]).includes(value)\n}\n\nfunction parseReportArgs(argv: readonly string[]): ReportArgs {\n let runDir: string | null = null\n let format: SupervisorRunReportFormat = 'headline'\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i] as string\n if (arg === '--format') {\n const raw = argv[++i]\n if (raw === undefined || !isFormat(raw)) {\n throw new Error(\n `--format expects one of ${FORMATS.join('|')}, got ${JSON.stringify(raw ?? '')}`,\n )\n }\n format = raw\n } else if (arg.startsWith('--format=')) {\n const raw = arg.slice('--format='.length)\n if (!isFormat(raw)) {\n throw new Error(`--format expects one of ${FORMATS.join('|')}, got ${JSON.stringify(raw)}`)\n }\n format = raw\n } else if (arg.startsWith('--')) {\n throw new Error(`unknown flag \"${arg}\"`)\n } else if (runDir === null) {\n runDir = arg\n } else {\n throw new Error(`unexpected argument \"${arg}\"`)\n }\n }\n if (runDir === null) throw new Error(SUPERVISOR_RUN_USAGE)\n return { runDir, format }\n}\n\n/**\n * CLI driver for `agent-eval supervisor-run`. `argv` is everything after the\n * command name, so `['report', runDir, ...flags]`. Returns the process exit code.\n */\nexport async function runSupervisorRunCommand(\n argv: readonly string[],\n io: SupervisorRunCommandIo = PROCESS_IO,\n): Promise<number> {\n const [verb, ...rest] = argv\n if (verb === undefined || verb === '--help' || verb === '-h' || verb === 'help') {\n io.stdout(`${SUPERVISOR_RUN_USAGE}\\n`)\n return verb === undefined ? 2 : 0\n }\n if (verb === 'rollouts') {\n if (rest.includes('--help') || rest.includes('-h')) {\n io.stdout(`${ROLLOUTS_USAGE}\\n`)\n return 0\n }\n return runRolloutsCommand(rest, io)\n }\n if (verb !== 'report') {\n io.stderr(`unknown supervisor-run subcommand \"${verb}\"\\n${SUPERVISOR_RUN_USAGE}\\n`)\n return 2\n }\n if (rest.includes('--help') || rest.includes('-h')) {\n io.stdout(`${SUPERVISOR_RUN_USAGE}\\n`)\n return 0\n }\n\n let args: ReportArgs\n try {\n args = parseReportArgs(rest)\n } catch (error) {\n io.stderr(`${errorMessage(error)}\\n`)\n return 2\n }\n\n const runDir = resolve(args.runDir)\n // A path that is not a directory is a caller error, not a run with every\n // measurement missing: reporting an absent-shaped run for a typo would read\n // as evidence about a run that never existed.\n const entry = await stat(runDir).catch(() => null)\n if (entry === null || !entry.isDirectory()) {\n io.stderr(`[agent-eval] supervisor-run report: ${runDir} is not a directory\\n`)\n return 1\n }\n\n try {\n const report = await analyzeSupervisorRun(runDir)\n switch (args.format) {\n case 'headline':\n io.stdout(`${renderSupervisorRunHeadline(report)}\\n`)\n break\n case 'markdown':\n io.stdout(renderSupervisorRunMarkdown(report))\n break\n case 'json':\n io.stdout(`${JSON.stringify(report, null, 2)}\\n`)\n break\n }\n return 0\n } catch (error) {\n io.stderr(`[agent-eval] supervisor-run report failed for ${runDir}: ${errorMessage(error)}\\n`)\n return 1\n }\n}\n","#!/usr/bin/env node\n/**\n * agent-eval CLI.\n *\n * agent-eval serve [--port 5005] [--host 127.0.0.1]\n * agent-eval rpc <method> # one request from stdin → one response on stdout\n * agent-eval rpc-batch <method> # JSONL stdin → JSONL stdout\n * agent-eval analyst-benchmark ... # benchmark a real-model trace analyst\n * agent-eval supervisor-run report <runDir> [--format headline|markdown|json]\n * agent-eval search ship <search-ledger.jsonl> --run-kind optimization|eval\n * agent-eval search show <search-ledger.jsonl>\n * agent-eval skill-usage <transcripts-dir> [--since 7d]\n * agent-eval procedure-registry <sessions-dir> [--ledger <path>]... [--since 30d] [--outcomes <file>] [--change-ledger <file>]...\n * agent-eval openapi [--out path] # write OpenAPI spec\n * agent-eval version\n *\n * <method> is one of: judge, listRubrics, version. When omitted, the\n * stdin payload must be a full {method, params} envelope.\n */\nimport { writeFileSync } from 'node:fs'\nimport { runAnalystBenchmarkCommand } from './analyst/benchmark-command'\nimport { resolveCliLlmConfig } from './cli-config'\nimport { runProcedureRegistryCommand } from './procedure-registry/command'\nimport { runRolloutReleaseCli } from './rollout/release/hf-dataset'\nimport { runSearchCommand } from './search-command'\nimport { runSkillUsageCommand } from './skill-usage/command'\nimport { runSupervisorRunCommand } from './supervisor-run/report-command'\nimport { handleVersion } from './wire/handlers'\nimport { buildOpenApi } from './wire/openapi'\nimport { runRpcBatch, runRpcOnce } from './wire/rpc'\nimport { startServerAsync } from './wire/server'\n\ninterface Args {\n command: string\n positional: string[]\n flags: Record<string, string>\n}\n\nfunction parseArgs(argv: string[]): Args {\n const [command, ...rest] = argv\n const positional: string[] = []\n const flags: Record<string, string> = {}\n for (let i = 0; i < rest.length; i++) {\n const tok = rest[i]!\n if (tok.startsWith('--')) {\n const raw = tok.slice(2)\n const equalsAt = raw.indexOf('=')\n if (equalsAt >= 0) {\n flags[raw.slice(0, equalsAt)] = raw.slice(equalsAt + 1)\n continue\n }\n const key = raw\n if (key === 'help') {\n flags[key] = 'true'\n continue\n }\n const next = rest[i + 1]\n if (next != null && !next.startsWith('--')) {\n flags[key] = next\n i++\n } else {\n flags[key] = 'true'\n }\n } else if (tok === '-h') {\n flags.help = 'true'\n } else {\n positional.push(tok)\n }\n }\n return { command: command ?? 'help', positional, flags }\n}\n\nconst HELP = `agent-eval: evaluation RPC and HTTP server.\n\nCommands:\n serve [--port 5005] [--host 127.0.0.1]\n Start the HTTP server. POST /v1/judge, GET /v1/rubrics, GET /v1/version, GET /openapi.json.\n rpc <method>\n Read one JSON object from stdin (the params for <method>), write one\n JSON object to stdout. Methods: judge, listRubrics, version.\n rpc-batch <method>\n Like 'rpc' but JSONL in / JSONL out.\n openapi [--out openapi.json]\n Write the OpenAPI 3.1 spec.\n rollout-release <ledger.jsonl...> --out <dir> [--formats sft,verifiers,rft,raw] [--include-proposers] [--denylist <terms.txt>] [--push <org/name>]\n Build a HuggingFace-ready dataset dir from tangle.rollout.v1 ledgers:\n validate, fail-closed split and license filters, drop any line with a\n secret or private detail, scrub, export formats + card.\n analyst-benchmark --dataset <agentrx|codetracebench> --labels <path> --trace-dir <path> [--artifact-dir <path>] --out <dir> ...\n Compare an empty baseline with a real-model trace analyst on public labels.\n Run with --help for all required inputs and controls.\n supervisor-run rollouts [<runDir>...] [--sessions [<harness>:]<path>]... [--since <ISO>] [--gate-receipts <file>] [--denylist <file>] --out <ledger.jsonl>\n Import Discovery run dirs, native harness sessions and beelink-gate receipts\n into one rollout ledger; rows with any secret or private detail are dropped.\n supervisor-run report <runDir> [--format headline|markdown|json]\n Report one Runtime or loops supervisor run directory. The status comes\n from Runtime's own result.json / failure.json; every missing measurement\n stays named. Exits 1 when the directory cannot be read.\n search ship <search-ledger.jsonl> --run-kind optimization|eval [--content full|digests]\n Ship a search ledger and its blobs to the hosted store in TANGLE_INGEST_URL,\n starting from the store's head. Run with --help for the environment it reads.\n search show <search-ledger.jsonl>\n Verify a search ledger and print its summary: leading nodes, recently\n discarded nodes and recent proposals, the same text a proposer reads.\n skill-usage <transcripts-dir> [--since <7d|36h|90m|ISO time>] [--format both|json|table] [--limit <rows>] [--pricing <rates.json>]\n Read a directory of Claude Code transcripts and report each skill and\n version: invocations by agent, user and harness, sessions, and the tool\n calls, tool errors, tokens, wall time and cost after its first invocation.\n The JSON report goes to stdout and the table to stderr.\n procedure-registry <sessions-dir> [--ledger <search-ledger.jsonl>]... [--since <7d|36h|90m|ISO time>] [--outcomes <changes.json>] [--change-ledger <changes.jsonl>]... [--intents [<labeler.mjs>]] [--format both|json|table] [--limit <rows>] [--pricing <rates.json>]\n Join search ledgers and recorded Claude Code sessions on the version digest:\n per procedure version, its lineage, every execution, tokens, cost and wall\n time, the outcome of the changes its sessions produced, and the decisions\n taken on it. With --intents, also each typed turn's intent: the versions\n that served it, its cost and how it ended; the labeler module's default\n export labels turns, and without one no turn has a kind or a correction.\n The JSON registry goes to stdout and the table to stderr.\n version\n Print server + wire-protocol version JSON.\n\nJudge provider:\n Set AGENT_EVAL_LLM_BASE_URL, AGENT_EVAL_LLM_API_KEY, and AGENT_EVAL_LLM_MODEL.\n OPENAI_* and TANGLE_* equivalents are also accepted. This binary is the only\n place that reads a provider credential; the library never does. Without both\n a base URL and a key, /v1/judge refuses with llm_not_configured.\n\nWithout arguments, prints this help.`\n\nasync function main(): Promise<number> {\n const { command, positional, flags } = parseArgs(process.argv.slice(2))\n assertKnownFlags(command, flags)\n\n if (command === 'analyst-benchmark' && flags.help === 'true') {\n return await runAnalystBenchmarkCommand(process.argv.slice(3))\n }\n if (command === 'search') return await runSearchCommand(process.argv.slice(3))\n if (flags.help === 'true') {\n process.stdout.write(`${HELP}\\n`)\n return 0\n }\n\n switch (command) {\n case 'serve': {\n const port = parsePort(flags.port ?? '5005')\n const host = flags.host ?? '127.0.0.1'\n const llm = resolveCliLlmConfig()\n const { server } = await startServerAsync({\n port,\n host,\n ...(llm.chat ? { chat: llm.chat } : {}),\n ...(llm.model ? { judgeModel: llm.model } : {}),\n })\n // Keep process alive on SIGINT/SIGTERM\n const shutdown = (sig: string) => {\n // eslint-disable-next-line no-console\n console.log(`[agent-eval] received ${sig}, shutting down`)\n server.close(() => process.exit(0))\n // Force exit after 5s if close hangs\n setTimeout(() => process.exit(1), 5000).unref()\n }\n process.on('SIGINT', () => shutdown('SIGINT'))\n process.on('SIGTERM', () => shutdown('SIGTERM'))\n // Block forever\n await new Promise(() => {})\n return 0\n }\n case 'rpc': {\n const [method] = positional\n const llm = resolveCliLlmConfig()\n return await runRpcOnce(method, {\n ...(llm.chat ? { chat: llm.chat } : {}),\n ...(llm.model ? { judgeModel: llm.model } : {}),\n })\n }\n case 'rpc-batch': {\n const [method] = positional\n const llm = resolveCliLlmConfig()\n return await runRpcBatch(method, {\n ...(llm.chat ? { chat: llm.chat } : {}),\n ...(llm.model ? { judgeModel: llm.model } : {}),\n })\n }\n case 'openapi': {\n const out = flags.out ?? 'openapi.json'\n const spec = buildOpenApi(handleVersion().version)\n writeFileSync(out, `${JSON.stringify(spec, null, 2)}\\n`, 'utf-8')\n // eslint-disable-next-line no-console\n console.log(`[agent-eval] wrote OpenAPI 3.1 spec to ${out}`)\n return 0\n }\n case 'rollout-release': {\n // The subcommand owns its own flag grammar (multi-value --formats,\n // boolean --include-proposers) — pass raw argv through untouched.\n return await runRolloutReleaseCli(process.argv.slice(3))\n }\n case 'analyst-benchmark': {\n return await runAnalystBenchmarkCommand(process.argv.slice(3))\n }\n case 'supervisor-run': {\n // The subcommand owns its own flag grammar; pass raw argv through.\n return await runSupervisorRunCommand(process.argv.slice(3))\n }\n case 'skill-usage': {\n return await runSkillUsageCommand(process.argv.slice(3))\n }\n case 'procedure-registry': {\n return await runProcedureRegistryCommand(process.argv.slice(3))\n }\n case 'version': {\n process.stdout.write(`${JSON.stringify(handleVersion(), null, 2)}\\n`)\n return 0\n }\n case '--version': {\n process.stdout.write(`${handleVersion().version}\\n`)\n return 0\n }\n case 'help':\n case '--help':\n case '-h':\n case '':\n process.stdout.write(`${HELP}\\n`)\n return 0\n default:\n process.stderr.write(`unknown command: ${command}\\n${HELP}\\n`)\n return 1\n }\n}\n\nconst FLAGS_BY_COMMAND: Record<string, ReadonlySet<string>> = {\n serve: new Set(['help', 'host', 'port']),\n rpc: new Set(['help']),\n 'rpc-batch': new Set(['help']),\n openapi: new Set(['help', 'out']),\n version: new Set(['help']),\n help: new Set(),\n '--help': new Set(),\n '-h': new Set(),\n '--version': new Set(),\n '': new Set(),\n}\n\nfunction assertKnownFlags(command: string, flags: Record<string, string>): void {\n // These subcommands parse their own argv.\n if (\n command === 'rollout-release' ||\n command === 'analyst-benchmark' ||\n command === 'supervisor-run' ||\n command === 'skill-usage' ||\n command === 'procedure-registry' ||\n command === 'search'\n ) {\n return\n }\n const allowed = FLAGS_BY_COMMAND[command]\n if (!allowed) return\n const unknown = Object.keys(flags).filter((flag) => !allowed.has(flag))\n if (unknown.length > 0) {\n throw new Error(`unknown flag for ${command || 'help'}: --${unknown[0]}`)\n }\n}\n\nfunction parsePort(raw: string): number {\n const port = Number(raw)\n if (!Number.isInteger(port) || port < 0 || port > 65_535) {\n throw new Error(`--port must be an integer from 0 to 65535; received ${JSON.stringify(raw)}`)\n }\n return port\n}\n\nmain()\n .then((code) => {\n process.exitCode = code\n })\n .catch((err) => {\n // eslint-disable-next-line no-console\n console.error('[agent-eval] cli error:', err)\n process.exitCode = 1\n })\n"],"mapp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I,IAAI;EAAC;EAAQ;EAAQ;CAAM,CAAC;CACvC,qBAAK,IAAI,IAAI,CAAC,MAAM,CAAC;CACrB,6BAAa,IAAI,IAAI,CAAC,MAAM,CAAC;CAC7B,yBAAS,IAAI,IAAI,CAAC,QAAQ,KAAK,CAAC;CAChC,yBAAS,IAAI,IAAI,CAAC,MAAM,CAAC;CACzB,sBAAM,IAAI,IAAI;CACd,0BAAU,IAAI,IAAI;CAClB,sBAAM,IAAI,IAAI;CACd,6BAAa,IAAI,IAAI;CACrB,oBAAI,IAAI,IAAI;AACd;AAEA,SAAS,iBAAiB,SAAiB,OAAqC;CAE9E,IACE,YAAY,qBACZ,YAAY,uBACZ,YAAY,oBACZ,YAAY,iBACZ,YAAY,wBACZ,YAAY,UAEZ;CAEF,MAAM,UAAU,iBAAiB;CACjC,IAAI,CAAC,SAAS;CACd,MAAM,UAAU,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,SAAS,CAAC,QAAQ,IAAI,IAAI,CAAC;CACtE,IAAI,QAAQ,SAAS,GACnB,MAAM,IAAI,MAAM,oBAAoB,WAAW,OAAO,MAAM,QAAQ,IAAI;AAE5E;AAEA,SAAS,UAAU,KAAqB;CACtC,MAAM,OAAO,OAAO,GAAG;CACvB,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OAChD,MAAM,IAAI,MAAM,uDAAuD,KAAK,UAAU,GAAG,GAAG;CAE9F,OAAO;AACT;AAEA,KAAK,CAAC,CACH,MAAM,SAAS;CACd,QAAQ,WAAW;AACrB,CAAC,CAAC,CACD,OAAO,QAAQ;CAEd,QAAQ,MAAM,2BAA2B,GAAG;CAC5C,QAAQ,WAAW;AACrB,CAAC"}
|
|
1
|
+
{"version":3,"file":"cli.js","names":["FORMATS","USAGE","PROCESS_IO","parseArgs","NOTES","FORMATS","USAGE","PROCESS_IO","parseArgs","parseArgs"],"sources":["../src/cli-config.ts","../src/skill-usage/command.ts","../src/intent-record/derive.ts","../src/intent-record/contract.ts","../src/intent-record/report.ts","../src/procedure-registry/change-outcome.ts","../src/procedure-registry/registry.ts","../src/procedure-registry/render.ts","../src/procedure-registry/command.ts","../src/search-command.ts","../src/supervisor-run/rollouts-command.ts","../src/supervisor-run/report-command.ts","../src/cli.ts"],"sourcesContent":["/**\n * Provider configuration for the `agent-eval` binary.\n *\n * The binary reads endpoint and credential values from its environment.\n * TypeScript library callers bind a transport explicitly. The maintained\n * HTTP transport accepts their credential and sends provider requests.\n */\n\nimport { type ChatClient, createChatClient } from './analyst/chat-client'\n\ninterface CliLlmConfig {\n /** Judge transport for the wire handlers. Absent when no provider is configured. */\n chat?: ChatClient\n model?: string\n}\n\n/** The endpoint the binary resolved from its environment. */\ninterface CliProviderRoute {\n baseUrl: string\n apiKey: string\n model?: string\n}\n\n/**\n * Environment precedence for the binary's provider route, with no client built.\n *\n * Both halves are required: a base URL without a key, or a key without an\n * endpoint, is a half-configured server. `/v1/judge` then refuses with\n * `llm_not_configured` instead of calling an unintended endpoint.\n */\nfunction resolveCliProviderRoute(\n env: NodeJS.ProcessEnv = process.env,\n): CliProviderRoute | undefined {\n const explicitBaseUrl = nonEmpty(env.AGENT_EVAL_LLM_BASE_URL)\n const explicitApiKey = nonEmpty(env.AGENT_EVAL_LLM_API_KEY)\n const openAiApiKey = nonEmpty(env.OPENAI_API_KEY)\n const tangleApiKey = nonEmpty(env.TANGLE_API_KEY)\n const baseUrl =\n explicitBaseUrl ??\n nonEmpty(env.OPENAI_BASE_URL) ??\n nonEmpty(env.TANGLE_ROUTER_URL) ??\n (openAiApiKey ? 'https://api.openai.com/v1' : undefined) ??\n (tangleApiKey ? 'https://router.tangle.tools/v1' : undefined)\n const apiKey = explicitApiKey ?? openAiApiKey ?? tangleApiKey\n const model =\n nonEmpty(env.AGENT_EVAL_LLM_MODEL) ?? nonEmpty(env.OPENAI_MODEL) ?? nonEmpty(env.TANGLE_MODEL)\n\n if (!baseUrl || !apiKey) return undefined\n return { baseUrl, apiKey, ...(model ? { model } : {}) }\n}\n\nexport function resolveCliLlmConfig(env: NodeJS.ProcessEnv = process.env): CliLlmConfig {\n const route = resolveCliProviderRoute(env)\n if (!route) return {}\n return {\n chat: cliChatClient({ baseUrl: route.baseUrl, apiKey: route.apiKey }, route.model),\n ...(route.model ? { model: route.model } : {}),\n }\n}\n\n/**\n * The binary's transport IS the published one — `createChatClient({ transport:\n * 'openai-compatible' })` — so the server and a library consumer cannot drift\n * onto two different clients for the same endpoint.\n *\n * The one thing kept local is the error text. A generic \"no model on the\n * request\" tells a server operator nothing; this names the variable to set.\n */\nfunction cliChatClient(\n route: { baseUrl: string; apiKey: string },\n defaultModel: string | undefined,\n): ChatClient {\n const client = createChatClient({\n transport: 'openai-compatible',\n baseUrl: route.baseUrl,\n apiKey: route.apiKey,\n ...(defaultModel ? { defaultModel } : {}),\n })\n return {\n ...client,\n chat: (req, callOpts) => {\n if (!req.model && !defaultModel) {\n throw new Error(\n 'agent-eval: no model on the request and no AGENT_EVAL_LLM_MODEL configured',\n )\n }\n return client.chat(req, callOpts)\n },\n }\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n const trimmed = value?.trim()\n return trimmed ? trimmed : undefined\n}\n","/**\n * `agent-eval skill-usage <sessions-dir>` reads a directory of Claude Code\n * transcripts (or, with `--harness codex`, Codex rollouts) and prints the\n * skill-usage report.\n *\n * By default the JSON report goes to stdout and the short table to stderr, so\n * `> report.json` keeps the report while the table stays on the terminal.\n *\n * `--pricing <file>` names a JSON object of per-million rates by model id, for a\n * model the cost ledger has no rate for or prices too coarsely (its table has no\n * cache-read rate).\n *\n * Exit codes follow the other self-parsing subcommands: 2 for a usage error, 1\n * when the directory cannot be read, 0 after the report was written.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport type { CustomTokenPricing } from '../cost-ledger/contract'\nimport { costForTokenPricing } from '../cost-ledger/pricing'\nimport { errorMessage } from '../errors'\nimport { claudeCodeSkillSessions } from './claude-code'\nimport { codexSkillSessions } from './codex'\nimport { buildSkillUsageReport, renderSkillUsageTable } from './report'\nimport type { SkillSessionSource } from './session-record'\nimport { readSkillFile } from './skill-file'\n\ntype SkillUsageFormat = 'both' | 'json' | 'table'\n\nconst FORMATS: readonly SkillUsageFormat[] = ['both', 'json', 'table']\n\nconst USAGE =\n 'usage: agent-eval skill-usage <sessions-dir> [--harness claude-code|codex] [--since <7d|36h|90m|ISO time>] [--format both|json|table] [--limit <rows>] [--pricing <rates.json>]'\n\n/** Output sinks, injectable so a test reads the exact bytes a terminal would. */\nexport interface SkillUsageCommandIo {\n readonly stdout: (text: string) => void\n readonly stderr: (text: string) => void\n /** The instant `--since 7d` counts back from. */\n readonly now?: () => number\n}\n\nconst PROCESS_IO: SkillUsageCommandIo = {\n stdout: (text) => {\n process.stdout.write(text)\n },\n stderr: (text) => {\n process.stderr.write(text)\n },\n}\n\n/** The harnesses whose session stores the commands read. */\nexport const SESSION_HARNESSES = ['claude-code', 'codex'] as const\nexport type SessionHarness = (typeof SESSION_HARNESSES)[number]\n\n/** The sessions under a harness's store: Claude Code's projects directory, or Codex's sessions directory. */\nexport function harnessSkillSessions(\n harness: SessionHarness,\n directory: string,\n options: { sinceMs?: number },\n): SkillSessionSource {\n return harness === 'codex'\n ? codexSkillSessions(directory, options)\n : claudeCodeSkillSessions(directory, options)\n}\n\n/** The value of `--harness`, checked. */\nexport function parseHarness(raw: string): SessionHarness {\n if (!(SESSION_HARNESSES as readonly string[]).includes(raw)) {\n throw new Error(\n `--harness expects one of ${SESSION_HARNESSES.join('|')}, got ${JSON.stringify(raw)}`,\n )\n }\n return raw as SessionHarness\n}\n\ninterface SkillUsageArgs {\n directory: string\n harness: SessionHarness\n since: string | null\n format: SkillUsageFormat\n limit: number\n pricing: string | null\n}\n\nconst DURATION = /^(\\d+(?:\\.\\d+)?)([dhm])$/\nconst UNIT_MS = { d: 86_400_000, h: 3_600_000, m: 60_000 } as const\n\n/** `7d`, `36h` or `90m` back from `nowMs`, or an ISO instant. */\nexport function parseSince(raw: string, nowMs: number): number {\n const duration = DURATION.exec(raw)\n if (duration !== null) {\n return nowMs - Number(duration[1]) * UNIT_MS[duration[2] as keyof typeof UNIT_MS]\n }\n const at = Date.parse(raw)\n if (!Number.isFinite(at)) {\n throw new Error(\n `--since expects a duration such as 7d or an ISO time, got ${JSON.stringify(raw)}`,\n )\n }\n return at\n}\n\nfunction parseArgs(argv: readonly string[]): SkillUsageArgs {\n const args: SkillUsageArgs = {\n directory: '',\n harness: 'claude-code',\n since: null,\n format: 'both',\n limit: 30,\n pricing: null,\n }\n const value = (flag: string, index: number): string => {\n const raw = argv[index]\n if (raw === undefined) throw new Error(`${flag} expects a value`)\n return raw\n }\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i] as string\n if (arg === '--harness') {\n args.harness = parseHarness(value(arg, ++i))\n } else if (arg === '--since') {\n args.since = value(arg, ++i)\n } else if (arg === '--format') {\n const raw = value(arg, ++i)\n if (!(FORMATS as readonly string[]).includes(raw)) {\n throw new Error(`--format expects one of ${FORMATS.join('|')}, got ${JSON.stringify(raw)}`)\n }\n args.format = raw as SkillUsageFormat\n } else if (arg === '--limit') {\n const raw = Number(value(arg, ++i))\n if (!Number.isInteger(raw) || raw < 1) throw new Error('--limit expects a positive integer')\n args.limit = raw\n } else if (arg === '--pricing') {\n args.pricing = value(arg, ++i)\n } else if (arg.startsWith('--')) {\n throw new Error(`unknown flag \"${arg}\"`)\n } else if (args.directory === '') {\n args.directory = arg\n } else {\n throw new Error(`unexpected argument \"${arg}\"`)\n }\n }\n if (args.directory === '') throw new Error('a transcripts directory is required')\n return args\n}\n\nconst RATE_FIELDS = [\n 'inputUsdPerMillion',\n 'cachedInputUsdPerMillion',\n 'cacheWriteUsdPerMillion',\n 'outputUsdPerMillion',\n] as const\n\n/** A rates file: `{ \"<model id>\": { inputUsdPerMillion, outputUsdPerMillion, ... } }`. */\nexport function readPricingFile(path: string): Map<string, CustomTokenPricing> {\n const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error(`--pricing ${path}: expected a JSON object of rates by model id`)\n }\n const rates = new Map<string, CustomTokenPricing>()\n for (const [model, value] of Object.entries(parsed)) {\n const fields = typeof value === 'object' && value !== null ? value : {}\n for (const field of RATE_FIELDS) {\n const rate = (fields as Record<string, unknown>)[field]\n const required = field === 'inputUsdPerMillion' || field === 'outputUsdPerMillion'\n if (typeof rate !== 'number' && (required || rate !== undefined)) {\n throw new Error(`--pricing ${path}: ${JSON.stringify(model)}.${field} must be a number`)\n }\n }\n const pricing = fields as CustomTokenPricing\n // The cost ledger owns what a valid rate is; price nothing to have it check these.\n costForTokenPricing(pricing, { inputTokens: 0, outputTokens: 0 })\n rates.set(model, pricing)\n }\n return rates\n}\n\nexport async function runSkillUsageCommand(\n argv: readonly string[],\n io: SkillUsageCommandIo = PROCESS_IO,\n): Promise<number> {\n if (argv.includes('--help') || argv.includes('-h')) {\n io.stdout(`${USAGE}\\n`)\n return 0\n }\n let args: SkillUsageArgs\n let sinceMs: number | undefined\n let rates: Map<string, CustomTokenPricing> | undefined\n try {\n args = parseArgs(argv)\n rates = args.pricing === null ? undefined : readPricingFile(resolve(args.pricing))\n sinceMs = args.since === null ? undefined : parseSince(args.since, (io.now ?? Date.now)())\n } catch (error) {\n io.stderr(`${errorMessage(error)}\\n${USAGE}\\n`)\n return 2\n }\n try {\n const report = await buildSkillUsageReport(\n harnessSkillSessions(\n args.harness,\n resolve(args.directory),\n sinceMs === undefined ? {} : { sinceMs },\n ),\n {\n ...(sinceMs === undefined ? {} : { sinceMs }),\n ...(rates === undefined ? {} : { pricing: (model: string) => rates?.get(model) }),\n readSkillFile,\n },\n )\n const table = renderSkillUsageTable(report, args.limit)\n if (args.format === 'table') {\n io.stdout(table)\n } else {\n io.stdout(`${JSON.stringify(report, null, 2)}\\n`)\n if (args.format === 'both') io.stderr(table)\n }\n return 0\n } catch (error) {\n io.stderr(`agent-eval skill-usage: ${errorMessage(error)}\\n`)\n return 1\n }\n}\n","/**\n * Intent records from recorded sessions.\n *\n * A session's typed turns are cut into intents. A turn that a labeler calls a\n * correction or a re-ask attaches to the intent already open; any other turn\n * opens a new one and closes the open one. A turn nobody labeled opens a new\n * intent, and the intent it closes then cannot say how many corrections it\n * drew. The span of an intent runs from its opening turn to the turn that\n * closes it, or to the session's end, and its cost and procedures are those of\n * the events in that span.\n */\n\nimport { createHash } from 'node:crypto'\nimport type { InvocationChanges } from '../procedure-registry/change-outcome'\nimport type { SessionChange, SkillSessionRecord, SkillUsageReportOptions } from '../skill-usage'\nimport { afterInvocation, instant } from '../skill-usage/report'\nimport type {\n IntentCost,\n IntentLabeler,\n IntentRecord,\n IntentTurn,\n IntentTurnLabel,\n} from './contract'\n\ninterface Thread {\n openedAtIndex: number\n startEvent: number\n startAt: string | null\n promptSha256: string\n promptChars: number\n turnId: string\n label: IntentTurnLabel | null\n userTurns: number\n corrections: number\n reasks: number\n correctionsKnown: boolean\n reasksKnown: boolean\n endEvent: number\n endAt: string | null\n closedBy: 'next-intent' | 'session-end'\n}\n\n/** An intent before its procedures and outcomes are joined. */\nexport interface IntentDraft {\n record: Omit<IntentRecord, 'procedures' | 'changes' | 'end'> & {\n end: Omit<IntentRecord['end'], 'reachedDone' | 'abandoned' | 'evidence'>\n }\n /** Events [from, to) of the session. */\n span: { from: number; to: number }\n /** The span's instants, for work done in subagents. `to` null: open. */\n window: { from: string | null; to: string | null }\n /** Changes whose tool call is in the span. undefined: the reader records none. */\n changeRefs: string[] | undefined\n}\n\nconst sha256 = (text: string): string => createHash('sha256').update(text).digest('hex')\n\nfunction isCorrection(label: IntentTurnLabel | null): boolean | null {\n if (label === null) return null\n if (label.kind === 'correction') return true\n return label.correction\n}\n\nfunction cost(\n session: SkillSessionRecord,\n thread: Thread,\n options: SkillUsageReportOptions,\n): IntentCost {\n const after = afterInvocation(session, thread.startEvent - 1, thread.startAt, options, {\n eventIndex: thread.endEvent,\n at: thread.endAt,\n })\n return {\n tokens: after.modelCalls > 0 && after.modelCallsWithoutUsage === 0 ? after.tokens.total : null,\n usd: after.pricedModelCalls > 0 && after.unpricedModelCalls === 0 ? after.costUsd : null,\n wallMs: after.wallMs,\n modelCalls: after.modelCalls,\n }\n}\n\nfunction refsInSpan(session: SkillSessionRecord, from: number, to: number): string[] | undefined {\n if (session.changes === undefined) return undefined\n const position = new Map<string, number>()\n session.events.forEach((event, index) => {\n if (event.kind === 'tool') position.set(event.id, index)\n else if (event.kind === 'skill') position.set(event.callId, index)\n })\n const refs = new Set<string>()\n for (const change of session.changes as SessionChange[]) {\n const index = position.get(change.callId)\n if (index !== undefined && index >= from && index < to) refs.add(change.ref)\n }\n return [...refs].sort()\n}\n\n/**\n * Cut one session's typed turns into intents. Returns none when the reader\n * records no typed turns, and the caller counts that session apart.\n */\nexport async function deriveSessionIntents(\n session: SkillSessionRecord,\n labeler: IntentLabeler | undefined,\n options: SkillUsageReportOptions,\n /** True for a typed turn that is no intent: another agent's relay, a harness probe. Such a turn is skipped whole. */\n ignore?: (turn: IntentTurn) => boolean,\n): Promise<IntentDraft[] | null> {\n if (session.turns === undefined) return null\n const threads: Thread[] = []\n let open: Thread | null = null\n let previousText: string | null = null\n\n const close = (\n thread: Thread,\n by: 'next-intent' | 'session-end',\n at: string | null,\n event: number,\n ): void => {\n thread.closedBy = by\n thread.endAt = at\n thread.endEvent = event\n }\n\n for (const [index, turn] of session.turns.entries()) {\n if (options.sinceMs !== undefined) {\n const at = instant(turn.at)\n if (at === null || at < options.sinceMs) continue\n }\n const context: IntentTurn = {\n harness: session.harness,\n sessionId: session.sessionId,\n index,\n at: turn.at,\n text: turn.text,\n previousText,\n }\n if (ignore?.(context) === true) continue\n const label = labeler === undefined ? null : await labeler(context)\n previousText = turn.text\n const correction = isCorrection(label)\n const reask = label === null ? null : label.reask\n const attaches = open !== null && (correction === true || reask === true)\n if (open !== null) {\n // Every turn after an intent says whether it corrected or re-asked it.\n if (correction === null) open.correctionsKnown = false\n else if (correction) open.corrections += 1\n if (reask === null) open.reasksKnown = false\n else if (reask) open.reasks += 1\n }\n if (attaches && open !== null) {\n open.userTurns += 1\n continue\n }\n if (open !== null) close(open, 'next-intent', turn.at, turn.eventIndex)\n open = {\n openedAtIndex: index,\n startEvent: turn.eventIndex,\n startAt: turn.at,\n promptSha256: sha256(turn.text),\n promptChars: turn.text.length,\n turnId: turn.id,\n label,\n userTurns: 1,\n corrections: 0,\n reasks: 0,\n correctionsKnown: true,\n reasksKnown: true,\n endEvent: session.events.length,\n endAt: session.endedAt,\n closedBy: 'session-end',\n }\n threads.push(open)\n }\n\n return threads.map((thread) => {\n const intentId = sha256(`${session.harness}\\u0000${session.sessionId}\\u0000${thread.turnId}`)\n return {\n record: {\n intentId,\n harness: session.harness,\n sessionId: session.sessionId,\n at: thread.startAt,\n prompt: { sha256: thread.promptSha256, chars: thread.promptChars },\n label:\n thread.label === null\n ? null\n : { source: thread.label.source, kind: thread.label.kind, done: thread.label.done },\n cost: cost(session, thread, options),\n end: {\n userTurns: thread.userTurns,\n corrections: thread.correctionsKnown ? thread.corrections : null,\n reasks: thread.reasksKnown ? thread.reasks : null,\n closedBy: thread.closedBy,\n },\n },\n span: { from: thread.startEvent, to: thread.endEvent },\n window: { from: thread.startAt, to: thread.closedBy === 'next-intent' ? thread.endAt : null },\n changeRefs: refsInSpan(session, thread.startEvent, thread.endEvent),\n }\n })\n}\n\n/** Whether a change reading says the change reached its done line: merged and not fixed within the window. */\nexport function changesReachedDone(changes: InvocationChanges): {\n reachedDone: boolean | null\n abandoned: boolean | null\n} {\n if (changes.status !== 'joined' || changes.outcomes.length === 0) {\n return { reachedDone: null, abandoned: null }\n }\n const outcomes = changes.outcomes\n const unmerged = outcomes.some((outcome) => outcome.merged === false)\n const fixed = outcomes.some((outcome) => outcome.merged === true && outcome.hotfixed === true)\n const clean = outcomes.every((outcome) => outcome.merged === true && outcome.hotfixed === false)\n return {\n reachedDone: unmerged || fixed ? false : clean ? true : null,\n abandoned: unmerged ? true : outcomes.every((o) => o.merged === true) ? false : null,\n }\n}\n","/**\n * The intent record: what a person asked for, what served it, what it cost and\n * how it ended.\n *\n * An intent is the input to everything else. Any prompt counts: a task, a\n * problem, a project, information the person shares, or a correction. The\n * record holds the prompt's digest and length, never its text, so a record can\n * be kept and shared where the words cannot.\n *\n * Three things are kept apart from zero throughout: a label nobody gave, a\n * measure no event reported, and a change whose outcome nobody supplied. A\n * correction is counted after the fact as an outcome. Nothing here predicts one.\n */\n\nimport type { InvocationChanges } from '../procedure-registry/change-outcome'\n\nexport type IntentKind = 'task' | 'problem' | 'project' | 'information' | 'correction'\n\nexport const INTENT_KINDS: readonly IntentKind[] = [\n 'task',\n 'problem',\n 'project',\n 'information',\n 'correction',\n]\n\n/**\n * How a prompt says when it is finished. `stated`: the prompt names a done\n * line. `inferred`: it names none and the labeler supplied one. `none`: the\n * labeler found none to state or infer.\n */\nexport type IntentDoneBasis = 'stated' | 'inferred' | 'none'\n\n/**\n * What a labeler says of one typed turn. Each field is the labeler's or null:\n * a labeler that did not look says null, and null is never read as `false`.\n */\nexport interface IntentTurnLabel {\n /** Who labeled: a model, a lexical rule, a person. Carried onto the record. */\n source: string\n kind: IntentKind | null\n done: IntentDoneBasis | null\n /** The turn tells the agent its last work was wrong. */\n correction: boolean | null\n /** The turn asks again for what an open intent already asked. */\n reask: boolean | null\n}\n\n/** One typed turn, as a labeler reads it. The text is private: do not keep it. */\nexport interface IntentTurn {\n harness: string\n sessionId: string\n /** Position among the session's typed turns, from 0. */\n index: number\n at: string | null\n text: string\n /** The turn before this one in the session, when there is one. */\n previousText: string | null\n}\n\n/** The labeler is the caller's: a model pass, a lexical rule, a person's labels looked up by turn. */\nexport type IntentLabeler = (\n turn: IntentTurn,\n) => IntentTurnLabel | null | Promise<IntentTurnLabel | null>\n\nexport interface IntentCost {\n /** Tokens of the model calls in the intent's span; null where any call recorded no usage, or there was none. */\n tokens: number | null\n /** null where any call could not be priced: unknown, not free. */\n usd: number | null\n /** From the intent's turn to the turn that closed it, or the session's end. */\n wallMs: number | null\n modelCalls: number\n}\n\nexport type IntentClosedBy = 'next-intent' | 'session-end'\n\n/** What the evidence for `reachedDone` is. `none`: nothing says. */\nexport type IntentEndEvidence = 'change-outcome' | 'moved-on' | 'none'\n\nexport interface IntentEnd {\n /** The opening turn and every turn attached to it. */\n userTurns: number\n /** Corrections after the opening turn. null when a following turn's label did not say. */\n corrections: number | null\n reasks: number | null\n closedBy: IntentClosedBy\n /**\n * The intent reached its done line. From the outcome of its changes when they\n * have one (merged, and no fix within the window); else true when the person\n * moved on to another intent; else null. A session that simply ends says nothing.\n */\n reachedDone: boolean | null\n /** The change the intent produced did not merge. Never inferred from silence. */\n abandoned: boolean | null\n evidence: IntentEndEvidence\n}\n\nexport interface IntentRecord {\n /** sha256 of the harness, session and the opening turn's id. */\n intentId: string\n harness: string\n sessionId: string\n at: string | null\n prompt: { sha256: string; chars: number }\n /** The opening turn's label; null when no labeler said anything of it. */\n label: Pick<IntentTurnLabel, 'source' | 'kind' | 'done'> | null\n /** Registry keys of the procedure versions invoked in the intent's span, in this session and in the subagents it spawned. */\n procedures: string[]\n cost: IntentCost\n end: IntentEnd\n /** The changes produced in the intent's span, in this session, with the outcomes supplied for them. */\n changes: InvocationChanges\n}\n\nexport interface IntentKindSummary {\n /** null: intents no labeler gave a kind. */\n kind: IntentKind | null\n intents: number\n /** `reachedDone` is known. */\n knownEnd: number\n knownEndShare: number | null\n /** The correction count is known. */\n knownCorrections: number\n joinedToChange: number\n withChangeOutcome: number\n}\n\nexport interface IntentReport {\n intents: IntentRecord[]\n summary: {\n intents: number\n sessionsWithTurns: number\n /** Sessions whose reader does not tell a person's turn from other messages. */\n sessionsWithoutTurns: number\n /** Intents whose opening turn a labeler labeled. */\n labeled: number\n knownEnd: number\n knownEndShare: number | null\n byKind: IntentKindSummary[]\n }\n notes: string[]\n}\n","/** Join intent drafts to the procedure versions that served them and the outcomes of their changes. */\n\nimport type { ChangeOutcomeIndex, InvocationChanges } from '../procedure-registry/change-outcome'\nimport { instant } from '../skill-usage/report'\nimport { INTENT_KINDS, type IntentKind, type IntentRecord, type IntentReport } from './contract'\nimport { changesReachedDone, type IntentDraft } from './derive'\n\n/** One counted procedure invocation, placed in its session. */\nexport interface SessionInvocation {\n /** The event's position in the session. */\n index: number\n at: string | null\n /** The registry key of the version that ran. */\n key: string\n}\n\nexport interface SessionIntents {\n sessionId: string\n parentSessionId: string | null\n /** null: the reader records no typed turns. */\n drafts: IntentDraft[] | null\n invocations: SessionInvocation[]\n}\n\nconst NOTES = [\n 'Intents are cut from typed turns: a turn a labeler calls a correction or a re-ask attaches to the open intent, and any other turn, labeled or not, opens a new one. Without labels every turn is its own intent and no intent knows its corrections.',\n 'An intent joins the changes whose tool call lies in its span, in its own session only. Work and changes in subagents count toward the procedures that served it, by time, and not toward its cost or changes.',\n 'reachedDone comes from the outcome of the intent’s changes when they have one, else is true when the person moved on to another intent, else unknown. A session that ends says nothing.',\n]\n\nfunction joinChanges(refs: string[] | undefined, outcomes: ChangeOutcomeIndex): InvocationChanges {\n if (refs === undefined) return { status: 'not-recorded' }\n if (refs.length === 0) return { status: 'none' }\n return {\n status: 'joined',\n refs,\n outcomes: refs.flatMap((ref) => {\n const reading = outcomes.byRef.get(ref)\n return reading === undefined ? [] : [reading]\n }),\n }\n}\n\nexport function buildIntentReport(\n sessions: readonly SessionIntents[],\n outcomes: ChangeOutcomeIndex,\n): IntentReport {\n const byId = new Map(sessions.map((session) => [session.sessionId, session]))\n // Work in a subagent belongs to the intents of the sessions that spawned it, when it ran inside their span.\n const inherited = new Map<IntentDraft, Set<string>>()\n for (const session of sessions) {\n for (\n let parent = session.parentSessionId, hops = 0;\n parent !== null && hops < 64;\n parent = byId.get(parent)?.parentSessionId ?? null, hops++\n ) {\n for (const draft of byId.get(parent)?.drafts ?? []) {\n const from = instant(draft.window.from)\n const to = instant(draft.window.to)\n if (from === null) continue\n for (const invocation of session.invocations) {\n const at = instant(invocation.at)\n if (at === null || at < from || (to !== null && at >= to)) continue\n const keys = inherited.get(draft) ?? new Set<string>()\n keys.add(invocation.key)\n inherited.set(draft, keys)\n }\n }\n }\n }\n\n const intents: IntentRecord[] = []\n let sessionsWithTurns = 0\n let sessionsWithoutTurns = 0\n for (const session of sessions) {\n if (session.drafts === null) {\n sessionsWithoutTurns += 1\n continue\n }\n sessionsWithTurns += 1\n for (const draft of session.drafts) {\n const keys = new Set(inherited.get(draft))\n for (const invocation of session.invocations) {\n if (invocation.index >= draft.span.from && invocation.index < draft.span.to) {\n keys.add(invocation.key)\n }\n }\n const changes = joinChanges(draft.changeRefs, outcomes)\n const fromChanges = changesReachedDone(changes)\n const movedOn = draft.record.end.closedBy === 'next-intent'\n const evidence =\n fromChanges.reachedDone !== null ? 'change-outcome' : movedOn ? 'moved-on' : 'none'\n intents.push({\n ...draft.record,\n procedures: [...keys].sort(),\n end: {\n ...draft.record.end,\n reachedDone: fromChanges.reachedDone ?? (movedOn ? true : null),\n abandoned: fromChanges.abandoned,\n evidence,\n },\n changes,\n })\n }\n }\n\n const kinds: Array<IntentKind | null> = [...INTENT_KINDS, null]\n const share = (part: number, whole: number): number | null => (whole === 0 ? null : part / whole)\n const known = (record: IntentRecord): boolean => record.end.reachedDone !== null\n return {\n intents,\n summary: {\n intents: intents.length,\n sessionsWithTurns,\n sessionsWithoutTurns,\n labeled: intents.filter((record) => record.label !== null).length,\n knownEnd: intents.filter(known).length,\n knownEndShare: share(intents.filter(known).length, intents.length),\n byKind: kinds.map((kind) => {\n const of = intents.filter((record) => (record.label?.kind ?? null) === kind)\n return {\n kind,\n intents: of.length,\n knownEnd: of.filter(known).length,\n knownEndShare: share(of.filter(known).length, of.length),\n knownCorrections: of.filter((record) => record.end.corrections !== null).length,\n joinedToChange: of.filter((record) => record.changes.status === 'joined').length,\n withChangeOutcome: of.filter(\n (record) => record.changes.status === 'joined' && record.changes.outcomes.length > 0,\n ).length,\n }\n }),\n },\n notes: [...NOTES],\n }\n}\n","/**\n * What happened to a change, supplied by the caller, and the join that attaches\n * it to the procedure invocations of the session that produced the change.\n *\n * A turn-level signal predicts an operator's correction poorly; a change is the\n * unit that has an outcome. The caller says, per change (a commit or a pull\n * request, named by one reference string), whether it merged, whether its gate\n * passed on the first try, and whether a fix to it followed. Any of the three\n * can be unknown, and unknown is never read as `false`.\n */\n\nimport { ValidationError } from '../errors'\n\n/** A later merged change that fixes this one lands within this many days. */\nexport const HOTFIX_WINDOW_DAYS = 7\n\nexport interface ChangeOutcome {\n /** The change's reference, as the session reader names it: `owner/repo#123` for a pull request. */\n ref: string\n /** null: not known. */\n merged: boolean | null\n /** The gate passed on its first run. null: no gate result, or not known. */\n gateGreenFirstTry: boolean | null\n /**\n * A later merged change fixed this one within `hotfixWindowDays`. `false`\n * asserts the whole window was observed with no such fix; null means the\n * window was still open or the fixes were not searched.\n */\n hotfixed: boolean | null\n /** The window `hotfixed` was judged over. Must be {@link HOTFIX_WINDOW_DAYS}. */\n hotfixWindowDays: number\n}\n\n/** A change's outcome as the registry reads it: each field is the caller's, or unknown. */\nexport interface ChangeOutcomeReading {\n ref: string\n merged: boolean | null\n gateGreenFirstTry: boolean | null\n hotfixed: boolean | null\n}\n\nexport interface ChangeOutcomeIndex {\n byRef: ReadonlyMap<string, ChangeOutcomeReading>\n /** Outcomes whose window is not the 7-day one: their `hotfixed` is read as unknown. */\n otherWindow: number\n duplicates: number\n}\n\n/**\n * Index outcomes by change reference. An outcome judged over another window\n * keeps `merged` and `gateGreenFirstTry` and loses `hotfixed`: a 3-day and a\n * 14-day \"no fix\" are different claims, and the registry has one definition.\n * Two outcomes for one reference must agree; a reference given twice with\n * different readings throws.\n */\nexport function indexChangeOutcomes(outcomes: Iterable<ChangeOutcome>): ChangeOutcomeIndex {\n const byRef = new Map<string, ChangeOutcomeReading>()\n let otherWindow = 0\n let duplicates = 0\n for (const outcome of outcomes) {\n if (typeof outcome.ref !== 'string' || outcome.ref === '') {\n throw new ValidationError('a change outcome needs a non-empty ref')\n }\n const sameWindow = outcome.hotfixWindowDays === HOTFIX_WINDOW_DAYS\n if (!sameWindow) otherWindow += 1\n const reading: ChangeOutcomeReading = {\n ref: outcome.ref,\n merged: outcome.merged,\n gateGreenFirstTry: outcome.gateGreenFirstTry,\n hotfixed: sameWindow ? outcome.hotfixed : null,\n }\n const known = byRef.get(outcome.ref)\n if (known !== undefined) {\n duplicates += 1\n if (JSON.stringify(known) !== JSON.stringify(reading)) {\n throw new ValidationError(`change ${outcome.ref} has two different outcomes`)\n }\n continue\n }\n byRef.set(outcome.ref, reading)\n }\n return { byRef, otherWindow, duplicates }\n}\n\n/** One invocation's changes with their outcomes. */\nexport type InvocationChanges =\n /** The session reader does not record changes: the join has no evidence either way. */\n | { status: 'not-recorded' }\n /** The reader looked, and neither the session nor an ancestor produced a change. */\n | { status: 'none' }\n | {\n status: 'joined'\n /** Changes of the invocation's own session and of the sessions that spawned it. */\n refs: string[]\n /** Outcomes the caller supplied for those changes; a change absent here has none. */\n outcomes: ChangeOutcomeReading[]\n }\n\nexport interface SessionChanges {\n parentSessionId: string | null\n /** undefined: the reader does not record changes. */\n refs: readonly string[] | undefined\n}\n\n/**\n * The changes an invocation produced: those of its session, and of every\n * session that spawned it, since a subagent's work belongs to the change its\n * parent shipped. A session absent from `sessions` ends the walk, and a cycle\n * in the parent links is cut where it repeats.\n */\nexport function joinInvocationToChanges(\n sessionId: string,\n sessions: ReadonlyMap<string, SessionChanges>,\n outcomes: ChangeOutcomeIndex,\n): InvocationChanges {\n const refs = new Set<string>()\n let recorded = false\n const visited = new Set<string>()\n for (\n let current: string | null = sessionId;\n current !== null && !visited.has(current);\n current = sessions.get(current)?.parentSessionId ?? null\n ) {\n visited.add(current)\n const session = sessions.get(current)\n if (session?.refs === undefined) continue\n recorded = true\n for (const ref of session.refs) refs.add(ref)\n }\n if (!recorded) return { status: 'not-recorded' }\n if (refs.size === 0) return { status: 'none' }\n const sorted = [...refs].sort()\n return {\n status: 'joined',\n refs: sorted,\n outcomes: sorted.flatMap((ref) => {\n const reading = outcomes.byRef.get(ref)\n return reading === undefined ? [] : [reading]\n }),\n }\n}\n","/**\n * The procedure registry: a projection, not a service.\n *\n * A procedure is anything an agent can be given and have taken away: a skill, a\n * workflow, a workflow whose steps are workflows, or a skill whose object is\n * other procedures. A version of it is named by the sha256 of its materialized\n * files. This module reads search ledgers and recorded sessions and answers,\n * for each version: where it came from, every time it ran, what that cost, what\n * came of the change it was part of, and every decision taken on it.\n *\n * Nothing here writes. The search ledger stays the one record of a search and\n * the session records stay the one record of a session; the registry is the\n * join of the two on the version digest, rebuilt from them on demand.\n *\n * Three things are kept apart from zero throughout, as in the sources: a\n * measure no execution reported, a change whose outcome the caller did not\n * supply, and a session whose reader does not record changes.\n */\n\nimport type {\n SearchEdgeAttribution,\n SearchEdgeOperator,\n SearchTokenUnknownCause,\n} from '../campaign/search-ledger-types'\nimport type { SearchStateView } from '../campaign/search-state'\nimport type { SearchNode } from '../campaign/search-state-types'\nimport { ValidationError } from '../errors'\nimport type { IntentLabeler, IntentReport, IntentTurn } from '../intent-record/contract'\nimport { deriveSessionIntents } from '../intent-record/derive'\nimport { buildIntentReport, type SessionIntents } from '../intent-record/report'\nimport type {\n SkillInvocationEvent,\n SkillInvoker,\n SkillSessionSource,\n SkillUsageReportOptions,\n} from '../skill-usage'\nimport { afterInvocation, instant } from '../skill-usage/report'\nimport {\n type ChangeOutcome,\n type ChangeOutcomeIndex,\n type ChangeOutcomeReading,\n HOTFIX_WINDOW_DAYS,\n type InvocationChanges,\n indexChangeOutcomes,\n joinInvocationToChanges,\n type SessionChanges,\n} from './change-outcome'\n\n/** What a procedure is. The registry never infers it; the caller classifies, and an unclassified version says so. */\nexport type ProcedureKind = 'skill' | 'workflow' | 'higher-order-workflow' | 'operator-skill'\n\nexport interface ProcedureNodeIdentity {\n /** The version digest when the node's artifact is not the procedure's own bytes, for example a profile that mounts a skill. */\n digest?: string\n kind?: ProcedureKind\n name?: string\n}\n\nexport interface ProcedureRegistryInput {\n searches?: Iterable<SearchStateView>\n sessions?: SkillSessionSource\n outcomes?: Iterable<ChangeOutcome>\n}\n\nexport interface ProcedureRegistryOptions extends SkillUsageReportOptions {\n /** Which procedure a search node is. Default: the node's own artifact digest, unclassified. */\n procedureOfNode?: (node: SearchNode, search: SearchStateView) => ProcedureNodeIdentity | null\n /** What kind of procedure a session's skill is. Default: `skill`. */\n kindOfSkill?: (skill: string) => ProcedureKind\n /**\n * Cut each session's typed turns into intents and join them to the versions\n * and outcomes. Absent: no intents are derived. A labeler is the caller's;\n * without one every turn is an unlabeled intent.\n */\n intents?: { labeler?: IntentLabeler; ignore?: (turn: IntentTurn) => boolean }\n}\n\n/** A measure summed over the executions that reported it. */\nexport interface MeasureTotal {\n sum: number\n /** Executions that reported it. */\n measured: number\n /** Executions that did not: they are not in `sum`, and are not zero. */\n unmeasured: number\n}\n\nexport interface ExecutionMeasures {\n tokens: number | null\n /** null where no model call could be priced: unknown, not free. */\n usd: number | null\n wallMs: number | null\n}\n\nexport interface CellExecution extends ExecutionMeasures {\n source: 'search-cell'\n searchId: string\n nodeId: string\n cellId: string\n split: string\n stage: string\n /** `passed`, `failed` or `errored`; null for a cell never settled. */\n outcome: string | null\n /** Why a cell failed or errored, as its producer coded it; null for a pass. */\n outcomeReason: { code: string; message: string } | null\n score: number | null\n /**\n * Why `tokens` is null: the producer's cause (`not-recorded`, `partial`, `not-measurable`, or\n * null on a ledger written before causes) and its words. Null when the tokens are known.\n */\n tokensUnknown: { cause: SearchTokenUnknownCause | null; reason: string } | null\n /** What the cell's attempts did report when `tokens` is null: a floor, never the total. Null when they reported none. */\n tokensFloor: number | null\n /**\n * How the cell's dollars are known. `measured`: `usd` is the charge. `subscription`: every\n * attempt ran on a seat that bills nothing per call, so there is no dollar figure and `usd`\n * is null by design, neither unknown nor a measured zero. `unknown`: no charge was read.\n */\n costBasis: 'measured' | 'subscription' | 'unknown'\n}\n\nexport interface SessionExecution extends ExecutionMeasures {\n source: 'session'\n harness: string\n sessionId: string\n callId: string\n skill: string\n invoker: SkillInvoker\n at: string | null\n /** The harness refused the call; null when no result is recorded. */\n failed: boolean | null\n /** What the invocation's changes came to. Tokens, cost and wall time run from the invocation to the session's end. */\n changes: InvocationChanges\n}\n\nexport type ProcedureExecution = CellExecution | SessionExecution\n\nexport interface ProcedureEdge {\n searchId: string\n edgeId: string\n operator: SearchEdgeOperator\n attribution: SearchEdgeAttribution\n proposer: { kind: string; name: string } | null\n parents: Array<{ searchId: string; nodeId: string; digest: string | null }>\n /** A later edge into a node that already existed: the same content proposed again. */\n reproposal: boolean\n}\n\nexport interface ProcedureDecision {\n searchId: string\n nodeId: string\n source: 'node-decided' | 'claim'\n /** `advanced`, `pruned`, `invalid`, `finalist`, `selected`, `rejected`; or the claim's `ship`, `hold`, `test-cannot-resolve`. */\n status: string\n rung: number | null\n rule: string | null\n reason: string\n /** The node's latest decision in its search; earlier ones are history. */\n current: boolean\n}\n\nexport interface SearchAppearance {\n searchId: string\n nodeId: string\n subject: string\n closed: boolean\n /** The node's latest decision, or null while undecided. */\n status: string | null\n}\n\nexport interface ChangeCounts {\n yes: number\n no: number\n /** No outcome supplied, or that field unknown. */\n unknown: number\n}\n\nexport interface ProcedureChanges {\n /** Counted invocations in sessions. */\n invocations: number\n joined: number\n none: number\n notRecorded: number\n /** Changes the joined invocations are part of, each counted once. */\n distinctChanges: number\n /** Of those, the changes the caller supplied an outcome for. */\n withOutcome: number\n merged: ChangeCounts\n gateGreenFirstTry: ChangeCounts\n hotfixed: ChangeCounts\n}\n\nexport interface ProcedureVersion {\n /** `sha256:<hex>`, or `unversioned:<skill>` when no invocation recorded the text it loaded. */\n key: string\n digest: string | null\n names: string[]\n /** null: unclassified, never guessed. */\n kind: ProcedureKind | null\n /** Digests of the lineage parents. A parent whose digest is unknown is absent here and null in its edge. */\n parents: string[]\n edges: ProcedureEdge[]\n searches: SearchAppearance[]\n decisions: ProcedureDecision[]\n cells: {\n count: number\n passed: number\n failed: number\n errored: number\n /** Cells whose dollars are a subscription seat's: a known basis with no figure, counted in neither `usd.measured` nor `usd.unmeasured`. */\n subscription: number\n tokens: MeasureTotal\n usd: MeasureTotal\n wallMs: MeasureTotal\n }\n sessions: {\n invocations: number\n tokens: MeasureTotal\n usd: MeasureTotal\n wallMs: MeasureTotal\n changes: ProcedureChanges\n }\n executions: ProcedureExecution[]\n}\n\nexport interface ChangeJoinSummary {\n /** The definition of \"needed a hot-fix\" every outcome was held to. */\n hotfixWindowDays: number\n invocations: number\n joined: number\n none: number\n notRecorded: number\n /** joined / invocations; null when there are none. This is the share the program's first check reads. */\n joinedShare: number | null\n /** Joined invocations with an outcome for at least one of their changes. */\n withOutcome: number\n withOutcomeShare: number | null\n distinctChanges: number\n outcomesSupplied: number\n outcomesInWrongWindow: number\n}\n\nexport interface ProcedureRegistry {\n searches: { read: number; closed: number }\n sessions: { read: number; unreadable: number; withInvocation: number }\n invocations: number\n changeJoin: ChangeJoinSummary\n versions: ProcedureVersion[]\n /** Present when the options asked for intents. */\n intents: IntentReport | null\n unreadable: Array<{ source: string; error: string }>\n notes: string[]\n}\n\nconst NOTES = [\n 'Session executions measure from the invocation to the end of its session, as `skill-usage` does, so a session that invokes several procedures counts its later work under each and the totals overlap across versions.',\n 'Search-cell and session measures are different quantities (a cell is one task, a session is open-ended) and are never added together.',\n 'An invocation joins the changes of its own session and of the sessions that spawned it. It joins every change the session produced, before and after the invocation.',\n]\n\ninterface Builder {\n key: string\n digest: string | null\n names: Set<string>\n kind: ProcedureKind | null\n parents: Set<string>\n edges: ProcedureEdge[]\n searches: SearchAppearance[]\n decisions: ProcedureDecision[]\n executions: ProcedureExecution[]\n}\n\nfunction normalizeDigest(value: string): string {\n const hex = value.startsWith('sha256:') ? value.slice('sha256:'.length) : value\n if (!/^[0-9a-f]{64}$/.test(hex)) {\n throw new ValidationError(`a procedure digest is a sha256, got ${JSON.stringify(value)}`)\n }\n return `sha256:${hex}`\n}\n\nfunction compareText(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0\n}\n\nfunction emptyMeasure(): MeasureTotal {\n return { sum: 0, measured: 0, unmeasured: 0 }\n}\n\nfunction addMeasure(total: MeasureTotal, value: number | null): void {\n if (value === null) {\n total.unmeasured += 1\n } else {\n total.sum += value\n total.measured += 1\n }\n}\n\nfunction emptyCounts(): ChangeCounts {\n return { yes: 0, no: 0, unknown: 0 }\n}\n\nfunction count(counts: ChangeCounts, value: boolean | null): void {\n if (value === null) counts.unknown += 1\n else if (value) counts.yes += 1\n else counts.no += 1\n}\n\n/** The caller's reading of one change field, across the readings of every outcome the change has. */\nfunction pick(\n readings: ChangeOutcomeReading | undefined,\n field: 'merged' | 'gateGreenFirstTry' | 'hotfixed',\n): boolean | null {\n return readings === undefined ? null : readings[field]\n}\n\nfunction summarizeChanges(executions: readonly SessionExecution[], index: ChangeOutcomeIndex) {\n const changes: ProcedureChanges = {\n invocations: executions.length,\n joined: 0,\n none: 0,\n notRecorded: 0,\n distinctChanges: 0,\n withOutcome: 0,\n merged: emptyCounts(),\n gateGreenFirstTry: emptyCounts(),\n hotfixed: emptyCounts(),\n }\n const refs = new Set<string>()\n for (const execution of executions) {\n const joined = execution.changes\n if (joined.status === 'joined') {\n changes.joined += 1\n for (const ref of joined.refs) refs.add(ref)\n } else if (joined.status === 'none') {\n changes.none += 1\n } else {\n changes.notRecorded += 1\n }\n }\n changes.distinctChanges = refs.size\n for (const ref of [...refs].sort(compareText)) {\n const reading = index.byRef.get(ref)\n if (reading !== undefined) changes.withOutcome += 1\n count(changes.merged, pick(reading, 'merged'))\n count(changes.gateGreenFirstTry, pick(reading, 'gateGreenFirstTry'))\n count(changes.hotfixed, pick(reading, 'hotfixed'))\n }\n return changes\n}\n\nclass Registry {\n private readonly builders = new Map<string, Builder>()\n\n builder(key: string): Builder {\n let builder = this.builders.get(key)\n if (builder === undefined) {\n builder = {\n key,\n digest: key.startsWith('sha256:') ? key : null,\n names: new Set(),\n kind: null,\n parents: new Set(),\n edges: [],\n searches: [],\n decisions: [],\n executions: [],\n }\n this.builders.set(key, builder)\n }\n return builder\n }\n\n all(): Builder[] {\n return [...this.builders.values()]\n }\n}\n\ninterface NodeRef {\n searchId: string\n nodeId: string\n}\n\nconst nodeKey = (searchId: string, nodeId: string): string => `${searchId}\\u0000${nodeId}`\n\nfunction addSearch(\n registry: Registry,\n search: SearchStateView,\n keys: ReadonlyMap<string, string>,\n options: ProcedureRegistryOptions,\n): void {\n const subject = search.header?.subject ?? ''\n const closed = search.closed !== null\n const claim = search.closed?.claim ?? null\n const rootNodeId = search.rootNodeId\n\n for (const node of search.nodes()) {\n const key = keys.get(nodeKey(search.searchId, node.nodeId)) as string\n const identity = options.procedureOfNode?.(node, search) ?? null\n const builder = registry.builder(key)\n if (identity?.kind !== undefined) builder.kind = identity.kind\n if (identity?.name !== undefined) builder.names.add(identity.name)\n const latest = node.decisions.at(-1)\n builder.searches.push({\n searchId: search.searchId,\n nodeId: node.nodeId,\n subject,\n closed,\n status: latest === undefined ? null : latest.decision.status,\n })\n\n const resolve = (ref: NodeRef): string | null => {\n const parentKey = keys.get(nodeKey(ref.searchId, ref.nodeId))\n return parentKey?.startsWith('sha256:') ? parentKey : null\n }\n for (const parent of node.parents) {\n const digest = resolve(parent)\n if (digest !== null) builder.parents.add(digest)\n }\n node.edgeIds.forEach((edgeId, position) => {\n const edge = search.edge(edgeId)\n if (edge === undefined) return\n builder.edges.push({\n searchId: search.searchId,\n edgeId,\n operator: edge.operator,\n attribution: edge.attribution,\n proposer:\n edge.proposer === null ? null : { kind: edge.proposer.kind, name: edge.proposer.name },\n parents: edge.parents.map((parent) => ({\n searchId: parent.searchId,\n nodeId: parent.nodeId,\n digest: resolve(parent),\n })),\n reproposal: position > 0,\n })\n })\n\n node.decisions.forEach((record, position) => {\n builder.decisions.push({\n searchId: search.searchId,\n nodeId: node.nodeId,\n source: 'node-decided',\n status: record.decision.status,\n rung: record.decision.status === 'advanced' ? record.decision.rung : null,\n rule: record.rule,\n reason: record.reason,\n current: position === node.decisions.length - 1,\n })\n })\n\n for (const cell of search.cells({ nodeId: node.nodeId })) {\n // A cell that never ran, or never settled, is not an execution.\n if (cell.attempts === 0) continue\n const onSeat = cell.subscriptionAttempts === cell.attempts\n const countedTokens =\n cell.tokens.inputTokens + cell.tokens.outputTokens + cell.tokens.cachedTokens\n builder.executions.push({\n source: 'search-cell',\n searchId: search.searchId,\n nodeId: node.nodeId,\n cellId: cell.cellId,\n split: cell.split,\n stage: cell.stage,\n outcome: cell.outcome,\n outcomeReason: cell.outcomeReason,\n score: cell.score,\n tokens: cell.tokensKnown ? countedTokens : null,\n tokensUnknown: cell.tokensKnown ? null : cell.tokensUnknown,\n tokensFloor: cell.tokensKnown || countedTokens === 0 ? null : countedTokens,\n usd: cell.costKnown && !onSeat ? cell.spentUsd : null,\n costBasis: !cell.costKnown ? 'unknown' : onSeat ? 'subscription' : 'measured',\n wallMs: cell.wallKnown ? cell.wallMs : null,\n })\n }\n }\n\n // The claim is the search's own ship-or-hold decision. A hold or an\n // unresolved test keeps the root, so that is the node it is about.\n if (claim !== null) {\n const nodeId = claim.selected ?? rootNodeId\n const key = nodeId === null ? undefined : keys.get(nodeKey(search.searchId, nodeId))\n if (nodeId !== null && key !== undefined) {\n registry.builder(key).decisions.push({\n searchId: search.searchId,\n nodeId,\n source: 'claim',\n status: claim.decision,\n rung: null,\n rule: claim.rule.uri,\n reason: claim.reason,\n current: true,\n })\n }\n }\n}\n\ninterface PendingInvocation {\n builderKey: string\n sessionId: string\n harness: string\n event: SkillInvocationEvent\n measures: ExecutionMeasures\n}\n\n/**\n * Build the registry from search ledgers, recorded sessions and the outcomes of\n * the changes those sessions produced. Any of the three may be absent.\n *\n * An invocation is counted once per call id across the whole source, and with\n * `sinceMs` only invocations at or after it count, exactly as `skill-usage`\n * counts them; an undated invocation cannot be placed in the window and is\n * left out. Versions are ordered by executions, most first, then by key.\n */\nexport async function buildProcedureRegistry(\n input: ProcedureRegistryInput,\n options: ProcedureRegistryOptions = {},\n): Promise<ProcedureRegistry> {\n if (options.sinceMs !== undefined && !Number.isFinite(options.sinceMs)) {\n throw new ValidationError(\n `buildProcedureRegistry: sinceMs must be finite, got ${options.sinceMs}`,\n )\n }\n const outcomes = indexChangeOutcomes(input.outcomes ?? [])\n const registry = new Registry()\n\n const searches = [...(input.searches ?? [])]\n const keys = new Map<string, string>()\n for (const search of searches) {\n for (const node of search.nodes()) {\n const identity = options.procedureOfNode?.(node, search) ?? null\n keys.set(\n nodeKey(search.searchId, node.nodeId),\n normalizeDigest(identity?.digest ?? node.artifactDigest),\n )\n }\n }\n for (const search of searches) addSearch(registry, search, keys, options)\n\n const sessionChanges = new Map<string, SessionChanges>()\n const pending: PendingInvocation[] = []\n const unreadable: Array<{ source: string; error: string }> = []\n const seenCalls = new Set<string>()\n const sessions = { read: 0, unreadable: 0, withInvocation: 0 }\n const intentSessions: SessionIntents[] = []\n\n const versionDigest = (event: SkillInvocationEvent): string | null => {\n if (event.version !== null) return event.version.bodySha256\n if (event.skillFile === null || options.readSkillFile === undefined) return null\n const file = options.readSkillFile(event.skillFile)\n return file.succeeded ? file.bodySha256 : null\n }\n\n for await (const read of input.sessions ?? []) {\n if (!read.succeeded) {\n sessions.unreadable += 1\n unreadable.push({ source: read.source, error: read.error })\n continue\n }\n const session = read.value\n sessions.read += 1\n sessionChanges.set(session.sessionId, {\n parentSessionId: session.parentSessionId,\n refs: session.changes?.map((change) => change.ref),\n })\n let counted = false\n const placed: SessionIntents['invocations'] = []\n session.events.forEach((event, position) => {\n if (event.kind !== 'skill') return\n if (seenCalls.has(event.callId)) return\n seenCalls.add(event.callId)\n if (options.sinceMs !== undefined) {\n const at = instant(event.at)\n if (at === null || at < options.sinceMs) return\n }\n counted = true\n const hex = versionDigest(event)\n const key = hex === null ? `unversioned:${event.skill}` : normalizeDigest(hex)\n const builder = registry.builder(key)\n builder.names.add(event.skill)\n builder.kind ??= options.kindOfSkill?.(event.skill) ?? 'skill'\n placed.push({ index: position, at: event.at, key })\n const after = afterInvocation(session, position, event.at, options)\n pending.push({\n builderKey: key,\n sessionId: session.sessionId,\n harness: session.harness,\n event,\n measures: {\n tokens:\n after.modelCalls > 0 && after.modelCallsWithoutUsage === 0 ? after.tokens.total : null,\n usd: after.pricedModelCalls > 0 && after.unpricedModelCalls === 0 ? after.costUsd : null,\n wallMs: after.wallMs,\n },\n })\n })\n if (counted) sessions.withInvocation += 1\n if (options.intents !== undefined) {\n intentSessions.push({\n sessionId: session.sessionId,\n parentSessionId: session.parentSessionId,\n drafts: await deriveSessionIntents(\n session,\n options.intents.labeler,\n options,\n options.intents.ignore,\n ),\n invocations: placed,\n })\n }\n }\n\n const joins = { joined: 0, none: 0, notRecorded: 0, withOutcome: 0 }\n const joinedRefs = new Set<string>()\n for (const invocation of pending) {\n const { event } = invocation\n const changes = joinInvocationToChanges(invocation.sessionId, sessionChanges, outcomes)\n if (changes.status === 'joined') {\n joins.joined += 1\n for (const ref of changes.refs) joinedRefs.add(ref)\n if (changes.outcomes.length > 0) joins.withOutcome += 1\n } else if (changes.status === 'none') {\n joins.none += 1\n } else {\n joins.notRecorded += 1\n }\n registry.builder(invocation.builderKey).executions.push({\n source: 'session',\n harness: invocation.harness,\n sessionId: invocation.sessionId,\n callId: event.callId,\n skill: event.skill,\n invoker: event.invoker,\n at: event.at,\n failed: event.failed,\n ...invocation.measures,\n changes,\n })\n }\n\n const versions = registry.all().map((builder): ProcedureVersion => {\n const cells = {\n count: 0,\n passed: 0,\n failed: 0,\n errored: 0,\n subscription: 0,\n tokens: emptyMeasure(),\n usd: emptyMeasure(),\n wallMs: emptyMeasure(),\n }\n const sessionRuns = {\n invocations: 0,\n tokens: emptyMeasure(),\n usd: emptyMeasure(),\n wallMs: emptyMeasure(),\n }\n const runs: SessionExecution[] = []\n for (const execution of builder.executions) {\n if (execution.source === 'search-cell') {\n cells.count += 1\n if (execution.outcome === 'passed') cells.passed += 1\n else if (execution.outcome === 'failed') cells.failed += 1\n else if (execution.outcome === 'errored') cells.errored += 1\n addMeasure(cells.tokens, execution.tokens)\n if (execution.costBasis === 'subscription') cells.subscription += 1\n else addMeasure(cells.usd, execution.usd)\n addMeasure(cells.wallMs, execution.wallMs)\n } else {\n sessionRuns.invocations += 1\n addMeasure(sessionRuns.tokens, execution.tokens)\n addMeasure(sessionRuns.usd, execution.usd)\n addMeasure(sessionRuns.wallMs, execution.wallMs)\n runs.push(execution)\n }\n }\n return {\n key: builder.key,\n digest: builder.digest,\n names: [...builder.names].sort(compareText),\n kind: builder.kind,\n parents: [...builder.parents].sort(compareText),\n edges: builder.edges,\n searches: builder.searches,\n decisions: builder.decisions,\n cells,\n sessions: { ...sessionRuns, changes: summarizeChanges(runs, outcomes) },\n executions: builder.executions,\n }\n })\n versions.sort((a, b) => {\n const left = a.cells.count + a.sessions.invocations\n const right = b.cells.count + b.sessions.invocations\n return left !== right ? right - left : compareText(a.key, b.key)\n })\n\n const share = (part: number): number | null =>\n pending.length === 0 ? null : part / pending.length\n\n return {\n searches: { read: searches.length, closed: searches.filter((s) => s.closed !== null).length },\n sessions,\n invocations: pending.length,\n changeJoin: {\n hotfixWindowDays: HOTFIX_WINDOW_DAYS,\n invocations: pending.length,\n ...joins,\n joinedShare: share(joins.joined),\n withOutcomeShare: share(joins.withOutcome),\n distinctChanges: joinedRefs.size,\n outcomesSupplied: outcomes.byRef.size,\n outcomesInWrongWindow: outcomes.otherWindow,\n },\n versions,\n intents: options.intents === undefined ? null : buildIntentReport(intentSessions, outcomes),\n unreadable,\n notes: [...NOTES],\n }\n}\n","/** The registry as a short table: one row per procedure version. */\n\nimport type { MeasureTotal, ProcedureRegistry, ProcedureVersion } from './registry'\n\nfunction percent(share: number | null): string {\n return share === null ? 'n/a' : `${(share * 100).toFixed(1)}%`\n}\n\n/** A measure's sum, with how many executions did not report it. */\nfunction measure(total: MeasureTotal, digits = 0): string {\n if (total.measured === 0) return total.unmeasured === 0 ? '-' : 'unknown'\n const text = total.sum.toFixed(digits)\n return total.unmeasured === 0 ? text : `${text}+${total.unmeasured}?`\n}\n\nfunction digest(version: ProcedureVersion): string {\n return version.digest === null ? '(no version)' : version.digest.slice(7, 19)\n}\n\nfunction decided(version: ProcedureVersion): string {\n const latest = version.decisions.filter((decision) => decision.current)\n return latest.length === 0 ? '-' : [...new Set(latest.map((d) => d.status))].join(',')\n}\n\nexport function renderProcedureRegistryTable(registry: ProcedureRegistry, limit = 30): string {\n const join = registry.changeJoin\n const lines = [\n `${registry.versions.length} procedure versions; ${registry.invocations} invocations in ${registry.sessions.read} sessions (${registry.sessions.unreadable} unreadable); ${registry.searches.read} searches`,\n `joined to a change: ${join.joined} of ${join.invocations} invocations (${percent(join.joinedShare)}); none ${join.none}, not recorded ${join.notRecorded}`,\n `with an outcome for a change: ${join.withOutcome} (${percent(join.withOutcomeShare)}); ${join.distinctChanges} distinct changes, ${join.outcomesSupplied} outcomes supplied (hot-fix window ${join.hotfixWindowDays} days)`,\n `cells on a subscription seat (a known basis with no dollar figure): ${registry.versions.reduce((n, v) => n + v.cells.subscription, 0)}`,\n '',\n 'version kind names cells runs chg-joined merged y/n/? hotfix y/n/? tokens(runs) decided',\n ]\n for (const version of registry.versions.slice(0, limit)) {\n const changes = version.sessions.changes\n const counts = (c: { yes: number; no: number; unknown: number }): string =>\n `${c.yes}/${c.no}/${c.unknown}`\n lines.push(\n [\n digest(version).padEnd(13),\n (version.kind ?? 'unclassified').padEnd(11),\n version.names.join(',').slice(0, 30).padEnd(30),\n String(version.cells.count).padStart(5),\n String(version.sessions.invocations).padStart(5),\n String(changes.joined).padStart(10),\n counts(changes.merged).padStart(13),\n counts(changes.hotfixed).padStart(13),\n measure(version.sessions.tokens).padStart(13),\n decided(version),\n ].join(' '),\n )\n }\n if (registry.versions.length > limit) {\n lines.push(`... ${registry.versions.length - limit} more versions in the JSON`)\n }\n const intents = registry.intents\n if (intents !== null) {\n const summary = intents.summary\n lines.push(\n '',\n `${summary.intents} intents in ${summary.sessionsWithTurns} sessions (${summary.sessionsWithoutTurns} record no typed turns); ${summary.labeled} labeled; known end ${summary.knownEnd} (${percent(summary.knownEndShare)})`,\n 'kind intents known-end share corrections-known joined-to-change with-outcome',\n )\n for (const row of summary.byKind) {\n if (row.intents === 0) continue\n lines.push(\n [\n (row.kind ?? 'unlabeled').padEnd(12),\n String(row.intents).padStart(8),\n String(row.knownEnd).padStart(10),\n percent(row.knownEndShare).padStart(7),\n String(row.knownCorrections).padStart(18),\n String(row.joinedToChange).padStart(17),\n String(row.withChangeOutcome).padStart(13),\n ].join(' '),\n )\n }\n for (const note of intents.notes) lines.push('', `note: ${note}`)\n }\n for (const note of registry.notes) lines.push('', `note: ${note}`)\n return `${lines.join('\\n')}\\n`\n}\n","/**\n * `agent-eval procedure-registry <sessions-dir>` prints the procedure registry\n * for a directory of Claude Code transcripts (or, with `--harness codex`, Codex\n * rollouts) and any number of search ledgers.\n *\n * `--change-ledger <file>` (repeatable) names a change ledger, the harness's own\n * record of each commit and pull request a session made (see\n * `src/skill-usage/change-ledger.ts`). A session the ledger observed has exactly\n * the changes it lists; a session it never saw has only what its transcript\n * shows, and none recorded when the transcript shows none.\n *\n * `--outcomes <file>` names a JSON array of {@link ChangeOutcome}: what the\n * caller knows of each change the sessions produced. Without it every change is\n * joined and none has an outcome. The JSON registry goes to stdout and the\n * short table to stderr, as `skill-usage` does.\n *\n * Exit codes: 2 for a usage error, 1 when a directory or ledger cannot be\n * read, 0 after the registry was written.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { replaySearchLedgerText } from '../campaign/search-ledger'\nimport type { SearchStateView } from '../campaign/search-state'\nimport type { CustomTokenPricing } from '../cost-ledger/contract'\nimport { errorMessage } from '../errors'\nimport type { IntentLabeler, IntentTurn } from '../intent-record/contract'\nimport { readChangeLedger, withChangeLedger } from '../skill-usage/change-ledger'\nimport {\n harnessSkillSessions,\n parseHarness,\n parseSince,\n readPricingFile,\n type SessionHarness,\n} from '../skill-usage/command'\nimport { readSkillFile } from '../skill-usage/skill-file'\nimport type { ChangeOutcome } from './change-outcome'\nimport { buildProcedureRegistry } from './registry'\nimport { renderProcedureRegistryTable } from './render'\n\ntype Format = 'both' | 'json' | 'table'\nconst FORMATS: readonly Format[] = ['both', 'json', 'table']\n\nconst USAGE =\n 'usage: agent-eval procedure-registry <sessions-dir> [--harness claude-code|codex] [--ledger <search-ledger.jsonl>]... [--since <7d|36h|90m|ISO time>] [--outcomes <changes.json>] [--change-ledger <changes.jsonl>]... [--intents [<labeler.mjs>]] [--format both|json|table] [--limit <rows>] [--pricing <rates.json>]'\n\nexport interface ProcedureRegistryCommandIo {\n readonly stdout: (text: string) => void\n readonly stderr: (text: string) => void\n /** The instant `--since 30d` counts back from. */\n readonly now?: () => number\n}\n\nconst PROCESS_IO: ProcedureRegistryCommandIo = {\n stdout: (text) => {\n process.stdout.write(text)\n },\n stderr: (text) => {\n process.stderr.write(text)\n },\n}\n\ninterface Args {\n directory: string\n harness: SessionHarness\n ledgers: string[]\n since: string | null\n outcomes: string | null\n changeLedgers: string[]\n intents: { labeler: string | null } | null\n format: Format\n limit: number\n pricing: string | null\n}\n\nfunction parseArgs(argv: readonly string[]): Args {\n const args: Args = {\n directory: '',\n harness: 'claude-code',\n ledgers: [],\n since: null,\n outcomes: null,\n changeLedgers: [],\n intents: null,\n format: 'both',\n limit: 30,\n pricing: null,\n }\n const value = (flag: string, index: number): string => {\n const raw = argv[index]\n if (raw === undefined) throw new Error(`${flag} expects a value`)\n return raw\n }\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i] as string\n if (arg === '--harness') args.harness = parseHarness(value(arg, ++i))\n else if (arg === '--ledger') args.ledgers.push(value(arg, ++i))\n else if (arg === '--since') args.since = value(arg, ++i)\n else if (arg === '--outcomes') args.outcomes = value(arg, ++i)\n else if (arg === '--change-ledger') args.changeLedgers.push(value(arg, ++i))\n else if (arg === '--intents') {\n // The labeler module is optional: a value that is not a flag.\n const next = argv[i + 1]\n const labeler = next !== undefined && !next.startsWith('--') ? next : null\n if (labeler !== null) i += 1\n args.intents = { labeler }\n } else if (arg === '--pricing') args.pricing = value(arg, ++i)\n else if (arg === '--format') {\n const raw = value(arg, ++i)\n if (!(FORMATS as readonly string[]).includes(raw)) {\n throw new Error(`--format expects one of ${FORMATS.join('|')}, got ${JSON.stringify(raw)}`)\n }\n args.format = raw as Format\n } else if (arg === '--limit') {\n const raw = Number(value(arg, ++i))\n if (!Number.isInteger(raw) || raw < 1) throw new Error('--limit expects a positive integer')\n args.limit = raw\n } else if (arg.startsWith('--')) {\n throw new Error(`unknown flag \"${arg}\"`)\n } else if (args.directory === '') {\n args.directory = arg\n } else {\n throw new Error(`unexpected argument \"${arg}\"`)\n }\n }\n if (args.directory === '') throw new Error('a sessions directory is required')\n return args\n}\n\n/** An outcomes file: a JSON array of change outcomes; each field is checked, so a typo is not read as unknown. */\nfunction readOutcomes(path: string): ChangeOutcome[] {\n const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))\n if (!Array.isArray(parsed)) throw new Error(`--outcomes ${path}: expected a JSON array`)\n const tri = (item: Record<string, unknown>, field: string, index: number): boolean | null => {\n const raw = item[field]\n if (raw === null || typeof raw === 'boolean') return raw\n throw new Error(`--outcomes ${path}: entry ${index} ${field} must be true, false or null`)\n }\n return parsed.map((entry: unknown, index) => {\n const item = (typeof entry === 'object' && entry !== null ? entry : {}) as Record<\n string,\n unknown\n >\n if (typeof item.ref !== 'string' || item.ref === '') {\n throw new Error(`--outcomes ${path}: entry ${index} needs a ref`)\n }\n if (typeof item.hotfixWindowDays !== 'number') {\n throw new Error(`--outcomes ${path}: entry ${index} needs hotfixWindowDays`)\n }\n return {\n ref: item.ref,\n merged: tri(item, 'merged', index),\n gateGreenFirstTry: tri(item, 'gateGreenFirstTry', index),\n hotfixed: tri(item, 'hotfixed', index),\n hotfixWindowDays: item.hotfixWindowDays,\n }\n })\n}\n\n/** A labeler module: its default export is an {@link IntentLabeler}. It lives with the caller, where the labels and the words they read do. */\nasync function loadLabeler(\n path: string,\n): Promise<{ labeler: IntentLabeler; ignore?: (turn: IntentTurn) => boolean }> {\n const loaded = (await import(pathToFileURL(resolve(path)).href)) as {\n default?: unknown\n ignore?: unknown\n }\n if (typeof loaded.default !== 'function') {\n throw new Error(`--intents ${path}: the module must export a labeler function as its default`)\n }\n return {\n labeler: loaded.default as IntentLabeler,\n ...(typeof loaded.ignore === 'function'\n ? { ignore: loaded.ignore as (turn: IntentTurn) => boolean }\n : {}),\n }\n}\n\nasync function readLedger(path: string): Promise<SearchStateView> {\n const text = await readFile(path, 'utf8')\n const first = JSON.parse(text.slice(0, Math.max(0, text.indexOf('\\n')))) as { searchId?: unknown }\n if (typeof first.searchId !== 'string') throw new Error(`${path} line 1 names no searchId`)\n return replaySearchLedgerText(text, first.searchId, path)\n}\n\nexport async function runProcedureRegistryCommand(\n argv: readonly string[],\n io: ProcedureRegistryCommandIo = PROCESS_IO,\n): Promise<number> {\n if (argv.includes('--help') || argv.includes('-h')) {\n io.stdout(`${USAGE}\\n`)\n return 0\n }\n let args: Args\n let sinceMs: number | undefined\n let rates: Map<string, CustomTokenPricing> | undefined\n let outcomes: ChangeOutcome[] = []\n try {\n args = parseArgs(argv)\n rates = args.pricing === null ? undefined : readPricingFile(resolve(args.pricing))\n sinceMs = args.since === null ? undefined : parseSince(args.since, (io.now ?? Date.now)())\n if (args.outcomes !== null) outcomes = readOutcomes(resolve(args.outcomes))\n } catch (error) {\n io.stderr(`${errorMessage(error)}\\n${USAGE}\\n`)\n return 2\n }\n try {\n const labeler =\n args.intents?.labeler == null ? undefined : await loadLabeler(args.intents.labeler)\n const searches = await Promise.all(args.ledgers.map((path) => readLedger(resolve(path))))\n const changeLedger =\n args.changeLedgers.length === 0\n ? undefined\n : await readChangeLedger(args.changeLedgers.map((path) => resolve(path)))\n if (changeLedger !== undefined && changeLedger.malformed > 0) {\n io.stderr(`change ledger: ${changeLedger.malformed} lines are not rows and were not read\\n`)\n }\n const transcripts = harnessSkillSessions(\n args.harness,\n resolve(args.directory),\n sinceMs === undefined ? {} : { sinceMs },\n )\n const registry = await buildProcedureRegistry(\n {\n searches,\n sessions:\n changeLedger === undefined ? transcripts : withChangeLedger(transcripts, changeLedger),\n outcomes,\n },\n {\n ...(sinceMs === undefined ? {} : { sinceMs }),\n ...(rates === undefined ? {} : { pricing: (model: string) => rates?.get(model) }),\n readSkillFile,\n ...(args.intents === null ? {} : { intents: { ...labeler } }),\n },\n )\n const table = renderProcedureRegistryTable(registry, args.limit)\n if (args.format === 'table') {\n io.stdout(table)\n } else {\n io.stdout(`${JSON.stringify(registry, null, 2)}\\n`)\n if (args.format === 'both') io.stderr(table)\n }\n return 0\n } catch (error) {\n io.stderr(`agent-eval procedure-registry: ${errorMessage(error)}\\n`)\n return 1\n }\n}\n","/**\n * `agent-eval search <subcommand>`: work with a search ledger from a terminal.\n *\n * agent-eval search ship <search-ledger.jsonl> --run-kind optimization|eval [--content full|digests]\n * agent-eval search show <search-ledger.jsonl> [--tree] [--operator-yield] [--front] [--task-matrix]\n * [--edit-credit] [--landscape] [--skill-manifold] [--json]\n * agent-eval search show <search-ledger.jsonl> [<search-ledger.jsonl> ...] --meta [--objective <key>] [--json]\n *\n * `ship` sends the ledger to the hosted store named by `TANGLE_INGEST_URL`,\n * `TANGLE_INGEST_API_KEY` and `TANGLE_TENANT_ID`, starting from the store's\n * head, so it finishes or resumes a ship that a loop could not complete.\n *\n * `show` verifies the ledger and prints `renderSearchSummary`: the same\n * compact text a proposer reads, on the search's own ranking split (the\n * selection split when the search declares one, else train). There is no\n * local HTML renderer; the hosted store's page is the visual view (§5 of the\n * search-tree design). A lens flag adds that lens's text form after the\n * summary, so an agent reads what a person sees; `--json` prints the lens\n * results as JSON instead, the shape a view renders.\n *\n * `show --meta` reads every ledger it is given and prints the `metaSearch`\n * lens over them instead of one search's summary: each search as one node\n * scored by its held-out lift per known dollar, the configurations best first,\n * and the searches arranged by derivation and containment.\n */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { open, readFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { replaySearchLedgerText } from './campaign/search-ledger'\nimport type { SearchArtifactRef } from './campaign/search-ledger-types'\nimport type { SearchStateView } from './campaign/search-state'\nimport { renderSearchSummary } from './campaign/search-summary'\nimport { hostedTenantFromEnv } from './hosted/client'\nimport { SEARCH_LEDGER_BATCH_MAX_BYTES, SearchRunKindSchema } from './hosted/search-ledger-wire'\nimport { SearchShipConflictError, shipSearchLedger } from './hosted/search-shipper'\nimport { editCredit, editCreditText } from './search/lenses/edit-credit'\nimport { type FrontData, front } from './search/lenses/front'\nimport { formatLandscape, landscape, surfaceTextEdits } from './search/lenses/landscape'\nimport { metaSearch } from './search/lenses/meta-search'\nimport { renderMetaSearchText } from './search/lenses/meta-search-text'\nimport { type OperatorYieldData, operatorYield } from './search/lenses/operator-yield'\nimport { INSUFFICIENT_FROM } from './search/lenses/shared'\nimport { formatSkillManifold, skillManifold } from './search/lenses/skill-manifold'\nimport { type TaskMatrixData, taskMatrix } from './search/lenses/task-matrix'\nimport { type TreeData, type TreeNode, tree } from './search/lenses/tree'\n\nconst USAGE = `usage: agent-eval search <subcommand> ...\n\n ship <search-ledger.jsonl> --run-kind optimization|eval [--content full|digests]\n Ships the ledger's entries, and the blobs they name, to the hosted store in\n TANGLE_INGEST_URL (or TANGLE_ORCHESTRATOR_URL) as tenant TANGLE_TENANT_ID with\n TANGLE_INGEST_API_KEY (or TANGLE_API_KEY). It starts from the store's head, so\n running it again sends only what the store lacks. Prints the result as JSON.\n Exits 1 when the store holds a different chain for the search.\n\n show <search-ledger.jsonl> [--tree] [--operator-yield] [--front] [--task-matrix]\n [--edit-credit] [--landscape] [--skill-manifold] [--json]\n Verifies the ledger and prints its search summary: the leading nodes\n against the root, the most recently discarded nodes and why, and a log\n of recent proposals. The same text a proposer reads as context, on the\n search's own ranking split. Each lens flag adds that lens's text form\n (search-tree-design §12) below the summary — the same JSON\n Intelligence, discovery lab, VerticalBench and agent-runtime read.\n --tree the tidy tree of nodes and edges.\n --operator-yield outcome counts and yield per known dollar, by edge operator.\n --front the Pareto front over score and known cost per cell.\n --task-matrix nodes × units, clustered, with specialist gain per cluster.\n --edit-credit every edit as a gene followed down the lineage, its\n credit, interacting pairs, and skill candidates. It\n reads node artifacts from the blobs the ledger names,\n verified by digest.\n --landscape nodes placed by line edits between their profile\n surfaces (read from the blobs, verified by digest), the\n kriged score surface, its basins, and the plateau score\n a policy drafts on.\n --skill-manifold the node × unit score matrix factored into skill axes,\n its cross-validated intrinsic dimension, and the unit\n that best separates the leaders.\n --json prints the requested lenses as JSON instead of text.\n\n show <search-ledger.jsonl> [<search-ledger.jsonl> ...] --meta [--objective <key>] [--json]\n Verifies every ledger and prints the meta-search lens over them: each\n search as one node, scored by its claim's held-out lift per known\n dollar (unscored searches say why), configurations best first with\n their interval, method and n, and the searches arranged by derivation\n and containment. --objective names the objective the best\n configuration is chosen within when the searches span several.`\n\nexport async function runSearchCommand(argv: string[]): Promise<number> {\n const [subcommand, ...rest] = argv\n if (subcommand === undefined || subcommand === '--help' || subcommand === '-h') {\n process.stdout.write(`${USAGE}\\n`)\n return 0\n }\n if (subcommand === 'show') return await runShowCommand(rest)\n if (subcommand !== 'ship') {\n process.stderr.write(`unknown search subcommand: ${subcommand}\\n${USAGE}\\n`)\n return 1\n }\n if (rest.some((arg) => arg === undefined || arg === '--help' || arg === '-h')) {\n process.stdout.write(`${USAGE}\\n`)\n return 0\n }\n const { path, flags } = parseShipArgs(rest)\n const runKind = SearchRunKindSchema.safeParse(flags['run-kind'])\n if (!runKind.success) throw new Error(`--run-kind must be optimization or eval\\n${USAGE}`)\n const content = flags.content ?? 'full'\n if (content !== 'full' && content !== 'digests') {\n throw new Error(`--content must be full or digests\\n${USAGE}`)\n }\n const tenant = hostedTenantFromEnv()\n if (!tenant) {\n throw new Error(\n 'set TANGLE_INGEST_URL, TANGLE_INGEST_API_KEY and TANGLE_TENANT_ID to name the store',\n )\n }\n const searchId = await firstLineSearchId(path)\n try {\n const shipped = await shipSearchLedger({\n tenant,\n ledger: { path, searchId },\n runKind: runKind.data,\n content,\n })\n process.stdout.write(`${JSON.stringify(shipped, null, 2)}\\n`)\n return shipped.head.nextSequence === shipped.localLines ? 0 : 1\n } catch (error) {\n if (!(error instanceof SearchShipConflictError)) throw error\n process.stderr.write(`${error.message}\\n`)\n return 1\n }\n}\n\nasync function runShowCommand(argv: string[]): Promise<number> {\n if (argv.includes('--help') || argv.includes('-h')) {\n process.stdout.write(`${USAGE}\\n`)\n return 0\n }\n if (argv.includes('--meta')) return await runShowMetaCommand(argv)\n const positional = argv.filter((arg) => !arg.startsWith('--'))\n const flags = new Set(argv.filter((arg) => arg.startsWith('--')))\n const unknown = [...flags].filter((flag) => !SHOW_FLAGS.has(flag))\n if (positional.length !== 1 || unknown.length > 0) {\n if (unknown.length > 0) process.stderr.write(`unknown flag ${unknown.join(', ')}\\n`)\n process.stdout.write(`${USAGE}\\n`)\n return 1\n }\n const path = positional[0]!\n const searchId = await firstLineSearchId(path)\n const text = await readFile(path, 'utf8')\n const state = replaySearchLedgerText(text, searchId, path)\n const split =\n state.header && state.header.splits.selection.tasks.length > 0 ? 'selection' : 'train'\n const lenses = showLenses(state, path, flags)\n if (flags.has('--json')) {\n if (lenses.length === 0) {\n process.stderr.write('--json needs a lens flag\\n')\n return 1\n }\n const json = Object.fromEntries(lenses.map((lens) => [lens.name, lens.result]))\n process.stdout.write(`${JSON.stringify(json, null, 2)}\\n`)\n return 0\n }\n const sections = [renderSearchSummary(state, { split }), ...lenses.map((lens) => lens.text)]\n process.stdout.write(`${sections.join('\\n\\n')}\\n`)\n return 0\n}\n\nasync function runShowMetaCommand(argv: string[]): Promise<number> {\n const paths: string[] = []\n let objective: string | undefined\n let json = false\n for (let index = 0; index < argv.length; index++) {\n const token = argv[index]!\n if (token === '--meta') continue\n if (token === '--json') {\n json = true\n continue\n }\n if (token === '--objective') {\n objective = argv[++index]\n if (objective === undefined) throw new Error(`--objective needs a value\\n${USAGE}`)\n continue\n }\n if (token.startsWith('--')) throw new Error(`unknown flag ${token}\\n${USAGE}`)\n paths.push(token)\n }\n if (paths.length === 0) throw new Error(`show --meta needs at least one ledger\\n${USAGE}`)\n const states = []\n for (const path of paths) {\n const searchId = await firstLineSearchId(path)\n states.push(replaySearchLedgerText(await readFile(path, 'utf8'), searchId, path))\n }\n const lens = metaSearch(states, objective === undefined ? {} : { objective })\n process.stdout.write(\n json ? `${JSON.stringify({ metaSearch: lens }, null, 2)}\\n` : `${renderMetaSearchText(lens)}\\n`,\n )\n return 0\n}\n\nconst SHOW_FLAGS = new Set([\n '--edit-credit',\n '--json',\n '--tree',\n '--operator-yield',\n '--front',\n '--task-matrix',\n '--landscape',\n '--skill-manifold',\n])\n\nfunction showLenses(\n state: SearchStateView,\n ledgerPath: string,\n flags: ReadonlySet<string>,\n): Array<{ name: string; result: unknown; text: string }> {\n const lenses: Array<{ name: string; result: unknown; text: string }> = []\n if (flags.has('--tree')) {\n const result = tree(state)\n lenses.push({ name: 'tree', result, text: renderTreeText(result.data) })\n }\n if (flags.has('--operator-yield')) {\n const result = operatorYield(state)\n lenses.push({ name: 'operatorYield', result, text: renderOperatorYieldText(result.data) })\n }\n if (flags.has('--front')) {\n const result = front(state)\n lenses.push({ name: 'front', result, text: renderFrontText(result.data) })\n }\n if (flags.has('--task-matrix')) {\n const result = taskMatrix(state)\n lenses.push({ name: 'taskMatrix', result, text: renderTaskMatrixText(result.data) })\n }\n if (flags.has('--edit-credit')) {\n const result = editCredit(state, { readArtifact: ledgerBlobReader(ledgerPath) })\n lenses.push({ name: 'editCredit', result, text: editCreditText(result) })\n }\n if (flags.has('--landscape')) {\n const read = ledgerBlobReader(ledgerPath)\n const result = landscape(\n state,\n surfaceTextEdits((surface) => read(surface.artifact) ?? null),\n )\n lenses.push({ name: 'landscape', result, text: formatLandscape(result) })\n }\n if (flags.has('--skill-manifold')) {\n const result = skillManifold(state)\n lenses.push({ name: 'skillManifold', result, text: formatSkillManifold(result) })\n }\n return lenses\n}\n\n/**\n * Reads a blob a ledger names: at its `file:` URI, else under `blobs/` beside\n * the ledger, where `SearchRecorder` writes them. Bytes that do not hash to the\n * reference's digest and length read as unavailable, never as content.\n */\nfunction ledgerBlobReader(ledgerPath: string): (ref: SearchArtifactRef) => unknown | undefined {\n const cache = new Map<string, unknown>()\n return (ref) => {\n if (cache.has(ref.sha256)) return cache.get(ref.sha256)\n const hex = ref.sha256.slice('sha256:'.length)\n const candidates = [join(dirname(ledgerPath), 'blobs', `${hex}.json`)]\n if (ref.uri.startsWith('file:')) candidates.unshift(fileURLToPath(ref.uri))\n let value: unknown\n for (const candidate of candidates) {\n if (!existsSync(candidate)) continue\n const bytes = readFileSync(candidate)\n const digest = createHash('sha256').update(bytes).digest('hex')\n if (digest !== hex || bytes.byteLength !== ref.byteLength) continue\n try {\n value = JSON.parse(bytes.toString('utf8'))\n } catch {\n // Verified bytes that are not JSON are not content a lens can read.\n }\n break\n }\n cache.set(ref.sha256, value)\n return value\n }\n}\n\nfunction renderTreeText(data: TreeData): string {\n const lines = [\n `tree: ${data.nodeCount} node${data.nodeCount === 1 ? '' : 's'}, ${data.edgeCount} edge${data.edgeCount === 1 ? '' : 's'}`,\n ]\n const walk = (node: TreeNode, prefix: string, isLast: boolean): void => {\n const branch = prefix === '' ? '' : isLast ? '└─ ' : '├─ '\n const op = node.operator ? `${node.operator} → ` : ''\n const rung = node.rung === null ? '' : ` rung ${node.rung}`\n const depth = node.depth === null ? ' depth unknown' : ''\n const cost =\n node.unknownCostCells === 0\n ? `$${node.knownCostUsd.toFixed(2)}`\n : `$${node.knownCostUsd.toFixed(2)} known + at least $${node.floorUsd.toFixed(2)} over ${node.unknownCostCells} unknown-cost cell${node.unknownCostCells === 1 ? '' : 's'}`\n lines.push(\n `${prefix}${branch}${op}${node.nodeId} (${node.status ?? 'undecided'}${rung}${depth}) ${cost}`,\n )\n const childPrefix = prefix + (prefix === '' ? '' : isLast ? ' ' : '│ ')\n node.children.forEach((child, index) => {\n walk(child, childPrefix, index === node.children.length - 1)\n })\n }\n data.roots.forEach((root, index) => {\n walk(root, '', index === data.roots.length - 1)\n })\n return lines.join('\\n')\n}\n\nfunction renderOperatorYieldText(data: OperatorYieldData): string {\n const lines = [`operator yield (${data.split} split, gain per known $ of proposal + screen):`]\n if (data.rows.length === 0) lines.push(' no edges yet')\n for (const row of data.rows) {\n const y = row.yield\n const outcomes = Object.entries(row.outcomes)\n .filter(([, count]) => count > 0)\n .map(([status, count]) => `${status}=${count}`)\n .join(' ')\n const yieldText =\n y.method === 'none'\n ? y.n === 0\n ? 'yield: no measured children'\n : `yield unknown (${y.n} of ${INSUFFICIENT_FROM}, none)`\n : y.method === 'insufficient'\n ? `yield≈${y.mean!.toFixed(4)}/$ (${y.n} of ${INSUFFICIENT_FROM}, insufficient)`\n : `yield≈${y.mean!.toFixed(4)}/$ [${y.interval![0].toFixed(4)}, ${y.interval![1].toFixed(4)}] (${y.method}, ${y.intervalMethod}, n=${y.n})`\n const nodes = Object.values(row.outcomes).reduce((sum, count) => sum + count, 0)\n const reproposals = row.reproposals > 0 ? `, ${row.reproposals} re-proposals` : ''\n lines.push(\n ` ${row.operator}: ${row.proposals} proposals${reproposals} → ${nodes} node${nodes === 1 ? '' : 's'} (${outcomes || 'no decisions yet'}); ${yieldText}; ${row.excluded} excluded`,\n )\n }\n return lines.join('\\n')\n}\n\nfunction renderFrontText(data: FrontData): string {\n const onFront = data.rows.filter((row) => row.onFront)\n const reasons = Object.entries(data.exclusions)\n .filter(([, count]) => count > 0)\n .map(([reason, count]) => `${reason} ${count}`)\n .join(', ')\n const lines = [\n `front (${data.split} split, axes: ${data.axes.join(', ')}): ${data.frontierSize} of ${data.rows.length} node(s) on the frontier, ${data.excludedCount} excluded${reasons ? ` (${reasons})` : ''}`,\n ]\n for (const row of onFront) {\n lines.push(\n ` ${row.nodeId}: score=${row.score!.toFixed(4)} on ${row.units} units (${row.method}) costPerCell=$${row.costPerCellUsd!.toFixed(4)}`,\n )\n }\n return lines.join('\\n')\n}\n\nfunction renderTaskMatrixText(data: TaskMatrixData): string {\n const lines = [\n `task matrix (${data.split} split, ${data.direction}): ${data.nodeIds.length} node(s) × ${data.unitIds.length} unit(s), ${data.nodeClusters.length} node cluster(s), ${data.unitClusters.length} unit cluster(s)`,\n ]\n if (data.sampling) {\n lines.push(\n ` clustered ${data.sampling.nodesClustered} of ${data.sampling.nodesTotal} nodes (cap ${data.sampling.cap}), evenly sampled in registration order; unit clusters and specialist gains use the same nodes`,\n )\n }\n for (const row of data.specialistGain) {\n const gain =\n row.gain === null\n ? `insufficient (${row.insufficient})`\n : `${row.gain.toFixed(4)} (best ${row.bestNodeId}, ${row.nodesContributing} nodes on ${row.unitIds.length} units)`\n lines.push(` cluster ${row.clusterId} [${row.unitIds.join(', ')}]: specialist gain ${gain}`)\n }\n return lines.join('\\n')\n}\n\nfunction parseShipArgs(argv: string[]): { path: string; flags: Record<string, string> } {\n const flags: Record<string, string> = {}\n const positional: string[] = []\n for (let index = 0; index < argv.length; index++) {\n const token = argv[index]!\n if (!token.startsWith('--')) {\n positional.push(token)\n continue\n }\n const [name, inline] = token.slice(2).split('=', 2) as [string, string | undefined]\n if (name !== 'run-kind' && name !== 'content') throw new Error(`unknown flag --${name}`)\n const value = inline ?? argv[++index]\n if (value === undefined) throw new Error(`--${name} needs a value`)\n flags[name] = value\n }\n if (positional.length !== 1) throw new Error(USAGE)\n return { path: positional[0]!, flags }\n}\n\n/** The ledger names its search on every line; read the first. */\nasync function firstLineSearchId(path: string): Promise<string> {\n const handle = await open(path, 'r')\n try {\n // A line longer than one request's limit cannot ship anyway.\n const bytes = Buffer.alloc(SEARCH_LEDGER_BATCH_MAX_BYTES + 1)\n const { bytesRead } = await handle.read(bytes, 0, bytes.byteLength, 0)\n const newline = bytes.subarray(0, bytesRead).indexOf(0x0a)\n if (newline < 0) throw new Error(`${path} holds no complete ledger line`)\n const first = JSON.parse(bytes.toString('utf8', 0, newline)) as { searchId?: unknown }\n if (typeof first.searchId !== 'string') throw new Error(`${path} line 1 names no searchId`)\n return first.searchId\n } finally {\n await handle.close()\n }\n}\n","/**\n * `agent-eval supervisor-run rollouts` writes one rollout ledger from the\n * places the fleet's work is recorded:\n *\n * <runDir...> Runtime run directories (`runtimeRunRolloutLines`)\n * --sessions [<harness>:]<path> a HOME, store directory, session file or OpenCode .db;\n * the prefix limits a directory to one harness and names a file's\n * --since <ISO> limit --sessions to stores changed since then\n * --gate-receipts <file> beelink-gate receipts.jsonl, as verifiable labels\n * --denylist <file> literal private terms, one per line\n * --otlp <file> also write each kept run row's session as OTLP spans\n *\n * Every row passes the privacy screen before it is written: a row with any\n * secret or private detail is dropped whole and counted by rule, so the\n * ledger never holds one. Rows are written under the write policy and read\n * back with `readRolloutJournal`; their rewards are unscreened.\n */\n\nimport { appendFile, readFile, rm } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { errorMessage } from '../errors'\nimport { appendRolloutLines } from '../rollout/ledger'\nimport { gateReceiptRolloutLines } from '../rollout/readers/gate-receipts'\nimport {\n harnessSessionRefs,\n harnessSessionRolloutLines,\n} from '../rollout/readers/harness-session-lines'\nimport { PRIVACY_RULE_NAMES, privacyHit } from '../rollout/release/scrub'\nimport type { RolloutLine } from '../rollout/schema'\nimport type { SupervisorRunCommandIo } from './report-command'\nimport { runtimeRunRolloutLines } from './runtime-rollouts'\n\nexport const ROLLOUTS_USAGE =\n 'usage: agent-eval supervisor-run rollouts [<runDir>...] [--sessions [<harness>:]<path>]... [--since <ISO>] [--gate-receipts <file>]... [--denylist <file>] [--otlp <file>] --out <ledger.jsonl>'\n\ninterface RolloutsArgs {\n runDirs: string[]\n sessions: Array<{ path: string; harness?: string }>\n sinceMs?: number\n gateReceipts: string[]\n denylist: string | null\n otlp: string | null\n out: string\n}\n\nfunction parseArgs(argv: readonly string[]): RolloutsArgs {\n const args: RolloutsArgs = {\n runDirs: [],\n sessions: [],\n gateReceipts: [],\n denylist: null,\n otlp: null,\n out: '',\n }\n const value = (i: number, flag: string): string => {\n const v = argv[i]\n if (v === undefined || v.startsWith('--')) throw new Error(`${flag} expects a value`)\n return v\n }\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i] as string\n if (arg === '--out') args.out = value(++i, arg)\n else if (arg === '--sessions') {\n const raw = value(++i, arg)\n const prefixed = /^([a-z][a-z-]*):(.+)$/u.exec(raw)\n args.sessions.push(prefixed ? { harness: prefixed[1]!, path: prefixed[2]! } : { path: raw })\n } else if (arg === '--since') {\n const ms = Date.parse(value(++i, arg))\n if (Number.isNaN(ms)) throw new Error(`--since expects an ISO time, got ${argv[i]}`)\n args.sinceMs = ms\n } else if (arg === '--gate-receipts') args.gateReceipts.push(value(++i, arg))\n else if (arg === '--denylist') args.denylist = value(++i, arg)\n else if (arg === '--otlp') args.otlp = value(++i, arg)\n else if (arg.startsWith('--')) throw new Error(`unknown flag \"${arg}\"`)\n else args.runDirs.push(arg)\n }\n if (!args.out) throw new Error(ROLLOUTS_USAGE)\n if (args.runDirs.length + args.sessions.length + args.gateReceipts.length === 0) {\n throw new Error(`no sources given\\n${ROLLOUTS_USAGE}`)\n }\n return args\n}\n\nexport interface RolloutsSummary {\n out: string\n written: number\n dropped: Record<string, number>\n sources: Array<{ source: string; kind: string; read: number; written: number; errors: string[] }>\n}\n\nexport async function runRolloutsCommand(\n argv: readonly string[],\n io: SupervisorRunCommandIo,\n): Promise<number> {\n let args: RolloutsArgs\n try {\n args = parseArgs(argv)\n } catch (error) {\n io.stderr(`${errorMessage(error)}\\n`)\n return 2\n }\n const out = resolve(args.out)\n const denylist =\n args.denylist === null\n ? []\n : (await readFile(args.denylist, 'utf8'))\n .split('\\n')\n .map((line) => line.replace(/#.*/u, '').trim())\n .filter(Boolean)\n const capturedAt = new Date().toISOString()\n const summary: RolloutsSummary = {\n out,\n written: 0,\n dropped: Object.fromEntries(PRIVACY_RULE_NAMES.map((name) => [name, 0])),\n sources: [],\n }\n await rm(out, { force: true })\n if (args.otlp !== null) await rm(args.otlp, { force: true })\n\n const write = async (source: RolloutsSummary['sources'][number], lines: RolloutLine[]) => {\n source.read += lines.length\n const kept = lines.filter((line) => {\n const hit = privacyHit(line, denylist)\n if (hit !== null) summary.dropped[hit] = (summary.dropped[hit] ?? 0) + 1\n return hit === null\n })\n await appendRolloutLines(out, kept)\n source.written += kept.length\n summary.written += kept.length\n return kept\n }\n\n for (const runDir of args.runDirs) {\n const source = { source: runDir, kind: 'run-dir', read: 0, written: 0, errors: [] as string[] }\n summary.sources.push(source)\n try {\n const run = await runtimeRunRolloutLines(resolve(runDir), { capturedAt })\n source.errors.push(...run.gaps.map((gap) => `${gap.code}: ${gap.message}`))\n const kept = await write(source, run.lines)\n const spans = kept.map((line) => run.otlp.get(line.rollout_id) ?? '')\n if (args.otlp !== null) await appendFile(args.otlp, spans.join(''))\n } catch (error) {\n source.errors.push(errorMessage(error))\n }\n }\n for (const target of args.sessions) {\n const source = {\n source: target.path,\n kind: `sessions:${target.harness ?? 'all'}`,\n read: 0,\n written: 0,\n errors: [] as string[],\n }\n summary.sources.push(source)\n try {\n const refs = await harnessSessionRefs(resolve(target.path), {\n ...(target.harness === undefined ? {} : { harness: target.harness }),\n ...(args.sinceMs === undefined ? {} : { sinceMs: args.sinceMs }),\n })\n let batch: RolloutLine[] = []\n for await (const item of harnessSessionRolloutLines(refs, capturedAt)) {\n if (item.line) batch.push(item.line)\n else source.errors.push(`${item.ref.path}: ${item.error}`)\n if (batch.length >= 100) {\n await write(source, batch)\n batch = []\n }\n }\n await write(source, batch)\n } catch (error) {\n source.errors.push(errorMessage(error))\n }\n }\n for (const path of args.gateReceipts) {\n const source = {\n source: path,\n kind: 'gate-receipts',\n read: 0,\n written: 0,\n errors: [] as string[],\n }\n summary.sources.push(source)\n try {\n const { lines, skipped } = await gateReceiptRolloutLines(path, capturedAt)\n if (skipped > 0) source.errors.push(`${skipped} receipts carried no verdict`)\n await write(source, lines)\n } catch (error) {\n source.errors.push(errorMessage(error))\n }\n }\n io.stdout(`${JSON.stringify(summary, null, 2)}\\n`)\n return summary.sources.some((s) => s.read === 0 && s.errors.length > 0) ? 1 : 0\n}\n","/**\n * `agent-eval supervisor-run report <runDir>` takes one run directory and\n * prints the report the module already renders. The command reads through\n * `analyzeSupervisorRun`, so a Runtime run directory takes the\n * same path and the status comes from the record `terminal-record.ts` names.\n *\n * Exit codes follow the other self-parsing subcommands: 2 for a usage error,\n * 1 when the directory cannot be read (missing, not a directory, or a corrupt\n * journal or terminal record), 0 after the report was written to stdout.\n */\n\nimport { stat } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { errorMessage } from '../errors'\nimport { analyzeSupervisorRun } from './reader'\nimport { renderSupervisorRunHeadline, renderSupervisorRunMarkdown } from './render'\nimport { ROLLOUTS_USAGE, runRolloutsCommand } from './rollouts-command'\n\nexport type SupervisorRunReportFormat = 'headline' | 'markdown' | 'json'\n\nconst FORMATS: readonly SupervisorRunReportFormat[] = ['headline', 'markdown', 'json']\n\nconst SUPERVISOR_RUN_USAGE = `usage: agent-eval supervisor-run report <runDir> [--format headline|markdown|json]\n ${ROLLOUTS_USAGE.replace('usage: ', '')}`\n\n/** Output sinks, injectable so tests read the exact bytes a terminal would. */\nexport interface SupervisorRunCommandIo {\n readonly stdout: (text: string) => void\n readonly stderr: (text: string) => void\n}\n\nconst PROCESS_IO: SupervisorRunCommandIo = {\n stdout: (text) => {\n process.stdout.write(text)\n },\n stderr: (text) => {\n process.stderr.write(text)\n },\n}\n\ninterface ReportArgs {\n readonly runDir: string\n readonly format: SupervisorRunReportFormat\n}\n\nfunction isFormat(value: string): value is SupervisorRunReportFormat {\n return (FORMATS as readonly string[]).includes(value)\n}\n\nfunction parseReportArgs(argv: readonly string[]): ReportArgs {\n let runDir: string | null = null\n let format: SupervisorRunReportFormat = 'headline'\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i] as string\n if (arg === '--format') {\n const raw = argv[++i]\n if (raw === undefined || !isFormat(raw)) {\n throw new Error(\n `--format expects one of ${FORMATS.join('|')}, got ${JSON.stringify(raw ?? '')}`,\n )\n }\n format = raw\n } else if (arg.startsWith('--format=')) {\n const raw = arg.slice('--format='.length)\n if (!isFormat(raw)) {\n throw new Error(`--format expects one of ${FORMATS.join('|')}, got ${JSON.stringify(raw)}`)\n }\n format = raw\n } else if (arg.startsWith('--')) {\n throw new Error(`unknown flag \"${arg}\"`)\n } else if (runDir === null) {\n runDir = arg\n } else {\n throw new Error(`unexpected argument \"${arg}\"`)\n }\n }\n if (runDir === null) throw new Error(SUPERVISOR_RUN_USAGE)\n return { runDir, format }\n}\n\n/**\n * CLI driver for `agent-eval supervisor-run`. `argv` is everything after the\n * command name, so `['report', runDir, ...flags]`. Returns the process exit code.\n */\nexport async function runSupervisorRunCommand(\n argv: readonly string[],\n io: SupervisorRunCommandIo = PROCESS_IO,\n): Promise<number> {\n const [verb, ...rest] = argv\n if (verb === undefined || verb === '--help' || verb === '-h' || verb === 'help') {\n io.stdout(`${SUPERVISOR_RUN_USAGE}\\n`)\n return verb === undefined ? 2 : 0\n }\n if (verb === 'rollouts') {\n if (rest.includes('--help') || rest.includes('-h')) {\n io.stdout(`${ROLLOUTS_USAGE}\\n`)\n return 0\n }\n return runRolloutsCommand(rest, io)\n }\n if (verb !== 'report') {\n io.stderr(`unknown supervisor-run subcommand \"${verb}\"\\n${SUPERVISOR_RUN_USAGE}\\n`)\n return 2\n }\n if (rest.includes('--help') || rest.includes('-h')) {\n io.stdout(`${SUPERVISOR_RUN_USAGE}\\n`)\n return 0\n }\n\n let args: ReportArgs\n try {\n args = parseReportArgs(rest)\n } catch (error) {\n io.stderr(`${errorMessage(error)}\\n`)\n return 2\n }\n\n const runDir = resolve(args.runDir)\n // A path that is not a directory is a caller error, not a run with every\n // measurement missing: reporting an absent-shaped run for a typo would read\n // as evidence about a run that never existed.\n const entry = await stat(runDir).catch(() => null)\n if (entry === null || !entry.isDirectory()) {\n io.stderr(`[agent-eval] supervisor-run report: ${runDir} is not a directory\\n`)\n return 1\n }\n\n try {\n const report = await analyzeSupervisorRun(runDir)\n switch (args.format) {\n case 'headline':\n io.stdout(`${renderSupervisorRunHeadline(report)}\\n`)\n break\n case 'markdown':\n io.stdout(renderSupervisorRunMarkdown(report))\n break\n case 'json':\n io.stdout(`${JSON.stringify(report, null, 2)}\\n`)\n break\n }\n return 0\n } catch (error) {\n io.stderr(`[agent-eval] supervisor-run report failed for ${runDir}: ${errorMessage(error)}\\n`)\n return 1\n }\n}\n","#!/usr/bin/env node\n/**\n * agent-eval CLI.\n *\n * agent-eval serve [--port 5005] [--host 127.0.0.1]\n * agent-eval rpc <method> # one request from stdin → one response on stdout\n * agent-eval rpc-batch <method> # JSONL stdin → JSONL stdout\n * agent-eval analyst-benchmark ... # benchmark a real-model trace analyst\n * agent-eval supervisor-run report <runDir> [--format headline|markdown|json]\n * agent-eval search ship <search-ledger.jsonl> --run-kind optimization|eval\n * agent-eval search show <search-ledger.jsonl>\n * agent-eval skill-usage <transcripts-dir> [--since 7d]\n * agent-eval procedure-registry <sessions-dir> [--ledger <path>]... [--since 30d] [--outcomes <file>] [--change-ledger <file>]...\n * agent-eval openapi [--out path] # write OpenAPI spec\n * agent-eval version\n *\n * <method> is one of: judge, listRubrics, version. When omitted, the\n * stdin payload must be a full {method, params} envelope.\n */\nimport { writeFileSync } from 'node:fs'\nimport { runAnalystBenchmarkCommand } from './analyst/benchmark-command'\nimport { resolveCliLlmConfig } from './cli-config'\nimport { runProcedureRegistryCommand } from './procedure-registry/command'\nimport { runRolloutReleaseCli } from './rollout/release/hf-dataset'\nimport { runSearchCommand } from './search-command'\nimport { runSkillUsageCommand } from './skill-usage/command'\nimport { runSupervisorRunCommand } from './supervisor-run/report-command'\nimport { handleVersion } from './wire/handlers'\nimport { buildOpenApi } from './wire/openapi'\nimport { runRpcBatch, runRpcOnce } from './wire/rpc'\nimport { startServerAsync } from './wire/server'\n\ninterface Args {\n command: string\n positional: string[]\n flags: Record<string, string>\n}\n\nfunction parseArgs(argv: string[]): Args {\n const [command, ...rest] = argv\n const positional: string[] = []\n const flags: Record<string, string> = {}\n for (let i = 0; i < rest.length; i++) {\n const tok = rest[i]!\n if (tok.startsWith('--')) {\n const raw = tok.slice(2)\n const equalsAt = raw.indexOf('=')\n if (equalsAt >= 0) {\n flags[raw.slice(0, equalsAt)] = raw.slice(equalsAt + 1)\n continue\n }\n const key = raw\n if (key === 'help') {\n flags[key] = 'true'\n continue\n }\n const next = rest[i + 1]\n if (next != null && !next.startsWith('--')) {\n flags[key] = next\n i++\n } else {\n flags[key] = 'true'\n }\n } else if (tok === '-h') {\n flags.help = 'true'\n } else {\n positional.push(tok)\n }\n }\n return { command: command ?? 'help', positional, flags }\n}\n\nconst HELP = `agent-eval: evaluation RPC and HTTP server.\n\nCommands:\n serve [--port 5005] [--host 127.0.0.1]\n Start the HTTP server. POST /v1/judge, GET /v1/rubrics, GET /v1/version, GET /openapi.json.\n rpc <method>\n Read one JSON object from stdin (the params for <method>), write one\n JSON object to stdout. Methods: judge, listRubrics, version.\n rpc-batch <method>\n Like 'rpc' but JSONL in / JSONL out.\n openapi [--out openapi.json]\n Write the OpenAPI 3.1 spec.\n rollout-release <ledger.jsonl...> --out <dir> [--formats sft,verifiers,rft,raw] [--include-proposers] [--denylist <terms.txt>] [--push <org/name>]\n Build a HuggingFace-ready dataset dir from tangle.rollout.v1 ledgers:\n validate, fail-closed split and license filters, drop any line with a\n secret or private detail, scrub, export formats + card.\n analyst-benchmark --dataset <agentrx|codetracebench> --labels <path> --trace-dir <path> [--artifact-dir <path>] --out <dir> ...\n Compare an empty baseline with a real-model trace analyst on public labels.\n Run with --help for all required inputs and controls.\n supervisor-run rollouts [<runDir>...] [--sessions [<harness>:]<path>]... [--since <ISO>] [--gate-receipts <file>] [--denylist <file>] --out <ledger.jsonl>\n Import Discovery run dirs, native harness sessions and beelink-gate receipts\n into one rollout ledger; rows with any secret or private detail are dropped.\n supervisor-run report <runDir> [--format headline|markdown|json]\n Report one Runtime or loops supervisor run directory. The status comes\n from Runtime's own result.json / failure.json; every missing measurement\n stays named. Exits 1 when the directory cannot be read.\n search ship <search-ledger.jsonl> --run-kind optimization|eval [--content full|digests]\n Ship a search ledger and its blobs to the hosted store in TANGLE_INGEST_URL,\n starting from the store's head. Run with --help for the environment it reads.\n search show <search-ledger.jsonl>\n Verify a search ledger and print its summary: leading nodes, recently\n discarded nodes and recent proposals, the same text a proposer reads.\n skill-usage <transcripts-dir> [--since <7d|36h|90m|ISO time>] [--format both|json|table] [--limit <rows>] [--pricing <rates.json>]\n Read a directory of Claude Code transcripts and report each skill and\n version: invocations by agent, user and harness, sessions, and the tool\n calls, tool errors, tokens, wall time and cost after its first invocation.\n The JSON report goes to stdout and the table to stderr.\n procedure-registry <sessions-dir> [--ledger <search-ledger.jsonl>]... [--since <7d|36h|90m|ISO time>] [--outcomes <changes.json>] [--change-ledger <changes.jsonl>]... [--intents [<labeler.mjs>]] [--format both|json|table] [--limit <rows>] [--pricing <rates.json>]\n Join search ledgers and recorded Claude Code sessions on the version digest:\n per procedure version, its lineage, every execution, tokens, cost and wall\n time, the outcome of the changes its sessions produced, and the decisions\n taken on it. With --intents, also each typed turn's intent: the versions\n that served it, its cost and how it ended; the labeler module's default\n export labels turns, and without one no turn has a kind or a correction.\n The JSON registry goes to stdout and the table to stderr.\n version\n Print server + wire-protocol version JSON.\n\nJudge provider:\n Set AGENT_EVAL_LLM_BASE_URL, AGENT_EVAL_LLM_API_KEY, and AGENT_EVAL_LLM_MODEL.\n OPENAI_* and TANGLE_* equivalents are also accepted. This binary is the only\n place that reads a provider credential; the library never does. Without both\n a base URL and a key, /v1/judge refuses with llm_not_configured.\n\nWithout arguments, prints this help.`\n\nasync function main(): Promise<number> {\n const { command, positional, flags } = parseArgs(process.argv.slice(2))\n assertKnownFlags(command, flags)\n\n if (command === 'analyst-benchmark' && flags.help === 'true') {\n return await runAnalystBenchmarkCommand(process.argv.slice(3))\n }\n if (command === 'search') return await runSearchCommand(process.argv.slice(3))\n if (flags.help === 'true') {\n process.stdout.write(`${HELP}\\n`)\n return 0\n }\n\n switch (command) {\n case 'serve': {\n const port = parsePort(flags.port ?? '5005')\n const host = flags.host ?? '127.0.0.1'\n const llm = resolveCliLlmConfig()\n const { server } = await startServerAsync({\n port,\n host,\n ...(llm.chat ? { chat: llm.chat } : {}),\n ...(llm.model ? { judgeModel: llm.model } : {}),\n })\n // Keep process alive on SIGINT/SIGTERM\n const shutdown = (sig: string) => {\n // eslint-disable-next-line no-console\n console.log(`[agent-eval] received ${sig}, shutting down`)\n server.close(() => process.exit(0))\n // Force exit after 5s if close hangs\n setTimeout(() => process.exit(1), 5000).unref()\n }\n process.on('SIGINT', () => shutdown('SIGINT'))\n process.on('SIGTERM', () => shutdown('SIGTERM'))\n // Block forever\n await new Promise(() => {})\n return 0\n }\n case 'rpc': {\n const [method] = positional\n const llm = resolveCliLlmConfig()\n return await runRpcOnce(method, {\n ...(llm.chat ? { chat: llm.chat } : {}),\n ...(llm.model ? { judgeModel: llm.model } : {}),\n })\n }\n case 'rpc-batch': {\n const [method] = positional\n const llm = resolveCliLlmConfig()\n return await runRpcBatch(method, {\n ...(llm.chat ? { chat: llm.chat } : {}),\n ...(llm.model ? { judgeModel: llm.model } : {}),\n })\n }\n case 'openapi': {\n const out = flags.out ?? 'openapi.json'\n const spec = buildOpenApi(handleVersion().version)\n writeFileSync(out, `${JSON.stringify(spec, null, 2)}\\n`, 'utf-8')\n // eslint-disable-next-line no-console\n console.log(`[agent-eval] wrote OpenAPI 3.1 spec to ${out}`)\n return 0\n }\n case 'rollout-release': {\n // The subcommand owns its own flag grammar (multi-value --formats,\n // boolean --include-proposers) — pass raw argv through untouched.\n return await runRolloutReleaseCli(process.argv.slice(3))\n }\n case 'analyst-benchmark': {\n return await runAnalystBenchmarkCommand(process.argv.slice(3))\n }\n case 'supervisor-run': {\n // The subcommand owns its own flag grammar; pass raw argv through.\n return await runSupervisorRunCommand(process.argv.slice(3))\n }\n case 'skill-usage': {\n return await runSkillUsageCommand(process.argv.slice(3))\n }\n case 'procedure-registry': {\n return await runProcedureRegistryCommand(process.argv.slice(3))\n }\n case 'version': {\n process.stdout.write(`${JSON.stringify(handleVersion(), null, 2)}\\n`)\n return 0\n }\n case '--version': {\n process.stdout.write(`${handleVersion().version}\\n`)\n return 0\n }\n case 'help':\n case '--help':\n case '-h':\n case '':\n process.stdout.write(`${HELP}\\n`)\n return 0\n default:\n process.stderr.write(`unknown command: ${command}\\n${HELP}\\n`)\n return 1\n }\n}\n\nconst FLAGS_BY_COMMAND: Record<string, ReadonlySet<string>> = {\n serve: new Set(['help', 'host', 'port']),\n rpc: new Set(['help']),\n 'rpc-batch': new Set(['help']),\n openapi: new Set(['help', 'out']),\n version: new Set(['help']),\n help: new Set(),\n '--help': new Set(),\n '-h': new Set(),\n '--version': new Set(),\n '': new Set(),\n}\n\nfunction assertKnownFlags(command: string, flags: Record<string, string>): void {\n // These subcommands parse their own argv.\n if (\n command === 'rollout-release' ||\n command === 'analyst-benchmark' ||\n command === 'supervisor-run' ||\n command === 'skill-usage' ||\n command === 'procedure-registry' ||\n command === 'search'\n ) {\n return\n }\n const allowed = FLAGS_BY_COMMAND[command]\n if (!allowed) return\n const unknown = Object.keys(flags).filter((flag) => !allowed.has(flag))\n if (unknown.length > 0) {\n throw new Error(`unknown flag for ${command || 'help'}: --${unknown[0]}`)\n }\n}\n\nfunction parsePort(raw: string): number {\n const port = Number(raw)\n if (!Number.isInteger(port) || port < 0 || port > 65_535) {\n throw new Error(`--port must be an integer from 0 to 65535; received ${JSON.stringify(raw)}`)\n }\n return port\n}\n\nmain()\n .then((code) => {\n process.exitCode = code\n })\n .catch((err) => {\n // eslint-disable-next-line no-console\n console.error('[agent-eval] cli error:', err)\n process.exitCode = 1\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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