@tangle-network/agent-eval 2.0.19 → 2.0.21

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.
Files changed (106) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-_A7aMA4F.d.ts → agent-profile-CTneqKs4.d.ts} +4 -4
  4. package/dist/{agent-profile-_A7aMA4F.d.ts.map → agent-profile-CTneqKs4.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +25 -11
  6. package/dist/analyst/index.d.ts.map +1 -1
  7. package/dist/analyst/index.js +1 -1
  8. package/dist/{analyze-runs-Izz_ZeWg.d.ts → analyze-runs-ByEuSMUT.d.ts} +2 -2
  9. package/dist/{analyze-runs-Izz_ZeWg.d.ts.map → analyze-runs-ByEuSMUT.d.ts.map} +1 -1
  10. package/dist/app-grade/index.d.ts +3 -3
  11. package/dist/{benchmark-command-DOQeozeM.js → benchmark-command-pmeFawvb.js} +17 -8
  12. package/dist/{benchmark-command-DOQeozeM.js.map → benchmark-command-pmeFawvb.js.map} +1 -1
  13. package/dist/benchmarks/index.d.ts +4 -4
  14. package/dist/benchmarks/index.js +2 -2
  15. package/dist/campaign/index.d.ts +6 -6
  16. package/dist/campaign/index.js +6 -6
  17. package/dist/{campaign-CJRlis5N.js → campaign-DPB35MjP.js} +25 -8
  18. package/dist/{campaign-CJRlis5N.js.map → campaign-DPB35MjP.js.map} +1 -1
  19. package/dist/{campaign-evidence-Biq06MQ9.d.ts → campaign-evidence-CSb3y1ob.d.ts} +3 -3
  20. package/dist/{campaign-evidence-Biq06MQ9.d.ts.map → campaign-evidence-CSb3y1ob.d.ts.map} +1 -1
  21. package/dist/cli.js +2145 -26
  22. package/dist/cli.js.map +1 -1
  23. package/dist/contract/index.d.ts +10 -10
  24. package/dist/contract/index.js +5 -5
  25. package/dist/{default-registry-BKHpiYiW.d.ts → default-registry-CKAFLuJg.d.ts} +6 -6
  26. package/dist/{default-registry-BKHpiYiW.d.ts.map → default-registry-CKAFLuJg.d.ts.map} +1 -1
  27. package/dist/{define-agent-eval-Dd6hFx0-.js → define-agent-eval-CBhYD7Gq.js} +3 -3
  28. package/dist/{define-agent-eval-Dd6hFx0-.js.map → define-agent-eval-CBhYD7Gq.js.map} +1 -1
  29. package/dist/{define-agent-eval-Bh8tJHZI.d.ts → define-agent-eval-DyVma2pV.d.ts} +4 -4
  30. package/dist/{define-agent-eval-Bh8tJHZI.d.ts.map → define-agent-eval-DyVma2pV.d.ts.map} +1 -1
  31. package/dist/diagnosis/index.d.ts +2 -2
  32. package/dist/{evaluation-f-UIDwbL.d.ts → evaluation-BnRaBCKu.d.ts} +4 -4
  33. package/dist/{evaluation-f-UIDwbL.d.ts.map → evaluation-BnRaBCKu.d.ts.map} +1 -1
  34. package/dist/evaluation.d.ts +1 -1
  35. package/dist/{exact-types-BIHqYBYf.d.ts → exact-types-QwxMWchv.d.ts} +2 -2
  36. package/dist/{exact-types-BIHqYBYf.d.ts.map → exact-types-QwxMWchv.d.ts.map} +1 -1
  37. package/dist/experiment/index.d.ts +1 -1
  38. package/dist/{feedback-trajectory-CoQPmSJV.d.ts → feedback-trajectory-BkWAgoY0.d.ts} +3 -3
  39. package/dist/{feedback-trajectory-CoQPmSJV.d.ts.map → feedback-trajectory-BkWAgoY0.d.ts.map} +1 -1
  40. package/dist/{index-C1jQ7qqy.d.ts → index-BrALSxZU.d.ts} +9 -9
  41. package/dist/{index-C1jQ7qqy.d.ts.map → index-BrALSxZU.d.ts.map} +1 -1
  42. package/dist/{index-DH_Jxu9p.d.ts → index-CUpIEvoN.d.ts} +2 -2
  43. package/dist/{index-DH_Jxu9p.d.ts.map → index-CUpIEvoN.d.ts.map} +1 -1
  44. package/dist/{index-Cq_5SLfF.d.ts → index-D4SWfwQe.d.ts} +18 -18
  45. package/dist/{index-Cq_5SLfF.d.ts.map → index-D4SWfwQe.d.ts.map} +1 -1
  46. package/dist/{index-4khf0Q7g.d.ts → index-DmsDwlPe.d.ts} +5 -5
  47. package/dist/{index-4khf0Q7g.d.ts.map → index-DmsDwlPe.d.ts.map} +1 -1
  48. package/dist/index.d.ts +18 -18
  49. package/dist/index.js +4 -4
  50. package/dist/{llm-judge-Bf3p1WNA.js → llm-judge-DRHTRT66.js} +2 -2
  51. package/dist/{llm-judge-Bf3p1WNA.js.map → llm-judge-DRHTRT66.js.map} +1 -1
  52. package/dist/{matrix-BtyN7jpb.d.ts → matrix-CHbTz1bP.d.ts} +2 -2
  53. package/dist/{matrix-BtyN7jpb.d.ts.map → matrix-CHbTz1bP.d.ts.map} +1 -1
  54. package/dist/multishot/golden/index.d.ts +1 -1
  55. package/dist/multishot/index.d.ts +7 -7
  56. package/dist/multishot/index.js +2 -2
  57. package/dist/openapi.json +1 -1
  58. package/dist/{optimization-method-BO2sb1m4.js → optimization-method-B-NFaHom.js} +3 -3
  59. package/dist/{optimization-method-BO2sb1m4.js.map → optimization-method-B-NFaHom.js.map} +1 -1
  60. package/dist/{prime-protocol-BRMk6dGI.d.ts → prime-protocol-46WvqIIt.d.ts} +2 -2
  61. package/dist/{prime-protocol-BRMk6dGI.d.ts.map → prime-protocol-46WvqIIt.d.ts.map} +1 -1
  62. package/dist/{registry-BeInzotS.d.ts → registry-Bh1M9hrf.d.ts} +3 -3
  63. package/dist/{registry-BeInzotS.d.ts.map → registry-Bh1M9hrf.d.ts.map} +1 -1
  64. package/dist/rl.d.ts +3 -3
  65. package/dist/rollout/index.d.ts +2 -2
  66. package/dist/{run-improvement-loop-D9IAZviC.d.ts → run-improvement-loop-E4Uec3my.d.ts} +6 -6
  67. package/dist/{run-improvement-loop-D9IAZviC.d.ts.map → run-improvement-loop-E4Uec3my.d.ts.map} +1 -1
  68. package/dist/search/index.d.ts +2 -2
  69. package/dist/search/index.js +2 -2
  70. package/dist/{search-kernel-C2XOJHvk.d.ts → search-kernel-By0lhdoJ.d.ts} +2 -2
  71. package/dist/{search-kernel-C2XOJHvk.d.ts.map → search-kernel-By0lhdoJ.d.ts.map} +1 -1
  72. package/dist/{search-kernel-D96Eibc_.js → search-kernel-DezUrquk.js} +3 -3
  73. package/dist/{search-kernel-D96Eibc_.js.map → search-kernel-DezUrquk.js.map} +1 -1
  74. package/dist/{search-summary-DjgKz7B1.js → search-summary-DOhRouoT.js} +2 -2
  75. package/dist/{search-summary-DjgKz7B1.js.map → search-summary-DOhRouoT.js.map} +1 -1
  76. package/dist/{self-improve-DZ8W-QY-.d.ts → self-improve-CpmIIb57.d.ts} +6 -6
  77. package/dist/{self-improve-DZ8W-QY-.d.ts.map → self-improve-CpmIIb57.d.ts.map} +1 -1
  78. package/dist/{self-improve-BiTuylQQ.js → self-improve-Dm9PvLF2.js} +2 -2
  79. package/dist/{self-improve-BiTuylQQ.js.map → self-improve-Dm9PvLF2.js.map} +1 -1
  80. package/dist/{skillopt-optimization-method-CJkejuSP.js → skillopt-optimization-method-QZoNbg57.js} +2 -2
  81. package/dist/{skillopt-optimization-method-CJkejuSP.js.map → skillopt-optimization-method-QZoNbg57.js.map} +1 -1
  82. package/dist/{store-tool-spans-wH8y7InB.d.ts → store-tool-spans-B9zc0I1r.d.ts} +3 -3
  83. package/dist/{store-tool-spans-wH8y7InB.d.ts.map → store-tool-spans-B9zc0I1r.d.ts.map} +1 -1
  84. package/dist/{systemone-CpW1U2Uy.d.ts → systemone-Co2Lv810.d.ts} +6 -6
  85. package/dist/{systemone-CpW1U2Uy.d.ts.map → systemone-Co2Lv810.d.ts.map} +1 -1
  86. package/dist/{systemone-review-DpAXWDkL.d.ts → systemone-review-CRJ-Zdfo.d.ts} +3 -3
  87. package/dist/{systemone-review-DpAXWDkL.d.ts.map → systemone-review-CRJ-Zdfo.d.ts.map} +1 -1
  88. package/dist/systemone.d.ts +3 -3
  89. package/dist/{tool-groups-SlnoQNyT.d.ts → tool-groups-BHX9G_oE.d.ts} +2 -2
  90. package/dist/tool-groups-BHX9G_oE.d.ts.map +1 -0
  91. package/dist/{trace-questions-ybyF0B6N.d.ts → trace-questions-DfaIVysB.d.ts} +2 -2
  92. package/dist/{trace-questions-ybyF0B6N.d.ts.map → trace-questions-DfaIVysB.d.ts.map} +1 -1
  93. package/dist/trace-repair/index.d.ts +1 -1
  94. package/dist/traces.d.ts +2 -2
  95. package/dist/{tree-lU9KWuxr.js → tree-DBvepwFt.js} +2 -2
  96. package/dist/{tree-lU9KWuxr.js.map → tree-DBvepwFt.js.map} +1 -1
  97. package/dist/{types-DSU3qb_o.d.ts → types-Ci2r6el5.d.ts} +2 -2
  98. package/dist/{types-DSU3qb_o.d.ts.map → types-Ci2r6el5.d.ts.map} +1 -1
  99. package/dist/{types-B1W3v8dT.d.ts → types-CjrzKsOK.d.ts} +8 -8
  100. package/dist/{types-B1W3v8dT.d.ts.map → types-CjrzKsOK.d.ts.map} +1 -1
  101. package/dist/{types-BpIAnRCe.d.ts → types-CmHcpGl0.d.ts} +2 -2
  102. package/dist/{types-BpIAnRCe.d.ts.map → types-CmHcpGl0.d.ts.map} +1 -1
  103. package/dist/wire/index.d.ts +1 -1
  104. package/docs/real-work.md +81 -0
  105. package/package.json +1 -1
  106. package/dist/tool-groups-SlnoQNyT.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 {\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAS,wBACP,MAAyB,QAAQ,KACH;CAC9B,MAAM,kBAAkB,SAAS,IAAI,uBAAuB;CAC5D,MAAM,iBAAiB,SAAS,IAAI,sBAAsB;CAC1D,MAAM,eAAe,SAAS,IAAI,cAAc;CAChD,MAAM,eAAe,SAAS,IAAI,cAAc;CAChD,MAAM,UACJ,mBACA,SAAS,IAAI,eAAe,KAC5B,SAAS,IAAI,iBAAiB,MAC7B,eAAe,8BAA8B,KAAA,OAC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,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":["nonEmpty","FORMATS","USAGE","PROCESS_IO","parseArgs","NOTES","FORMATS","USAGE","PROCESS_IO","parseArgs","DAY_MS","USAGE","PROCESS_IO","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/real-work/config.ts","../src/real-work/files.ts","../src/real-work/process.ts","../src/real-work/git-history.ts","../src/real-work/runner-output.ts","../src/real-work/grader.ts","../src/real-work/harness.ts","../src/real-work/environment.ts","../src/real-work/receipts.ts","../src/real-work/later-fix.ts","../src/real-work/report.ts","../src/real-work/seal.ts","../src/real-work/solvers.ts","../src/real-work/state.ts","../src/real-work/time-cut.ts","../src/real-work/pipeline.ts","../src/real-work/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 * The builder's configuration: which repositories to read, how each one's own\n * gate runs, and which commands stand in as solvers. Everything a product\n * decides arrives here; the builder ships no product's values.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { z } from 'zod'\nimport { ConfigError } from '../errors'\n\nconst nonEmpty = z.string().min(1)\nconst timeoutMs = z.number().int().positive()\n\nexport const RUNNERS = ['jest', 'vitest', 'tap', 'cargo', 'pytest', 'go'] as const\nexport type RunnerKind = (typeof RUNNERS)[number]\n\nconst repoSchema = z.strictObject({\n /** `owner/name`; the task id and family are built from it. */\n name: z.string().regex(/^[\\w.-]+\\/[\\w.-]+$/, 'repository name must be owner/name'),\n /** Anything `git clone` accepts. */\n url: nonEmpty,\n defaultBranch: nonEmpty.default('main'),\n /** Which per-test result parser reads the gate's output. */\n runner: z.enum(RUNNERS).default('tap'),\n /** The image a task's environment names. Recorded, not pulled. */\n image: nonEmpty.default('node:22'),\n gate: z\n .strictObject({\n command: nonEmpty,\n /** How the gate is restricted to a change's test files. */\n mode: z.enum(['argv', 'env', 'none']).default('argv'),\n lockfile: nonEmpty.default('package-lock.json'),\n timeout: timeoutMs.default(120_000),\n })\n .optional(),\n /** Installs the frozen environment; run after every clean checkout. */\n build: z\n .strictObject({\n command: nonEmpty,\n outputs: z.array(nonEmpty).default(['dist', 'build', '.cache']),\n timeout: timeoutMs.default(600_000),\n })\n .optional(),\n /** The ref whose lockfile every environment must match. Defaults to the default branch. */\n gateRef: nonEmpty.optional(),\n service: z\n .strictObject({\n needs: z.boolean().default(false),\n gateHas: z.boolean().default(false),\n services: z.array(z.unknown()).default([]),\n })\n .optional(),\n graderAuthorKind: nonEmpty.default('merged-change'),\n})\n\n/**\n * A caller-defined change kind. A change matches when one of its paths has a\n * segment equal to or starting with one of `pathSegments`, or when its subject\n * or one of its added lines matches `linePattern` (case-insensitive). Rules are\n * tried in order before the built-in change types.\n */\nconst kindRuleSchema = z\n .strictObject({\n kind: z.string().regex(/^[a-z][a-z0-9-]*$/, 'a kind is a lowercase identifier'),\n pathSegments: z.array(nonEmpty).optional(),\n linePattern: nonEmpty.optional(),\n })\n .refine((rule) => rule.pathSegments !== undefined || rule.linePattern !== undefined, {\n message: 'a kind rule needs pathSegments, linePattern or both',\n })\n\nconst configSchema = z.strictObject({\n repos: z.array(repoSchema).min(1),\n windowDays: z.number().positive().default(90),\n outDir: nonEmpty.default('real-work-out'),\n /** A change with more added lines than this is `too-large`. */\n maxAddedLines: z.number().int().positive().default(400),\n /** A change touching more files than this is `too-large`. */\n maxFiles: z.number().int().positive().default(60),\n /** Paths (exact, or a prefix) whose change alone is `generated-only`. */\n generatedOnly: z\n .array(nonEmpty)\n .default(['package-lock.json', 'pnpm-lock.yaml', 'dist/', 'generated/']),\n kinds: z.array(kindRuleSchema).default([]),\n builderAgent: nonEmpty.default('real-work-builder'),\n /** The command recorded in the manifest, when the caller ran the builder some other way. */\n builderCommand: nonEmpty.optional(),\n /** The builder commit, required only when the builder does not run from a git checkout. */\n builderCommit: z\n .string()\n .regex(/^[0-9a-f]{40}$/)\n .optional(),\n /** Pins the build time, and with it the census window. */\n builtAt: z\n .string()\n .refine((value) => Number.isFinite(Date.parse(value)), 'builtAt must be an ISO time')\n .optional(),\n visibility: nonEmpty.default('private'),\n /** Invoked as `<command> <workdir> <gate> <prompt>`. */\n middleModel: z.strictObject({\n name: nonEmpty,\n command: nonEmpty,\n timeout: timeoutMs.default(600_000),\n }),\n /** Invoked as `<command> <workdir> <prompt> <storesRoot>`, the tools in `REAL_WORK_RETRIEVAL_TOOLS`. */\n retrieval: z.strictObject({\n scope: z.literal('tasks').default('tasks'),\n tools: z.array(nonEmpty).min(1).default(['qmd', 'knowledge', 'search']),\n command: nonEmpty,\n timeout: timeoutMs.default(600_000),\n }),\n audit: z\n .strictObject({\n agent: nonEmpty,\n count: z.number().int().positive().nullable().default(null),\n })\n .default({ agent: 'outside-auditor', count: null }),\n seal: z\n .strictObject({\n minTest: z.number().int().positive().default(40),\n maxTestShare: z.number().positive().max(1).default(0.4),\n minPerRepo: z.number().int().positive().default(5),\n })\n .default({ minTest: 40, maxTestShare: 0.4, minPerRepo: 5 }),\n /** Where receipts ran, for example a gate or a sandbox. The id defaults to this machine's hostname. */\n host: z\n .strictObject({ kind: nonEmpty.default('local'), id: nonEmpty.optional() })\n .default({ kind: 'local' }),\n /** The directory holding the memory, knowledge, docs and history stores. */\n stores: z.strictObject({ root: nonEmpty }).optional(),\n /** Grade at most this many buildable candidates per invocation. */\n gradeBatchSize: z.number().int().positive().optional(),\n})\n\nexport type RealWorkRepo = z.output<typeof repoSchema>\nexport type ChangeKindRule = z.output<typeof kindRuleSchema>\nexport type RealWorkConfig = Omit<z.output<typeof configSchema>, 'stores'> & {\n stores: { root: string }\n}\n\nexport function parseRealWorkConfig(value: unknown): RealWorkConfig {\n const parsed = configSchema.safeParse(value)\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`)\n .join('; ')\n throw new ConfigError(`real-work config is invalid: ${issues}`)\n }\n const config = parsed.data\n for (const rule of config.kinds) {\n if (rule.linePattern !== undefined) {\n try {\n new RegExp(rule.linePattern, 'i')\n } catch (error) {\n throw new ConfigError(`kind ${rule.kind}: linePattern is not a regular expression`, {\n cause: error,\n })\n }\n }\n }\n return {\n ...config,\n stores: config.stores ?? { root: join(config.outDir, '.work', 'stores') },\n }\n}\n\nexport function loadRealWorkConfig(path: string): RealWorkConfig {\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(path, 'utf8'))\n } catch (error) {\n throw new ConfigError(`cannot read real-work config ${path}`, { cause: error })\n }\n return parseRealWorkConfig(raw)\n}\n\nexport function repoNamed(config: RealWorkConfig, name: string): RealWorkRepo {\n const repo = config.repos.find((candidate) => candidate.name === name)\n if (!repo) throw new ConfigError(`repository ${name} is in the build state but not in the config`)\n return repo\n}\n","/**\n * File walks, byte digests and durable JSON writes for the real-work builder.\n * `sha256Of` hashes raw bytes (a file, a log, a line); structured values go\n * through the package's one canonical encoder.\n */\n\nimport { createHash } from 'node:crypto'\nimport {\n chmodSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n statSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join, relative, sep } from 'node:path'\nimport type { LedgerHash } from '../ledger-core/canonical'\n\nexport function sha256Of(content: string | Buffer): LedgerHash {\n return `sha256:${createHash('sha256').update(content).digest('hex')}`\n}\n\n/**\n * Every non-directory entry under `root`, as sorted `/`-separated relative\n * paths. Symlinks are listed and never followed, so a package manager's\n * virtual store is walked once, through its real directory.\n */\nexport function walkFiles(root: string, skipDirectories: readonly string[] = ['.git']): string[] {\n const out: string[] = []\n const walk = (directory: string): void => {\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n const full = join(directory, entry.name)\n if (entry.isDirectory()) {\n if (!skipDirectories.includes(entry.name)) walk(full)\n } else {\n out.push(relative(root, full).split(sep).join('/'))\n }\n }\n }\n walk(root)\n return out.sort()\n}\n\n/** Write JSON through a temporary file and a rename, so a reader never sees half a file. */\nexport function writeJsonAtomic(path: string, value: unknown): void {\n mkdirSync(dirname(path), { recursive: true })\n const temporary = `${path}.${process.pid}.tmp`\n writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\\n`)\n renameSync(temporary, path)\n}\n\nexport function readJsonFile(path: string): unknown {\n return JSON.parse(readFileSync(path, 'utf8'))\n}\n\nexport function isFile(path: string): boolean {\n try {\n return statSync(path).isFile()\n } catch {\n return false\n }\n}\n\n/** Write a file and make it read-only: how a grader is mounted into a checkout. */\nexport function writeReadOnly(path: string, content: string): void {\n mkdirSync(dirname(path), { recursive: true })\n try {\n chmodSync(path, 0o644)\n } catch {\n // The file does not exist yet.\n }\n writeFileSync(path, content)\n chmodSync(path, 0o444)\n}\n","/**\n * Process execution for the real-work builder.\n *\n * Git plumbing runs synchronously: it is short, local and its output is the\n * data the builder reads. A repository's gate, its environment build and every\n * solver command are someone else's programs, so they run through\n * `runBoundedProcess`, which bounds them in time and kills their whole process\n * group. No command passes through a shell.\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { runBoundedProcess } from '../bounded-process'\n\nexport interface CommandOutcome {\n /** The command ran and exited 0 within its bound. */\n ok: boolean\n exitCode: number\n stdout: string\n stderr: string\n /** False when the program could not be started at all. */\n spawned: boolean\n timedOut: boolean\n}\n\nconst GIT_MAX_BUFFER = 256 * 1024 * 1024\nconst COMMAND_MAX_OUTPUT = 64 * 1024 * 1024\n\n/**\n * Split a command string into an argument vector. Single and double quotes\n * group words; nothing else is interpreted, because no shell reads the result.\n */\nexport function tokenizeCommand(command: string): string[] {\n const argv: string[] = []\n let current = ''\n let inWord = false\n let quote: string | null = null\n for (const char of command) {\n if (quote !== null) {\n if (char === quote) quote = null\n else current += char\n } else if (char === '\"' || char === \"'\") {\n quote = char\n inWord = true\n } else if (/\\s/.test(char)) {\n if (inWord) argv.push(current)\n current = ''\n inWord = false\n } else {\n current += char\n inWord = true\n }\n }\n if (quote !== null) throw new Error(`unterminated quote in command: ${command}`)\n if (inWord) argv.push(current)\n return argv\n}\n\nexport function git(\n args: readonly string[],\n options: { cwd?: string; env?: Record<string, string> } = {},\n): CommandOutcome {\n const result = spawnSync('git', args, {\n cwd: options.cwd,\n encoding: 'utf8',\n maxBuffer: GIT_MAX_BUFFER,\n env: { ...process.env, ...options.env },\n })\n const spawned = result.error === undefined\n return {\n ok: spawned && result.status === 0,\n exitCode: result.status ?? 1,\n stdout: result.stdout ?? '',\n stderr: spawned ? (result.stderr ?? '') : String(result.error?.message),\n spawned,\n timedOut: false,\n }\n}\n\n/** Run git and return its stdout, or throw with its stderr. */\nexport function gitOrThrow(\n args: readonly string[],\n options: { cwd?: string; env?: Record<string, string> } = {},\n): string {\n const result = git(args, options)\n if (!result.ok) throw new Error(`git ${args.join(' ')} failed: ${result.stderr.trim()}`)\n return result.stdout\n}\n\nexport async function runCommand(\n argv: readonly string[],\n options: { cwd?: string; env?: Record<string, string>; timeoutMs: number },\n): Promise<CommandOutcome> {\n const [program, ...args] = argv\n if (program === undefined) throw new Error('cannot run an empty command')\n const result = await runBoundedProcess({\n command: program,\n args,\n cwd: options.cwd,\n env: options.env,\n envMode: 'merge',\n timeoutMs: options.timeoutMs,\n maxOutputBytes: COMMAND_MAX_OUTPUT,\n })\n const killed = result.killedByTimeout || result.killedBySignal\n return {\n ok: result.spawned && !killed && result.exitCode === 0,\n exitCode: result.exitCode,\n stdout: result.stdout,\n stderr:\n result.runnerError === undefined ? result.stderr : `${result.stderr}\\n${result.runnerError}`,\n spawned: result.spawned,\n timedOut: result.killedByTimeout,\n }\n}\n","/**\n * What the builder reads from git: a bare cache per repository, the merged\n * changes on its default branch, and each change's files and added lines.\n * Every value comes from a git object; nothing here is inferred.\n */\n\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { RealWorkRepo } from './config'\nimport { git, gitOrThrow } from './process'\n\nexport interface MergedChange {\n mergedCommit: string\n /** The merge's first parent: the default branch just before the change. */\n snapshotCommit: string\n mergedAt: string\n /** The merge commit's subject. */\n subject: string\n /** The subject of the merged branch's tip commit, which names the change itself. */\n branchSubject: string\n authorName: string\n authorEmail: string\n prNumber: number | null\n}\n\nexport interface ChangedFile {\n path: string\n status: 'A' | 'M' | 'D' | 'T'\n}\n\nconst slugOf = (value: string): string => value.replace(/[^A-Za-z0-9._-]+/g, '-')\n\nexport function cachePath(outDir: string, repo: RealWorkRepo): string {\n return join(outDir, '.work', 'cache', `${slugOf(repo.name)}.git`)\n}\n\n/**\n * A bare clone of the repository's branches, fetched again on every call so a\n * resumed build sees merges made since the last one. A cache that can be\n * neither cloned nor fetched is an error, never an empty history.\n */\nexport function ensureCache(outDir: string, repo: RealWorkRepo): string {\n const cache = cachePath(outDir, repo)\n if (!existsSync(cache)) {\n gitOrThrow(['clone', '--bare', '--quiet', repo.url, cache])\n return cache\n }\n gitOrThrow(['fetch', '--quiet', '--prune', 'origin', '+refs/heads/*:refs/heads/*'], {\n cwd: cache,\n })\n return cache\n}\n\nconst LOG_FORMAT = '%H%x09%P%x09%cI%x09%an%x09%ae%x09%s'\n\n/**\n * First-parent merges on the default branch, newest first, optionally bounded\n * by committer time. A later fix is looked for in the same list, so a merge on\n * some other branch never counts as one.\n */\nexport function listMerges(\n cache: string,\n repo: RealWorkRepo,\n window: { sinceMs?: number; untilMs?: number } = {},\n): MergedChange[] {\n const args = ['log', '--first-parent', '--merges', '--no-show-signature']\n if (window.sinceMs !== undefined) args.push(`--since=${new Date(window.sinceMs).toISOString()}`)\n if (window.untilMs !== undefined) args.push(`--until=${new Date(window.untilMs).toISOString()}`)\n args.push(`--pretty=format:${LOG_FORMAT}`, repo.defaultBranch, '--')\n const out = gitOrThrow(args, { cwd: cache })\n return out\n .split('\\n')\n .filter(Boolean)\n .map((line) => {\n const [\n mergedCommit = '',\n parents = '',\n mergedAt = '',\n authorName = '',\n authorEmail = '',\n subject = '',\n ] = line.split('\\t')\n const [firstParent = '', branchTip] = parents.split(' ')\n const prMatch = subject.match(/#(\\d+)/)\n return {\n mergedCommit,\n snapshotCommit: firstParent,\n mergedAt,\n subject,\n branchSubject: branchTip === undefined ? subject : commitSubject(cache, branchTip),\n authorName,\n authorEmail,\n prNumber: prMatch?.[1] === undefined ? null : Number(prMatch[1]),\n }\n })\n}\n\nfunction commitSubject(cache: string, commit: string): string {\n const res = git(['show', '-s', '--no-show-signature', '--pretty=format:%s', commit], {\n cwd: cache,\n })\n return res.stdout.trim() || 'merged change'\n}\n\n/** Files a change touched. Renames are reported as a deletion and an addition. */\nexport function changedFiles(cache: string, from: string, to: string): ChangedFile[] {\n const out = gitOrThrow(\n ['diff-tree', '-r', '--no-commit-id', '--name-status', '--no-renames', from, to],\n { cwd: cache },\n )\n return out\n .split('\\n')\n .filter(Boolean)\n .map((line) => {\n const [status = '', path = ''] = line.split('\\t')\n const code = status.charAt(0)\n if (code !== 'A' && code !== 'M' && code !== 'D' && code !== 'T') {\n throw new Error(`unexpected diff-tree status ${status} for ${path}`)\n }\n return { path, status: code }\n })\n}\n\n/** The lines a change added to one file, without their leading `+`. */\nexport function addedLines(cache: string, from: string, to: string, path: string): string[] {\n const res = git(['diff', '--no-ext-diff', '--no-color', '--no-renames', from, to, '--', path], {\n cwd: cache,\n })\n if (!res.ok) return []\n const lines: string[] = []\n for (const line of res.stdout.split('\\n')) {\n if (line.startsWith('+++')) continue\n if (line.startsWith('+')) lines.push(line.slice(1))\n }\n return lines\n}\n\n/** A file's content at a commit, or null when the file does not exist there. */\nexport function blobContent(cache: string, ref: string, path: string): string | null {\n const res = git(['cat-file', 'blob', `${ref}:${path}`], { cwd: cache })\n return res.ok ? res.stdout : null\n}\n\nexport function candidateIdOf(repo: RealWorkRepo, merge: MergedChange): string {\n const name = repo.name.split('/')[1] ?? repo.name\n return `${slugOf(name)}-${merge.prNumber ?? merge.mergedCommit.slice(0, 8)}`\n}\n","/**\n * Per-test results read from a test runner's own output. A parser reports only\n * what the output names; output it cannot read yields no tests, which the\n * pipeline rejects as `no-tests` rather than guessing a verdict.\n */\n\nimport { extractJsonPayload, isRecord } from '../llm-client/json'\nimport type { RunnerKind } from './config'\n\nexport interface ParsedTests {\n passed: number\n failed: number\n passedTests: string[]\n failedTests: string[]\n}\n\nconst unique = (names: readonly string[]): string[] => [...new Set(names)]\n\nconst result = (passedTests: string[], failedTests: string[]): ParsedTests => ({\n passed: passedTests.length,\n failed: failedTests.length,\n passedTests: unique(passedTests),\n failedTests: unique(failedTests),\n})\n\nfunction parseJsonReport(text: string): Record<string, unknown> | null {\n try {\n const value: unknown = JSON.parse(extractJsonPayload(text))\n return isRecord(value) ? value : null\n } catch {\n return null\n }\n}\n\n/** jest `--json` and vitest `--reporter=json`: `testResults[].assertionResults[]`. */\nfunction parseJestShape(text: string): ParsedTests {\n const report = parseJsonReport(text)\n const passedTests: string[] = []\n const failedTests: string[] = []\n const suites: unknown[] =\n report !== null && Array.isArray(report.testResults) ? report.testResults : []\n for (const suite of suites) {\n if (!isRecord(suite) || !Array.isArray(suite.assertionResults)) continue\n for (const assertion of suite.assertionResults as unknown[]) {\n if (!isRecord(assertion)) continue\n const name = String(assertion.fullName ?? assertion.title ?? suite.name)\n if (assertion.status === 'passed') passedTests.push(name)\n else if (assertion.status === 'failed') failedTests.push(name)\n }\n }\n return result(passedTests, failedTests)\n}\n\n/** TAP: `ok N - name` / `not ok N - name`; a `# SKIP` or `# TODO` failure is not a failure. */\nfunction parseTap(text: string): ParsedTests {\n const passedTests: string[] = []\n const failedTests: string[] = []\n for (const line of text.split('\\n')) {\n const match = line.match(/^(not )?ok(?:\\s+\\d+)?\\s+-\\s+(.+?)\\s*(#\\s*(SKIP|TODO)\\b.*|#.*)?$/i)\n if (!match?.[2]) continue\n const name = match[2].trim()\n if (match[4] !== undefined) continue\n if (match[1]) failedTests.push(name)\n else passedTests.push(name)\n }\n return result(passedTests, failedTests)\n}\n\n/** cargo test: `test <path> ... ok|FAILED`. */\nfunction parseCargo(text: string): ParsedTests {\n const passedTests: string[] = []\n const failedTests: string[] = []\n for (const line of text.split('\\n')) {\n const match = line.match(/^test\\s+(\\S+)\\s+\\.\\.\\.\\s+(ok|FAILED)\\b/)\n if (!match?.[1]) continue\n if (match[2] === 'ok') passedTests.push(match[1])\n else failedTests.push(match[1])\n }\n return result(passedTests, failedTests)\n}\n\n/** pytest -v (`path::name PASSED`), falling back to the short summary (`FAILED path::name`). */\nfunction parsePytest(text: string): ParsedTests {\n const passedTests: string[] = []\n const failedTests: string[] = []\n for (const line of text.split('\\n')) {\n const match = line.match(\n /^(\\S+::\\S+?)\\s+(PASSED|FAILED|ERROR|SKIPPED|XFAIL|XPASS)(?:\\s*\\[[^\\]]*\\])?\\s*$/,\n )\n if (!match?.[1]) continue\n if (match[2] === 'PASSED' || match[2] === 'XPASS') passedTests.push(match[1])\n else if (match[2] === 'FAILED' || match[2] === 'ERROR') failedTests.push(match[1])\n }\n if (passedTests.length === 0 && failedTests.length === 0) {\n for (const line of text.split('\\n')) {\n const match = line.match(/^(FAILED|PASSED)\\s+(\\S+::\\S+?)(?:\\s+-.*)?$/)\n if (!match?.[2]) continue\n if (match[1] === 'FAILED') failedTests.push(match[2])\n else passedTests.push(match[2])\n }\n }\n return result(passedTests, failedTests)\n}\n\n/** go test -v: `--- PASS: TestName (0.00s)` / `--- FAIL: ...`, subtests included. */\nfunction parseGo(text: string): ParsedTests {\n const passedTests: string[] = []\n const failedTests: string[] = []\n for (const line of text.split('\\n')) {\n const match = line.match(/^\\s*---\\s+(PASS|FAIL):\\s+(\\S+)/)\n if (!match?.[2]) continue\n if (match[1] === 'PASS') passedTests.push(match[2])\n else failedTests.push(match[2])\n }\n return result(passedTests, failedTests)\n}\n\nconst PARSERS: Record<RunnerKind, (text: string) => ParsedTests> = {\n jest: parseJestShape,\n vitest: parseJestShape,\n tap: parseTap,\n cargo: parseCargo,\n pytest: parsePytest,\n go: parseGo,\n}\n\n/**\n * Read the tests a run reported. A JSON runner is read from its report file\n * when it wrote one, else from stdout alone: stderr carries code frames whose\n * braces would corrupt the payload. Line runners read stdout and stderr.\n */\nexport function parseRunnerOutput(\n runner: RunnerKind,\n output: { stdout: string; stderr: string; report: string | null },\n): ParsedTests {\n if (runner === 'jest' || runner === 'vitest') {\n return PARSERS[runner](output.report ?? output.stdout)\n }\n return PARSERS[runner](`${output.stdout}\\n${output.stderr}`)\n}\n","/**\n * A task's grader is the repository's own gate restricted to the test files the\n * merged change added or changed, with those files mounted read-only into the\n * checkout after any solver has finished.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { hashCanonical, type LedgerHash } from '../ledger-core/canonical'\nimport type { ChangeKindRule, RealWorkRepo } from './config'\nimport { isFile, sha256Of, writeReadOnly } from './files'\nimport { blobContent } from './git-history'\nimport { runCommand, tokenizeCommand } from './process'\nimport { type ParsedTests, parseRunnerOutput } from './runner-output'\n\n/** Paths under a test directory, or named as a test file, in the common layouts. */\nconst TEST_PATH =\n /(^|\\/)(tests?|__tests__|spec|acceptance|fixtures)\\/|\\.(test|spec)\\.[a-z]+$|_test\\.[a-z]+$|test_[^/]*\\.py$/i\n\nexport function isTestFile(path: string): boolean {\n return TEST_PATH.test(path)\n}\n\nexport interface GraderFile {\n path: string\n content: string\n}\n\nexport interface Grader {\n paths: string[]\n files: GraderFile[]\n /** Canonical digest of the sorted `[path, sha256(content)]` pairs. */\n sha256: LedgerHash\n /** The gate command, restricted to the grader's files when the gate takes them as arguments. */\n command: string\n /** Variables the gate reads, holding the grader's files when the gate takes them that way. */\n env: Record<string, string>\n}\n\nexport interface GraderRun extends ParsedTests {\n exitCode: number\n log: string\n /** The frozen environment failed to install, so the gate never ran. */\n environmentError: boolean\n}\n\n/** The grader's files as the commit that authored them holds them. */\nexport function graderAt(\n cache: string,\n repo: RealWorkRepo,\n commit: string,\n testPaths: readonly string[],\n): Grader {\n const gate = repo.gate\n if (!gate) throw new Error(`repository ${repo.name} declares no gate command`)\n const files: GraderFile[] = []\n for (const path of [...testPaths].sort()) {\n const content = blobContent(cache, commit, path)\n if (content !== null) files.push({ path, content })\n }\n if (files.length === 0) throw new Error(`no grader files at ${commit}`)\n const paths = files.map((file) => file.path)\n const sha256 = hashCanonical(files.map((file) => [file.path, sha256Of(file.content)]))\n if (gate.mode === 'none') return { paths, files, sha256, command: gate.command, env: {} }\n if (gate.mode === 'env') {\n return { paths, files, sha256, command: gate.command, env: { TEST_FILES: paths.join(' ') } }\n }\n const args = paths.map((path) => (/\\s/.test(path) ? `\"${path}\"` : path)).join(' ')\n return { paths, files, sha256, command: `${gate.command} ${args}`, env: {} }\n}\n\nexport function mountGrader(workdir: string, grader: Grader): void {\n for (const file of grader.files) writeReadOnly(join(workdir, file.path), file.content)\n}\n\n/**\n * Run the grader in a checkout and read its per-test results. vitest writes\n * its JSON report to `--outputFile`, so for that runner the flags are added\n * when the gate does not name a report, and the report is read back.\n */\nexport async function runGrader(\n workdir: string,\n repo: RealWorkRepo,\n grader: Grader,\n): Promise<GraderRun> {\n let argv = tokenizeCommand(grader.command)\n let reportPath: string | null = null\n if (repo.runner === 'vitest') {\n const at = argv.findIndex((arg) => arg === '--outputFile' || arg.startsWith('--outputFile='))\n const declared = at < 0 ? undefined : argv[at]\n if (declared !== undefined) {\n const value =\n declared === '--outputFile' ? (argv[at + 1] ?? '') : declared.slice('--outputFile='.length)\n reportPath = resolve(workdir, value)\n } else if (!argv.includes('--reporter=json')) {\n reportPath = join(workdir, '.real-work-vitest.json')\n argv = [...argv, '--reporter=json', `--outputFile=${reportPath}`]\n }\n }\n const res = await runCommand(argv, {\n cwd: workdir,\n env: grader.env,\n timeoutMs: repo.gate?.timeout ?? 120_000,\n })\n const report = reportPath !== null && isFile(reportPath) ? readFileSync(reportPath, 'utf8') : null\n const parsed = parseRunnerOutput(repo.runner, { stdout: res.stdout, stderr: res.stderr, report })\n return {\n ...parsed,\n exitCode: res.exitCode,\n log: `exit ${res.exitCode}\\n${res.stdout}\\n${res.stderr}`,\n environmentError: false,\n }\n}\n\nexport const BUILT_IN_KINDS = ['perf', 'refactor', 'test', 'fix', 'feature'] as const\n\nconst segmentMatches = (segment: string, token: string): boolean => {\n const s = segment.toLowerCase()\n const t = token.toLowerCase()\n return t.endsWith('*') ? s.startsWith(t.slice(0, -1)) : s === t\n}\n\n/**\n * A change's kind. The caller's rules are tried in order; the first that\n * matches names the kind. Otherwise the change type comes from its own subject:\n * perf, refactor, test (or a change touching only test files), fix, else feature.\n */\nexport function classifyKind(\n change: { subject: string; paths: readonly string[]; addedLines: readonly string[] },\n rules: readonly ChangeKindRule[],\n): string {\n const lines = [change.subject, ...change.addedLines]\n for (const rule of rules) {\n const tokens = rule.pathSegments ?? []\n const byPath = change.paths.some((path) =>\n path.split('/').some((segment) => tokens.some((token) => segmentMatches(segment, token))),\n )\n if (byPath) return rule.kind\n if (rule.linePattern !== undefined) {\n const pattern = new RegExp(rule.linePattern, 'i')\n if (lines.some((line) => pattern.test(line))) return rule.kind\n }\n }\n const subject = change.subject.toLowerCase()\n if (/\\b(perf|performance|optimi[sz]\\w*)\\b/.test(subject)) return 'perf'\n if (/\\b(refactor\\w*|cleanup|clean up|renam\\w*|prune)\\b/.test(subject)) return 'refactor'\n if (\n /\\b(tests?|coverage)\\b/.test(subject) ||\n (change.paths.length > 0 && change.paths.every(isTestFile))\n ) {\n return 'test'\n }\n if (/\\b(fix\\w*|bug\\w*|patch\\w*|repair\\w*|regression)\\b/.test(subject)) return 'fix'\n return 'feature'\n}\n","/**\n * The run harness: a clean checkout at a commit, the frozen environment\n * installed, the grader mounted read-only, and the gate run. A solver acts on\n * the checkout before the grader is mounted, and every path it changed is\n * recorded.\n */\n\nimport { existsSync, readFileSync, rmSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { RealWorkRepo } from './config'\nimport { sha256Of, walkFiles } from './files'\nimport { type Grader, type GraderRun, mountGrader, runGrader } from './grader'\nimport { type CommandOutcome, git, gitOrThrow, runCommand, tokenizeCommand } from './process'\n\nexport function removeDirectory(path: string): void {\n rmSync(path, { recursive: true, force: true })\n}\n\n/**\n * A working clone of `source` at `dest`, reused when one is already there.\n * Reuse requires `dest/.git` itself: a directory inside some other checkout\n * must never be mistaken for a clone and cleaned.\n */\nexport function ensureRunClone(source: string, dest: string): string {\n if (existsSync(join(dest, '.git'))) return dest\n removeDirectory(dest)\n gitOrThrow(['clone', '--quiet', source, dest])\n return dest\n}\n\n/** Reset the checkout to exactly the tree of `commit`: nothing untracked, ignored or modified survives. */\nexport function checkoutTree(workdir: string, commit: string): void {\n git(['clean', '-q', '-f', '-d', '-x'], { cwd: workdir })\n gitOrThrow(['checkout', '--quiet', '--force', '--detach', commit], { cwd: workdir })\n git(['clean', '-q', '-f', '-d', '-x'], { cwd: workdir })\n gitOrThrow(['reset', '--hard', '-q', commit], { cwd: workdir })\n}\n\n/** Content hash of every working-tree file outside `.git` and `node_modules`. */\nexport function treeState(workdir: string): Map<string, string> {\n const state = new Map<string, string>()\n for (const path of walkFiles(workdir, ['.git', 'node_modules'])) {\n try {\n state.set(path, sha256Of(readFileSync(join(workdir, path))))\n } catch {\n // A path that vanished between the walk and the read was not written.\n }\n }\n return state\n}\n\n/** Paths whose content changed or appeared, and paths that disappeared. */\nexport function changedPaths(before: Map<string, string>, after: Map<string, string>): string[] {\n const changed = new Set<string>()\n for (const [path, hash] of after) if (before.get(path) !== hash) changed.add(path)\n for (const path of before.keys()) if (!after.has(path)) changed.add(path)\n return [...changed].sort()\n}\n\nexport async function installEnvironment(\n workdir: string,\n repo: RealWorkRepo,\n): Promise<CommandOutcome | null> {\n if (!repo.build) return null\n return await runCommand(tokenizeCommand(repo.build.command), {\n cwd: workdir,\n timeoutMs: repo.build.timeout,\n })\n}\n\nconst environmentFailure = (installed: CommandOutcome): GraderRun => ({\n exitCode: installed.exitCode === 0 ? 1 : installed.exitCode,\n passed: 0,\n failed: 0,\n passedTests: [],\n failedTests: [],\n environmentError: true,\n log: `environment install failed\\n${installed.stdout}\\n${installed.stderr}`,\n})\n\n/** One graded run: clean checkout at `applied` (or the snapshot), install, mount, run. */\nexport async function gradedRun(\n workdir: string,\n run: { repo: RealWorkRepo; snapshot: string; applied: string | null; grader: Grader },\n): Promise<GraderRun> {\n checkoutTree(workdir, run.applied ?? run.snapshot)\n const installed = await installEnvironment(workdir, run.repo)\n if (installed && !installed.ok) return environmentFailure(installed)\n mountGrader(workdir, run.grader)\n return await runGrader(workdir, run.repo, run.grader)\n}\n\nexport interface SolverInput {\n workdir: string\n repo: RealWorkRepo\n prompt: string\n}\n\nexport interface SolverReport {\n kind: string\n /** Tokens the solver reported spending, or null when it reported none. */\n tokens: number | null\n /** Bytes of the change the solver applied, when the builder applied it. */\n appliedBytes: number\n tools?: string[]\n}\n\nexport type Solver = (input: SolverInput) => Promise<SolverReport>\n\n/**\n * A solver run: the solver works on a clean checkout of `snapshot` with the\n * environment installed; then the harness mounts the grader and grades.\n */\nexport async function solverRun(\n workdir: string,\n run: { repo: RealWorkRepo; snapshot: string; grader: Grader; solver: Solver; prompt: string },\n): Promise<{ run: GraderRun; wrote: string[]; report: SolverReport }> {\n checkoutTree(workdir, run.snapshot)\n const installed = await installEnvironment(workdir, run.repo)\n if (installed && !installed.ok) {\n throw new Error(`environment install failed: ${installed.stdout}\\n${installed.stderr}`)\n }\n const before = treeState(workdir)\n const report = await run.solver({ workdir, repo: run.repo, prompt: run.prompt })\n const wrote = changedPaths(before, treeState(workdir))\n mountGrader(workdir, run.grader)\n return { run: await runGrader(workdir, run.repo, run.grader), wrote, report }\n}\n","/**\n * A task's environment is the repository's own build, run twice in two clean\n * directories at the snapshot from the same frozen lockfile.\n *\n * - `treeDigest` covers the source tree at the snapshot, without the install\n * and build outputs.\n * - `imageDigest` covers the installed tree. Symlinks hash as their link text,\n * pnpm's timestamped bookkeeping is left out, and the build directory's own\n * path is normalized so two directories can compare equal.\n *\n * Both builds must exit 0 and agree on both digests, or the candidate is\n * `env-unbuildable`.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { lstatSync, readFileSync, readlinkSync, realpathSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { hashCanonical, type LedgerHash } from '../ledger-core/canonical'\nimport type { RealWorkRepo } from './config'\nimport { sha256Of, walkFiles } from './files'\nimport { blobContent } from './git-history'\nimport { checkoutTree, ensureRunClone, installEnvironment, removeDirectory } from './harness'\n\nexport interface EnvironmentBuild {\n buildId: string\n exitCode: number\n treeDigest: LedgerHash\n imageDigest: LedgerHash\n}\n\nexport interface EnvironmentRecord {\n buildable: boolean\n builds: EnvironmentBuild[]\n lockfileSha256: LedgerHash | null\n error: string | null\n}\n\nconst INSTALL_BOOKKEEPING = [\n 'node_modules/.modules.yaml',\n 'node_modules/.pnpm-workspace-state-v1.json',\n]\n\n/** Literal substitutions applied before hashing, so two build directories compare equal. */\ntype PathReplacements = ReadonlyArray<readonly [from: string, to: string]>\n\n/** A symlink hashes its link text; a file hashes its bytes. */\nfunction entrySha(path: string, replace: PathReplacements = []): LedgerHash {\n if (lstatSync(path).isSymbolicLink()) {\n let target = readlinkSync(path)\n for (const [from, to] of replace) target = target.split(from).join(to)\n return sha256Of(target)\n }\n let content = readFileSync(path)\n for (const [from, to] of replace) {\n if (content.includes(from)) content = Buffer.from(content.toString('utf8').split(from).join(to))\n }\n return sha256Of(content)\n}\n\n/** Digest of a directory: the canonical form of its sorted `[path, sha256]` pairs. */\nfunction linkPreservingTreeDigest(\n root: string,\n options: { exclude?: readonly string[]; replace?: PathReplacements } = {},\n): LedgerHash {\n const exclude = options.exclude ?? []\n const pairs = walkFiles(root)\n .filter(\n (path) => !exclude.some((pattern) => path === pattern || path.startsWith(`${pattern}/`)),\n )\n .map((path) => [path, entrySha(join(root, path), options.replace)])\n return hashCanonical(pairs)\n}\n\nexport function lockfileSha(cache: string, ref: string, lockfile: string): LedgerHash {\n const content = blobContent(cache, ref, lockfile)\n if (content === null) throw new Error(`lockfile ${lockfile} not found at ${ref}`)\n return sha256Of(content)\n}\n\nexport async function buildEnvironment(\n cache: string,\n repo: RealWorkRepo,\n at: { snapshot: string; workRoot: string },\n): Promise<EnvironmentRecord> {\n const lockfile = lockfileSha(cache, at.snapshot, repo.gate?.lockfile ?? 'package-lock.json')\n if (!repo.build) {\n return { buildable: false, builds: [], lockfileSha256: lockfile, error: 'no build command' }\n }\n const outputs = ['node_modules', ...repo.build.outputs]\n const builds: EnvironmentBuild[] = []\n let error: string | null = null\n for (let index = 1; index <= 2; index++) {\n const id = randomUUID().slice(0, 8)\n const dir = join(at.workRoot, `env-build-${index}-${id}`)\n try {\n ensureRunClone(cache, dir)\n checkoutTree(dir, at.snapshot)\n const installed = await installEnvironment(dir, repo)\n const replace = [...new Set([dir, realpathSync(dir)])].map(\n (from) => [from, '~BUILD~'] as const,\n )\n builds.push({\n buildId: `build-${index}-${id}`,\n exitCode: installed?.exitCode ?? 1,\n treeDigest: linkPreservingTreeDigest(dir, { exclude: outputs }),\n imageDigest: linkPreservingTreeDigest(dir, { exclude: INSTALL_BOOKKEEPING, replace }),\n })\n } catch (caught) {\n error = caught instanceof Error ? caught.message : String(caught)\n break\n } finally {\n removeDirectory(dir)\n }\n }\n const [first, second] = builds\n const buildable =\n error === null &&\n first !== undefined &&\n second !== undefined &&\n builds.every((build) => build.exitCode === 0) &&\n first.treeDigest === second.treeDigest &&\n first.imageDigest === second.imageDigest\n return { buildable, builds, lockfileSha256: lockfile, error }\n}\n","/**\n * A receipt is one grader verdict on one tree, repeated three times from a\n * clean checkout. Red is the snapshot alone; green applies the merged change.\n * `receiptDigest` is the canonical digest of the receipt without that field,\n * so anyone holding the JSON can recompute it and see an edit.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { hostname } from 'node:os'\nimport { hashCanonical, type LedgerHash } from '../ledger-core/canonical'\nimport type { RealWorkConfig, RealWorkRepo } from './config'\nimport { sha256Of } from './files'\nimport type { Grader, GraderRun } from './grader'\nimport { ensureRunClone, gradedRun, removeDirectory } from './harness'\n\nexport const RECEIPT_RUNS = 3\n\nexport interface ReceiptHost {\n kind: string\n id: string\n runId: string\n}\n\nexport interface ReceiptRun {\n exitCode: number\n failedTests: string[]\n}\n\nexport interface Receipt {\n snapshotCommit: string\n appliedCommit: string | null\n graderSha256: LedgerHash\n /** The first failing run's verdict, or the first run's when every run passed. */\n exitCode: number\n passed: number\n failed: number\n failedTests: string[]\n passedTests: string[]\n clean: true\n host: ReceiptHost\n logSha256: LedgerHash\n ranAt: string\n runs: ReceiptRun[]\n receiptDigest: LedgerHash\n}\n\nexport interface TakenReceipt {\n receipt: Receipt\n /** The environment failed to install on some run, so the receipt holds no verdict. */\n environmentError: boolean\n}\n\n/** Where receipts run: the configured host kind, and its id or this machine's hostname. */\nexport function receiptMachine(config: Pick<RealWorkConfig, 'host'>): Omit<ReceiptHost, 'runId'> {\n return { kind: config.host.kind, id: config.host.id ?? hostname() }\n}\n\nexport function receiptDigestOf(\n receipt: Omit<Receipt, 'receiptDigest'> & { receiptDigest?: unknown },\n): LedgerHash {\n const { receiptDigest: _digest, ...rest } = receipt\n return hashCanonical(rest)\n}\n\nexport async function takeReceipt(\n cache: string,\n workdir: string,\n run: {\n repo: RealWorkRepo\n snapshot: string\n applied: string | null\n grader: Grader\n machine: Omit<ReceiptHost, 'runId'>\n },\n): Promise<TakenReceipt> {\n try {\n ensureRunClone(cache, workdir)\n const details: GraderRun[] = []\n const logs: string[] = []\n for (let index = 0; index < RECEIPT_RUNS; index++) {\n const result = await gradedRun(workdir, run)\n details.push(result)\n logs.push(`--- run ${index + 1} ---\\n${result.log}`)\n if (result.environmentError) break\n }\n const verdict = details.find((result) => result.exitCode !== 0) ?? details[0]\n if (verdict === undefined) throw new Error('a receipt ran no grader')\n const unsigned = {\n snapshotCommit: run.snapshot,\n appliedCommit: run.applied,\n graderSha256: run.grader.sha256,\n exitCode: verdict.exitCode,\n passed: verdict.passed,\n failed: verdict.failed,\n failedTests: [...verdict.failedTests],\n passedTests: [...verdict.passedTests],\n clean: true as const,\n host: { ...run.machine, runId: randomUUID() },\n logSha256: sha256Of(logs.join('\\n')),\n ranAt: new Date().toISOString(),\n runs: details.map((result) => ({\n exitCode: result.exitCode,\n failedTests: [...result.failedTests],\n })),\n }\n return {\n receipt: { ...unsigned, receiptDigest: receiptDigestOf(unsigned) },\n environmentError: details.some((result) => result.environmentError),\n }\n } finally {\n removeDirectory(workdir)\n }\n}\n\n/** The runs agree on their exit code and on the set of failing tests. */\nexport function runsAgree(runs: readonly ReceiptRun[]): boolean {\n const verdicts = new Set(\n runs.map((run) => `${run.exitCode}:${[...run.failedTests].sort().join('|')}`),\n )\n return verdicts.size === 1\n}\n\nexport function receiptVerdict(receipt: Receipt): { passes: boolean; fails: boolean } {\n return {\n passes: receipt.exitCode === 0 && receipt.failed === 0 && receipt.passed >= 1,\n fails: receipt.exitCode !== 0 && receipt.failed >= 1 && receipt.failedTests.length > 0,\n }\n}\n","/**\n * Later fixes. A merged change that a later merge fixed is graded by the fix's\n * tests: the shipped change must fail them and the fix must pass them, so an\n * oracle that replays the shipped change scores below 100% there.\n *\n * A fix merges on the default branch within seven days after the change and\n * before the build, touches a non-test file the change touched, and brings\n * tests the change does not hold back.\n */\n\nimport { join } from 'node:path'\nimport type { RealWorkRepo } from './config'\nimport { changedFiles, type MergedChange } from './git-history'\nimport { type Grader, graderAt, isTestFile } from './grader'\nimport { type Receipt, type ReceiptHost, receiptVerdict, runsAgree, takeReceipt } from './receipts'\n\nexport const LATER_FIX_DAYS = 7\nconst DAY_MS = 86_400_000\n\nexport interface LaterFix {\n fixCommit: string\n fixMergedAt: string\n touchedPaths: string[]\n hiddenGrader: {\n paths: string[]\n testIds: string[]\n sha256: string\n author: { kind: 'fix-change'; ref: string }\n }\n receipts: { merged: Receipt; fix: Receipt }\n}\n\nexport interface LaterFixCandidate {\n merge: MergedChange\n testPaths: string[]\n}\n\nexport function findLaterFixes(\n cache: string,\n task: { mergedCommit: string; snapshotCommit: string; mergedAt: string; heldBackPaths: string[] },\n merges: readonly MergedChange[],\n untilMs: number,\n): LaterFixCandidate[] {\n const codePaths = new Set(\n changedFiles(cache, task.snapshotCommit, task.mergedCommit)\n .map((file) => file.path)\n .filter((path) => !isTestFile(path)),\n )\n const mergedAt = Date.parse(task.mergedAt)\n const fixes: LaterFixCandidate[] = []\n for (const merge of merges) {\n if (merge.mergedCommit === task.mergedCommit) continue\n const at = Date.parse(merge.mergedAt)\n const after = at - mergedAt\n if (!(after > 0 && after <= LATER_FIX_DAYS * DAY_MS) || at > untilMs) continue\n const paths = changedFiles(cache, merge.snapshotCommit, merge.mergedCommit).map(\n (file) => file.path,\n )\n const testPaths = paths.filter(isTestFile)\n if (testPaths.length === 0) continue\n if (!paths.some((path) => codePaths.has(path))) continue\n if (testPaths.some((path) => task.heldBackPaths.includes(path))) continue\n fixes.push({ merge, testPaths })\n }\n return fixes\n}\n\n/**\n * The later-fix record for one candidate fix, or null when its receipts do not\n * show the shipped change failing the fix's tests and the fix passing them.\n */\nexport async function buildLaterFix(\n cache: string,\n repo: RealWorkRepo,\n task: { id: string; mergedCommit: string; snapshotCommit: string },\n fix: LaterFixCandidate,\n run: { workRoot: string; machine: Omit<ReceiptHost, 'runId'> },\n): Promise<{ laterFix: LaterFix; grader: Grader } | null> {\n const grader = graderAt(cache, repo, fix.merge.mergedCommit, fix.testPaths)\n const receiptFor = (applied: string, name: string) =>\n takeReceipt(cache, join(run.workRoot, `${task.id}-${name}`), {\n repo,\n snapshot: task.snapshotCommit,\n applied,\n grader,\n machine: run.machine,\n })\n const merged = await receiptFor(task.mergedCommit, 'later-fix-merged')\n if (merged.environmentError) return null\n const fixed = await receiptFor(fix.merge.mergedCommit, 'later-fix-fix')\n if (fixed.environmentError) return null\n const mergedFails = runsAgree(merged.receipt.runs) && receiptVerdict(merged.receipt).fails\n const fixPasses = runsAgree(fixed.receipt.runs) && receiptVerdict(fixed.receipt).passes\n if (!mergedFails || !fixPasses) return null\n const testIds = [\n ...new Set([\n ...fixed.receipt.failedTests,\n ...fixed.receipt.passedTests,\n ...merged.receipt.failedTests,\n ]),\n ]\n return {\n laterFix: {\n fixCommit: fix.merge.mergedCommit,\n fixMergedAt: fix.merge.mergedAt,\n touchedPaths: changedFiles(cache, fix.merge.snapshotCommit, fix.merge.mergedCommit).map(\n (file) => file.path,\n ),\n hiddenGrader: {\n paths: grader.paths,\n testIds,\n sha256: grader.sha256,\n author: { kind: 'fix-change', ref: fix.merge.authorEmail },\n },\n receipts: { merged: merged.receipt, fix: fixed.receipt },\n },\n grader,\n }\n}\n","/**\n * The delivered pages: `manifest.json`, `candidates.json`, `yield.json`,\n * `tasks/<id>.json`, `spread.json` and `retrieval.json`. Every value is read\n * from the build state; the report computes nothing a stage did not measure.\n */\n\nimport { join } from 'node:path'\nimport type { LedgerHash } from '../ledger-core/canonical'\nimport type { RealWorkConfig } from './config'\nimport type { EnvironmentRecord } from './environment'\nimport { writeJsonAtomic } from './files'\nimport type { RealWorkState, TaskRecord } from './state'\n\nexport const MANIFEST_SCHEMA = 'real-work-benchmark.v2'\n\nexport interface BuilderIdentity {\n repo: string\n commit: string\n path: string\n command: string\n}\n\nfunction taskPage(\n task: TaskRecord,\n config: RealWorkConfig,\n context: {\n builderCommit: string\n lockfileSha256: LedgerHash | null\n environment: EnvironmentRecord\n },\n) {\n const repo = config.repos.find((candidate) => candidate.name === task.repo)\n if (!repo?.gate || task.timeCut === null || task.split === null) {\n throw new Error(`task ${task.id} reached the report before every stage recorded it`)\n }\n return {\n id: task.id,\n repo: task.repo,\n kind: task.kind,\n family: `${task.repo}/${task.kind}`,\n prNumber: task.prNumber,\n snapshotCommit: task.snapshotCommit,\n mergedParent: task.snapshotCommit,\n mergedCommit: task.mergedCommit,\n mergedAt: task.mergedAt,\n builderCommit: context.builderCommit,\n prompt: task.prompt,\n split: task.split,\n solvers: task.solvers,\n solution: {\n files: task.changeFiles.map((file) => ({\n path: file.path,\n postSha256: file.postSha256,\n addedLineHashes: file.addedLineHashes,\n })),\n },\n snapshot: {\n touched: task.changeFiles.map((file) => ({ path: file.path, sha256: file.snapshotSha256 })),\n },\n heldBack: { paths: task.heldBackPaths, inSnapshot: false },\n grader: {\n kind: 'tests',\n command: task.grader.command,\n env: task.grader.env,\n paths: task.grader.paths,\n testIds: task.testIds,\n sha256: task.grader.sha256,\n author: task.graderAuthor,\n },\n graderIntegrity: { mountedReadOnly: true, solverWrites: task.solverWrites },\n environment: {\n image: repo.image,\n gateCommand: repo.gate.command,\n lockfileSha256: context.lockfileSha256,\n needsService: repo.service?.needs ?? false,\n gateHasService: repo.service?.gateHas ?? false,\n services: repo.service?.services ?? [],\n builds: context.environment.builds,\n },\n timeCut: {\n baseTime: task.timeCut.baseTime,\n fullHistory: false,\n latestObjectTime: task.timeCut.latestObjectTime,\n // The builder gives a solver no search index, so there is none to stamp.\n indexes: [],\n canaries: task.timeCut.canaries.map((canary) => ({\n store: canary.store,\n token: canary.token,\n plantedAt: canary.plantedAt,\n probeQueries: canary.probeQueries,\n solverContextSha256: canary.solverContextSha256,\n hits: canary.hits,\n })),\n },\n receipts: task.receipts,\n ...(task.laterFix === null ? {} : { laterFix: task.laterFix }),\n }\n}\n\nexport function writeReport(\n config: RealWorkConfig,\n state: RealWorkState,\n build: { builtAt: string; builder: BuilderIdentity },\n): void {\n const { outDir } = config\n if (state.seal === null) throw new Error('the report needs a sealed build')\n const candidates = state.candidates.map((candidate) => ({\n id: candidate.id,\n repo: candidate.repo,\n prNumber: candidate.prNumber,\n mergedCommit: candidate.mergedCommit,\n mergedAt: candidate.mergedAt,\n reason: candidate.reason,\n }))\n const byReason: Record<string, number> = {}\n for (const candidate of candidates) {\n byReason[candidate.reason] = (byReason[candidate.reason] ?? 0) + 1\n }\n const taskIds = new Set(state.tasks.map((task) => task.id))\n writeJsonAtomic(join(outDir, 'candidates.json'), candidates)\n writeJsonAtomic(join(outDir, 'yield.json'), {\n candidates: candidates.length,\n tasks: state.tasks.length,\n yield: Math.round((state.tasks.length / Math.max(1, candidates.length)) * 1e4) / 1e4,\n byReason,\n })\n for (const task of state.tasks) {\n const environment = state.environments[task.id]\n if (!environment) throw new Error(`task ${task.id} has no environment record`)\n writeJsonAtomic(\n join(outDir, 'tasks', `${task.id}.json`),\n taskPage(task, config, {\n builderCommit: build.builder.commit,\n lockfileSha256: state.repoLockfiles[task.repo] ?? null,\n environment,\n }),\n )\n }\n const repoGates: Record<string, { command: string | null; lockfileSha256: LedgerHash | null }> =\n {}\n for (const repo of config.repos) {\n repoGates[repo.name] = {\n command: repo.gate?.command ?? null,\n lockfileSha256: state.repoLockfiles[repo.name] ?? null,\n }\n }\n writeJsonAtomic(join(outDir, 'manifest.json'), {\n schema: MANIFEST_SCHEMA,\n builtAt: build.builtAt,\n visibility: config.visibility,\n builder: build.builder,\n agents: [...new Set([config.builderAgent, config.middleModel.name])],\n repoGates,\n census: state.census,\n seal: { testSetSha256: state.seal.testSetSha256, sealedAt: state.seal.sealedAt },\n tasks: state.tasks.map((task) => task.id),\n audit: { reruns: state.auditReruns },\n })\n writeJsonAtomic(join(outDir, 'spread.json'), {\n middleModel: config.middleModel.name,\n cells: state.spreadCells.filter((cell) => taskIds.has(cell.task)),\n })\n const notesAnswered = new Set(\n state.candidates\n .filter((candidate) => candidate.reason === 'answer-in-notes')\n .map((candidate) => candidate.id),\n )\n writeJsonAtomic(join(outDir, 'retrieval.json'), {\n cells: state.retrievalCells.filter(\n (cell) => taskIds.has(cell.task) || notesAnswered.has(cell.task),\n ),\n })\n}\n","/**\n * The seal: train, selection and test splits, assigned deterministically from\n * the tasks' merge times and ids, and the digest that fixes the test set.\n *\n * The test split holds at least `minTest` tasks and at most `maxTestShare` of\n * all tasks; every repository with at least `minPerRepo` tasks is represented\n * in it; and train and selection each hold at least one task. Tasks are taken\n * at a stride through the merge-time order, so the test set spans the window.\n */\n\nimport { compareCodeUnits, type LedgerHash } from '../ledger-core/canonical'\nimport type { RealWorkConfig } from './config'\nimport { sha256Of } from './files'\n\nexport type Split = 'train' | 'selection' | 'test'\n\nexport interface SealedSplits {\n splits: Map<string, Split>\n testIds: string[]\n testSetSha256: LedgerHash\n}\n\n/** sha256 of the sorted test task ids joined by newlines. */\nexport function testSetSha256(testIds: readonly string[]): LedgerHash {\n return sha256Of([...testIds].sort(compareCodeUnits).join('\\n'))\n}\n\nexport function sealSplits(\n tasks: ReadonlyArray<{ id: string; repo: string; mergedAt: string }>,\n { minTest, maxTestShare, minPerRepo }: RealWorkConfig['seal'],\n): SealedSplits {\n if (tasks.length === 0) throw new Error('seal: there are no tasks to split')\n const maxTest = Math.floor(tasks.length * maxTestShare)\n if (minTest > maxTest) {\n throw new Error(\n `seal: ${tasks.length} tasks cannot hold a test split of at least ${minTest} within ${maxTestShare} of all tasks (at most ${maxTest})`,\n )\n }\n const ordered = [...tasks].sort((a, b) =>\n compareCodeUnits(`${a.mergedAt} ${a.id}`, `${b.mergedAt} ${b.id}`),\n )\n const perRepo = new Map<string, number>()\n for (const task of tasks) perRepo.set(task.repo, (perRepo.get(task.repo) ?? 0) + 1)\n const bigRepos = [...perRepo].filter(([, count]) => count >= minPerRepo).map(([repo]) => repo)\n const testCount = Math.min(\n maxTest,\n Math.max(minTest, bigRepos.length, Math.ceil((tasks.length * maxTestShare) / 3)),\n )\n\n const test = new Set<string>()\n for (const repo of bigRepos) {\n if (test.size >= testCount) break\n const first = ordered.find((task) => task.repo === repo)\n if (first) test.add(first.id)\n }\n const pool = ordered.filter((task) => !test.has(task.id))\n const stride = Math.max(1, Math.floor(pool.length / Math.max(1, testCount - test.size)))\n for (let index = 0; test.size < testCount && index < pool.length; index += stride) {\n const task = pool[index]\n if (task) test.add(task.id)\n }\n for (const task of ordered) {\n if (test.size >= testCount) break\n test.add(task.id)\n }\n\n const rest = ordered.filter((task) => !test.has(task.id))\n if (rest.length < 2) {\n throw new Error(\n `seal: ${rest.length} tasks remain outside the test split; train and selection must each hold one`,\n )\n }\n const selectionCount = Math.max(1, Math.min(rest.length - 1, Math.ceil(rest.length / 4)))\n const selection = new Set(rest.slice(0, selectionCount).map((task) => task.id))\n const splits = new Map<string, Split>()\n for (const task of ordered) {\n splits.set(task.id, test.has(task.id) ? 'test' : selection.has(task.id) ? 'selection' : 'train')\n }\n const testIds = [...test].sort(compareCodeUnits)\n return { splits, testIds, testSetSha256: testSetSha256(testIds) }\n}\n","/**\n * The controls that show a task separates setups. The oracle applies the real\n * change, the null solver does nothing, and the middle model is the caller's\n * command. The retrieval control is a caller's command with search over the\n * stores alone. Every verdict comes from a real grader run.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { mkdirSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { RealWorkConfig, RealWorkRepo } from './config'\nimport type { Grader } from './grader'\nimport { type Solver, type SolverReport, solverRun } from './harness'\nimport { runCommand, tokenizeCommand } from './process'\n\nexport interface ChangeFileContent {\n path: string\n /** Null when the change deleted the file. */\n content: string | null\n}\n\nexport interface SpreadCell {\n task: string\n solver: 'oracle' | 'null' | 'middle'\n pass: boolean\n runId: string\n tokens: number\n /** `reported` by the solver, or `estimated` at four bytes a token from the prompt and the applied change. */\n tokensSource: 'reported' | 'estimated'\n}\n\nconst BYTES_PER_TOKEN = 4\n\n/** The last `TOKENS <n>` line a solver printed, which is how it reports its usage. */\nfunction reportedTokens(output: string): number | null {\n const line = output\n .split('\\n')\n .reverse()\n .find((candidate) => /^TOKENS\\s+\\d+$/.test(candidate.trim()))\n return line === undefined ? null : Number(line.trim().split(/\\s+/)[1])\n}\n\nfunction applyChange(workdir: string, files: readonly ChangeFileContent[]): number {\n let bytes = 0\n for (const file of files) {\n const dest = join(workdir, file.path)\n if (file.content === null) {\n rmSync(dest, { force: true })\n } else {\n mkdirSync(dirname(dest), { recursive: true })\n writeFileSync(dest, file.content)\n bytes += Buffer.byteLength(file.content)\n }\n }\n return bytes\n}\n\n/** Applies every file of the real change except the graders, which only the harness writes. */\nexport function oracleSolver(\n change: readonly ChangeFileContent[],\n guarded: ReadonlySet<string>,\n): Solver {\n return async ({ workdir }) => ({\n kind: 'apply-merged-change',\n tokens: null,\n appliedBytes: applyChange(\n workdir,\n change.filter((file) => !guarded.has(file.path)),\n ),\n })\n}\n\nexport const nullSolver: Solver = async () => ({ kind: 'no-op', tokens: null, appliedBytes: 0 })\n\n/**\n * The caller's model, invoked as `<command> <workdir> <gate> <prompt>`. A\n * model that exits nonzero has still attempted the task and is graded; a\n * command that cannot start is a measurement failure and stops the build.\n */\nexport function middleSolver(model: RealWorkConfig['middleModel']): Solver {\n return async ({ workdir, repo, prompt }) => {\n const argv = [...tokenizeCommand(model.command), workdir, repo.gate?.command ?? '', prompt]\n const res = await runCommand(argv, { timeoutMs: model.timeout })\n if (!res.spawned) throw new Error(`the middle model command did not start: ${res.stderr}`)\n return {\n kind: 'model',\n tokens: reportedTokens(`${res.stdout}\\n${res.stderr}`),\n appliedBytes: 0,\n }\n }\n}\n\n/**\n * The notes-only control, invoked as `<command> <workdir> <prompt> <storesRoot>`\n * with the allowed tools in `REAL_WORK_RETRIEVAL_TOOLS`. It must attempt the\n * task, so a failing command stops the build instead of reading as a miss.\n */\nexport function retrievalSolver(\n retrieval: RealWorkConfig['retrieval'],\n storesRoot: string,\n): Solver {\n return async ({ workdir, prompt }) => {\n const argv = [...tokenizeCommand(retrieval.command), workdir, prompt, storesRoot]\n const res = await runCommand(argv, {\n timeoutMs: retrieval.timeout,\n env: { REAL_WORK_RETRIEVAL_TOOLS: retrieval.tools.join(',') },\n })\n if (!res.ok) throw new Error(`the retrieval solver failed: ${res.stdout}\\n${res.stderr}`)\n return {\n kind: 'notes-only',\n tokens: reportedTokens(`${res.stdout}\\n${res.stderr}`),\n appliedBytes: 0,\n tools: [...retrieval.tools],\n }\n }\n}\n\nexport async function runSolverCell(\n workdir: string,\n task: { id: string; prompt: string; solverSnapshot: string },\n run: { repo: RealWorkRepo; grader: Grader; solver: Solver; name: SpreadCell['solver'] },\n): Promise<{ cell: SpreadCell; wrote: string[]; report: SolverReport }> {\n const {\n run: graded,\n wrote,\n report,\n } = await solverRun(workdir, {\n repo: run.repo,\n snapshot: task.solverSnapshot,\n grader: run.grader,\n solver: run.solver,\n prompt: task.prompt,\n })\n const estimated = Math.max(\n 1,\n Math.ceil((Buffer.byteLength(task.prompt) + report.appliedBytes) / BYTES_PER_TOKEN),\n )\n return {\n cell: {\n task: task.id,\n solver: run.name,\n pass: graded.exitCode === 0 && graded.failed === 0 && graded.passed >= 1,\n runId: randomUUID(),\n tokens: report.tokens ?? estimated,\n tokensSource: report.tokens === null ? 'estimated' : 'reported',\n },\n wrote,\n report,\n }\n}\n","/**\n * The build's persisted state, `<outDir>/.work/state.json`. Each stage extends\n * it and checkpoints after every candidate, so an interrupted build resumes\n * from the last completed stage and the candidates still `pending`.\n */\n\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { LedgerHash } from '../ledger-core/canonical'\nimport type { RealWorkConfig } from './config'\nimport type { EnvironmentRecord } from './environment'\nimport { readJsonFile, writeJsonAtomic } from './files'\nimport type { ChangedFile } from './git-history'\nimport type { Grader } from './grader'\nimport type { LaterFix } from './later-fix'\nimport type { Receipt } from './receipts'\nimport type { Split } from './seal'\nimport type { SpreadCell } from './solvers'\nimport type { ProbedCanary } from './time-cut'\n\nexport const CANDIDATE_REASONS = [\n 'task',\n 'no-tests',\n 'tests-flaky',\n 'already-passes',\n 'no-gate',\n 'env-unbuildable',\n 'merged-fails',\n 'answer-in-notes',\n 'too-large',\n 'generated-only',\n 'duplicate',\n] as const\nexport type CandidateReason = (typeof CANDIDATE_REASONS)[number]\n\nexport interface Candidate {\n id: string\n repo: string\n prNumber: number | null\n mergedCommit: string\n mergedAt: string\n snapshotCommit: string\n subject: string\n branchSubject: string\n authorEmail: string\n paths: string[]\n testPaths: string[]\n addedLineCount: number\n /** `pending` until the grade stage decides; every other value is final. */\n reason: CandidateReason | 'pending'\n}\n\nexport interface ChangeFile {\n path: string\n status: ChangedFile['status']\n /** The file at the merged commit, or null when the change deleted it. */\n content: string | null\n snapshotSha256: LedgerHash | null\n postSha256: LedgerHash | null\n added: string[]\n addedLineHashes: LedgerHash[]\n}\n\nexport interface TaskRecord {\n id: string\n repo: string\n kind: string\n prNumber: number | null\n snapshotCommit: string\n mergedCommit: string\n mergedAt: string\n subject: string\n prompt: string\n changeFiles: ChangeFile[]\n grader: Grader\n testIds: string[]\n graderAuthor: { kind: string; ref: string }\n heldBackPaths: string[]\n receipts: { red: Receipt; green: Receipt }\n laterFix: LaterFix | null\n /** The fix's tests, which grade solvers on a later-fix task. */\n hiddenGrader: Grader | null\n solverWrites: string[]\n solvers: string[]\n timeCut: {\n baseTime: string\n latestObjectTime: string\n solverCommit: string\n canaries: ProbedCanary[]\n } | null\n split: Split | null\n}\n\nexport interface RetrievalCell {\n task: string\n pass: boolean\n runId: string\n tools: string[]\n}\n\nexport interface AuditRerun {\n task: string\n by: string\n redExit: number\n greenExit: number\n}\n\nexport interface RealWorkState {\n stagesRun: string[]\n census: Record<string, number>\n candidates: Candidate[]\n repoLockfiles: Record<string, LedgerHash>\n environments: Record<string, EnvironmentRecord>\n tasks: TaskRecord[]\n spreadCells: SpreadCell[]\n retrievalCells: RetrievalCell[]\n auditReruns: AuditRerun[]\n seal: { testSetSha256: LedgerHash; testIds: string[]; sealedAt: string } | null\n}\n\nexport interface BuildContext {\n config: RealWorkConfig\n workRoot: string\n statePath: string\n state: RealWorkState\n}\n\nconst emptyState = (): RealWorkState => ({\n stagesRun: [],\n census: {},\n candidates: [],\n repoLockfiles: {},\n environments: {},\n tasks: [],\n spreadCells: [],\n retrievalCells: [],\n auditReruns: [],\n seal: null,\n})\n\n/** The build context, resumed from the persisted state when there is one. */\nexport function openBuild(config: RealWorkConfig): BuildContext {\n const workRoot = join(config.outDir, '.work')\n const statePath = join(workRoot, 'state.json')\n let state = emptyState()\n if (existsSync(statePath)) {\n const saved = readJsonFile(statePath)\n if (\n saved === null ||\n typeof saved !== 'object' ||\n !Array.isArray((saved as RealWorkState).stagesRun)\n ) {\n throw new Error(`${statePath} is not a real-work build state`)\n }\n state = { ...state, ...(saved as RealWorkState) }\n }\n return { config, workRoot, statePath, state }\n}\n\nexport function saveState(ctx: BuildContext): void {\n writeJsonAtomic(ctx.statePath, ctx.state)\n}\n","/**\n * The time cut: what a solver may see is the snapshot and nothing after it.\n *\n * The solver's repository is one orphan commit of the snapshot tree with every\n * held-back test removed. Remotes, branches, tags and reflogs are deleted and\n * unreachable objects pruned, so neither the original history nor a held-back\n * blob survives. Receipts and audits keep using the original snapshot.\n *\n * Canaries are fresh random tokens planted in the four stores after the base.\n * The probe proves each is findable in its store, then counts its occurrences\n * in the solver's context: the prompt and every file of the solver's repository.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { hashCanonical, type LedgerHash } from '../ledger-core/canonical'\nimport { readJsonFile, sha256Of, walkFiles, writeJsonAtomic } from './files'\nimport { git, gitOrThrow } from './process'\n\nexport const CANARY_STORES = ['memory', 'knowledge', 'docs', 'history'] as const\nexport type CanaryStore = (typeof CANARY_STORES)[number]\n\nexport interface TimeCutRepo {\n baseTime: string\n latestObjectTime: string\n /** The orphan commit solvers check out. */\n runCommit: string\n}\n\nexport interface Canary {\n store: CanaryStore\n token: string\n plantedAt: string\n}\n\nexport interface ProbedCanary extends Canary {\n /** The token was found in the store it was planted in, so the probe is not vacuous. */\n inStore: boolean\n probeQueries: number\n hits: number\n solverContextSha256: LedgerHash\n}\n\nexport interface SolverContext {\n prompt: string\n files: Array<[path: string, sha256: LedgerHash]>\n visibleText: string\n sha256: LedgerHash\n}\n\nfunction assertSafeRelativePath(path: string): void {\n const parts = path.split('/')\n if (\n path === '' ||\n path.startsWith('/') ||\n path.includes('\\0') ||\n parts.some((part) => part === '' || part === '.' || part === '..')\n ) {\n throw new Error(`unsafe held-back path: ${JSON.stringify(path)}`)\n }\n}\n\nconst commitTime = (dir: string, commit: string): string =>\n gitOrThrow(['show', '-s', '--no-show-signature', '--pretty=format:%cI', commit], {\n cwd: dir,\n }).trim()\n\n/** Cut the solver's repository at `snapshot` into `dest`. Throws when the cut leaks. */\nexport function cutTaskRepo(\n cache: string,\n branch: string,\n snapshot: string,\n dest: string,\n heldBackPaths: readonly string[],\n): TimeCutRepo {\n for (const path of heldBackPaths) assertSafeRelativePath(path)\n gitOrThrow([\n 'clone',\n '--quiet',\n '--single-branch',\n '--no-checkout',\n '--branch',\n branch,\n cache,\n dest,\n ])\n gitOrThrow(['checkout', '--quiet', '--detach', snapshot], { cwd: dest })\n const baseTime = commitTime(dest, snapshot)\n if (heldBackPaths.length > 0) {\n gitOrThrow(['rm', '-r', '--quiet', '--ignore-unmatch', '--', ...heldBackPaths], { cwd: dest })\n }\n const tree = gitOrThrow(['write-tree'], { cwd: dest }).trim()\n const runCommit = gitOrThrow(\n ['commit-tree', '--no-gpg-sign', tree, '-m', 'Time-cut solver snapshot'],\n {\n cwd: dest,\n env: {\n GIT_AUTHOR_NAME: 'Time cut',\n GIT_AUTHOR_EMAIL: 'time-cut@localhost',\n GIT_COMMITTER_NAME: 'Time cut',\n GIT_COMMITTER_EMAIL: 'time-cut@localhost',\n GIT_AUTHOR_DATE: baseTime,\n GIT_COMMITTER_DATE: baseTime,\n },\n },\n ).trim()\n gitOrThrow(['checkout', '--quiet', '--detach', runCommit], { cwd: dest })\n git(['remote', 'remove', 'origin'], { cwd: dest })\n const branches = gitOrThrow(['for-each-ref', '--format=%(refname:short)', 'refs/heads'], {\n cwd: dest,\n })\n for (const name of branches.split('\\n').filter(Boolean)) {\n gitOrThrow(['branch', '-D', name], { cwd: dest })\n }\n const tags = gitOrThrow(['tag', '-l'], { cwd: dest }).split('\\n').filter(Boolean)\n if (tags.length > 0) gitOrThrow(['tag', '-d', ...tags], { cwd: dest })\n gitOrThrow(['reflog', 'expire', '--expire=all', '--all'], { cwd: dest })\n gitOrThrow(['gc', '--quiet', '--prune=now'], { cwd: dest })\n const latestObjectTime = latestCommitTime(dest)\n if (Date.parse(latestObjectTime) > Date.parse(baseTime)) {\n throw new Error(\n `the solver repository ${dest} holds a commit from ${latestObjectTime}, after the base ${baseTime}`,\n )\n }\n if (git(['cat-file', '-e', `${snapshot}^{commit}`], { cwd: dest }).ok) {\n throw new Error(`the solver repository ${dest} still holds the original snapshot ${snapshot}`)\n }\n return { baseTime, latestObjectTime, runCommit }\n}\n\n/** The latest committer time of any commit reachable from a ref or HEAD. */\nexport function latestCommitTime(dir: string): string {\n const out = gitOrThrow(['log', '--all', 'HEAD', '--no-show-signature', '--pretty=format:%cI'], {\n cwd: dir,\n })\n let latest: string | null = null\n for (const time of out.split('\\n').filter(Boolean)) {\n if (latest === null || Date.parse(time) > Date.parse(latest)) latest = time\n }\n if (latest === null) throw new Error(`no commit is reachable in ${dir}`)\n return latest\n}\n\n/** Plant one fresh token in each store, dated now, which is after any snapshot. */\nexport function plantCanaries(storesRoot: string, baseTime: string): Canary[] {\n const plantedAt = new Date().toISOString()\n if (!(Date.parse(plantedAt) > Date.parse(baseTime))) {\n throw new Error(`canaries must be planted after the base ${baseTime}`)\n }\n const token = (): string => `canary-${randomUUID().replaceAll('-', '')}`\n const fileId = (): string => randomUUID().slice(0, 8)\n mkdirSync(storesRoot, { recursive: true })\n\n const memory: Canary = { store: 'memory', token: token(), plantedAt }\n const memoryPath = join(storesRoot, 'memory.json')\n const entries = existsSync(memoryPath) ? readJsonFile(memoryPath) : []\n if (!Array.isArray(entries)) throw new Error(`${memoryPath} must hold a JSON array`)\n entries.push({\n id: `canary-${fileId()}`,\n text: `recorded after ${baseTime}: ${memory.token}`,\n at: plantedAt,\n })\n writeJsonAtomic(memoryPath, entries)\n\n const pages = (['knowledge', 'docs'] as const).map((store): Canary => {\n const canary: Canary = { store, token: token(), plantedAt }\n mkdirSync(join(storesRoot, store), { recursive: true })\n writeFileSync(\n join(storesRoot, store, `canary-${fileId()}.md`),\n `# canary\\n\\nRecorded after ${baseTime}. Token: ${canary.token}\\n`,\n )\n return canary\n })\n\n const history: Canary = { store: 'history', token: token(), plantedAt }\n appendFileSync(\n join(storesRoot, 'history.jsonl'),\n `${JSON.stringify({ actor: 'builder', at: plantedAt, text: `token ${history.token}` })}\\n`,\n )\n return [memory, ...pages, history]\n}\n\n/** What a solver is given: the prompt and every file of its repository. */\nexport function solverContext(prompt: string, solverRepo: string): SolverContext {\n const files: Array<[string, LedgerHash]> = []\n const visible = [prompt]\n for (const path of walkFiles(solverRepo)) {\n const content = readFileSync(join(solverRepo, path))\n files.push([path, sha256Of(content)])\n visible.push(`${path}\\n${content.toString('utf8')}`)\n }\n return {\n prompt,\n files,\n visibleText: visible.join('\\n'),\n sha256: hashCanonical({ prompt, files }),\n }\n}\n\nexport function probeCanaries(\n context: SolverContext,\n canaries: readonly Canary[],\n storesRoot: string,\n): ProbedCanary[] {\n const storeFiles = walkFiles(storesRoot).map((path) =>\n readFileSync(join(storesRoot, path), 'utf8'),\n )\n return canaries.map((canary) => ({\n ...canary,\n inStore: storeFiles.some((content) => content.includes(canary.token)),\n probeQueries: storeFiles.length + 1,\n hits: context.visibleText.split(canary.token).length - 1,\n solverContextSha256: context.sha256,\n }))\n}\n","/**\n * The build's stages. Each reads the state the earlier stages left and extends\n * it; `command.ts` runs them in order and skips the ones already complete.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { compareCodeUnits } from '../ledger-core/canonical'\nimport { type RealWorkConfig, type RealWorkRepo, repoNamed } from './config'\nimport { buildEnvironment, lockfileSha } from './environment'\nimport { sha256Of } from './files'\nimport {\n addedLines,\n blobContent,\n cachePath,\n candidateIdOf,\n changedFiles,\n ensureCache,\n listMerges,\n} from './git-history'\nimport { classifyKind, graderAt, isTestFile } from './grader'\nimport { ensureRunClone, gradedRun, removeDirectory, solverRun } from './harness'\nimport { buildLaterFix, findLaterFixes } from './later-fix'\nimport { receiptMachine, receiptVerdict, runsAgree, takeReceipt } from './receipts'\nimport { type BuilderIdentity, writeReport } from './report'\nimport { sealSplits } from './seal'\nimport { middleSolver, nullSolver, oracleSolver, retrievalSolver, runSolverCell } from './solvers'\nimport {\n type BuildContext,\n type Candidate,\n type CandidateReason,\n type ChangeFile,\n saveState,\n type TaskRecord,\n} from './state'\nimport { cutTaskRepo, plantCanaries, probeCanaries, solverContext } from './time-cut'\n\nconst DAY_MS = 86_400_000\n/** Added lines shorter than this are too common to identify a solution. */\nconst IDENTIFYING_LINE_LENGTH = 30\n\nconst windowEnd = (config: RealWorkConfig): number =>\n config.builtAt === undefined ? Date.now() : Date.parse(config.builtAt)\n\nfunction requireCache(ctx: BuildContext, repo: RealWorkRepo): string {\n const cache = cachePath(ctx.config.outDir, repo)\n if (!existsSync(cache)) throw new Error(`the census has not cached ${repo.name}`)\n return cache\n}\n\nconst solverRepoPath = (ctx: BuildContext, taskId: string): string =>\n join(ctx.workRoot, 'solver-repos', taskId)\nconst runPath = (ctx: BuildContext, name: string): string => join(ctx.workRoot, 'runs', name)\n\nfunction promptFor(task: Pick<TaskRecord, 'id' | 'repo' | 'prNumber' | 'subject' | 'changeFiles'>) {\n return [\n `Real-work task ${task.id} in repository ${task.repo}.`,\n `A merged change (pull request ${task.prNumber ?? 'without number'}, subject: ${task.subject}) is held back.`,\n `The change touches these paths: ${task.changeFiles.map((file) => file.path).join(', ')}.`,\n `Implement the change so the repository's own gate passes when restricted to the tests the change adds or changes.`,\n 'Those tests are held back and are not part of the repository you see; write the implementation the tests expect.',\n 'You may run the repository gate. Do not modify held-back tests.',\n ].join('\\n')\n}\n\n/** Every first-parent merge on each default branch within the window, as a candidate. */\nexport function stageCensus(ctx: BuildContext): void {\n const { config, state } = ctx\n const until = windowEnd(config)\n const since = until - config.windowDays * DAY_MS\n state.census = {}\n state.candidates = []\n const seen = new Map<string, number>()\n for (const repo of config.repos) {\n const cache = ensureCache(config.outDir, repo)\n let count = 0\n for (const merge of listMerges(cache, repo, { sinceMs: since, untilMs: until })) {\n const paths = changedFiles(cache, merge.snapshotCommit, merge.mergedCommit).map(\n (file) => file.path,\n )\n const baseId = candidateIdOf(repo, merge)\n const occurrence = (seen.get(baseId) ?? 0) + 1\n seen.set(baseId, occurrence)\n state.candidates.push({\n id: occurrence === 1 ? baseId : `${baseId}-${occurrence}`,\n repo: repo.name,\n prNumber: merge.prNumber,\n mergedCommit: merge.mergedCommit,\n mergedAt: merge.mergedAt,\n snapshotCommit: merge.snapshotCommit,\n subject: merge.subject,\n branchSubject: merge.branchSubject,\n authorEmail: merge.authorEmail,\n paths,\n testPaths: paths.filter(isTestFile),\n addedLineCount: paths.reduce(\n (sum, path) =>\n sum + addedLines(cache, merge.snapshotCommit, merge.mergedCommit, path).length,\n 0,\n ),\n reason: 'pending',\n })\n count++\n }\n state.census[repo.name] = count\n }\n saveState(ctx)\n}\n\n/** The reason a candidate is rejected before any environment is built, if there is one. */\nfunction preEnvironmentReason(\n candidate: Candidate,\n config: RealWorkConfig,\n): CandidateReason | null {\n if (candidate.testPaths.length === 0) return 'no-tests'\n if (candidate.addedLineCount > config.maxAddedLines || candidate.paths.length > config.maxFiles) {\n return 'too-large'\n }\n const nonTest = candidate.paths.filter((path) => !isTestFile(path))\n const generated = (path: string) =>\n config.generatedOnly.some((pattern) => path === pattern || path.startsWith(pattern))\n if (nonTest.length > 0 && nonTest.every(generated)) return 'generated-only'\n return null\n}\n\n/** Two clean environment builds per eligible candidate, at its snapshot, from the frozen lockfile. */\nexport async function stageBuildEnv(ctx: BuildContext): Promise<void> {\n const { config, state } = ctx\n for (const repo of config.repos) {\n const cache = requireCache(ctx, repo)\n const lockfile = repo.gate?.lockfile ?? 'package-lock.json'\n const gateRef = repo.gateRef ?? repo.defaultBranch\n if (blobContent(cache, gateRef, lockfile) !== null) {\n state.repoLockfiles[repo.name] = lockfileSha(cache, gateRef, lockfile)\n }\n }\n for (const candidate of state.candidates) {\n if (state.environments[candidate.id]) continue\n const repo = repoNamed(config, candidate.repo)\n const cache = requireCache(ctx, repo)\n const lockfile = repo.gate?.lockfile ?? 'package-lock.json'\n const frozen = state.repoLockfiles[repo.name]\n const unbuildable = (error: string | null) => ({\n buildable: false,\n builds: [],\n lockfileSha256: null,\n error,\n })\n if (!repo.gate || preEnvironmentReason(candidate, config) !== null) {\n state.environments[candidate.id] = unbuildable(null)\n } else if (frozen === undefined) {\n state.environments[candidate.id] = unbuildable(\n `${lockfile} is missing at ${repo.gateRef ?? repo.defaultBranch}`,\n )\n } else if (blobContent(cache, candidate.snapshotCommit, lockfile) === null) {\n state.environments[candidate.id] = unbuildable(`${lockfile} is missing at the snapshot`)\n } else if (lockfileSha(cache, candidate.snapshotCommit, lockfile) !== frozen) {\n state.environments[candidate.id] = unbuildable(\n `the snapshot's ${lockfile} differs from ${repo.gateRef ?? repo.defaultBranch}`,\n )\n } else {\n state.environments[candidate.id] = await buildEnvironment(cache, repo, {\n snapshot: candidate.snapshotCommit,\n workRoot: join(ctx.workRoot, 'env'),\n })\n }\n saveState(ctx)\n }\n}\n\n/** Red and green receipts for each pending candidate, in batches of `gradeBatchSize`. */\nexport async function stageGrade(ctx: BuildContext): Promise<{ paused: boolean }> {\n const { config, state } = ctx\n const graded = new Set(state.tasks.map((task) => task.id))\n const seenMerged = new Set(state.tasks.map((task) => task.mergedCommit))\n let batch = 0\n for (const candidate of state.candidates) {\n if (candidate.reason !== 'pending') {\n if (candidate.reason === 'task' && !graded.has(candidate.id)) {\n throw new Error(`the checkpoint is missing graded task ${candidate.id}`)\n }\n continue\n }\n const buildable = state.environments[candidate.id]?.buildable === true\n if (buildable && config.gradeBatchSize !== undefined && batch >= config.gradeBatchSize) {\n return { paused: true }\n }\n if (buildable) batch++\n const task = await gradeCandidate(ctx, candidate, seenMerged)\n if (task) state.tasks.push(task)\n saveState(ctx)\n }\n return { paused: false }\n}\n\nasync function gradeCandidate(\n ctx: BuildContext,\n candidate: Candidate,\n seenMerged: Set<string>,\n): Promise<TaskRecord | null> {\n const { config } = ctx\n const reject = (reason: CandidateReason): null => {\n candidate.reason = reason\n return null\n }\n const repo = repoNamed(config, candidate.repo)\n if (!repo.gate) return reject('no-gate')\n const early = preEnvironmentReason(candidate, config)\n if (early) return reject(early)\n if (ctx.state.environments[candidate.id]?.buildable !== true) return reject('env-unbuildable')\n if (seenMerged.has(candidate.mergedCommit)) return reject('duplicate')\n\n const cache = requireCache(ctx, repo)\n const { snapshotCommit, mergedCommit } = candidate\n const changeFiles: ChangeFile[] = changedFiles(cache, snapshotCommit, mergedCommit).map(\n (file) => {\n const content = blobContent(cache, mergedCommit, file.path)\n const before = blobContent(cache, snapshotCommit, file.path)\n const added =\n file.status === 'D' ? [] : addedLines(cache, snapshotCommit, mergedCommit, file.path)\n return {\n path: file.path,\n status: file.status,\n content,\n snapshotSha256: before === null ? null : sha256Of(before),\n postSha256: content === null ? null : sha256Of(content),\n added,\n addedLineHashes: added\n .filter((line) => line.trim().length >= IDENTIFYING_LINE_LENGTH)\n .map((line) => sha256Of(line.trim())),\n }\n },\n )\n const grader = graderAt(cache, repo, mergedCommit, candidate.testPaths)\n const machine = receiptMachine(config)\n const red = await takeReceipt(cache, runPath(ctx, `${candidate.id}-red`), {\n repo,\n snapshot: snapshotCommit,\n applied: null,\n grader,\n machine,\n })\n if (red.environmentError) return reject('env-unbuildable')\n const green = await takeReceipt(cache, runPath(ctx, `${candidate.id}-green`), {\n repo,\n snapshot: snapshotCommit,\n applied: mergedCommit,\n grader,\n machine,\n })\n if (green.environmentError) return reject('env-unbuildable')\n if (green.receipt.passed + green.receipt.failed === 0) return reject('no-tests')\n if (!runsAgree(red.receipt.runs) || !runsAgree(green.receipt.runs)) return reject('tests-flaky')\n const redVerdict = receiptVerdict(red.receipt)\n if (redVerdict.passes) return reject('already-passes')\n if (!redVerdict.fails) return reject('tests-flaky')\n if (candidate.paths.every(isTestFile)) return reject('generated-only')\n if (!receiptVerdict(green.receipt).passes) return reject('merged-fails')\n const greenPassed = new Set(green.receipt.passedTests)\n if (!red.receipt.failedTests.every((name) => greenPassed.has(name))) return reject('tests-flaky')\n\n seenMerged.add(mergedCommit)\n candidate.reason = 'task'\n const subject = candidate.branchSubject\n const task: TaskRecord = {\n id: candidate.id,\n repo: repo.name,\n kind: classifyKind(\n {\n subject,\n paths: candidate.paths,\n addedLines: changeFiles.flatMap((file) => file.added),\n },\n config.kinds,\n ),\n prNumber: candidate.prNumber,\n snapshotCommit,\n mergedCommit,\n mergedAt: candidate.mergedAt,\n subject,\n prompt: '',\n changeFiles,\n grader,\n testIds: [...new Set([...green.receipt.passedTests, ...green.receipt.failedTests])],\n graderAuthor: { kind: repo.graderAuthorKind, ref: candidate.authorEmail },\n heldBackPaths: [...candidate.testPaths],\n receipts: { red: red.receipt, green: green.receipt },\n laterFix: null,\n hiddenGrader: null,\n solverWrites: [],\n solvers: [],\n timeCut: null,\n split: null,\n }\n task.prompt = promptFor(task)\n return task\n}\n\n/** Hidden graders from fixes merged within seven days that touch the same code. */\nexport async function stageLaterFix(ctx: BuildContext): Promise<void> {\n const { config, state } = ctx\n const until = windowEnd(config)\n for (const repo of config.repos) {\n const cache = requireCache(ctx, repo)\n const merges = listMerges(cache, repo)\n for (const task of state.tasks.filter((candidate) => candidate.repo === repo.name)) {\n if (task.laterFix !== null) continue\n for (const fix of findLaterFixes(cache, task, merges, until)) {\n const built = await buildLaterFix(cache, repo, task, fix, {\n workRoot: join(ctx.workRoot, 'runs'),\n machine: receiptMachine(config),\n })\n if (built) {\n task.laterFix = built.laterFix\n task.hiddenGrader = built.grader\n saveState(ctx)\n break\n }\n }\n }\n }\n saveState(ctx)\n}\n\n/** Each task's solver repository, cut at its snapshot, and canaries planted and probed. */\nexport function stageTimeCut(ctx: BuildContext): void {\n const { config, state } = ctx\n for (const task of state.tasks) {\n const repo = repoNamed(config, task.repo)\n const dest = solverRepoPath(ctx, task.id)\n removeDirectory(dest)\n const cut = cutTaskRepo(\n requireCache(ctx, repo),\n repo.defaultBranch,\n task.snapshotCommit,\n dest,\n task.heldBackPaths,\n )\n const context = solverContext(task.prompt, dest)\n const probed = probeCanaries(\n context,\n plantCanaries(config.stores.root, cut.baseTime),\n config.stores.root,\n )\n const vacuous = probed.find((canary) => !canary.inStore)\n if (vacuous) throw new Error(`the ${vacuous.store} canary for ${task.id} is not in its store`)\n const leaked = probed.find((canary) => canary.hits > 0)\n if (leaked)\n throw new Error(`the ${leaked.store} canary reached the solver context of ${task.id}`)\n task.timeCut = {\n baseTime: cut.baseTime,\n latestObjectTime: cut.latestObjectTime,\n solverCommit: cut.runCommit,\n canaries: probed,\n }\n saveState(ctx)\n }\n}\n\nfunction requireTimeCut(task: TaskRecord): NonNullable<TaskRecord['timeCut']> {\n if (task.timeCut === null) throw new Error(`task ${task.id} has no time cut`)\n return task.timeCut\n}\n\n/** The oracle, null and middle-model cells, each graded on the solver's own checkout. */\nexport async function stageSolve(ctx: BuildContext): Promise<void> {\n const { config, state } = ctx\n state.spreadCells = []\n const middle = middleSolver(config.middleModel)\n for (const task of state.tasks) {\n const repo = repoNamed(config, task.repo)\n const timeCut = requireTimeCut(task)\n const workdir = ensureRunClone(solverRepoPath(ctx, task.id), runPath(ctx, `${task.id}-solve`))\n const guarded = new Set([...task.grader.paths, ...(task.hiddenGrader?.paths ?? [])])\n const writes = new Set<string>()\n try {\n for (const [name, solver] of [\n ['oracle', oracleSolver(task.changeFiles, guarded)],\n ['null', nullSolver],\n ['middle', middle],\n ] as const) {\n const { cell, wrote } = await runSolverCell(\n workdir,\n { id: task.id, prompt: task.prompt, solverSnapshot: timeCut.solverCommit },\n { repo, grader: task.hiddenGrader ?? task.grader, solver, name },\n )\n state.spreadCells.push(cell)\n for (const path of wrote) writes.add(path)\n }\n } finally {\n removeDirectory(workdir)\n }\n task.solvers = [config.middleModel.name]\n task.solverWrites = [...writes].sort(compareCodeUnits)\n saveState(ctx)\n }\n}\n\n/** The notes-only control on every task; a task it solves is dropped as `answer-in-notes`. */\nexport async function stageRetrieval(ctx: BuildContext): Promise<void> {\n const { config, state } = ctx\n state.retrievalCells = []\n const solver = retrievalSolver(config.retrieval, config.stores.root)\n const answered = new Set<string>()\n for (const task of state.tasks) {\n const timeCut = requireTimeCut(task)\n const workdir = ensureRunClone(\n solverRepoPath(ctx, task.id),\n runPath(ctx, `${task.id}-retrieval`),\n )\n try {\n const { run, report } = await solverRun(workdir, {\n repo: repoNamed(config, task.repo),\n snapshot: timeCut.solverCommit,\n grader: task.grader,\n solver,\n prompt: task.prompt,\n })\n const pass = run.exitCode === 0 && run.failed === 0 && run.passed >= 1\n state.retrievalCells.push({\n task: task.id,\n pass,\n runId: randomUUID(),\n tools: report.tools ?? [],\n })\n if (pass) answered.add(task.id)\n } finally {\n removeDirectory(workdir)\n }\n }\n for (const candidate of state.candidates) {\n if (answered.has(candidate.id)) candidate.reason = 'answer-in-notes'\n }\n state.tasks = state.tasks.filter((task) => !answered.has(task.id))\n saveState(ctx)\n}\n\n/**\n * Red and green rerun for a sample of tasks, recorded under the configured\n * auditor. The builder cannot verify who invoked it, so a rerun is independent\n * only when the auditor runs this stage: the builder runs `seal`, the auditor\n * runs `report`.\n */\nexport async function stageAudit(ctx: BuildContext): Promise<void> {\n const { config, state } = ctx\n const count = config.audit.count ?? Math.max(3, Math.ceil(state.tasks.length / 10))\n const sample = [...state.tasks].sort((a, b) => compareCodeUnits(a.id, b.id)).slice(0, count)\n state.auditReruns = []\n for (const task of sample) {\n const repo = repoNamed(config, task.repo)\n const workdir = ensureRunClone(requireCache(ctx, repo), runPath(ctx, `${task.id}-audit`))\n try {\n const run = { repo, snapshot: task.snapshotCommit, grader: task.grader }\n const red = await gradedRun(workdir, { ...run, applied: null })\n const green = await gradedRun(workdir, { ...run, applied: task.mergedCommit })\n state.auditReruns.push({\n task: task.id,\n by: config.audit.agent,\n redExit: red.exitCode,\n greenExit: green.exitCode,\n })\n } finally {\n removeDirectory(workdir)\n }\n }\n saveState(ctx)\n}\n\nexport function stageSeal(ctx: BuildContext): void {\n const { state } = ctx\n const sealed = sealSplits(state.tasks, ctx.config.seal)\n for (const task of state.tasks) task.split = sealed.splits.get(task.id) ?? null\n state.seal = {\n testSetSha256: sealed.testSetSha256,\n testIds: sealed.testIds,\n sealedAt: new Date().toISOString(),\n }\n saveState(ctx)\n}\n\nexport function stageReport(ctx: BuildContext, builder: BuilderIdentity): void {\n writeReport(ctx.config, ctx.state, {\n builtAt: ctx.config.builtAt ?? new Date().toISOString(),\n builder,\n })\n}\n","/**\n * `agent-eval real-work <stage> <config.json>`: build a benchmark of real work\n * from merged changes in git history. `build` runs every stage; any other\n * stage runs the incomplete stages up to it. Progress persists in\n * `<outDir>/.work/state.json`, so an interrupted build resumes.\n */\n\nimport { existsSync, readFileSync, realpathSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { AgentEvalError, ConfigError } from '../errors'\nimport { loadRealWorkConfig, type RealWorkConfig } from './config'\nimport {\n stageAudit,\n stageBuildEnv,\n stageCensus,\n stageGrade,\n stageLaterFix,\n stageReport,\n stageRetrieval,\n stageSeal,\n stageSolve,\n stageTimeCut,\n} from './pipeline'\nimport { git } from './process'\nimport { type BuildContext, openBuild, saveState } from './state'\n\nconst PACKAGE_NAME = '@tangle-network/agent-eval'\nconst BUILDER_REPO = 'tangle-network/agent-eval'\nconst BUILDER_PATH = 'src/real-work/'\n\ntype StageName =\n | 'census'\n | 'build-env'\n | 'grade'\n | 'laterfix'\n | 'timecut'\n | 'solve'\n | 'retrieval'\n | 'audit'\n | 'seal'\n | 'report'\n\nconst PIPELINE: StageName[] = [\n 'census',\n 'build-env',\n 'grade',\n 'laterfix',\n 'timecut',\n 'solve',\n 'retrieval',\n 'audit',\n 'seal',\n 'report',\n]\n\n/** The stages each subcommand runs. `seal` stops before the audit, so an auditor can run `report`. */\nconst SUBCOMMANDS: Record<string, StageName[]> = {\n census: PIPELINE.slice(0, 1),\n 'build-env': PIPELINE.slice(0, 2),\n grade: PIPELINE.slice(0, 3),\n laterfix: PIPELINE.slice(0, 4),\n timecut: PIPELINE.slice(0, 5),\n seal: PIPELINE.filter((stage) => stage !== 'audit' && stage !== 'report'),\n report: PIPELINE,\n build: PIPELINE,\n}\n\nconst USAGE = `usage: agent-eval real-work <${Object.keys(SUBCOMMANDS).join('|')}> <config.json>\n\nBuilds a benchmark of real work from merged changes: each task starts at the\ncode before a merged change, holds back the tests the change added or changed,\nand is graded by them. See docs/real-work.md for the config and every page.`\n\nexport interface RealWorkCommandIo {\n stdout: (text: string) => void\n stderr: (text: string) => void\n}\n\nconst PROCESS_IO: RealWorkCommandIo = {\n stdout: (text) => process.stdout.write(text),\n stderr: (text) => process.stderr.write(text),\n}\n\n/** The directory of this package: the agent-eval checkout or the installed package. */\nfunction packageRoot(): string | null {\n let dir = dirname(fileURLToPath(import.meta.url))\n for (;;) {\n const manifest = join(dir, 'package.json')\n if (existsSync(manifest)) {\n try {\n if (\n (JSON.parse(readFileSync(manifest, 'utf8')) as { name?: unknown }).name === PACKAGE_NAME\n )\n return dir\n } catch {\n // Not a readable manifest; keep walking.\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/**\n * The commit of the builder that ran: HEAD of the agent-eval checkout holding\n * this code. An installed package is not a checkout, so it needs\n * `builderCommit` in the config. A config commit that disagrees with the\n * checkout is refused rather than recorded.\n */\nexport function resolveBuilderCommit(config: Pick<RealWorkConfig, 'builderCommit'>): string {\n const root = packageRoot()\n if (root !== null) {\n const top = git(['rev-parse', '--show-toplevel'], { cwd: root })\n if (top.ok && realpathSync(top.stdout.trim()) === realpathSync(root)) {\n const head = git(['rev-parse', 'HEAD'], { cwd: root })\n if (head.ok) {\n const commit = head.stdout.trim()\n if (config.builderCommit !== undefined && config.builderCommit !== commit) {\n throw new ConfigError(\n `builderCommit ${config.builderCommit} disagrees with the checkout running the builder (${commit})`,\n )\n }\n return commit\n }\n }\n }\n if (config.builderCommit !== undefined) return config.builderCommit\n throw new ConfigError(\n 'cannot resolve the builder commit: run from an agent-eval git checkout, or set builderCommit',\n )\n}\n\nasync function runStage(\n ctx: BuildContext,\n stage: StageName,\n builder: { commit: string; command: string } | null,\n): Promise<{ paused: boolean }> {\n switch (stage) {\n case 'census':\n stageCensus(ctx)\n return { paused: false }\n case 'build-env':\n await stageBuildEnv(ctx)\n return { paused: false }\n case 'grade':\n return await stageGrade(ctx)\n case 'laterfix':\n await stageLaterFix(ctx)\n return { paused: false }\n case 'timecut':\n stageTimeCut(ctx)\n return { paused: false }\n case 'solve':\n await stageSolve(ctx)\n return { paused: false }\n case 'retrieval':\n await stageRetrieval(ctx)\n return { paused: false }\n case 'audit':\n await stageAudit(ctx)\n return { paused: false }\n case 'seal':\n stageSeal(ctx)\n return { paused: false }\n case 'report':\n if (builder === null) throw new Error('the report stage needs the builder identity')\n stageReport(ctx, { repo: BUILDER_REPO, path: BUILDER_PATH, ...builder })\n return { paused: false }\n }\n}\n\nexport async function runRealWorkCommand(\n argv: readonly string[],\n io: RealWorkCommandIo = PROCESS_IO,\n): Promise<number> {\n if (argv.includes('--help') || argv.includes('-h')) {\n io.stdout(`${USAGE}\\n`)\n return 0\n }\n const [subcommand, configPath, ...extra] = argv\n const stages = subcommand === undefined ? undefined : SUBCOMMANDS[subcommand]\n if (stages === undefined || configPath === undefined || extra.length > 0) {\n io.stderr(`${USAGE}\\n`)\n return 2\n }\n let config: RealWorkConfig\n try {\n config = loadRealWorkConfig(configPath)\n } catch (error) {\n io.stderr(`${error instanceof Error ? error.message : String(error)}\\n`)\n return 2\n }\n try {\n const ctx = openBuild(config)\n // Resolved before any work, so a build that cannot name its builder fails at once.\n const builder = stages.includes('report')\n ? {\n commit: resolveBuilderCommit(config),\n command: config.builderCommand ?? `agent-eval real-work ${subcommand} ${configPath}`,\n }\n : null\n for (const stage of stages) {\n // The report is rewritten on every run: it reads the state, and the state may have moved.\n if (stage !== 'report' && ctx.state.stagesRun.includes(stage)) {\n io.stdout(`stage ${stage} already complete\\n`)\n continue\n }\n const { paused } = await runStage(ctx, stage, builder)\n if (paused) {\n saveState(ctx)\n io.stdout(`stage ${stage} paused after ${config.gradeBatchSize} candidates\\n`)\n return 0\n }\n if (stage === 'report') {\n io.stdout(\n `wrote the report to ${config.outDir}: ${ctx.state.tasks.length} tasks of ${ctx.state.candidates.length} candidates\\n`,\n )\n } else {\n ctx.state.stagesRun.push(stage)\n saveState(ctx)\n io.stdout(`stage ${stage} done\\n`)\n }\n }\n return 0\n } catch (error) {\n const message =\n error instanceof AgentEvalError || !(error instanceof Error)\n ? String(error instanceof Error ? error.message : error)\n : (error.stack ?? error.message)\n io.stderr(`real-work build failed: ${message}\\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 real-work <stage|build> <config.json>\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 { runRealWorkCommand } from './real-work/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 real-work <census|build-env|grade|laterfix|timecut|seal|report|build> <config.json>\n Build a benchmark of real work from merged changes in git history: each\n task starts before a merged change, holds back the tests it added or\n changed, and is graded by them. 'build' runs every stage; progress\n persists under the config's outDir, so a stopped build resumes.\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 (command === 'real-work') return await runRealWorkCommand(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 === 'real-work' ||\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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