@tangle-network/agent-eval 0.142.2 → 0.144.0

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 (85) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +42 -8
  3. package/dist/analyst/index.d.ts +6 -6
  4. package/dist/analyst/index.d.ts.map +1 -1
  5. package/dist/analyst/index.js +3 -3
  6. package/dist/{benchmark-command-bTf4ibj-.js → benchmark-command-4c7N_rlw.js} +7 -6
  7. package/dist/benchmark-command-4c7N_rlw.js.map +1 -0
  8. package/dist/benchmarks/index.d.ts +1 -1
  9. package/dist/benchmarks/index.js +1 -1
  10. package/dist/{benchmarks-Ce8GdJbc.js → benchmarks-05UGZ8sZ.js} +4 -4
  11. package/dist/{benchmarks-Ce8GdJbc.js.map → benchmarks-05UGZ8sZ.js.map} +1 -1
  12. package/dist/campaign/index.d.ts +5 -4
  13. package/dist/campaign/index.js +4 -4
  14. package/dist/{campaign-COFTVy3Q.js → campaign-BKOtvRAB.js} +15 -11
  15. package/dist/campaign-BKOtvRAB.js.map +1 -0
  16. package/dist/cli.js +1 -1
  17. package/dist/{client-BoqGxEqx.d.ts → client-Cgl6KasJ.d.ts} +2 -2
  18. package/dist/{client-BoqGxEqx.d.ts.map → client-Cgl6KasJ.d.ts.map} +1 -1
  19. package/dist/contract/index.d.ts +5 -5
  20. package/dist/contract/index.js +4 -4
  21. package/dist/{default-registry-Ci7wAAR8.d.ts → default-registry-D3uqKbo6.d.ts} +2 -2
  22. package/dist/{default-registry-Ci7wAAR8.d.ts.map → default-registry-D3uqKbo6.d.ts.map} +1 -1
  23. package/dist/{default-registry-BupFSXSN.js → default-registry-DfHJEwYh.js} +2 -2
  24. package/dist/{default-registry-BupFSXSN.js.map → default-registry-DfHJEwYh.js.map} +1 -1
  25. package/dist/{dspy-rlm-engine-Bw8Zz9CX.js → dspy-rlm-engine-CBFwlyaY.js} +89 -7
  26. package/dist/dspy-rlm-engine-CBFwlyaY.js.map +1 -0
  27. package/dist/external-optimizer-contracts-iK0yu4AR.d.ts +128 -0
  28. package/dist/external-optimizer-contracts-iK0yu4AR.d.ts.map +1 -0
  29. package/dist/hosted/index.d.ts +2 -2
  30. package/dist/{index-BKjcUH13.d.ts → index-BZUe-ODI.d.ts} +41 -5
  31. package/dist/index-BZUe-ODI.d.ts.map +1 -0
  32. package/dist/{index-DCP4I2Qx.d.ts → index-DgbFl4cv.d.ts} +14 -11
  33. package/dist/{index-DCP4I2Qx.d.ts.map → index-DgbFl4cv.d.ts.map} +1 -1
  34. package/dist/{index-CKI1CXTL.d.ts → index-DtMpBKVF.d.ts} +4 -4
  35. package/dist/{index-CKI1CXTL.d.ts.map → index-DtMpBKVF.d.ts.map} +1 -1
  36. package/dist/index.d.ts +11 -11
  37. package/dist/index.js +9 -8
  38. package/dist/index.js.map +1 -1
  39. package/dist/{integrity-hruKe6oe.js → integrity-DY6tIbl0.js} +48 -18
  40. package/dist/integrity-DY6tIbl0.js.map +1 -0
  41. package/dist/multishot/index.d.ts +1 -1
  42. package/dist/openapi.json +1 -1
  43. package/dist/{replay-BqTgoioO.d.ts → replay-BuJM6kLh.d.ts} +2 -2
  44. package/dist/{replay-BqTgoioO.d.ts.map → replay-BuJM6kLh.d.ts.map} +1 -1
  45. package/dist/{reward-hacking-GyN0kMd8.js → reward-hacking-DjTi9HLb.js} +34 -14
  46. package/dist/reward-hacking-DjTi9HLb.js.map +1 -0
  47. package/dist/rl.d.ts +263 -2
  48. package/dist/rl.d.ts.map +1 -1
  49. package/dist/rl.js +332 -3
  50. package/dist/rl.js.map +1 -1
  51. package/dist/{single-run-lock-BcvPQY57.js → single-run-lock-t1si1ob7.js} +371 -153
  52. package/dist/single-run-lock-t1si1ob7.js.map +1 -0
  53. package/dist/{skill-usage-CNZTk_LT.d.ts → skill-usage-BiVEU0QY.d.ts} +5 -5
  54. package/dist/{skill-usage-CNZTk_LT.d.ts.map → skill-usage-BiVEU0QY.d.ts.map} +1 -1
  55. package/dist/{skillopt-optimization-method-D1dqGzzH.d.ts → skillopt-optimization-method-B7o01OdX.d.ts} +63 -13
  56. package/dist/skillopt-optimization-method-B7o01OdX.d.ts.map +1 -0
  57. package/dist/{skillopt-optimization-method-DV6c4ooy.js → skillopt-optimization-method-Ds8J1_K8.js} +440 -270
  58. package/dist/skillopt-optimization-method-Ds8J1_K8.js.map +1 -0
  59. package/dist/supervisor-run/index.d.ts +3 -3
  60. package/dist/supervisor-run/index.js +3 -3
  61. package/dist/{supervisor-run-BEns49Nx.js → supervisor-run-DiyQVczd.js} +301 -25
  62. package/dist/supervisor-run-DiyQVczd.js.map +1 -0
  63. package/dist/{tool-groups-DVQTy9lq.d.ts → tool-groups-Bqy4A3QB.d.ts} +2 -2
  64. package/dist/{tool-groups-DVQTy9lq.d.ts.map → tool-groups-Bqy4A3QB.d.ts.map} +1 -1
  65. package/dist/traces.d.ts +2 -2
  66. package/dist/{types-Dk7PB7vh.d.ts → types-KEqL1pZc.d.ts} +6 -4
  67. package/dist/{types-Dk7PB7vh.d.ts.map → types-KEqL1pZc.d.ts.map} +1 -1
  68. package/dist/{types-Dea6tiVI.d.ts → types-yLK8gXE9.d.ts} +15 -2
  69. package/dist/types-yLK8gXE9.d.ts.map +1 -0
  70. package/docs/campaign-proposers.md +11 -7
  71. package/docs/verified-labels-flywheel.md +46 -0
  72. package/package.json +1 -1
  73. package/dist/benchmark-command-bTf4ibj-.js.map +0 -1
  74. package/dist/campaign-COFTVy3Q.js.map +0 -1
  75. package/dist/dspy-rlm-engine-Bw8Zz9CX.js.map +0 -1
  76. package/dist/external-optimizer-contracts-nb7c_WAR.d.ts +0 -42
  77. package/dist/external-optimizer-contracts-nb7c_WAR.d.ts.map +0 -1
  78. package/dist/index-BKjcUH13.d.ts.map +0 -1
  79. package/dist/integrity-hruKe6oe.js.map +0 -1
  80. package/dist/reward-hacking-GyN0kMd8.js.map +0 -1
  81. package/dist/single-run-lock-BcvPQY57.js.map +0 -1
  82. package/dist/skillopt-optimization-method-D1dqGzzH.d.ts.map +0 -1
  83. package/dist/skillopt-optimization-method-DV6c4ooy.js.map +0 -1
  84. package/dist/supervisor-run-BEns49Nx.js.map +0 -1
  85. package/dist/types-Dea6tiVI.d.ts.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"dspy-rlm-engine-Bw8Zz9CX.js","names":["isRecord"],"sources":["../src/analyst/trace-tool-callback.ts","../src/analyst/dspy-rlm-engine.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport { closeServer, listenLocal, sendJson } from '../campaign/external-optimizer-http'\nimport type { TraceAnalysisToolDescriptor } from '../trace-analyst/tools'\n\nconst MAX_REQUEST_BYTES = 1_000_000\nconst MAX_RESPONSE_BYTES = 4_000_000\n\nexport interface TraceToolCallback {\n url: string\n token: string\n calls: () => number\n close: () => Promise<void>\n}\n\n/** Expose one bounded trace-tool set only on an authenticated loopback socket. */\nexport async function startTraceToolCallback(args: {\n tools: readonly TraceAnalysisToolDescriptor[]\n maxCalls: number\n signal?: AbortSignal\n}): Promise<TraceToolCallback> {\n if (!Number.isSafeInteger(args.maxCalls) || args.maxCalls <= 0) {\n throw new TypeError('trace tool callback maxCalls must be a positive safe integer')\n }\n args.signal?.throwIfAborted()\n const byName = new Map(args.tools.map((tool) => [tool.name, tool]))\n if (byName.size !== args.tools.length) {\n throw new Error('trace tool callback received duplicate tool names')\n }\n\n const token = randomBytes(32).toString('hex')\n let calls = 0\n let accepting = true\n let closePromise: Promise<void> | undefined\n const activeControllers = new Set<AbortController>()\n const activeHandlers = new Set<Promise<void>>()\n const server = createServer((request, response) => {\n if (!accepting) {\n sendJsonIfOpen(response, 503, { error: 'trace tool callback is closing' })\n return\n }\n const controller = new AbortController()\n const abortRequest = (): void => {\n request.destroy()\n response.destroy()\n }\n activeControllers.add(controller)\n controller.signal.addEventListener('abort', abortRequest, { once: true })\n\n let handler!: Promise<void>\n handler = handleRequest(request, response, controller.signal).finally(() => {\n controller.signal.removeEventListener('abort', abortRequest)\n activeControllers.delete(controller)\n activeHandlers.delete(handler)\n })\n activeHandlers.add(handler)\n void handler.catch(() => undefined)\n })\n const port = await listenLocal(server)\n const close = (): Promise<void> => {\n closePromise ??= closeCallback()\n return closePromise\n }\n const onAbort = (): void => {\n void close().catch(() => undefined)\n }\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n\n return {\n url: `http://127.0.0.1:${port}/call`,\n token,\n calls: () => calls,\n close,\n }\n\n async function handleRequest(\n request: IncomingMessage,\n response: ServerResponse,\n signal: AbortSignal,\n ): Promise<void> {\n try {\n if (request.method !== 'POST' || request.url !== '/call') {\n sendJsonIfOpen(response, 404, { error: 'not found' })\n return\n }\n if (request.headers.authorization !== `Bearer ${token}`) {\n sendJsonIfOpen(response, 401, { error: 'unauthorized' })\n return\n }\n if (calls >= args.maxCalls) {\n sendJsonIfOpen(response, 429, { error: 'trace tool call limit reached' })\n return\n }\n const body = await readJson(request)\n if (!isRecord(body) || typeof body.name !== 'string' || !('args' in body)) {\n sendJsonIfOpen(response, 400, { error: 'name and args are required' })\n return\n }\n const tool = byName.get(body.name)\n if (!tool) {\n sendJsonIfOpen(response, 404, { error: `unknown trace tool '${body.name}'` })\n return\n }\n calls += 1\n const result = await tool.handler(body.args, { signal })\n const encoded = JSON.stringify({ result })\n if (Buffer.byteLength(encoded) > MAX_RESPONSE_BYTES) {\n sendJsonIfOpen(response, 413, { error: 'trace tool response too large' })\n return\n }\n response.writeHead(200, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': String(Buffer.byteLength(encoded)),\n })\n response.end(encoded)\n } catch (error) {\n sendJsonIfOpen(response, signal.aborted ? 499 : 400, {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n async function closeCallback(): Promise<void> {\n args.signal?.removeEventListener('abort', onAbort)\n accepting = false\n const closingServer = closeServer(server)\n server.closeIdleConnections?.()\n for (const controller of activeControllers) controller.abort()\n const [serverResult] = await Promise.allSettled([\n closingServer,\n waitForActiveHandlers(activeHandlers),\n ])\n if (activeControllers.size !== 0 || activeHandlers.size !== 0) {\n throw new Error('trace tool callback closed with active requests')\n }\n if (serverResult?.status === 'rejected') throw serverResult.reason\n }\n}\n\nasync function waitForActiveHandlers(activeHandlers: Set<Promise<void>>): Promise<void> {\n while (activeHandlers.size > 0) {\n await Promise.allSettled([...activeHandlers])\n }\n}\n\nfunction readJson(request: IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n let size = 0\n const chunks: Buffer[] = []\n request.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > MAX_REQUEST_BYTES) {\n reject(new Error('trace tool request too large'))\n request.destroy()\n return\n }\n chunks.push(chunk)\n })\n request.on('error', reject)\n request.on('end', () => {\n try {\n resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))\n } catch (error) {\n reject(error)\n }\n })\n })\n}\n\nfunction sendJsonIfOpen(response: ServerResponse, status: number, body: unknown): void {\n if (response.destroyed || response.writableEnded) return\n sendJson(response, status, body)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","import {\n type ExternalOptimizerModelProxy,\n type ExternalOptimizerRunnerCommand,\n removeCredentialEnvironment,\n} from '../campaign/external-optimizer-contracts'\nimport { startExternalOptimizerModelProxy } from '../campaign/external-optimizer-model-proxy'\nimport { runWithCleanup } from '../campaign/external-optimizer-resources'\nimport { runExternalOptimizerProcess } from '../campaign/external-optimizer-subprocess'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport { resolveModelPricing } from '../metrics'\nimport type { TraceAnalysisEngine, TraceAnalysisEngineResult } from './engine'\nimport { type RawAnalystFinding, RawAnalystFindingSchema } from './finding-signature'\nimport { startTraceToolCallback } from './trace-tool-callback'\n\nconst DEFAULT_TIMEOUT_MS = 10 * 60_000\n// 4096 is below what current coding models emit for a full findings array:\n// glm-5.2 through an OpenAI-compatible gateway returns 8192 and the request is\n// rejected outright (`502 — provider reported 8192 completion tokens,\n// exceeding requested limit 4096`), so the default failed 2/2 smoke cases\n// before any analysis ran. The cap exists to bound spend, and `maxCostUsd`\n// already does that directly, so it starts above what a real completion needs.\nconst DEFAULT_MODEL_OUTPUT_TOKENS = 16_384\nconst DEFAULT_MAX_COST_USD = 1\nconst MAX_MODEL_REQUEST_BYTES = 16 * 1024 * 1024\nconst MAX_MODEL_RESPONSE_BYTES = 4 * 1024 * 1024\nconst BRIDGE_MODULE = 'agent_eval_rpc.dspy_rlm_bridge'\n/** Bumped whenever this engine's execution behavior changes. */\nconst DSPY_RLM_ENGINE_VERSION = '1.0.0'\n\nexport interface DspyRlmTraceEngineOptions {\n baseUrl: string\n apiKey: string\n model: string\n /** Exact provider rates. Required when the model is absent from the pricing table. */\n pricing?: CustomTokenPricing\n /** Maximum provider spend for one investigation. Default: 1 USD. */\n maxCostUsd?: number\n /** Controller response cap. Default: 16384. */\n maxOutputTokens?: number\n /**\n * Thinking tokens one controller turn may bill on top of its completion.\n * A reasoning model bills these beyond `maxOutputTokens`, so the cost\n * reservation must cover them. Default: four times the completion cap.\n */\n maxReasoningTokens?: number\n /**\n * How the controller's reasoning and code fields are obtained.\n *\n * `tolerant` parses marker output strictly first, then recovers the fields\n * deterministically from prose plus a fenced code block — the shape coding\n * models naturally emit — at no extra model cost. `two-step` extracts with a\n * second call per turn. `chat` accepts marker output only. Default:\n * `tolerant`.\n */\n controlAdapter?: 'chat' | 'two-step' | 'tolerant'\n /** Python command used to load agent-eval-rpc[dspy]. Default: python. */\n runner?: ExternalOptimizerRunnerCommand\n /** Whole investigation deadline. Default: 10 minutes. */\n timeoutMs?: number\n}\n\n/** Use the official DSPy RLM as a bounded recursive trace-analysis engine. */\nexport function createDspyRlmTraceEngine(options: DspyRlmTraceEngineOptions): TraceAnalysisEngine {\n assertOptions(options)\n const maxOutputTokens = options.maxOutputTokens ?? DEFAULT_MODEL_OUTPUT_TOKENS\n if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) {\n throw new TypeError('DSPy RLM maxOutputTokens must be a positive safe integer')\n }\n const controlAdapter = options.controlAdapter ?? 'tolerant'\n const maxReasoningTokens = options.maxReasoningTokens ?? maxOutputTokens * 4\n if (!Number.isSafeInteger(maxReasoningTokens) || maxReasoningTokens < 0) {\n throw new TypeError('DSPy RLM maxReasoningTokens must be a non-negative safe integer')\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {\n throw new TypeError('DSPy RLM timeoutMs must be a positive safe integer')\n }\n const maxCostUsd = options.maxCostUsd ?? DEFAULT_MAX_COST_USD\n if (!Number.isFinite(maxCostUsd) || maxCostUsd <= 0) {\n throw new TypeError('DSPy RLM maxCostUsd must be positive and finite')\n }\n const pricing = options.pricing ?? pricingForModel(options.model)\n\n const runner = sanitizedRunner(options.runner)\n return {\n id: 'dspy-rlm',\n description: 'Official DSPy RLM with bounded trace tools and metered model calls.',\n model: options.model,\n version: DSPY_RLM_ENGINE_VERSION,\n executionConfig: {\n bridge_module: BRIDGE_MODULE,\n base_url: options.baseUrl,\n model: options.model,\n api_key_provided: true,\n pricing: { ...pricing },\n max_cost_usd: maxCostUsd,\n max_output_tokens: maxOutputTokens,\n max_reasoning_tokens: maxReasoningTokens,\n control_adapter: controlAdapter,\n timeout_ms: timeoutMs,\n max_request_bytes: MAX_MODEL_REQUEST_BYTES,\n max_response_bytes: MAX_MODEL_RESPONSE_BYTES,\n runner: runner ? 'caller-supplied' : 'default',\n runner_command: runner?.command ?? null,\n },\n async analyze(request) {\n const callback = await startTraceToolCallback({\n tools: request.tools,\n maxCalls: request.limits.maxToolCalls,\n ...(request.signal ? { signal: request.signal } : {}),\n })\n let modelProxy: ExternalOptimizerModelProxy | undefined\n const result = await runWithCleanup({\n label: 'DSPy RLM trace-analysis resources',\n run: async () => {\n modelProxy = await startExternalOptimizerModelProxy({\n upstreamBaseUrl: options.baseUrl,\n upstreamApiKey: options.apiKey,\n model: options.model,\n budget: {\n maxCostUsd,\n maxRequests: request.limits.maxIterations + request.limits.maxLlmCalls + 1,\n maxRequestBytes: MAX_MODEL_REQUEST_BYTES,\n maxResponseBytes: MAX_MODEL_RESPONSE_BYTES,\n maxOutputTokensPerRequest: maxOutputTokens,\n maxReasoningTokensPerRequest: maxReasoningTokens,\n requestTimeoutMs: timeoutMs,\n pricing,\n },\n costLedger: request.costLedger,\n channel: 'analyst',\n phase: request.costPhase,\n actor: request.analystId,\n ...(request.costTags ? { tags: request.costTags } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n request.log?.('trace analyst engine started', {\n engine: 'dspy-rlm',\n model: options.model,\n tools: request.tools.map((tool) => tool.name),\n limits: request.limits,\n })\n const raw = await runExternalOptimizerProcess<unknown>({\n label: 'DSPy RLM trace analysis',\n tempPrefix: 'agent-eval-dspy-rlm-',\n module: BRIDGE_MODULE,\n input: {\n operation: 'analyze',\n question: request.question,\n instructions: request.instructions,\n modelProxy: {\n baseUrl: modelProxy.baseUrl,\n apiKey: modelProxy.apiKey,\n model: options.model,\n maxOutputTokens,\n },\n toolCallback: {\n url: callback.url,\n token: callback.token,\n },\n toolSpecs: request.tools.map(({ name, description, parameters }) => ({\n name,\n description,\n parameters,\n })),\n controlAdapter,\n limits: {\n maxIterations: request.limits.maxIterations,\n maxLlmCalls: request.limits.maxLlmCalls,\n maxOutputChars: request.limits.maxOutputChars,\n },\n },\n ...(runner ? { runner } : {}),\n timeoutMs,\n ...(request.signal ? { signal: request.signal } : {}),\n })\n const parsed = parseBridgeOutput(raw, (index, reason) => {\n request.log?.('finding rejected: bridge row failed schema validation', {\n engine: 'dspy-rlm',\n index,\n reason,\n })\n })\n const successfulCompletions = modelProxy.successfulCompletions()\n const requestAttempts = modelProxy.requestAttempts()\n const rateLimitRetries = modelProxy.rateLimitRetries()\n if (parsed.modelCalls !== successfulCompletions) {\n throw new Error(\n `DSPy RLM reported ${parsed.modelCalls} model calls, but the provider proxy recorded ${successfulCompletions}`,\n )\n }\n return {\n ...parsed,\n toolCalls: callback.calls(),\n runtime: {\n ...parsed.runtime,\n modelRequestAttempts: requestAttempts,\n modelSuccessfulCompletions: successfulCompletions,\n modelRateLimitRetries: rateLimitRetries,\n },\n } satisfies TraceAnalysisEngineResult\n },\n cleanup: async () => {\n const results = await Promise.allSettled([\n ...(modelProxy ? [modelProxy.close()] : []),\n callback.close(),\n ])\n const errors = results.flatMap((entry) =>\n entry.status === 'rejected' ? [entry.reason] : [],\n )\n if (errors.length > 0) {\n throw new AggregateError(errors, 'DSPy RLM resource cleanup failed')\n }\n },\n })\n request.log?.('trace analyst engine completed', {\n engine: 'dspy-rlm',\n model_calls: result.modelCalls,\n model_request_attempts: result.runtime.modelRequestAttempts,\n model_rate_limit_retries: result.runtime.modelRateLimitRetries,\n tool_calls: result.toolCalls,\n findings: result.findings.length,\n })\n return result\n },\n }\n}\n\nfunction parseBridgeOutput(\n value: unknown,\n onRejectedFinding: (index: number, reason: string) => void,\n): Omit<TraceAnalysisEngineResult, 'toolCalls'> {\n if (!isRecord(value)) throw new Error('DSPy RLM bridge output must be an object')\n if (typeof value.answer !== 'string' || !value.answer.trim()) {\n throw new Error('DSPy RLM bridge returned no answer')\n }\n if (!Array.isArray(value.findings)) {\n throw new Error('DSPy RLM bridge findings must be an array')\n }\n // Findings are model output: one malformed row is model noise, not a bridge\n // fault, and the rest of the paid investigation must survive it. Rejected\n // rows are logged per row and counted in runtime.rejectedFindings.\n let rejectedFindings = 0\n const findings: RawAnalystFinding[] = []\n value.findings.forEach((finding, index) => {\n const parsed = RawAnalystFindingSchema.safeParse(finding)\n if (!parsed.success) {\n rejectedFindings += 1\n onRejectedFinding(\n index,\n parsed.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`).join('; '),\n )\n return\n }\n findings.push(parsed.data)\n })\n if (!Array.isArray(value.trajectory)) {\n throw new Error('DSPy RLM bridge trajectory must be an array')\n }\n if (!Number.isSafeInteger(value.modelCalls) || (value.modelCalls as number) <= 0) {\n throw new Error('DSPy RLM bridge modelCalls must be a positive safe integer')\n }\n if (!isRecord(value.runtime)) {\n throw new Error('DSPy RLM bridge runtime must be an object')\n }\n return {\n answer: value.answer,\n findings,\n trajectory: value.trajectory,\n modelCalls: value.modelCalls as number,\n runtime: { ...value.runtime, rejectedFindings },\n }\n}\n\nfunction assertOptions(options: DspyRlmTraceEngineOptions): void {\n for (const [name, value] of [\n ['baseUrl', options.baseUrl],\n ['apiKey', options.apiKey],\n ['model', options.model],\n ] as const) {\n if (typeof value !== 'string' || !value.trim()) {\n throw new TypeError(`DSPy RLM ${name} must be a non-empty string`)\n }\n }\n}\n\nfunction pricingForModel(model: string): CustomTokenPricing {\n const pricing = resolveModelPricing(model)\n if (!pricing) {\n throw new Error(\n `no pricing is configured for '${model}'; provide DspyRlmTraceEngineOptions.pricing`,\n )\n }\n return {\n inputUsdPerMillion: pricing.input * 1_000,\n outputUsdPerMillion: pricing.output * 1_000,\n }\n}\n\nfunction sanitizedRunner(\n runner: ExternalOptimizerRunnerCommand | undefined,\n): ExternalOptimizerRunnerCommand | undefined {\n if (!runner) return undefined\n return {\n ...(runner.command ? { command: runner.command } : {}),\n ...(runner.args ? { args: runner.args } : {}),\n ...(runner.env ? { env: removeCredentialEnvironment(runner.env) } : {}),\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n"],"mappings":";;;;;;AAKA,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;;AAU3B,eAAsB,uBAAuB,MAId;CAC7B,IAAI,CAAC,OAAO,cAAc,KAAK,QAAQ,KAAK,KAAK,YAAY,GAC3D,MAAM,IAAI,UAAU,8DAA8D;CAEpF,KAAK,QAAQ,eAAe;CAC5B,MAAM,SAAS,IAAI,IAAI,KAAK,MAAM,KAAK,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC,CAA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AC;EAC3C,GAAI,OAAO,MAAM,EAAE,KAAK,4BAA4B,OAAO,GAAG,EAAE,IAAI,CAAC;CACvE;AACF;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E"}
@@ -1,42 +0,0 @@
1
- import { b as CustomTokenPricing } from "./cost-ledger-FuQvHxPm.js";
2
- //#region src/campaign/external-optimizer-contracts.d.ts
3
- interface ExternalOptimizerRunnerCommand {
4
- command?: string;
5
- args?: readonly string[];
6
- env?: NodeJS.ProcessEnv;
7
- }
8
- type ExternalOptimizerResumeMode = 'never' | 'if-compatible' | 'required';
9
- type ExternalTextCandidate = string | Record<string, string>;
10
- interface ExternalTextEvaluationRequest {
11
- candidate: ExternalTextCandidate;
12
- exampleId: string;
13
- }
14
- interface ExternalOptimizerModelBudget {
15
- /** Maximum optimizer-model spend, independent of task-evaluation spend. */
16
- maxCostUsd: number;
17
- /** Network attempts, including provider retries. */
18
- maxRequests: number;
19
- /** Reject a request body above this byte count. */
20
- maxRequestBytes: number;
21
- /** Reject a provider response above this byte count. */
22
- maxResponseBytes: number;
23
- /** Reject a request asking the provider for more output tokens. */
24
- maxOutputTokensPerRequest: number;
25
- /**
26
- * Reasoning tokens a single response may bill beyond its completion limit.
27
- *
28
- * A reasoning model bounds only the completion by `max_tokens` and bills
29
- * thinking on top, so a reservation sized to the completion alone is always
30
- * too small and the ledger refuses the real charge. Callers that route a
31
- * reasoning model declare its thinking budget here; the reservation covers
32
- * it and a response exceeding it still fails loudly. Default: 0.
33
- */
34
- maxReasoningTokensPerRequest?: number;
35
- /** Rates used to estimate cost when the provider omits a valid `usage.cost`. */
36
- pricing: CustomTokenPricing;
37
- /** Per-provider-request deadline. Default: 300,000 ms. */
38
- requestTimeoutMs?: number;
39
- }
40
- //#endregion
41
- export { ExternalTextEvaluationRequest as a, ExternalTextCandidate as i, ExternalOptimizerResumeMode as n, ExternalOptimizerRunnerCommand as r, ExternalOptimizerModelBudget as t };
42
- //# sourceMappingURL=external-optimizer-contracts-nb7c_WAR.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"external-optimizer-contracts-nb7c_WAR.d.ts","names":[],"sources":["../src/campaign/external-optimizer-contracts.ts"],"mappings":";;UAKiB;EACf;EACA;EACA,MAAM,OAAO;;KAGH;KAEA,iCAAiC;UAE5B;EACf,WAAW;EACX;;UAUe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;EAUA;;EAEA,SAAS;;EAET"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-BKjcUH13.d.ts","names":[],"sources":["../src/supervisor-run/source-facts.ts","../src/supervisor-run/analyze.ts","../src/supervisor-run/claude-code-reader.ts","../src/supervisor-run/integrity-types.ts","../src/supervisor-run/integrity.ts","../src/supervisor-run/loops-reader.ts","../src/supervisor-run/render.ts","../src/supervisor-run/rollout-nodes.ts"],"mappings":";;;UAqBU;EACR;EACA;EACA;EACA;;EAEA;;UAGQ;EACR,QAAQ;EACR;;UAgFe;;EAEf;EACA;EACA;EACA;EACA,MAAM;EACN;;EAEA;EACA;;UAGe;EACf;EACA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA,OAAO;;EAEP;;UAGe;;EAEf;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;EAEA;;EAEA;EACA;;EAEA;;EAEA;EACA;EACA;EACA;EACA,eAAe;EACf,uBAAuB;;UAGR;;EAEf;EACA;;UAGe;;EAEf;;EAEA;EACA;;;;;;UAOe;WACN;WACA,iBAAiB;WACjB,iBAAiB;WACjB,uBAAuB;WACvB,uBAAuB;WACvB;IACP;IACA;IACA;IACA;;IAEA;IACA;IACA;;WAEO,YAAY,oBAAoB;;WAEhC,wBAAwB;;WAExB;;;;;;;;;WASA;;WAEA;;;;;;WAMA,0BAA0B,SAAS;;WAEnC,gBAAgB;;WAEhB,OAAO;WACP;WACA;;;;;;;;;;;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AAM,2BACL"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"integrity-hruKe6oe.js","names":["unhandled"],"sources":["../src/supervisor-run/integrity-issues.ts","../src/supervisor-run/integrity-steer.ts","../src/supervisor-run/integrity-source.ts","../src/supervisor-run/integrity-tree.ts","../src/supervisor-run/integrity-types.ts","../src/supervisor-run/source-facts.ts","../src/supervisor-run/rollout-nodes.ts","../src/supervisor-run/integrity.ts"],"sourcesContent":["import type { SupervisorRunIntegrityEvidence, SupervisorRunIntegrityIssue } from './integrity-types'\n\nexport const MAX_EXAMPLES = 20\n\nexport function evidence(path: string, value: unknown): SupervisorRunIntegrityEvidence {\n return { path, value }\n}\n\nexport function issue(\n init: Omit<SupervisorRunIntegrityIssue, 'evidence'> & {\n evidence?: readonly SupervisorRunIntegrityEvidence[]\n },\n): SupervisorRunIntegrityIssue {\n return { ...init, evidence: init.evidence ?? [] }\n}\n","import { evidence, issue, MAX_EXAMPLES } from './integrity-issues'\nimport type { JoinedWorker } from './integrity-source'\nimport type { SupervisorRunIntegrityIssue } from './integrity-types'\n\nfunction idListDetail(ids: readonly string[]): string {\n const examples = ids\n .slice(0, MAX_EXAMPLES)\n .map((id) => JSON.stringify(id))\n .join(', ')\n return ids.length <= MAX_EXAMPLES\n ? examples\n : `${examples}, and ${ids.length - MAX_EXAMPLES} more`\n}\n\nexport function steerIssues(\n joined: JoinedWorker,\n rootCompleted: boolean,\n): SupervisorRunIntegrityIssue[] {\n const { facts } = joined\n const subject = facts.workerId ?? joined.spawn.id\n const prefix = `workers/${facts.sourceIndex}`\n const out: SupervisorRunIntegrityIssue[] = []\n if (\n !facts.inboxCaptured ||\n !facts.eventsCaptured ||\n facts.inboxInvalidRows > 0 ||\n facts.eventsInvalidRows > 0\n ) {\n const missing = [\n ...(facts.inboxCaptured ? [] : ['inbox']),\n ...(facts.eventsCaptured ? [] : ['events']),\n ]\n const malformed = [\n ...(facts.inboxInvalidRows > 0 ? [`inbox:${facts.inboxInvalidRows}`] : []),\n ...(facts.eventsInvalidRows > 0 ? [`events:${facts.eventsInvalidRows}`] : []),\n ]\n out.push(\n issue({\n code: 'worker-controls-unavailable',\n area: 'capture-integrity',\n severity: 'medium',\n subject,\n claim:\n 'Steer delivery integrity is unavailable for a worker with missing control artifacts',\n detail:\n missing.length > 0\n ? `${JSON.stringify(subject)} is missing ${missing.join(' and ')}.`\n : `${JSON.stringify(subject)} has malformed control rows (${malformed.join(', ')}).`,\n evidence: [\n ...missing.map((artifact) => evidence(`${prefix}/${artifact}`, null)),\n ...(facts.inboxInvalidRows > 0\n ? [evidence(`${prefix}/inbox/malformed-rows/count`, facts.inboxInvalidRows)]\n : []),\n ...(facts.eventsInvalidRows > 0\n ? [evidence(`${prefix}/events/malformed-rows/count`, facts.eventsInvalidRows)]\n : []),\n ],\n recommendedAction:\n 'Retain both control artifacts and repair malformed rows before correlating requests.',\n metadata: {\n assessment: 'unavailable',\n missing_artifacts: missing,\n malformed_rows: malformed,\n },\n }),\n )\n return out\n }\n\n const requestsById = new Map<string, typeof facts.steerRequests>()\n const unidentifiedRequests = facts.steerRequests.filter((request) => request.requestId === null)\n for (const request of facts.steerRequests) {\n if (request.requestId === null) continue\n const rows = requestsById.get(request.requestId) ?? []\n rows.push(request)\n requestsById.set(request.requestId, rows)\n }\n if (unidentifiedRequests.length > 0) {\n out.push(\n issue({\n code: 'steer-request-id-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject,\n claim: 'Some queued steer requests cannot be correlated because their ids are missing',\n detail: `${unidentifiedRequests.length} queued request(s) omit id.`,\n evidence: unidentifiedRequests\n .slice(0, MAX_EXAMPLES)\n .map((request) => evidence(`${prefix}/inbox/${request.row}/id`, null)),\n recommendedAction: 'Assign one stable request id before appending a steer to the inbox.',\n metadata: { assessment: 'unavailable', unavailable_count: unidentifiedRequests.length },\n }),\n )\n }\n const duplicateRequestIds = [...requestsById]\n .filter(([, rows]) => rows.length > 1)\n .map(([id]) => id)\n if (duplicateRequestIds.length > 0) {\n out.push(\n issue({\n code: 'duplicate-steer-request-id',\n area: 'control-integrity',\n severity: 'high',\n subject,\n claim: 'A worker inbox contains duplicate steer request ids',\n detail: `${duplicateRequestIds.length} duplicate id(s): ${idListDetail(duplicateRequestIds)}.`,\n evidence: [\n evidence(\n `${prefix}/inbox/duplicate-request-ids`,\n duplicateRequestIds.slice(0, MAX_EXAMPLES),\n ),\n ],\n recommendedAction: 'Generate a unique request id for every queued steer.',\n }),\n )\n }\n\n const acknowledgementsById = new Map<string, typeof facts.steerAcknowledgements>()\n const unidentifiedAcks = facts.steerAcknowledgements.filter((ack) => ack.requestId === null)\n for (const ack of facts.steerAcknowledgements) {\n if (ack.requestId === null) continue\n const rows = acknowledgementsById.get(ack.requestId) ?? []\n rows.push(ack)\n acknowledgementsById.set(ack.requestId, rows)\n }\n if (unidentifiedAcks.length > 0) {\n out.push(\n issue({\n code: 'steer-ack-id-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject,\n claim: 'Some steer acknowledgements cannot be correlated because requestId is missing',\n detail: `${unidentifiedAcks.length} down-leg event(s) omit requestId.`,\n evidence: unidentifiedAcks\n .slice(0, MAX_EXAMPLES)\n .map((ack) => evidence(`${prefix}/events/${ack.row}/requestId`, null)),\n recommendedAction: 'Echo the queued request id on every worker acknowledgement.',\n metadata: { assessment: 'unavailable', unavailable_count: unidentifiedAcks.length },\n }),\n )\n }\n\n const unknownAckIds = [...acknowledgementsById.keys()].filter((id) => !requestsById.has(id))\n if (unknownAckIds.length > 0) {\n out.push(\n issue({\n code: 'unknown-steer-ack',\n area: 'control-integrity',\n severity: 'high',\n subject,\n claim: 'A worker acknowledged steer request ids absent from its captured inbox',\n detail: `${unknownAckIds.length} unknown id(s): ${idListDetail(unknownAckIds)}.`,\n evidence: [\n evidence(`${prefix}/events/unknown-request-ids`, unknownAckIds.slice(0, MAX_EXAMPLES)),\n ],\n recommendedAction:\n 'Reject acknowledgements whose request id was not queued for this worker.',\n }),\n )\n }\n\n const duplicateAckIds = [...acknowledgementsById]\n .filter(([, rows]) => rows.length > 1)\n .map(([id]) => id)\n if (duplicateAckIds.length > 0) {\n out.push(\n issue({\n code: 'duplicate-steer-ack',\n area: 'control-integrity',\n severity: 'high',\n subject,\n claim: 'A worker emitted duplicate acknowledgements for steer request ids',\n detail: `${duplicateAckIds.length} duplicated id(s): ${idListDetail(duplicateAckIds)}.`,\n evidence: [\n evidence(\n `${prefix}/events/duplicate-request-ids`,\n duplicateAckIds.slice(0, MAX_EXAMPLES),\n ),\n ],\n recommendedAction: 'Make steer acknowledgement append idempotent by request id.',\n }),\n )\n }\n\n const missingAckIds = [...requestsById.keys()].filter((id) => !acknowledgementsById.has(id))\n if (rootCompleted && missingAckIds.length > 0) {\n out.push(\n issue({\n code: 'missing-steer-ack',\n area: 'control-integrity',\n severity: 'high',\n subject,\n claim: 'A completed supervisor run has queued steer requests without acknowledgements',\n detail: `${missingAckIds.length}/${requestsById.size} request id(s) are unacknowledged: ${idListDetail(missingAckIds)}.`,\n evidence: [\n evidence(\n `${prefix}/inbox/unacknowledged-request-ids`,\n missingAckIds.slice(0, MAX_EXAMPLES),\n ),\n ],\n recommendedAction:\n 'Record one delivered or failed acknowledgement for every queued request id.',\n }),\n )\n }\n\n const statusUnavailableIds: string[] = []\n const notDeliveredIds: string[] = []\n for (const [id, acknowledgements] of acknowledgementsById) {\n if (!requestsById.has(id) || acknowledgements.length !== 1) continue\n const delivered = acknowledgements[0]?.delivered\n if (delivered === null || delivered === undefined) statusUnavailableIds.push(id)\n else if (!delivered) notDeliveredIds.push(id)\n }\n if (statusUnavailableIds.length > 0) {\n out.push(\n issue({\n code: 'steer-ack-status-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject,\n claim: 'Some steer acknowledgements omit delivery status',\n detail: `${statusUnavailableIds.length} id(s): ${idListDetail(statusUnavailableIds)}.`,\n evidence: [\n evidence(\n `${prefix}/events/status-unavailable-request-ids`,\n statusUnavailableIds.slice(0, MAX_EXAMPLES),\n ),\n ],\n recommendedAction: 'Record delivered: true or delivered: false on each acknowledgement.',\n metadata: { assessment: 'unavailable', unavailable_count: statusUnavailableIds.length },\n }),\n )\n }\n if (notDeliveredIds.length > 0) {\n out.push(\n issue({\n code: 'steer-not-delivered',\n area: 'control-integrity',\n severity: 'high',\n subject,\n claim: 'Queued steer requests were acknowledged but not delivered',\n detail: `${notDeliveredIds.length} id(s): ${idListDetail(notDeliveredIds)}.`,\n evidence: [\n evidence(\n `${prefix}/events/not-delivered-request-ids`,\n notDeliveredIds.slice(0, MAX_EXAMPLES),\n ),\n ],\n recommendedAction:\n 'Retry or explicitly fail the control request instead of treating it as delivered.',\n }),\n )\n }\n return out\n}\n","import { evidence, issue, MAX_EXAMPLES } from './integrity-issues'\nimport { steerIssues } from './integrity-steer'\nimport type { SupervisorRunIntegrityIssue } from './integrity-types'\nimport type { SpawnRow, SupervisorTreeFacts, WorkerLogFacts } from './source-facts'\nimport type { SupervisorRunSources, SupervisorRunTree } from './types'\n\nfunction sourceIdentityIssues(facts: SupervisorTreeFacts): SupervisorRunIntegrityIssue[] {\n const out: SupervisorRunIntegrityIssue[] = []\n const malformedSpawns = facts.spawns.filter((spawn) => !spawn.valid)\n if (facts.journalInvalidRows > 0 || malformedSpawns.length > 0) {\n out.push(\n issue({\n code: 'source-row-malformed',\n area: 'capture-integrity',\n severity: 'high',\n subject: 'journal-rows',\n claim: 'Some supervisor journal rows could not be interpreted',\n detail: `${facts.journalInvalidRows} of ${facts.journalRows} row(s) could not be interpreted (${facts.journalMalformedJsonRows} were not JSON objects) and ${malformedSpawns.length} malformed spawn row(s) were excluded from structural conclusions.`,\n evidence: [\n evidence('journal/uninterpretable-rows/count', facts.journalInvalidRows),\n evidence('journal/malformed-json-rows/count', facts.journalMalformedJsonRows),\n evidence('journal/rows/count', facts.journalRows),\n evidence('journal/dialect', facts.journalDialect),\n ...malformedSpawns\n .slice(0, MAX_EXAMPLES)\n .map((spawn) =>\n evidence(`journal/spawns/${spawn.sourceRow}/invalid-fields`, spawn.invalidFields),\n ),\n ],\n recommendedAction:\n 'Repair the rows, or teach the parser the shape they are in, before using the run for structural analysis. A row nobody can read must never be silently absent from the tree.',\n metadata: {\n assessment: 'unavailable',\n journal_rows: facts.journalRows,\n uninterpretable_rows: facts.journalInvalidRows,\n malformed_json_rows: facts.journalMalformedJsonRows,\n malformed_spawn_rows: malformedSpawns.length,\n journal_dialect: facts.journalDialect,\n },\n }),\n )\n }\n const unidentifiedSpawns = malformedSpawns.filter((spawn) => spawn.id.length === 0)\n const unidentifiedCloses = facts.closes.filter((close) => close.id.length === 0)\n if (unidentifiedSpawns.length + unidentifiedCloses.length > 0) {\n out.push(\n issue({\n code: 'source-event-identity-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject: 'journal-event-identity',\n claim: 'Some supervisor journal events have no usable invocation id',\n detail: `${unidentifiedSpawns.length} spawn and ${unidentifiedCloses.length} terminal event(s) lack an id.`,\n evidence: [\n evidence('journal/unidentified-spawns/count', unidentifiedSpawns.length),\n evidence('journal/unidentified-terminals/count', unidentifiedCloses.length),\n ],\n recommendedAction: 'Reject or repair control events that omit their stable invocation id.',\n metadata: { assessment: 'unavailable', checks: ['journal-event-linkage'] },\n }),\n )\n }\n\n const spawnCounts = new Map<string, number>()\n for (const spawn of facts.spawns) {\n if (!spawn.valid || spawn.id.length === 0) continue\n spawnCounts.set(spawn.id, (spawnCounts.get(spawn.id) ?? 0) + 1)\n }\n for (const [id, count] of spawnCounts) {\n if (count < 2) continue\n out.push(\n issue({\n code: 'duplicate-spawn',\n area: 'control-integrity',\n severity: 'critical',\n subject: id,\n claim: 'An invocation has more than one spawned control event',\n detail: `${count} spawned events name invocation ${JSON.stringify(id)}.`,\n evidence: [evidence(`journal/spawn-count/${encodeURIComponent(id)}`, count)],\n recommendedAction: 'Make spawn event append idempotent.',\n }),\n )\n }\n\n const closeCounts = new Map<string, number>()\n for (const close of facts.closes) {\n if (close.id.length === 0) continue\n closeCounts.set(close.id, (closeCounts.get(close.id) ?? 0) + 1)\n }\n const uncertainSpawnIds = new Set(\n malformedSpawns.filter((spawn) => spawn.id.length > 0).map((spawn) => spawn.id),\n )\n if (unidentifiedSpawns.length === 0 && facts.journalInvalidRows === 0) {\n const orphanCloses = new Map<string, Array<(typeof facts.closes)[number]>>()\n for (const close of facts.closes) {\n if (close.id.length === 0 || spawnCounts.has(close.id) || uncertainSpawnIds.has(close.id)) {\n continue\n }\n const rows = orphanCloses.get(close.id) ?? []\n rows.push(close)\n orphanCloses.set(close.id, rows)\n }\n for (const [id, closes] of orphanCloses) {\n out.push(\n issue({\n code: 'orphan-terminal',\n area: 'control-integrity',\n severity: 'critical',\n subject: id,\n claim: 'A terminal control event names an invocation that was never spawned',\n detail: `${closes.length} terminal event(s) for ${JSON.stringify(id)} have no matching spawn.`,\n evidence: [\n evidence(`journal/closes/${encodeURIComponent(id)}/count`, closes.length),\n ...closes\n .slice(0, MAX_EXAMPLES)\n .map((close, index) =>\n evidence(`journal/closes/${encodeURIComponent(id)}/${index}`, close),\n ),\n ],\n recommendedAction: 'Retain the matching spawn event or reject the orphan terminal event.',\n }),\n )\n }\n }\n for (const [id, count] of closeCounts) {\n if (count < 2) continue\n out.push(\n issue({\n code: 'duplicate-terminal',\n area: 'control-integrity',\n severity: 'critical',\n subject: id,\n claim: 'An invocation has more than one terminal control event',\n detail: `${count} settled/cancelled events name invocation ${JSON.stringify(id)}.`,\n evidence: [evidence(`journal/terminal-count/${encodeURIComponent(id)}`, count)],\n recommendedAction: 'Make terminal event append idempotent.',\n }),\n )\n }\n return out\n}\n\nexport interface JoinedWorker {\n readonly spawn: SpawnRow\n readonly facts: WorkerLogFacts\n}\n\nfunction joinWorkerControls(facts: SupervisorTreeFacts): {\n joined: JoinedWorker[]\n issue: SupervisorRunIntegrityIssue | null\n} {\n const spawnsById = new Map<string, SpawnRow[]>()\n const spawnsByLabel = new Map<string, SpawnRow[]>()\n for (const spawn of facts.workerSpawns) {\n const ids = spawnsById.get(spawn.id) ?? []\n ids.push(spawn)\n spawnsById.set(spawn.id, ids)\n const labels = spawnsByLabel.get(spawn.label) ?? []\n labels.push(spawn)\n spawnsByLabel.set(spawn.label, labels)\n }\n const rowsWithoutIdByLabel = new Map<string, WorkerLogFacts[]>()\n for (const row of facts.workerLogRows) {\n if (row.workerId !== null && row.workerId.length > 0) continue\n const matches = rowsWithoutIdByLabel.get(row.label) ?? []\n matches.push(row)\n rowsWithoutIdByLabel.set(row.label, matches)\n }\n\n const rowsBySpawn = new Map<string, WorkerLogFacts[]>()\n const unmatchedRows: number[] = []\n const ambiguousRows: number[] = []\n for (const row of facts.workerLogRows) {\n const matches =\n row.workerId !== null && row.workerId.length > 0\n ? (spawnsById.get(row.workerId) ?? [])\n : (rowsWithoutIdByLabel.get(row.label)?.length ?? 0) === 1\n ? (spawnsByLabel.get(row.label) ?? [])\n : []\n if (matches.length === 0) {\n unmatchedRows.push(row.sourceIndex)\n continue\n }\n if (matches.length !== 1) {\n ambiguousRows.push(row.sourceIndex)\n continue\n }\n const spawn = matches[0] as SpawnRow\n const joined = rowsBySpawn.get(spawn.id) ?? []\n joined.push(row)\n rowsBySpawn.set(spawn.id, joined)\n }\n\n const joined: JoinedWorker[] = []\n const missingSpawnIds: string[] = []\n const duplicateSpawnIds: string[] = []\n for (const spawn of facts.workerSpawns) {\n if ((spawnsById.get(spawn.id)?.length ?? 0) !== 1) continue\n const rows = rowsBySpawn.get(spawn.id) ?? []\n if (rows.length === 0) missingSpawnIds.push(spawn.id)\n else if (rows.length > 1) duplicateSpawnIds.push(spawn.id)\n else joined.push({ spawn, facts: rows[0] as WorkerLogFacts })\n }\n\n if (\n missingSpawnIds.length === 0 &&\n duplicateSpawnIds.length === 0 &&\n unmatchedRows.length === 0 &&\n ambiguousRows.length === 0\n ) {\n return { joined, issue: null }\n }\n return {\n joined,\n issue: issue({\n code: 'worker-control-join-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject: 'worker-control-join',\n claim: 'Worker control-log coverage does not match recorded child invocations',\n detail: `${missingSpawnIds.length} spawn(s) have no log, ${duplicateSpawnIds.length} have duplicate logs, ${unmatchedRows.length} log row(s) match no spawn, and ${ambiguousRows.length} row(s) are ambiguous.`,\n evidence: [\n evidence('workers/join/missing-spawn-ids', missingSpawnIds.slice(0, MAX_EXAMPLES)),\n evidence('workers/join/duplicate-spawn-ids', duplicateSpawnIds.slice(0, MAX_EXAMPLES)),\n evidence('workers/join/unmatched-source-rows', unmatchedRows.slice(0, MAX_EXAMPLES)),\n evidence('workers/join/ambiguous-source-rows', ambiguousRows.slice(0, MAX_EXAMPLES)),\n ],\n recommendedAction:\n 'Retain exactly one worker control row with workerId for every spawned invocation.',\n metadata: {\n assessment: 'unavailable',\n missing_count: missingSpawnIds.length,\n duplicate_count: duplicateSpawnIds.length,\n unmatched_count: unmatchedRows.length,\n ambiguous_count: ambiguousRows.length,\n },\n }),\n }\n}\n\nexport function sourceIssues(\n source: SupervisorRunSources,\n facts: SupervisorTreeFacts,\n tree: SupervisorRunTree,\n): SupervisorRunIntegrityIssue[] {\n const out = sourceIdentityIssues(facts)\n if (source.workers === null) {\n const reason = source.workersMissingReason ?? 'worker control-log store was not captured'\n out.push(\n issue({\n code: 'worker-controls-unavailable',\n area: 'capture-integrity',\n severity: 'medium',\n subject: 'steer-delivery',\n claim:\n 'Steer delivery integrity is unavailable because worker control logs were not captured',\n detail: reason,\n evidence: [evidence('sources/workers', null)],\n recommendedAction: 'Retain each worker inbox and event stream.',\n metadata: { assessment: 'unavailable', reason },\n }),\n )\n return out\n }\n\n const joined = joinWorkerControls(facts)\n if (joined.issue !== null) out.push(joined.issue)\n const rootCompleted =\n tree.rootId !== null &&\n tree.nodes.filter((node) => node.rollout_id === tree.rootId).length === 1 &&\n tree.nodes.find((node) => node.rollout_id === tree.rootId)?.outcome.is_completed === true\n for (const row of joined.joined) out.push(...steerIssues(row, rootCompleted))\n return out\n}\n","import { validateRolloutLine } from '../rollout/schema'\nimport { evidence, issue, MAX_EXAMPLES } from './integrity-issues'\nimport type { SupervisorRunIntegrityEvidence, SupervisorRunIntegrityIssue } from './integrity-types'\nimport type { SupervisorRunTree } from './types'\n\ninterface NodeRecord {\n readonly index: number\n readonly raw: Record<string, unknown>\n readonly errors: readonly string[]\n readonly id: string | null\n readonly parent: string | null | undefined\n readonly runId: string | null\n readonly role: string | null\n readonly messages: readonly unknown[] | null\n readonly profileId: string | null\n readonly completed: boolean | null\n readonly terminal: boolean | null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nfunction parentValue(raw: Record<string, unknown>): string | null | undefined {\n if (raw.parent_rollout_id === null) return null\n return nonEmptyString(raw.parent_rollout_id) ?? undefined\n}\n\nfunction terminalValue(outcome: Record<string, unknown> | null): boolean | null {\n if (outcome === null) return null\n if (typeof outcome.is_completed !== 'boolean' || typeof outcome.is_truncated !== 'boolean') {\n return null\n }\n if (outcome.error !== null && typeof outcome.error !== 'string') return null\n return outcome.is_completed || outcome.is_truncated || outcome.error !== null\n}\n\nfunction nodeRecord(value: unknown, index: number): NodeRecord {\n const raw = isRecord(value) ? value : {}\n const policy = isRecord(raw.policy) ? raw.policy : null\n const outcome = isRecord(raw.outcome) ? raw.outcome : null\n return {\n index,\n raw,\n errors: validateRolloutLine(value),\n id: nonEmptyString(raw.rollout_id),\n parent: parentValue(raw),\n runId: nonEmptyString(raw.run_id),\n role: nonEmptyString(raw.role),\n messages: Array.isArray(raw.messages) ? raw.messages : null,\n profileId: policy === null ? null : nonEmptyString(policy.agent_profile_cell_id),\n completed:\n outcome !== null && typeof outcome.is_completed === 'boolean' ? outcome.is_completed : null,\n terminal: terminalValue(outcome),\n }\n}\n\nfunction metric(\n record: NodeRecord,\n keys: readonly string[],\n): { key: string; value: number } | null {\n const outcome = isRecord(record.raw.outcome) ? record.raw.outcome : null\n const metrics = outcome !== null && isRecord(outcome.metrics) ? outcome.metrics : null\n if (metrics === null) return null\n for (const key of keys) {\n const value = metrics[key]\n if (typeof value === 'number' && Number.isFinite(value)) return { key, value }\n }\n return null\n}\n\nfunction nodeEvidence(\n record: NodeRecord,\n path: string,\n value: unknown,\n): SupervisorRunIntegrityEvidence {\n const key = record.id ?? `index-${record.index}`\n return evidence(`nodes/${encodeURIComponent(key)}/${path}`, value)\n}\n\nfunction unavailableNodeChecks(record: NodeRecord): string[] {\n const checks: string[] = []\n if (record.id === null) checks.push('identity', 'root-membership', 'parent-link', 'cycle')\n if (record.parent === undefined) checks.push('parent-link', 'cycle')\n if (record.runId === null) checks.push('cross-run-parent')\n if (record.role === null) checks.push('root-role')\n if (!isRecord(record.raw.outcome)) checks.push('timing', 'terminal-state')\n return [...new Set(checks)]\n}\n\ninterface TreeIssueUncertainty {\n readonly unknownIdentityRows?: number\n readonly uncertainIds?: ReadonlySet<string>\n}\n\nexport function treeIssues(\n tree: SupervisorRunTree,\n uncertainty: TreeIssueUncertainty = {},\n): SupervisorRunIntegrityIssue[] {\n const out: SupervisorRunIntegrityIssue[] = []\n const records = (tree.nodes as readonly unknown[]).map(nodeRecord)\n const malformedSourceRows = tree.gaps\n .filter((gap) => gap.code === 'source-row-malformed')\n .reduce((count, gap) => count + (gap.count ?? 1), 0)\n\n for (const record of records) {\n if (record.errors.length === 0) continue\n out.push(\n issue({\n code: 'node-schema-invalid',\n area: 'capture-integrity',\n severity: 'high',\n subject: record.id ?? `node-${record.index}`,\n claim: 'A supervisor-tree node fails canonical rollout validation',\n detail: record.errors.join('; '),\n evidence: [evidence(`nodes/${record.index}/validation`, record.errors)],\n recommendedAction:\n 'Fix the producer so every node validates as the existing tangle.rollout.v1 shape before analysis.',\n metadata: { validation_errors: record.errors },\n }),\n )\n const unavailableChecks = unavailableNodeChecks(record)\n if (unavailableChecks.length === 0) continue\n out.push(\n issue({\n code: 'node-checks-unavailable',\n area: 'capture-integrity',\n severity: 'medium',\n subject: record.id ?? `node-${record.index}`,\n claim: 'Some integrity checks are unavailable for a malformed supervisor-tree node',\n detail: `Unavailable checks: ${unavailableChecks.join(', ')}.`,\n evidence: [evidence(`nodes/${record.index}/unavailable-checks`, unavailableChecks)],\n recommendedAction:\n 'Retain the named identity and relationship fields with their canonical types.',\n metadata: { assessment: 'unavailable', checks: unavailableChecks },\n }),\n )\n }\n\n const byId = new Map<string, NodeRecord[]>()\n for (const record of records) {\n if (record.id === null) continue\n const matches = byId.get(record.id) ?? []\n matches.push(record)\n byId.set(record.id, matches)\n }\n\n for (const [rolloutId, matches] of byId) {\n if (matches.length < 2) continue\n out.push(\n issue({\n code: 'duplicate-rollout-id',\n area: 'control-integrity',\n severity: 'critical',\n subject: rolloutId,\n claim: 'A rollout id is duplicated within one supervisor tree',\n detail: `${matches.length} nodes claim rollout_id ${JSON.stringify(rolloutId)}, so references are ambiguous.`,\n evidence: [\n evidence(`duplicates/${encodeURIComponent(rolloutId)}/count`, matches.length),\n ...matches.slice(0, MAX_EXAMPLES).map((record) =>\n evidence(`nodes/${record.index}/identity`, {\n rollout_id: record.id,\n parent_rollout_id: record.parent,\n role: record.role,\n }),\n ),\n ],\n recommendedAction: 'Give every invocation one stable rollout id and regenerate the tree.',\n }),\n )\n }\n\n const unknownIdentityRows =\n records.filter((record) => record.id === null).length +\n Math.max(malformedSourceRows, uncertainty.unknownIdentityRows ?? 0)\n const unique = records.filter(\n (record): record is NodeRecord & { readonly id: string } =>\n record.id !== null && byId.get(record.id)?.length === 1,\n )\n\n let root: NodeRecord | undefined\n if (tree.rootId === null) {\n out.push(\n issue({\n code: 'root-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject: 'tree-root',\n claim: 'The supervisor-tree root is unavailable',\n detail: `rootId is null while ${records.length} node row(s) were captured.`,\n evidence: [evidence('rootId', null)],\n recommendedAction: 'Capture the root spawned event and preserve its rollout id as rootId.',\n metadata: { assessment: 'unavailable', node_rows: records.length },\n }),\n )\n } else {\n const rootRows = byId.get(tree.rootId) ?? []\n if (rootRows.length === 1) {\n root = rootRows[0]\n } else if (rootRows.length === 0 && unknownIdentityRows > 0) {\n out.push(\n issue({\n code: 'node-checks-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject: tree.rootId,\n claim: 'Root membership is unavailable because a malformed node lost its rollout id',\n detail: `${unknownIdentityRows} malformed node row(s) have no usable rollout_id, so absence of root ${JSON.stringify(tree.rootId)} cannot be established.`,\n evidence: [evidence('rootId', tree.rootId)],\n recommendedAction: 'Retain rollout_id even when another node field fails validation.',\n metadata: { assessment: 'unavailable', checks: ['root-membership'] },\n }),\n )\n } else if (rootRows.length === 0) {\n out.push(\n issue({\n code: 'declared-root-missing',\n area: 'control-integrity',\n severity: 'critical',\n subject: tree.rootId,\n claim: 'The declared supervisor-tree root has no matching invocation node',\n detail: `rootId ${JSON.stringify(tree.rootId)} is absent from ${records.length} node row(s).`,\n evidence: [evidence('rootId', tree.rootId)],\n recommendedAction: 'Restore the root rollout row or correct rootId.',\n }),\n )\n }\n }\n\n if (root !== undefined) {\n if (root.parent !== undefined && root.parent !== null) {\n out.push(\n issue({\n code: 'root-has-parent',\n area: 'control-integrity',\n severity: 'critical',\n subject: root.id ?? tree.rootId ?? 'tree-root',\n claim: 'The declared supervisor-tree root has a parent',\n detail: `Root points to parent ${JSON.stringify(root.parent)}.`,\n evidence: [nodeEvidence(root, 'parent_rollout_id', root.parent)],\n recommendedAction: 'Record the root with parent_rollout_id null.',\n }),\n )\n }\n if (root.role !== null && root.role !== 'supervisor') {\n out.push(\n issue({\n code: 'root-role-invalid',\n area: 'control-integrity',\n severity: 'high',\n subject: root.id ?? tree.rootId ?? 'tree-root',\n claim: 'The declared supervisor-tree root is not labeled as a supervisor',\n detail: `Root has role ${JSON.stringify(root.role)}.`,\n evidence: [nodeEvidence(root, 'role', root.role)],\n recommendedAction:\n 'Preserve the root invocation role as supervisor when minting rollout rows.',\n }),\n )\n }\n }\n\n for (const record of unique) {\n if (record.parent === undefined) continue\n if (record.parent === null) {\n if (record.id !== tree.rootId) {\n out.push(\n issue({\n code: 'detached-node',\n area: 'control-integrity',\n severity: 'critical',\n subject: record.id,\n claim: 'A non-root invocation is recorded as a detached parentless root',\n detail: `Node ${JSON.stringify(record.id)} is parentless while rootId is ${JSON.stringify(tree.rootId)}.`,\n evidence: [\n nodeEvidence(record, 'parent_rollout_id', null),\n evidence('rootId', tree.rootId),\n ],\n recommendedAction:\n 'Attach the invocation to its spawning parent or record a separate run.',\n }),\n )\n }\n continue\n }\n\n const parentRows = byId.get(record.parent) ?? []\n if (parentRows.length === 0) {\n if (unknownIdentityRows > 0 || uncertainty.uncertainIds?.has(record.parent) === true) {\n out.push(\n issue({\n code: 'node-checks-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject: record.id,\n claim: 'Parent membership is unavailable because a malformed node lost its rollout id',\n detail:\n uncertainty.uncertainIds?.has(record.parent) === true\n ? `Parent ${JSON.stringify(record.parent)} appears only in a malformed source row, so its absence cannot be established.`\n : `Parent ${JSON.stringify(record.parent)} cannot be matched while ${unknownIdentityRows} row(s) have no usable rollout_id.`,\n evidence: [nodeEvidence(record, 'parent_rollout_id', record.parent)],\n recommendedAction: 'Retain rollout_id on every row before assessing detached children.',\n metadata: { assessment: 'unavailable', checks: ['parent-membership'] },\n }),\n )\n } else {\n out.push(\n issue({\n code: 'parent-missing',\n area: 'control-integrity',\n severity: 'critical',\n subject: record.id,\n claim: 'An invocation points to a parent absent from the supervisor tree',\n detail: `Node ${JSON.stringify(record.id)} names missing parent ${JSON.stringify(record.parent)}.`,\n evidence: [nodeEvidence(record, 'parent_rollout_id', record.parent)],\n recommendedAction: 'Retain the parent invocation or remove the dangling edge.',\n }),\n )\n }\n continue\n }\n if (parentRows.length !== 1) continue\n const parent = parentRows[0] as NodeRecord\n\n if (record.runId !== null && parent.runId !== null && record.runId !== parent.runId) {\n out.push(\n issue({\n code: 'cross-run-parent',\n area: 'control-integrity',\n severity: 'critical',\n subject: record.id,\n claim: 'A parent-child edge crosses supervisor-run identities',\n detail: `Child run_id ${JSON.stringify(record.runId)} differs from parent run_id ${JSON.stringify(parent.runId)}.`,\n evidence: [\n nodeEvidence(record, 'run_id', record.runId),\n nodeEvidence(parent, 'run_id', parent.runId),\n ],\n recommendedAction:\n 'Keep one run_id across a supervision tree or remove the cross-run edge.',\n }),\n )\n }\n\n const childStart = metric(record, ['spawned_at', 'started_at'])\n const parentStart = metric(parent, ['spawned_at', 'started_at'])\n if (childStart !== null && parentStart !== null && childStart.value < parentStart.value) {\n out.push(\n issue({\n code: 'child-before-parent',\n area: 'control-integrity',\n severity: 'high',\n subject: record.id,\n claim: 'A child invocation is timestamped before its parent started',\n detail: `Child ${childStart.key} ${childStart.value} precedes parent ${parentStart.key} ${parentStart.value}.`,\n evidence: [\n nodeEvidence(record, `outcome.metrics.${childStart.key}`, childStart.value),\n nodeEvidence(parent, `outcome.metrics.${parentStart.key}`, parentStart.value),\n ],\n recommendedAction: 'Use one ordered clock for spawn events or retain clock metadata.',\n }),\n )\n }\n\n const parentClose = metric(parent, ['settled_at', 'completed_at', 'finished_at'])\n if (childStart !== null && parentClose !== null && childStart.value > parentClose.value) {\n out.push(\n issue({\n code: 'child-after-parent-close',\n area: 'control-integrity',\n severity: 'critical',\n subject: record.id,\n claim: 'A child invocation is timestamped after its parent closed',\n detail: `Child ${childStart.key} ${childStart.value} follows parent ${parentClose.key} ${parentClose.value}.`,\n evidence: [\n nodeEvidence(record, `outcome.metrics.${childStart.key}`, childStart.value),\n nodeEvidence(parent, `outcome.metrics.${parentClose.key}`, parentClose.value),\n ],\n recommendedAction:\n 'Correct the causal timestamps or attach the child to its actual spawner.',\n }),\n )\n }\n }\n\n for (const record of unique) {\n const start = metric(record, ['spawned_at', 'started_at'])\n const close = metric(record, ['settled_at', 'completed_at', 'finished_at'])\n if (start === null || close === null || close.value >= start.value) continue\n out.push(\n issue({\n code: 'close-before-start',\n area: 'control-integrity',\n severity: 'high',\n subject: record.id,\n claim: 'An invocation is timestamped as closing before it started',\n detail: `${start.key} is ${start.value} and ${close.key} is ${close.value}.`,\n evidence: [\n nodeEvidence(record, `outcome.metrics.${start.key}`, start.value),\n nodeEvidence(record, `outcome.metrics.${close.key}`, close.value),\n ],\n recommendedAction: 'Correct the event ordering or retain clock-domain metadata.',\n }),\n )\n }\n\n const emittedCycles = new Set<string>()\n const resolved = new Set<string>()\n for (const start of unique) {\n if (resolved.has(start.id)) continue\n const path: string[] = []\n const positions = new Map<string, number>()\n let current: string | null = start.id\n while (current !== null) {\n if (resolved.has(current)) break\n const position = positions.get(current)\n if (position !== undefined) {\n const cycle = path.slice(position)\n const key = [...cycle].sort().join('\\u0000')\n if (!emittedCycles.has(key)) {\n emittedCycles.add(key)\n out.push(\n issue({\n code: 'parent-cycle',\n area: 'control-integrity',\n severity: 'critical',\n subject: [...cycle].sort()[0] ?? 'cycle',\n claim: 'The supervisor tree contains a parent cycle',\n detail: `${cycle.join(' -> ')} -> ${cycle[0]}`,\n evidence: cycle.slice(0, MAX_EXAMPLES).flatMap((id) => {\n const rows = byId.get(id)\n const record = rows?.length === 1 ? rows[0] : undefined\n return record === undefined\n ? []\n : [nodeEvidence(record, 'parent_rollout_id', record.parent)]\n }),\n recommendedAction:\n 'Correct parent ids at ingestion; a cyclic graph is not a run tree.',\n }),\n )\n }\n break\n }\n positions.set(current, path.length)\n path.push(current)\n const rows = byId.get(current)\n if (rows?.length !== 1) break\n const parent = rows[0]?.parent\n if (parent === undefined) break\n current = parent\n }\n for (const id of path) resolved.add(id)\n }\n\n if (root?.completed === true) {\n const missingTerminal = unique.filter(\n (record) => record.id !== root?.id && record.terminal === false,\n )\n if (missingTerminal.length > 0) {\n out.push(\n issue({\n code: 'child-terminal-unavailable',\n area: 'capture-integrity',\n severity: 'high',\n subject: 'child-terminal-outcomes',\n claim: 'A completed supervisor run has children with no captured terminal outcome',\n detail: `${missingTerminal.length}/${Math.max(0, unique.length - 1)} child node(s) are neither completed, truncated, nor errored.`,\n evidence: [\n evidence('children/missing-terminal/count', missingTerminal.length),\n ...missingTerminal\n .slice(0, MAX_EXAMPLES)\n .map((record) => nodeEvidence(record, 'outcome', record.raw.outcome)),\n ],\n recommendedAction: 'Retain each child settlement or cancellation event.',\n metadata: { assessment: 'unavailable', unavailable_count: missingTerminal.length },\n }),\n )\n }\n }\n\n const missingTranscripts = records.filter((record) => record.messages?.length === 0)\n if (missingTranscripts.length > 0) {\n out.push(\n issue({\n code: 'transcript-unavailable',\n area: 'capture-integrity',\n severity: 'medium',\n subject: 'decision-transcripts',\n claim: 'Decision transcripts are unavailable for some supervisor-tree invocations',\n detail: `${missingTranscripts.length}/${records.length} node row(s) have messages: [].`,\n evidence: [\n evidence('capture/missing-transcripts/count', missingTranscripts.length),\n ...missingTranscripts\n .slice(0, MAX_EXAMPLES)\n .map((record) => nodeEvidence(record, 'messages', [])),\n ],\n recommendedAction: 'Hydrate canonical messages from the retained session transcript.',\n metadata: { assessment: 'unavailable', unavailable_count: missingTranscripts.length },\n }),\n )\n }\n\n const missingProfiles = records.filter((record) => record.profileId === null)\n if (missingProfiles.length > 0) {\n out.push(\n issue({\n code: 'profile-id-unavailable',\n area: 'capture-integrity',\n severity: 'medium',\n subject: 'agent-profile-identity',\n claim:\n 'Canonical agent-profile identity is unavailable for some supervisor-tree invocations',\n detail: `${missingProfiles.length}/${records.length} node row(s) omit policy.agent_profile_cell_id.`,\n evidence: [\n evidence('capture/missing-agent-profile-cell-id/count', missingProfiles.length),\n ...missingProfiles\n .slice(0, MAX_EXAMPLES)\n .map((record) => nodeEvidence(record, 'policy.agent_profile_cell_id', null)),\n ],\n recommendedAction:\n 'Record policy.agent_profile_cell_id on every invocation at dispatch time.',\n metadata: { assessment: 'unavailable', unavailable_count: missingProfiles.length },\n }),\n )\n }\n\n return out\n}\n","import type { SupervisorRunTree } from './types'\n\nexport const SUPERVISOR_RUN_INTEGRITY_SCHEMA = 'tangle.supervisor-run-integrity@1'\n\nexport type SupervisorRunIntegritySeverity = 'critical' | 'high' | 'medium' | 'low' | 'info'\n\nexport type SupervisorRunSourceOnlyCheckCode =\n | 'journal-event-cardinality'\n | 'worker-control-join'\n | 'steer-ack-correlation'\n\nexport type SupervisorRunIntegrityIssueCode =\n | 'source-checks-unavailable'\n | 'node-schema-invalid'\n | 'node-checks-unavailable'\n | 'root-unavailable'\n | 'duplicate-rollout-id'\n | 'declared-root-missing'\n | 'root-has-parent'\n | 'root-role-invalid'\n | 'detached-node'\n | 'parent-missing'\n | 'cross-run-parent'\n | 'child-before-parent'\n | 'child-after-parent-close'\n | 'close-before-start'\n | 'parent-cycle'\n | 'child-terminal-unavailable'\n | 'transcript-unavailable'\n | 'profile-id-unavailable'\n | 'source-row-malformed'\n | 'source-event-identity-unavailable'\n | 'duplicate-spawn'\n | 'orphan-terminal'\n | 'duplicate-terminal'\n | 'worker-controls-unavailable'\n | 'worker-control-join-unavailable'\n | 'steer-request-id-unavailable'\n | 'steer-ack-id-unavailable'\n | 'steer-ack-status-unavailable'\n | 'duplicate-steer-request-id'\n | 'missing-steer-ack'\n | 'duplicate-steer-ack'\n | 'unknown-steer-ack'\n | 'steer-not-delivered'\n\nexport interface SupervisorRunIntegrityEvidence {\n readonly path: string\n readonly value: unknown\n}\n\nexport interface SupervisorRunIntegrityIssue {\n readonly code: SupervisorRunIntegrityIssueCode\n readonly area: 'control-integrity' | 'capture-integrity'\n readonly severity: SupervisorRunIntegritySeverity\n readonly subject: string\n readonly claim: string\n readonly detail: string\n readonly evidence: readonly SupervisorRunIntegrityEvidence[]\n readonly recommendedAction: string\n readonly metadata?: Readonly<Record<string, unknown>>\n}\n\nexport interface SupervisorRunIntegrityReport {\n readonly schema: typeof SUPERVISOR_RUN_INTEGRITY_SCHEMA\n readonly runRef: string\n readonly input: 'sources' | 'tree'\n readonly tree: SupervisorRunTree\n readonly issues: readonly SupervisorRunIntegrityIssue[]\n}\n\nexport interface SupervisorRunIntegrityOptions {\n /** Pins rollout provenance when source input must be projected into a tree. */\n readonly capturedAt?: string\n}\n","import type { SupervisorRunNodeRole, SupervisorRunSources } from './types'\n\n// ---------------------------------------------------------------------------\n// Journal shapes — structurally parsed. The journal is the contract, not the type.\n// ---------------------------------------------------------------------------\n\ninterface JournalEvent {\n kind?: unknown\n id?: unknown\n parent?: unknown\n label?: unknown\n role?: unknown\n status?: unknown\n verdict?: unknown\n reason?: unknown\n seq?: unknown\n at?: unknown\n spend?: unknown\n spent?: unknown\n}\n\ninterface Tokens {\n input: number\n output: number\n cacheRead: number\n cacheWrite: number\n /** False when the event carried no cache counters at all — not \"zero cached\". */\n hasCache: boolean\n}\n\ninterface SpendLike {\n tokens: Tokens\n usd: number\n}\n\nexport function asRecord(v: unknown): Record<string, unknown> {\n return typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : {}\n}\n\nfunction num(v: unknown): number {\n return typeof v === 'number' && Number.isFinite(v) ? v : 0\n}\n\nfunction readSpend(v: unknown): SpendLike {\n const rec = asRecord(v)\n const tok = asRecord(rec.tokens)\n const cacheRead = tok.cacheRead ?? tok.cache_read\n const cacheWrite = tok.cacheWrite ?? tok.cache_write\n return {\n tokens: {\n input: num(tok.input),\n output: num(tok.output),\n cacheRead: num(cacheRead),\n cacheWrite: num(cacheWrite),\n hasCache: cacheRead !== undefined || cacheWrite !== undefined,\n },\n usd: num(rec.usd),\n }\n}\n\nexport function parseJsonl(text: string | null): Record<string, unknown>[] {\n return parseJsonlWithDiagnostics(text).rows\n}\n\ninterface ParsedJsonl {\n readonly rows: Record<string, unknown>[]\n readonly invalidRows: number\n}\n\nfunction parseJsonlWithDiagnostics(text: string | null): ParsedJsonl {\n if (text === null) return { rows: [], invalidRows: 0 }\n const out: Record<string, unknown>[] = []\n let invalidRows = 0\n for (const line of text.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n const parsed: unknown = JSON.parse(trimmed)\n if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n out.push(parsed as Record<string, unknown>)\n } else {\n invalidRows += 1\n }\n } catch {\n invalidRows += 1\n }\n }\n return { rows: out, invalidRows }\n}\n\nexport function parseJson(text: string | null): Record<string, unknown> | null {\n if (text === null) return null\n try {\n const parsed: unknown = JSON.parse(text)\n return typeof parsed === 'object' && parsed !== null\n ? (parsed as Record<string, unknown>)\n : null\n } catch {\n return null\n }\n}\n\nfunction ms(at: unknown): number | null {\n if (typeof at !== 'string') return null\n const t = Date.parse(at)\n return Number.isFinite(t) ? t : null\n}\n\n// ---------------------------------------------------------------------------\n// The supervision tree, as parsed from the journal event stream.\n// ---------------------------------------------------------------------------\n\nexport interface SpawnRow {\n /** Zero-based row among parsed journal objects. */\n sourceRow: number\n id: string\n parent: string | null\n label: string\n role: SupervisorRunNodeRole\n at: number | null\n /** False when identity, parentage, label, or role was malformed. */\n valid: boolean\n invalidFields: readonly string[]\n}\n\nexport interface CloseRow {\n id: string\n kind: 'settled' | 'cancelled'\n status: string | null\n /** String verdict from legacy journals, or valid/invalid for a structured verdict. */\n verdict: string | null\n /** Structured verdict validity, when recorded. */\n valid: boolean | null\n /** Structured verdict score, preserved without boolean coercion. */\n score: number | null\n /** The verdict exactly as the journal carried it. */\n rawVerdict: unknown | null\n at: number | null\n spend: SpendLike\n /** False when the close event carried no spend object — not \"spent nothing\". */\n hasSpend: boolean\n}\n\nexport interface WorkerLogFacts {\n /** Position in `SupervisorRunSources.workers`, retained for exact evidence paths. */\n sourceIndex: number\n workerId: string | null\n label: string\n /** `false` means the artifact was missing; a captured empty artifact is `true`. */\n inboxCaptured: boolean\n eventsCaptured: boolean\n inboxInvalidRows: number\n eventsInvalidRows: number\n started: number | null\n /** True once a `finished` event was seen — independent of whether its `at` parsed. */\n finished: boolean\n finishedAt: number | null\n passed: boolean | null\n /** Numeric score exactly as the finished event recorded it. */\n score: number | null\n /** `patchBytes` as reported by the finished event (not the patch file's size). */\n finishedPatchBytes: number | null\n evidenceBytes: number\n /** Unique queued request ids, or null when exact accounting is unavailable. */\n steersQueued: number | null\n /** Unique matched request ids acknowledged as delivered, or null when unavailable. */\n steersDelivered: number | null\n steersQueuedUnavailable: string | null\n steersDeliveredUnavailable: string | null\n questions: number\n steerRequests: SteerRequestFact[]\n steerAcknowledgements: SteerAcknowledgementFact[]\n}\n\nexport interface SteerRequestFact {\n /** Durable inbox request id; null when the row did not retain one. */\n requestId: string | null\n row: number\n}\n\nexport interface SteerAcknowledgementFact {\n /** Worker event request id; null when the event cannot be correlated. */\n requestId: string | null\n /** `null` means the acknowledgement omitted delivery status. */\n delivered: boolean | null\n row: number\n}\n\n/**\n * The tree + timeline the report is computed from, exposed because the rollout-row\n * minter needs exactly the same parse (one parser, two consumers).\n */\nexport interface SupervisorTreeFacts {\n readonly rootId: string | null\n readonly spawns: readonly SpawnRow[]\n readonly closes: readonly CloseRow[]\n readonly workerSpawns: readonly SpawnRow[]\n readonly workerCloses: readonly CloseRow[]\n readonly brain: {\n tokensIn: number\n tokensOut: number\n cacheRead: number\n cacheWrite: number\n /** False when no metered event carried cache counters — not \"nothing cached\". */\n hasCache: boolean\n usd: number\n meteredCount: number\n }\n readonly workerLogs: ReadonlyMap<string, WorkerLogFacts>\n /** Every worker source row, including duplicate identities that a map cannot retain. */\n readonly workerLogRows: readonly WorkerLogFacts[]\n /** Every non-empty journal line, whatever shape it turned out to have. */\n readonly journalRows: number\n /**\n * Journal lines this parser could not interpret at all: invalid JSON, non-objects, and\n * JSON objects carrying no record shape it recognizes.\n *\n * This count is what separates \"the run was empty\" from \"the input was unreadable\".\n * Zero spawns with zero invalid rows is a positive claim that nothing happened; it must\n * only ever be made about bytes the parser actually understood.\n */\n readonly journalInvalidRows: number\n /** The `journalInvalidRows` subset that was not valid JSON, or not a JSON object. */\n readonly journalMalformedJsonRows: number\n /**\n * Records recognized but deliberately not folded into the tree, counted by kind — the\n * runtime envelope's `begin` header and the `waiting` / `woken` wait-node events. Kept\n * separate from `journalInvalidRows` because these rows were understood, not rejected.\n */\n readonly journalIgnoredRowsByKind: Readonly<Record<string, number>>\n /** Which dialect(s) the journal's rows were actually written in. */\n readonly journalDialect: SupervisorJournalDialect\n /** Parsed once with the journal and worker artifacts. */\n readonly state: Record<string, unknown> | null\n readonly startedAt: number | null\n readonly completedAt: number | null\n}\n\ninterface VerdictFacts {\n label: string | null\n valid: boolean | null\n score: number | null\n raw: unknown | null\n}\n\nfunction readVerdict(v: unknown): VerdictFacts {\n if (typeof v === 'string') return { label: v, valid: null, score: null, raw: v }\n if (typeof v !== 'object' || v === null) {\n return { label: null, valid: null, score: null, raw: null }\n }\n const rec = v as Record<string, unknown>\n const valid = typeof rec.valid === 'boolean' ? rec.valid : null\n return {\n label: valid === null ? null : valid ? 'valid' : 'invalid',\n valid,\n score: typeof rec.score === 'number' && Number.isFinite(rec.score) ? rec.score : null,\n raw: v,\n }\n}\n\nexport function workerSourceKey(\n worker: NonNullable<SupervisorRunSources['workers']>[number],\n): string {\n return worker.workerId ?? worker.label\n}\n\n// ---------------------------------------------------------------------------\n// Journal dialects — the two shapes a supervision journal is actually written in.\n// ---------------------------------------------------------------------------\n\n/**\n * How a journal's rows were shaped on disk.\n *\n * `flat` — one event object per line (`{kind:'spawned', id, ...}`). The loops\n * supervisor writes this, and `readClaudeCodeSupervisorRun` synthesizes it.\n *\n * `runtime-envelope` — the records `agent-runtime`'s `FileSpawnJournal` writes:\n * a `{kind:'begin', root, at}` header followed by `{kind:'event', root, event}`\n * envelopes (`agent-runtime/src/durable/spawn-journal.ts`, `appendRecord`). It is\n * the layout `createFileRunContext(dir)` produces at `<dir>/spawn-journal.jsonl`.\n * This dialect is READ, not tolerated: agent-runtime is the writer, so a reader\n * that could not interpret it was the defect, and `journalDialect` records which\n * shape the bytes actually had so an unexpected one is never invisible.\n *\n * `mixed` — rows of both shapes in one file. `none` — no interpretable row at all.\n */\nexport type SupervisorJournalDialect = 'none' | 'flat' | 'runtime-envelope' | 'mixed'\n\ntype JournalRowDialect = 'flat' | 'runtime-envelope'\n\n/** Event kinds this parser folds into the tree. */\nconst TREE_EVENT_KINDS = ['spawned', 'settled', 'cancelled', 'metered'] as const\ntype TreeEventKind = (typeof TREE_EVENT_KINDS)[number]\n\n/**\n * Event kinds `agent-runtime` journals that this parser recognizes but does not model as\n * tree nodes: `waiting` arms a wait node and `woken` settles it. They are counted by kind\n * rather than dropped, so \"understood, not modeled\" can never be mistaken for \"absent\".\n */\nconst UNMODELLED_EVENT_KINDS: readonly string[] = ['waiting', 'woken']\n\nfunction treeEventKind(value: unknown): TreeEventKind | null {\n return (TREE_EVENT_KINDS as readonly unknown[]).includes(value) ? (value as TreeEventKind) : null\n}\n\ntype JournalRowReading =\n | {\n outcome: 'event'\n dialect: JournalRowDialect\n kind: TreeEventKind\n event: JournalEvent\n }\n | { outcome: 'ignored'; dialect: JournalRowDialect; kind: string }\n | { outcome: 'unreadable' }\n\n/**\n * Classify one parsed journal row. Every row lands in exactly one outcome — interpreted,\n * recognized-but-not-modeled, or unreadable — because a row that falls through silently is\n * how a run with events reads as a run with none.\n */\nfunction readJournalRow(row: Record<string, unknown>): JournalRowReading {\n const kind = row.kind\n if (typeof kind !== 'string') return { outcome: 'unreadable' }\n\n // agent-runtime's FileSpawnJournal record header. It carries no event.\n if (kind === 'begin' && typeof row.root === 'string') {\n return { outcome: 'ignored', dialect: 'runtime-envelope', kind: 'begin' }\n }\n if (kind === 'event') {\n const inner = row.event\n if (typeof inner !== 'object' || inner === null || Array.isArray(inner)) {\n return { outcome: 'unreadable' }\n }\n const innerKind = (inner as Record<string, unknown>).kind\n if (typeof innerKind !== 'string') return { outcome: 'unreadable' }\n const tree = treeEventKind(innerKind)\n if (tree !== null) {\n return {\n outcome: 'event',\n dialect: 'runtime-envelope',\n kind: tree,\n event: inner as JournalEvent,\n }\n }\n // The envelope proves this IS a journaled event, so an unmodelled kind is recorded by\n // name rather than called unreadable — the caller sees exactly what went uncounted.\n return { outcome: 'ignored', dialect: 'runtime-envelope', kind: innerKind }\n }\n\n const tree = treeEventKind(kind)\n if (tree !== null) {\n return { outcome: 'event', dialect: 'flat', kind: tree, event: row as JournalEvent }\n }\n if (UNMODELLED_EVENT_KINDS.includes(kind)) {\n return { outcome: 'ignored', dialect: 'flat', kind }\n }\n // A bare object with an unknown `kind` could be any record at all — unlike the envelope\n // case there is no evidence it is a journal event, so it counts as unreadable (fail closed).\n return { outcome: 'unreadable' }\n}\n\nfunction summarizeDialect(seen: ReadonlySet<JournalRowDialect>): SupervisorJournalDialect {\n if (seen.size === 0) return 'none'\n if (seen.size > 1) return 'mixed'\n return seen.has('runtime-envelope') ? 'runtime-envelope' : 'flat'\n}\n\nexport function parseSupervisorTree(src: SupervisorRunSources): SupervisorTreeFacts {\n const parsedJournal = parseJsonlWithDiagnostics(src.journal)\n const events = parsedJournal.rows\n const state = parseJson(src.state)\n\n const spawns: SpawnRow[] = []\n const closes: CloseRow[] = []\n let brainIn = 0\n let brainOut = 0\n let brainCacheRead = 0\n let brainCacheWrite = 0\n let brainHasCache = false\n let brainUsd = 0\n let meteredCount = 0\n let rootId: string | null = null\n let unreadableRows = 0\n const ignoredByKind = new Map<string, number>()\n const dialectsSeen = new Set<JournalRowDialect>()\n for (const [sourceRow, row] of events.entries()) {\n const reading = readJournalRow(row)\n if (reading.outcome === 'unreadable') {\n unreadableRows += 1\n continue\n }\n dialectsSeen.add(reading.dialect)\n if (reading.outcome === 'ignored') {\n ignoredByKind.set(reading.kind, (ignoredByKind.get(reading.kind) ?? 0) + 1)\n continue\n }\n const { kind, event: ev } = reading\n const id = typeof ev.id === 'string' ? ev.id : ''\n if (kind === 'spawned') {\n const parent = typeof ev.parent === 'string' && ev.parent.length > 0 ? ev.parent : null\n const label = typeof ev.label === 'string' ? ev.label : ''\n const invalidFields: string[] = []\n if (id.length === 0) invalidFields.push('id')\n const parentOmittedForFirstRoot = ev.parent === undefined && rootId === null\n if (\n ev.parent !== null &&\n !parentOmittedForFirstRoot &&\n !(typeof ev.parent === 'string' && ev.parent.length > 0)\n ) {\n invalidFields.push('parent')\n }\n if (label.length === 0) invalidFields.push('label')\n if (ev.role !== undefined && ev.role !== 'supervisor' && ev.role !== 'worker') {\n invalidFields.push('role')\n }\n const role: SupervisorRunNodeRole =\n ev.role === 'supervisor' || ev.role === 'worker'\n ? ev.role\n : parent === null\n ? 'supervisor'\n : 'worker'\n const valid = invalidFields.length === 0\n if (valid && parent === null && rootId === null) rootId = id\n spawns.push({\n sourceRow,\n id,\n parent,\n label,\n role,\n at: ms(ev.at),\n valid,\n invalidFields,\n })\n } else if (kind === 'settled') {\n const verdict = readVerdict(ev.verdict)\n closes.push({\n id,\n kind: 'settled',\n status: typeof ev.status === 'string' ? ev.status : null,\n verdict: verdict.label,\n valid: verdict.valid,\n score: verdict.score,\n rawVerdict: verdict.raw,\n at: ms(ev.at),\n spend: readSpend(ev.spent),\n hasSpend: asRecord(ev.spent).tokens !== undefined,\n })\n } else if (kind === 'cancelled') {\n closes.push({\n id,\n kind: 'cancelled',\n status: 'cancelled',\n verdict: typeof ev.reason === 'string' ? ev.reason : null,\n valid: null,\n score: null,\n rawVerdict: typeof ev.reason === 'string' ? ev.reason : null,\n at: ms(ev.at),\n spend: {\n tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, hasCache: false },\n usd: 0,\n },\n hasSpend: false,\n })\n } else if (kind === 'metered') {\n const s = readSpend(ev.spend)\n brainIn += s.tokens.input\n brainOut += s.tokens.output\n brainCacheRead += s.tokens.cacheRead\n brainCacheWrite += s.tokens.cacheWrite\n brainHasCache = brainHasCache || s.tokens.hasCache\n brainUsd += s.usd\n meteredCount += 1\n } else {\n // `TREE_EVENT_KINDS` and these branches are one contract: adding a kind to the set\n // without a branch here would silently drop its rows, which is the defect this\n // accounting exists to prevent. The compiler refuses the omission.\n const unhandled: never = kind\n throw new Error(`unhandled journal event kind ${JSON.stringify(unhandled)}`)\n }\n }\n\n const workerSpawns = spawns.filter((s) => s.valid && s.id !== rootId)\n const workerIds = new Set(workerSpawns.map((s) => s.id))\n const workerCloses = closes.filter((c) => workerIds.has(c.id))\n\n const workerLogs = new Map<string, WorkerLogFacts>()\n const workerLogRows: WorkerLogFacts[] = []\n for (const [sourceIndex, w] of (src.workers ?? []).entries()) {\n const facts: WorkerLogFacts = {\n sourceIndex,\n workerId: w.workerId ?? null,\n label: w.label,\n inboxCaptured: w.inbox !== null,\n eventsCaptured: w.events !== null,\n inboxInvalidRows: 0,\n eventsInvalidRows: 0,\n started: null,\n finished: false,\n finishedAt: null,\n passed: null,\n score: null,\n finishedPatchBytes: null,\n evidenceBytes: 0,\n steersQueued: null,\n steersDelivered: null,\n steersQueuedUnavailable: null,\n steersDeliveredUnavailable: null,\n questions: 0,\n steerRequests: [],\n steerAcknowledgements: [],\n }\n const parsedInbox = parseJsonlWithDiagnostics(w.inbox)\n const parsedEvents = parseJsonlWithDiagnostics(w.events)\n facts.inboxInvalidRows = parsedInbox.invalidRows\n facts.eventsInvalidRows = parsedEvents.invalidRows\n for (const [row, req] of parsedInbox.rows.entries()) {\n if (typeof req.message !== 'string' || req.message.trim().length === 0) continue\n facts.steerRequests.push({\n requestId: typeof req.id === 'string' && req.id.length > 0 ? req.id : null,\n row,\n })\n }\n for (const [row, ev] of parsedEvents.rows.entries()) {\n const kind = ev.kind\n if (kind === 'message') {\n if (ev.direction === 'up') {\n facts.questions += 1\n continue\n }\n facts.steerAcknowledgements.push({\n requestId:\n typeof ev.requestId === 'string' && ev.requestId.length > 0 ? ev.requestId : null,\n delivered: typeof ev.delivered === 'boolean' ? ev.delivered : null,\n row,\n })\n } else if (kind === 'started') {\n facts.started = ms(ev.at)\n } else if (kind === 'finished') {\n facts.finished = true\n facts.finishedAt = ms(ev.at)\n facts.passed = typeof ev.passed === 'boolean' ? ev.passed : null\n facts.score = typeof ev.score === 'number' && Number.isFinite(ev.score) ? ev.score : null\n facts.finishedPatchBytes = typeof ev.patchBytes === 'number' ? ev.patchBytes : null\n facts.evidenceBytes = typeof ev.evidence === 'string' ? ev.evidence.length : 0\n }\n }\n const requestsById = new Map<string, number>()\n for (const request of facts.steerRequests) {\n if (request.requestId === null) continue\n requestsById.set(request.requestId, (requestsById.get(request.requestId) ?? 0) + 1)\n }\n const acknowledgementsById = new Map<string, SteerAcknowledgementFact[]>()\n for (const acknowledgement of facts.steerAcknowledgements) {\n if (acknowledgement.requestId === null) continue\n const matches = acknowledgementsById.get(acknowledgement.requestId) ?? []\n matches.push(acknowledgement)\n acknowledgementsById.set(acknowledgement.requestId, matches)\n }\n const queueProblems: string[] = []\n if (!facts.inboxCaptured) queueProblems.push('inbox absent')\n if (!facts.eventsCaptured) queueProblems.push('events absent')\n if (facts.inboxInvalidRows > 0) queueProblems.push('inbox contains malformed rows')\n if (facts.eventsInvalidRows > 0) queueProblems.push('events contain malformed rows')\n if (facts.steerRequests.some((request) => request.requestId === null)) {\n queueProblems.push('queued request id missing')\n }\n if ([...requestsById.values()].some((count) => count > 1)) {\n queueProblems.push('queued request id duplicated')\n }\n if (facts.steerAcknowledgements.some((acknowledgement) => acknowledgement.requestId === null)) {\n queueProblems.push('acknowledgement request id missing')\n }\n if ([...acknowledgementsById.keys()].some((id) => !requestsById.has(id))) {\n queueProblems.push('acknowledgement has no queued request')\n }\n if (queueProblems.length === 0) {\n facts.steersQueued = requestsById.size\n } else {\n facts.steersQueuedUnavailable = [...new Set(queueProblems)].join('; ')\n }\n\n const deliveryProblems = [...queueProblems]\n if ([...acknowledgementsById.values()].some((rows) => rows.length > 1)) {\n deliveryProblems.push('acknowledgement request id duplicated')\n }\n if (facts.steerAcknowledgements.some((acknowledgement) => acknowledgement.delivered === null)) {\n deliveryProblems.push('acknowledgement delivery status missing')\n }\n if (deliveryProblems.length === 0) {\n facts.steersDelivered = [...requestsById.keys()].filter((id) => {\n const acknowledgement = acknowledgementsById.get(id)\n return acknowledgement?.length === 1 && acknowledgement[0]?.delivered === true\n }).length\n } else {\n facts.steersDeliveredUnavailable = [...new Set(deliveryProblems)].join('; ')\n }\n workerLogRows.push(facts)\n workerLogs.set(workerSourceKey(w), facts)\n }\n\n const startedAt = ms(state?.startedAt) ?? spawns[0]?.at ?? null\n const completedAt =\n ms(state?.completedAt) ??\n [...spawns.map((s) => s.at), ...closes.map((c) => c.at)].reduce<number | null>(\n (acc, t) => (t === null ? acc : acc === null ? t : Math.max(acc, t)),\n null,\n )\n\n return {\n rootId,\n spawns,\n closes,\n workerSpawns,\n workerCloses,\n brain: {\n tokensIn: brainIn,\n tokensOut: brainOut,\n cacheRead: brainCacheRead,\n cacheWrite: brainCacheWrite,\n hasCache: brainHasCache,\n usd: brainUsd,\n meteredCount,\n },\n workerLogs,\n workerLogRows,\n journalRows: events.length + parsedJournal.invalidRows,\n journalInvalidRows: parsedJournal.invalidRows + unreadableRows,\n journalMalformedJsonRows: parsedJournal.invalidRows,\n journalIgnoredRowsByKind: Object.fromEntries(ignoredByKind),\n journalDialect: summarizeDialect(dialectsSeen),\n state,\n startedAt,\n completedAt,\n }\n}\n","/**\n * The supervision tree as `tangle.rollout.v1` rows.\n *\n * A supervisor run IS a tree of rollouts, so its nodes are not a new shape:\n * the root becomes one `RolloutLine` with `role: 'supervisor'`, and every\n * spawned invocation keeps its explicit supervisor/worker role with\n * `parent_rollout_id` pointing at its spawner. The rows append to the same\n * ledger as solo-agent rollouts and join to them with the same keys.\n *\n * What the journal CANNOT supply is the transcript: a worker's messages live\n * in its harness store (opencode sqlite, Claude Code jsonl), which the\n * `src/rollout/readers/*` intake readers own. Rows minted here are therefore\n * GAP lines (`messages: []`, `provenance.gap` set) carrying identity,\n * structure, outcome and cost; hydrating them with messages is the readers'\n * job, keyed on `artifacts.transcript_ref`.\n *\n * Timing lives in `outcome.metrics` (`spawned_at` / `settled_at` / `wall_ms`)\n * rather than a schema field: `tangle.rollout.v1` describes ONE invocation,\n * and the inter-invocation event timeline — which is what waves, concurrency,\n * idle and utilization are computed from — is a property of the journal, not\n * of any single row. The analyzer reads that timeline; these rows carry the\n * per-node facts.\n */\n\nimport { unscreenedRewardFields } from '../rollout/reward'\nimport {\n isRolloutLine,\n ROLLOUT_SCHEMA,\n type RolloutLine,\n type RolloutSplit,\n} from '../rollout/schema'\nimport { asRecord, parseJson, parseSupervisorTree, type SupervisorTreeFacts } from './source-facts'\nimport type {\n SupervisorRunSources,\n SupervisorRunTree,\n SupervisorRunTreeGap,\n WorkerLogSource,\n} from './types'\n\nexport interface SupervisorRolloutOptions {\n /** Benchmark/suite id for `task.suite`. Defaults to `'supervisor-run'`. */\n readonly suite?: string\n /** `task.split`. Defaults to `'search'` (the trainable pool). */\n readonly split?: RolloutSplit\n /** Replicate index. Defaults to 0. */\n readonly rep?: number\n /** Sampling seed the campaign pinned. Defaults to null (not recorded). */\n readonly seed?: number | null\n /** `run_id` for every node. Defaults to the supervisor root id, else `runRef`. */\n readonly runId?: string\n /** Harness that drove the supervisor. */\n readonly supervisorHarness?: string | null\n /** Harness that drove the workers. */\n readonly workerHarness?: string | null\n /** Model the supervisor ran on. */\n readonly supervisorModel?: string | null\n /** Model the workers ran on. */\n readonly workerModel?: string | null\n readonly experimentId?: string | null\n readonly candidateId?: string | null\n readonly generation?: number | null\n readonly candidateIndex?: number | null\n /** Pins `provenance.captured_at`; defaults to now. */\n readonly capturedAt?: string\n}\n\nconst EMPTY_COST = {\n usd: null,\n tokens_in: null,\n tokens_out: null,\n tokens_reasoning: null,\n cache_read: null,\n cache_write: null,\n wall_s: null,\n} as const\n\nfunction hasWorkerId(\n worker: WorkerLogSource,\n): worker is WorkerLogSource & { readonly workerId: string } {\n return worker.workerId !== undefined\n}\n\n/**\n * Mint the supervision tree as rollout rows. Returns the rows plus the gaps\n * that made any of them incomplete — same unavailable-vs-zero discipline as\n * the report: a row with no transcript says WHY, it never pretends to be empty.\n */\nexport function supervisorRunRolloutLines(\n src: SupervisorRunSources,\n opts: SupervisorRolloutOptions = {},\n): SupervisorRunTree {\n return supervisorRunRolloutLinesFromFacts(src, parseSupervisorTree(src), opts)\n}\n\n/** Mint rollout rows from an already parsed source without reading its JSONL again. */\nexport function supervisorRunRolloutLinesFromFacts(\n src: SupervisorRunSources,\n tree: SupervisorTreeFacts,\n opts: SupervisorRolloutOptions = {},\n): SupervisorRunTree {\n const gaps: SupervisorRunTreeGap[] = []\n if (src.journal === null) {\n gaps.push({\n code: 'journal-unavailable',\n message: `${src.supRunDir === null ? 'no supervisor run dir' : 'journal absent'}; no nodes recoverable`,\n })\n return { rootId: null, nodes: [], gaps }\n }\n // `journalInvalidRows` covers rows the parser could not interpret at all, including JSON\n // objects in a shape it does not recognize — so a journal it read but understood none of\n // reports an explicit gap instead of an empty tree.\n const malformedSourceRows =\n tree.journalInvalidRows + tree.spawns.filter((spawn) => !spawn.valid).length\n if (malformedSourceRows > 0) {\n gaps.push({\n code: 'source-row-malformed',\n message: `${malformedSourceRows} of ${tree.journalRows} journal row(s) were unusable and excluded from the tree`,\n count: malformedSourceRows,\n })\n }\n\n const state = tree.state\n const result = parseJson(src.result)\n const judge = parseJson(src.judge)\n const stateResult = asRecord(state?.result)\n\n const rootId = tree.rootId\n const runId = opts.runId ?? rootId ?? src.runRef\n const suite = opts.suite ?? 'supervisor-run'\n const instanceId = src.instanceId ?? src.runRef\n const split: RolloutSplit = opts.split ?? 'search'\n const capturedAt = opts.capturedAt ?? new Date().toISOString()\n\n const base = {\n schema: ROLLOUT_SCHEMA,\n run_id: runId,\n experiment_id: opts.experimentId ?? null,\n candidate_id: opts.candidateId ?? null,\n generation: opts.generation ?? null,\n candidate_index: opts.candidateIndex ?? null,\n task: {\n suite,\n instance_id: instanceId,\n split,\n seed: opts.seed ?? null,\n rep: opts.rep ?? 0,\n },\n messages: [] as RolloutLine['messages'],\n tool_defs: [] as RolloutLine['tool_defs'],\n } satisfies Partial<RolloutLine> & Record<string, unknown>\n\n const nodes: RolloutLine[] = []\n\n // ── root: the supervisor invocation ────────────────────────────────────\n if (rootId !== null) {\n const rootSpawn = tree.spawns.find((spawn) => spawn.valid && spawn.id === rootId)\n const judgeResolved = typeof judge?.resolved === 'boolean' ? judge.resolved : null\n const judgeScore = typeof judge?.score === 'number' ? judge.score : null\n const reward = judgeScore ?? (judgeResolved === null ? null : judgeResolved ? 1 : 0)\n if (reward === null) {\n gaps.push({\n code: 'root-reward-unavailable',\n message: 'no judge verdict for this run',\n nodeId: rootId,\n })\n }\n const wallMs =\n tree.startedAt !== null && tree.completedAt !== null && tree.completedAt >= tree.startedAt\n ? tree.completedAt - tree.startedAt\n : null\n nodes.push({\n ...base,\n rollout_id: rootId,\n parent_rollout_id: null,\n role: rootSpawn?.role ?? 'supervisor',\n policy: {\n harness: opts.supervisorHarness ?? null,\n harness_version: null,\n model: opts.supervisorModel ?? null,\n provider: null,\n profile_commit: null,\n sampling: null,\n },\n outcome: {\n // `reward` and `realness_gated` are written by one call, in the module\n // that owns the gate. This is the SECOND producer of rollout rewards —\n // the judge verdict in the supervision run dir, not `mintRolloutRows` —\n // and it wrote `reward` by hand while never stating the flag, so\n // `isLineRealnessGated` was structurally false for every supervisor and\n // worker row ever emitted here. `unscreenedRewardFields` is the honest\n // name for what this producer can claim: a supervision journal carries\n // no `RunRecord.outcome.realness`, so no authenticity gate has run on\n // this score, and `realness_gated: false` states that rather than\n // implying it by omission. These rows stay plain `RolloutLine`s, so a\n // caller feeding them to a training exporter must `assertMinted` first.\n ...unscreenedRewardFields(reward),\n reward_source: src.judgeSource,\n verdict: judge ?? null,\n metrics: {\n arm: src.arm,\n sup_status: typeof state?.status === 'string' ? state.status : null,\n sup_verdict: typeof state?.verdict === 'string' ? state.verdict : null,\n delivered: typeof stateResult.delivered === 'boolean' ? stateResult.delivered : null,\n verify_pass: typeof result?.verify_pass === 'boolean' ? result.verify_pass : null,\n started_at: tree.startedAt,\n completed_at: tree.completedAt,\n workers_spawned: tree.workerSpawns.length,\n brain_metered_events: tree.brain.meteredCount,\n },\n is_completed: state?.status === 'completed',\n is_truncated: false,\n error: null,\n realness_gated: false,\n },\n cost: {\n ...EMPTY_COST,\n usd:\n src.limits.spendUsd !== null\n ? null\n : typeof stateResult.spentUsd === 'number'\n ? stateResult.spentUsd\n : tree.brain.usd,\n tokens_in: src.limits.managerTokens === null ? tree.brain.tokensIn : null,\n tokens_out: src.limits.managerTokens === null ? tree.brain.tokensOut : null,\n cache_read:\n src.limits.managerTokens === null && tree.brain.hasCache ? tree.brain.cacheRead : null,\n cache_write:\n src.limits.managerTokens === null && tree.brain.hasCache ? tree.brain.cacheWrite : null,\n wall_s: wallMs === null ? null : wallMs / 1000,\n },\n artifacts: {\n patch_path: typeof result?.patchPath === 'string' ? result.patchPath : null,\n run_dir: src.supRunDir,\n transcript_ref:\n src.rootTranscriptRef !== undefined\n ? src.rootTranscriptRef\n : src.supRunDir === null\n ? null\n : `${src.supRunDir}/journal.jsonl`,\n },\n provenance: {\n captured_at: capturedAt,\n capture: 'backfill',\n gap: 'supervision journal carries structure and spend, not the brain transcript',\n },\n })\n } else {\n gaps.push({\n code: 'root-spawn-unavailable',\n message: 'no parentless spawned event in the journal',\n })\n }\n\n // ── workers: one node per spawn, keyed to its spawner ───────────────────\n const closeById = new Map(tree.closes.map((c) => [c.id, c]))\n const sourceById = new Map(\n (src.workers ?? []).filter(hasWorkerId).map((worker) => [worker.workerId, worker]),\n )\n const fallbackSourceByLabel = new Map(\n (src.workers ?? [])\n .filter((worker) => worker.workerId === undefined)\n .map((worker) => [worker.label, worker]),\n )\n // Stable ids are authoritative. Labels are a compatibility join for stores\n // that predate workerId and are only safe when the store keeps them unique.\n for (const spawn of tree.workerSpawns) {\n const close = closeById.get(spawn.id) ?? null\n const workerSource = sourceById.get(spawn.id) ?? fallbackSourceByLabel.get(spawn.label) ?? null\n const facts =\n tree.workerLogs.get(workerSource?.workerId ?? workerSource?.label ?? spawn.label) ?? null\n const wallMs =\n facts?.started != null && facts.finishedAt != null ? facts.finishedAt - facts.started : null\n const score = close?.score ?? facts?.score ?? null\n const passed = close?.valid ?? facts?.passed ?? null\n const reward = score ?? (passed === null ? null : passed ? 1 : 0)\n if (reward === null) {\n gaps.push({\n code: 'child-reward-unavailable',\n message: `child ${JSON.stringify(spawn.label)} has no verify verdict`,\n nodeId: spawn.id,\n })\n }\n const isSupervisor = spawn.role === 'supervisor'\n nodes.push({\n ...base,\n rollout_id: spawn.id,\n parent_rollout_id: spawn.parent,\n role: spawn.role,\n policy: {\n harness: isSupervisor ? (opts.supervisorHarness ?? null) : (opts.workerHarness ?? null),\n harness_version: null,\n model: isSupervisor ? (opts.supervisorModel ?? null) : (opts.workerModel ?? null),\n provider: null,\n profile_commit: null,\n sampling: null,\n },\n outcome: {\n // Same producer, same claim: a child reward is a self-verify verdict\n // from the journal that no realness gate has seen.\n ...unscreenedRewardFields(reward),\n reward_source:\n reward === null ? null : score === null ? 'worker-self-verify' : 'worker-verdict-score',\n verdict:\n close === null\n ? null\n : {\n kind: close.kind,\n status: close.status,\n verdict: close.rawVerdict,\n valid: close.valid,\n score: close.score,\n },\n metrics: {\n label: spawn.label,\n spawned_at: spawn.at,\n settled_at: close?.at ?? null,\n started_at: facts?.started ?? null,\n finished_at: facts?.finishedAt ?? null,\n wall_ms: wallMs,\n patch_bytes: workerSource?.patchBytes ?? facts?.finishedPatchBytes ?? null,\n evidence_bytes: facts?.evidenceBytes ?? null,\n steers_queued: facts?.steersQueued ?? null,\n steers_delivered: facts?.steersDelivered ?? null,\n questions: facts?.questions ?? null,\n },\n is_completed: close?.kind === 'settled',\n is_truncated: close?.kind === 'cancelled',\n error: close?.kind === 'cancelled' ? (close.verdict ?? 'cancelled') : null,\n realness_gated: false,\n },\n // `close.spend` is only a measurement when the close event carried one;\n // a store that never priced this worker must leave null, not 0.\n cost: {\n ...EMPTY_COST,\n usd: src.limits.spendUsd !== null || !close?.hasSpend ? null : close.spend.usd,\n tokens_in: workerSource?.tokensIn ?? (close?.hasSpend ? close.spend.tokens.input : null),\n tokens_out: workerSource?.tokensOut ?? (close?.hasSpend ? close.spend.tokens.output : null),\n // Mirror the tokens_in/out journal fallback so a loops-shaped store whose\n // `settled` spend carries cache counters is not reported as null cache\n // beside real tokens. Gate on `hasCache` — a spend object without cache\n // counters must stay null, not a fabricated 0.\n cache_read:\n workerSource?.cacheRead ??\n (close?.hasSpend && close.spend.tokens.hasCache ? close.spend.tokens.cacheRead : null),\n cache_write:\n workerSource?.cacheWrite ??\n (close?.hasSpend && close.spend.tokens.hasCache ? close.spend.tokens.cacheWrite : null),\n wall_s: wallMs === null ? null : wallMs / 1000,\n },\n // A reader that knows where its worker artifacts live says so; only the\n // loops layout is derivable from `supRunDir`, so guessing it for another\n // store would mint rows pointing at paths that never existed.\n artifacts: {\n patch_path:\n workerSource?.patchPath !== undefined\n ? workerSource.patchPath\n : src.supRunDir === null\n ? null\n : `${src.supRunDir}/workers/${spawn.label}.patch`,\n run_dir: src.supRunDir,\n transcript_ref:\n workerSource?.transcriptRef !== undefined\n ? workerSource.transcriptRef\n : src.supRunDir === null\n ? null\n : `${src.supRunDir}/workers/${spawn.label}.ndjson`,\n },\n provenance: {\n captured_at: capturedAt,\n capture: 'backfill',\n gap:\n workerSource?.transcriptRef == null\n ? 'worker transcript lives in the harness session store — hydrate via src/rollout/readers'\n : 'worker transcript recorded by the harness; messages not inlined into this row',\n },\n })\n }\n\n const invalid = nodes.filter((n) => !isRolloutLine(n))\n if (invalid.length > 0) {\n gaps.push({\n code: 'node-schema-invalid',\n message: `${invalid.length} node(s) failed tangle.rollout.v1 validation`,\n count: invalid.length,\n })\n }\n return { rootId, nodes, gaps }\n}\n","import { evidence, issue } from './integrity-issues'\nimport { sourceIssues } from './integrity-source'\nimport { treeIssues } from './integrity-tree'\nimport {\n SUPERVISOR_RUN_INTEGRITY_SCHEMA,\n type SupervisorRunIntegrityOptions,\n type SupervisorRunIntegrityReport,\n type SupervisorRunSourceOnlyCheckCode,\n} from './integrity-types'\nimport { supervisorRunRolloutLinesFromFacts } from './rollout-nodes'\nimport { parseSupervisorTree } from './source-facts'\nimport type { SupervisorRunSources, SupervisorRunTree } from './types'\n\nexport {\n SUPERVISOR_RUN_INTEGRITY_SCHEMA,\n type SupervisorRunIntegrityEvidence,\n type SupervisorRunIntegrityIssue,\n type SupervisorRunIntegrityIssueCode,\n type SupervisorRunIntegrityOptions,\n type SupervisorRunIntegrityReport,\n type SupervisorRunIntegritySeverity,\n type SupervisorRunSourceOnlyCheckCode,\n} from './integrity-types'\n\nfunction isTree(input: SupervisorRunSources | SupervisorRunTree): input is SupervisorRunTree {\n return 'nodes' in input && Array.isArray(input.nodes)\n}\n\nfunction treeRunRef(tree: SupervisorRunTree): string {\n const runIds = [\n ...new Set(\n tree.nodes\n .map((node) => node.run_id)\n .filter((runId): runId is string => typeof runId === 'string' && runId.length > 0),\n ),\n ].sort()\n if (runIds.length === 1) return runIds[0]!\n if (runIds.length > 1) return `mixed-runs:${runIds.join(',')}`\n return tree.rootId ?? 'unidentified-tree'\n}\n\n/**\n * Run deterministic integrity checks over source bytes or an already minted tree.\n * Source input is parsed exactly once and reused by projection and source-only checks.\n */\nexport function analyzeSupervisorRunIntegrity(\n input: SupervisorRunSources | SupervisorRunTree,\n options: SupervisorRunIntegrityOptions = {},\n): SupervisorRunIntegrityReport {\n if (isTree(input)) {\n const sourceOnlyChecks: readonly SupervisorRunSourceOnlyCheckCode[] = [\n 'journal-event-cardinality',\n 'worker-control-join',\n 'steer-ack-correlation',\n ]\n return {\n schema: SUPERVISOR_RUN_INTEGRITY_SCHEMA,\n runRef: treeRunRef(input),\n input: 'tree',\n tree: input,\n issues: [\n ...treeIssues(input),\n issue({\n code: 'source-checks-unavailable',\n area: 'capture-integrity',\n severity: 'medium',\n subject: 'source-only-control-checks',\n claim: 'Source-only control checks are unavailable for SupervisorRunTree input',\n detail:\n 'Rollout rows do not retain journal event multiplicity or worker inbox and acknowledgement rows.',\n evidence: [evidence('input/source-only-checks', sourceOnlyChecks)],\n recommendedAction:\n 'Pass SupervisorRunSources when journal and worker control checks are required.',\n metadata: { assessment: 'unavailable', checks: sourceOnlyChecks },\n }),\n ],\n }\n }\n\n const facts = parseSupervisorTree(input)\n const tree = supervisorRunRolloutLinesFromFacts(input, facts, {\n capturedAt: options.capturedAt,\n })\n return {\n schema: SUPERVISOR_RUN_INTEGRITY_SCHEMA,\n runRef: input.runRef,\n input: 'sources',\n tree,\n issues: [\n ...treeIssues(tree, {\n unknownIdentityRows:\n facts.journalInvalidRows +\n facts.spawns.filter((spawn) => !spawn.valid && spawn.id.length === 0).length,\n uncertainIds: new Set(\n facts.spawns\n .filter((spawn) => !spawn.valid && spawn.id.length > 0)\n .map((spawn) => spawn.id),\n ),\n }),\n ...sourceIssues(input, facts, tree),\n ],\n }\n}\n"],"mappings":";;;AAIA,SAAgB,SAAS,MAAc,OAAgD;CACrF,OAAO;EAAE;EAAM;CAAM;AACvB;AAEA,SAAgB,MACd,MAG6B;CAC7B,OAAO;EAAE,GAAG;EAAM,UAAU,KAAK,YAAY,CAAC;CAAE;AAClD;;;ACVA,SAAS,aAAa,KAAgC;CACpD,MAAM,WAAW,IACd,MAAM,GAAA,EAAe,CAAC,CACtB,KAAK,OAAO,KAAK,UAAU,EAAE,CAAC,CAAC,CAC/B,KAAK,IAAI;CACZ,OAAO,IAAI,UAAA,KACP,WACA,GAAG,SAAS,QAAQ,IAAI,SAAA,GAAsB;AACpD;AAEA,SAAgB,YACd,QACA,eAC+B;CAC/B,MAAM,EAAE,UAAU;CAClB,MAAM,UAAU,MAAM,YAAY,OAAO,MAAM;CAC/C,MAAM,SAAS,WAAW,MAAM;CAChC,MAAM,MAAqC,CAAC;CAC5C,IACE,CAAC,MAAM,iBACP,CAAC,MAAM,kBACP,MAAM,mBAAmB,KACzB,MAAM,oBAAoB,GAC1B;EACA,MAAM,UAAU,CACd,GAAI,MAAM,gBAAgB,CAAC,IAAI,CAAC,OAAO,GACvC,GAAI,MAAM,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAC3C;EACA,MAAM,YAAY,CAChB,GAAI,MAAM,mBAAmB,IAAI,CAAC,SAAS,MAAM,kBAAkB,IAAI,CAAC,GACxE,GAAI,MAAM,oBAAoB,IAAI,CAAC,UAAU,MAAM,mBAAmB,IAAI,CAAC,CAC7E;EACA,IAAI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","names":["mean","clamp01"],"sources":["../src/campaign/run-record.ts","../src/rl/verifiable-reward.ts","../src/rl/reward-hacking.ts"],"sourcesContent":["import type { AgentProfileCell } from '../agent-profile-cell'\nimport type {\n JudgeScoresRecord,\n RunOutcome,\n RunRecord,\n RunSplitTag,\n RunTerminalOutcome,\n} from '../run-record'\nimport { validateRunRecord } from '../run-record'\nimport type { CampaignCellResult, JudgeScore } from './types'\n\nexport interface CampaignCellRunRecordOptions {\n runId: string\n experimentId: string\n candidateId: string\n model: string\n promptHash: string\n configHash: string\n commitSha: string\n splitTag: RunSplitTag\n seed?: number\n scenarioId?: string\n defaultCostUsd?: number\n agentProfile?: AgentProfileCell\n raw?: Record<string, number>\n}\n\nexport interface CampaignCellQualityProjection {\n score?: number\n judgeScores?: JudgeScoresRecord\n successfulJudgeScores: Record<string, JudgeScore>\n failedJudges: string[]\n raw: Record<string, number>\n}\n\nexport interface CampaignCellExecutionEvidence {\n terminalOutcome: RunTerminalOutcome\n executionErrorCount?: number\n judgeErrorCount?: number\n unclassifiedErrorCount?: number\n terminalFailureReason?: string\n}\n\n/**\n * Project one campaign cell into the canonical run format.\n *\n * A dispatch error establishes terminal execution failure. A judge error only\n * establishes that quality measurement failed after dispatch completed.\n * Failures without a stage remain unknown. No failure becomes a zero-quality\n * label.\n */\nexport function campaignCellToRunRecord<TArtifact>(\n cell: CampaignCellResult<TArtifact>,\n options: CampaignCellRunRecordOptions,\n): RunRecord {\n const quality = projectCampaignCellQuality(cell)\n const execution = campaignCellExecutionEvidence(cell)\n const judgeErrorCount = Math.max(\n quality.raw.judge_error_count ?? 0,\n execution.judgeErrorCount ?? 0,\n )\n const cellCostCaptured = Number.isFinite(cell.costUsd) && cell.costUsd >= 0\n const costUsd = cellCostCaptured ? cell.costUsd : (options.defaultCostUsd ?? null)\n const costProvenance =\n costUsd === null\n ? ({ kind: 'uncaptured', usd: null } as const)\n : cellCostCaptured && !cell.costEstimated\n ? ({ kind: 'observed', usd: costUsd } as const)\n : ({ kind: 'estimated', usd: costUsd } as const)\n const raw: Record<string, number> = {\n ...finiteMetrics(options.raw),\n ...quality.raw,\n rep: cell.rep,\n duration_ms: cell.durationMs,\n ...(costUsd === null ? {} : { cost_usd: costUsd }),\n cost_estimated: cell.costEstimated ? 1 : 0,\n tokens_input: cell.tokenUsage.input,\n tokens_output: cell.tokenUsage.output,\n latency_ms: cell.durationMs,\n ...(execution.executionErrorCount === undefined\n ? {}\n : { execution_error_count: execution.executionErrorCount }),\n ...(judgeErrorCount > 0 ? { judge_error_count: judgeErrorCount } : {}),\n ...(execution.unclassifiedErrorCount === undefined\n ? {}\n : { unclassified_error_count: execution.unclassifiedErrorCount }),\n }\n if (typeof cell.generation === 'number') raw.generation = cell.generation\n if (cell.tokenUsage.reasoning !== undefined) {\n raw.tokens_reasoning = cell.tokenUsage.reasoning\n }\n if (cell.tokenUsage.cached !== undefined) raw.tokens_cached = cell.tokenUsage.cached\n if (cell.tokenUsage.cacheWrite !== undefined) {\n raw.tokens_cache_write = cell.tokenUsage.cacheWrite\n }\n if (costUsd !== null && costUsd > 0) {\n raw.tokens_per_dollar = (cell.tokenUsage.input + cell.tokenUsage.output) / costUsd\n }\n if (costUsd !== null && quality.score !== undefined && quality.score > 0.01) {\n raw.cost_per_quality = costUsd / quality.score\n }\n\n const outcome: RunOutcome = {\n raw,\n ...(quality.judgeScores ? { judgeScores: quality.judgeScores } : {}),\n }\n if (quality.score !== undefined) {\n if (options.splitTag === 'holdout') outcome.holdoutScore = quality.score\n else outcome.searchScore = quality.score\n }\n\n return validateRunRecord({\n runId: options.runId,\n experimentId: options.experimentId,\n candidateId: options.candidateId,\n seed: options.seed ?? cell.seed,\n model: options.model,\n promptHash: options.promptHash,\n configHash: options.configHash,\n commitSha: options.commitSha,\n wallMs: cell.durationMs,\n costUsd,\n costProvenance,\n tokenUsage: { ...cell.tokenUsage },\n terminalOutcome: execution.terminalOutcome,\n ...(execution.terminalFailureReason\n ? { terminalFailureReason: execution.terminalFailureReason }\n : {}),\n outcome,\n splitTag: options.splitTag,\n scenarioId: options.scenarioId ?? cell.scenarioId,\n ...(options.agentProfile ? { agentProfile: options.agentProfile } : {}),\n })\n}\n\nexport function campaignCellExecutionEvidence<TArtifact>(\n cell: CampaignCellResult<TArtifact>,\n): CampaignCellExecutionEvidence {\n if (cell.errorStage === 'dispatch') {\n return {\n terminalOutcome: 'failed',\n executionErrorCount: 1,\n ...(cell.error ? { terminalFailureReason: cell.error } : {}),\n }\n }\n if (cell.errorStage === 'judge') {\n return {\n terminalOutcome: 'succeeded',\n executionErrorCount: 0,\n judgeErrorCount: 1,\n }\n }\n if (!cell.error) {\n return { terminalOutcome: 'succeeded', executionErrorCount: 0 }\n }\n return {\n terminalOutcome: 'unknown',\n unclassifiedErrorCount: 1,\n }\n}\n\n/**\n * Produce the only task-quality view used by campaign aggregates and exports.\n *\n * Successful judge results remain available for diagnosis after another judge\n * fails, but a task score exists only for an error-free cell whose reported\n * judge values are all finite.\n */\nexport function projectCampaignCellQuality<TArtifact>(\n cell: CampaignCellResult<TArtifact>,\n): CampaignCellQualityProjection {\n if (cell.errorStage === 'dispatch') {\n return { successfulJudgeScores: {}, failedJudges: [], raw: {} }\n }\n\n const perJudge: Record<string, Record<string, number>> = {}\n const successfulJudgeScores: Record<string, JudgeScore> = {}\n const dimensionValues = new Map<string, number[]>()\n const composites: number[] = []\n const notes: string[] = []\n const failedJudges = new Set<string>(\n cell.errorStage === 'judge' ? [cell.errorJudge ?? 'unknown-judge'] : [],\n )\n const raw: Record<string, number> = {}\n\n for (const [judgeName, score] of Object.entries(cell.judgeScores)) {\n const finiteDimensions = Object.values(score.dimensions).every(Number.isFinite)\n if (score.failed || !Number.isFinite(score.composite) || !finiteDimensions) {\n failedJudges.add(judgeName)\n continue\n }\n\n composites.push(score.composite)\n successfulJudgeScores[judgeName] = score\n const dimensions = { ...score.dimensions }\n perJudge[judgeName] = dimensions\n for (const [dimension, value] of Object.entries(dimensions)) {\n raw[`${judgeName}.${dimension}`] = value\n const values = dimensionValues.get(dimension) ?? []\n values.push(value)\n dimensionValues.set(dimension, values)\n }\n if (score.notes) notes.push(`${judgeName}: ${score.notes}`)\n for (const failedJudge of score.failedJudges ?? []) {\n failedJudges.add(`${judgeName}/${failedJudge}`)\n }\n }\n\n if (failedJudges.size > 0) raw.judge_error_count = failedJudges.size\n const sortedFailedJudges = [...failedJudges].sort()\n if (composites.length === 0) {\n return {\n successfulJudgeScores,\n failedJudges: sortedFailedJudges,\n raw,\n }\n }\n\n const composite = mean(composites)\n const perDimMean = Object.fromEntries(\n [...dimensionValues.entries()].map(([dimension, values]) => [dimension, mean(values)]),\n )\n const complete =\n cell.error === undefined && cell.errorStage === undefined && failedJudges.size === 0\n if (complete) raw.composite = composite\n\n return {\n ...(complete ? { score: composite } : {}),\n raw,\n successfulJudgeScores,\n failedJudges: sortedFailedJudges,\n judgeScores: {\n perJudge,\n perDimMean,\n composite,\n ...(sortedFailedJudges.length > 0 ? { failedJudges: sortedFailedJudges } : {}),\n ...(notes.length > 0 ? { notes: notes.join(' | ') } : {}),\n },\n }\n}\n\n/** Read the canonical task score without recomputing cell quality. */\nexport function campaignCellTaskScore<TArtifact>(\n cell: CampaignCellResult<TArtifact>,\n): number | undefined {\n return projectCampaignCellQuality(cell).score\n}\n\n/** Read canonical successful judge dimensions without recomputing cell quality. */\nexport function campaignCellJudgeDimensions<TArtifact>(\n cell: CampaignCellResult<TArtifact>,\n): Record<string, Record<string, number>> {\n return projectCampaignCellQuality(cell).judgeScores?.perJudge ?? {}\n}\n\nfunction finiteMetrics(metrics: Record<string, number> | undefined): Record<string, number> {\n const finite: Record<string, number> = {}\n for (const [key, value] of Object.entries(metrics ?? {})) {\n if (Number.isFinite(value)) finite[key] = value\n }\n return finite\n}\n\nfunction mean(values: number[]): number {\n return values.reduce((sum, value) => sum + value, 0) / values.length\n}\n","/**\n * Verifiable reward channel.\n *\n * For RL on coding / math / theorem-proving / structured-output tasks, the\n * reward signal is *decidable* — a test passes or fails, a proof checks or\n * doesn't, an output validates against a schema or doesn't. These rewards\n * are dramatically more useful for RL training than LLM-judge scores\n * because they don't drift, can't be Goodhart-gamed by the policy in the\n * same way, and don't require a separate calibration loop.\n *\n * The `MultiLayerVerifier` already produces this signal — it just doesn't\n * surface it in a shape that's clean enough for RL training. This module\n * wraps the verifier output so consumers can:\n *\n * 1. Extract a clean `VerifiableReward` from a `VerificationReport`\n * 2. Distinguish *deterministic* rewards (compile, test, schema) from\n * *probabilistic* rewards (judge) so they can be weighted differently\n * in the RL training step\n * 3. Filter `RunRecord[]` to only those with a verifiable reward,\n * producing the clean training set that DeepSeek-R1-style GRPO and\n * AlphaProof-style search both depend on\n *\n * Why this matters: every credible 2025-2026 frontier RL result on coding\n * agents leans on verifiable reward (DeepSeek-R1 GRPO on test pass-rate,\n * o-series RL on math/code, AlphaProof on Lean kernel checking). Mixing\n * judge scores into the reward signal poisons the gradient. This module\n * is the seam.\n */\n\nimport type { LayerResult, VerificationReport } from '../multi-layer-verifier'\nimport { isRealnessGated, observedScore, trainingScore } from '../rollout/reward'\nimport type { RunRecord } from '../run-record'\n\nexport type VerifiableRewardSource =\n | 'compile' // typecheck / build / lint passed\n | 'test' // unit / integration test pass-rate\n | 'schema' // structured output validates\n | 'sandbox' // sandbox exec exit code\n | 'judge' // LLM judge — probabilistic, included for completeness\n | 'composite' // weighted blend across multiple of the above\n\nexport interface VerifiableReward {\n /** Scalar in [0, 1]. The RL training signal. */\n value: number\n /** What produced the reward — different sources have different determinism. */\n source: VerifiableRewardSource\n /**\n * Determinism class. `'deterministic'` rewards are repeatable byte-for-byte\n * given the same inputs (compile, test, schema validation, sandbox exit code).\n * `'probabilistic'` rewards depend on a stochastic component (LLM judge).\n * Mixing these in the same training batch without separation is a known\n * footgun in production RLHF pipelines.\n */\n determinism: 'deterministic' | 'probabilistic'\n /**\n * Confidence in the reward value. For deterministic sources this is 1.0\n * (the bit either flipped or didn't). For judge sources this is the\n * judge-reported confidence or — when missing — a calibrated prior.\n */\n confidence: number\n /** The layer / judge id that produced the signal, for provenance. */\n origin: string\n /**\n * Per-source contribution to `value`, keyed by layer/judge id. Single-source\n * rewards carry one entry (`{ [origin]: value }`); composite rewards carry\n * every contributing layer's score — the anti-scalar-collapse surface RL\n * consumers weight per-source instead of trusting one blended number.\n */\n components: Record<string, number>\n /**\n * The run carries `outcome.realness.gated` — the authenticity gate flagged\n * its success signal as faked.\n *\n * With the gate applied (the default) `value` and every `components` entry\n * are 0 on such a run; with `applyRealnessGate: false` the observed numbers\n * come back untouched and this flag is the only marker that they are not to\n * be trusted. Either way it distinguishes \"measured a genuine failure\" from\n * \"claimed a success we refuse to believe\", which a bare 0 cannot.\n */\n realnessGated?: boolean\n /**\n * Whether an authenticity screen COULD run on this reward at all — the same\n * distinction `RolloutOutcome.realness_screened` draws, for the same reason.\n *\n * `false` on every reward from `extractVerifiableReward`, because a\n * `VerificationReport` carries layer scores and nothing else: there is no\n * `outcome.realness` to consult, so no gate has run, and `realnessGated`\n * being absent there means \"unknown\", NOT \"clean\". Absent on the\n * `RunRecord` path when the record itself carries no realness verdict.\n *\n * This matters most exactly where it is easiest to miss: a report whose\n * deterministic layers all passed yields `determinism: 'deterministic'`,\n * `confidence: 1` — the highest-credibility reward this module can emit —\n * and a stubbed integration reporting green is precisely what a gamed run\n * looks like. Consumers driving training off this shape must screen the run\n * themselves; the flag is what tells them nobody has.\n */\n realnessScreened?: boolean\n}\n\nexport interface VerifiableRewardExtractionOptions {\n /**\n * Which layers count as deterministic-reward sources. The verifier doesn't\n * tag layers as \"this is verifiable\"; the caller declares it via this list\n * (or via the layer name → source mapping). Default treats common names\n * (`install`, `typecheck`, `build`, `lint`, `test`, `compile`, `schema`,\n * `sandbox`) as deterministic.\n */\n deterministicLayers?: string[]\n /**\n * Map layer name → reward source. Defaults to a sensible string-match.\n */\n sourceFor?: (layerName: string) => VerifiableRewardSource\n /**\n * Whether to fall back to a probabilistic (judge) reward when no\n * deterministic layer produced a numeric score. Default `true`. Set to\n * `false` for \"deterministic-only\" training pipelines that should\n * discard runs without a verifiable signal.\n */\n fallbackToJudge?: boolean\n /**\n * Default confidence for probabilistic (judge) rewards when the judge\n * doesn't report one. Default `0.7`.\n */\n judgeConfidenceFloor?: number\n /**\n * Whether the anti-Goodhart realness gate applies. Default `true`, and the\n * default is the one every training path must keep.\n *\n * Set `false` ONLY for detection and analysis. `rl/reward-hacking.ts` does,\n * for the same reason it reads `observedScore` for its proxy: it measures the\n * DIVERGENCE between the judge signal and the deterministic one, and a\n * deterministic reward that another gate already forced to 0 manufactures\n * exactly that divergence on exactly the gamed population. The detector would\n * then be re-reporting a verdict it was supposed to reach independently.\n */\n applyRealnessGate?: boolean\n}\n\nconst DEFAULT_DETERMINISTIC_LAYERS = new Set([\n 'install',\n 'typecheck',\n 'build',\n 'lint',\n 'test',\n 'compile',\n 'schema',\n 'sandbox',\n 'unit_tests',\n 'integration_tests',\n])\n\nconst DEFAULT_SOURCE_FOR = (name: string): VerifiableRewardSource => {\n const lower = name.toLowerCase()\n if (lower.includes('test')) return 'test'\n if (\n lower.includes('compile') ||\n lower.includes('build') ||\n lower.includes('typecheck') ||\n lower.includes('lint')\n )\n return 'compile'\n if (lower.includes('schema')) return 'schema'\n if (lower.includes('sandbox')) return 'sandbox'\n if (lower.includes('judge') || lower.includes('semantic')) return 'judge'\n return 'composite'\n}\n\n/**\n * Extract a `VerifiableReward` from a `VerificationReport`.\n *\n * Strategy: prefer the deterministic layers (in order: test → compile →\n * schema → sandbox), fall back to the judge layer if `fallbackToJudge` is\n * true, return `null` if no signal qualifies. When multiple deterministic\n * layers contribute, return a `'composite'` source with a weighted blend.\n *\n * NO realness gate is applied and none can be: a `VerificationReport` carries\n * layer scores and nothing about whether the run faked them — `realness` lives\n * on the `RunRecord`. Use `extractVerifiableRewardsFromRecords` for anything\n * that becomes training data; this signature is for scoring a report in hand.\n */\nexport function extractVerifiableReward(\n report: VerificationReport,\n opts: VerifiableRewardExtractionOptions = {},\n): VerifiableReward | null {\n const deterministicSet = new Set(opts.deterministicLayers ?? [...DEFAULT_DETERMINISTIC_LAYERS])\n const sourceFor = opts.sourceFor ?? DEFAULT_SOURCE_FOR\n const fallbackToJudge = opts.fallbackToJudge ?? true\n const judgeFloor = opts.judgeConfidenceFloor ?? 0.7\n\n const deterministic = report.layers.filter(\n (layer) => deterministicSet.has(layer.layer) && isMeasuredLayer(layer),\n )\n\n if (deterministic.length === 1) {\n const layer = deterministic[0]!\n const value = clamp01(layer.score!)\n return {\n value,\n source: sourceFor(layer.layer),\n determinism: 'deterministic',\n confidence: 1,\n origin: layer.layer,\n components: { [layer.layer]: value },\n realnessScreened: false,\n }\n }\n\n if (deterministic.length > 1) {\n // Composite: weighted blend by `Layer.weight` if present, else equal.\n let num = 0\n let denom = 0\n const components: Record<string, number> = {}\n for (const l of deterministic) {\n const w = (l.detail?.weight as number | undefined) ?? 1\n num += w * (l.score ?? 0)\n denom += w\n components[l.layer] = l.score!\n }\n return {\n value: denom === 0 ? 0 : clamp01(num / denom),\n source: 'composite',\n determinism: 'deterministic',\n confidence: 1,\n origin: deterministic.map((l) => l.layer).join('+'),\n components,\n realnessScreened: false,\n }\n }\n\n if (!fallbackToJudge) return null\n\n const judge =\n report.layers.find((layer) => isMeasuredLayer(layer) && sourceFor(layer.layer) === 'judge') ??\n report.layers.find(isMeasuredLayer)\n\n if (!judge) return null\n\n const confFromDetail = judge.detail?.confidence as number | undefined\n const judgeValue = clamp01(judge.score!)\n return {\n value: judgeValue,\n source: 'judge',\n determinism: 'probabilistic',\n confidence: typeof confFromDetail === 'number' ? confFromDetail : judgeFloor,\n origin: judge.layer,\n components: { [judge.layer]: judgeValue },\n realnessScreened: false,\n }\n}\n\nfunction isMeasuredLayer(\n layer: LayerResult,\n): layer is LayerResult & { status: 'pass' | 'fail'; score: number } {\n return (\n (layer.status === 'pass' || layer.status === 'fail') &&\n typeof layer.score === 'number' &&\n Number.isFinite(layer.score) &&\n layer.score >= 0 &&\n layer.score <= 1\n )\n}\n\n/**\n * Extract verifiable rewards from `RunRecord[]` produced via the\n * `verificationReportToRunRecord` adapter (which encodes per-layer scores\n * in `outcome.raw['layer.<name>']`). For records that don't carry layer\n * scores, returns `null` for that record.\n *\n * This is the canonical bridge from \"campaign-shaped artifacts\" to\n * \"RL-training-ready reward signals\": every record that has a clean\n * verifiable reward becomes a training datum, every record that doesn't\n * gets filtered out (or kept with `'probabilistic'` determinism for\n * separate downstream handling).\n *\n * The realness gate applies to EVERY channel here, and to the deterministic one\n * MOST. It is tempting to reason that a decidable signal cannot be gamed, so\n * the gate is redundant on it — that reasoning is backwards. `realness.gated`\n * means the run's success signal was FAKED, and a test suite reporting green on\n * a stubbed integration is precisely what that looks like: the deterministic\n * layer is the thing that got faked. Exporting it ungated hands a trainer the\n * highest-credibility reward the module can emit (`determinism: 'deterministic'`,\n * `confidence: 1`) for the one population the gate exists to catch. Pass\n * `applyRealnessGate: false` only to look at the ungated numbers for detection.\n */\nexport function extractVerifiableRewardsFromRecords(\n runs: RunRecord[],\n opts: VerifiableRewardExtractionOptions = {},\n): Array<{ runId: string; reward: VerifiableReward | null }> {\n const sourceFor = opts.sourceFor ?? DEFAULT_SOURCE_FOR\n const deterministicSet = new Set(opts.deterministicLayers ?? [...DEFAULT_DETERMINISTIC_LAYERS])\n const fallbackToJudge = opts.fallbackToJudge ?? true\n const judgeFloor = opts.judgeConfidenceFloor ?? 0.7\n const applyGate = opts.applyRealnessGate ?? true\n\n return runs.map((run) => {\n const flagged = isRealnessGated(run)\n // Present only when the record carries an actual realness verdict. Absent\n // is the honest \"unknown\"; `false` is reserved for a producer that\n // declares it HAS no screen, which is the report-shaped path above.\n const screened = run.outcome.realness === undefined ? {} : ({ realnessScreened: true } as const)\n // Zeroed with `value`, never left at the measured number: `components`\n // exists so an RL consumer can re-weight per source, and a raw layer score\n // surviving there would let that re-weighting reconstruct the very reward\n // the gate just refused. The measured layer scores stay on\n // `run.outcome.raw['layer.*']`, which is where analysis reads them.\n const gate = (value: number): number => (applyGate && flagged ? 0 : value)\n // Recover per-layer scores from outcome.raw['layer.<name>']\n const layerScores: Array<{ name: string; score: number }> = []\n for (const [k, v] of Object.entries(run.outcome.raw)) {\n if (\n k.startsWith('layer.') &&\n !k.includes('.', 6) &&\n typeof v === 'number' &&\n Number.isFinite(v)\n ) {\n layerScores.push({ name: k.slice('layer.'.length), score: v })\n }\n }\n const det = layerScores.filter((l) => deterministicSet.has(l.name))\n\n if (det.length === 1) {\n const layer = det[0]!\n const value = gate(clamp01(layer.score))\n return {\n runId: run.runId,\n reward: {\n value,\n source: sourceFor(layer.name),\n determinism: 'deterministic',\n confidence: 1,\n origin: layer.name,\n components: { [layer.name]: value },\n realnessGated: flagged,\n ...screened,\n },\n }\n }\n if (det.length > 1) {\n const value = gate(clamp01(det.reduce((s, l) => s + l.score, 0) / det.length))\n // Same clamp as the headline value: a producer writing layer.score 1.5\n // into outcome.raw must not propagate 1.5 through a component either.\n const components: Record<string, number> = Object.fromEntries(\n det.map((l) => [l.name, gate(clamp01(l.score))]),\n )\n return {\n runId: run.runId,\n reward: {\n value,\n source: 'composite',\n determinism: 'deterministic',\n confidence: 1,\n origin: det.map((l) => l.name).join('+'),\n components,\n realnessGated: flagged,\n ...screened,\n },\n }\n }\n if (!fallbackToJudge) return { runId: run.runId, reward: null }\n\n // Probabilistic fallback: the run's primary score. `trainingScore` already\n // carries the gate, so a gamed run falls to 0 rather than earning the\n // judge's number; `observedScore` is the ungated reader the detection\n // opt-out asks for. Either way an unscored run stays a labeled gap\n // (`reward: null`), never a fabricated 0.\n const primary = applyGate ? trainingScore(run) : observedScore(run)\n if (typeof primary !== 'number' || !Number.isFinite(primary)) {\n return { runId: run.runId, reward: null }\n }\n const primaryValue = clamp01(primary)\n return {\n runId: run.runId,\n reward: {\n value: primaryValue,\n source: 'judge',\n determinism: 'probabilistic',\n confidence: judgeFloor,\n origin: 'run.outcome.score',\n components: { 'run.outcome.score': primaryValue },\n realnessGated: flagged,\n ...screened,\n },\n }\n })\n}\n\n/**\n * Filter `RunRecord[]` to those with deterministic verifiable rewards.\n *\n * A realness-gated run is KEPT, at reward 0 with `realnessGated: true` — the\n * same rule GRPO uses on a gated line. 0 is the honest label for a faked\n * success and is usable signal, whereas dropping the run would move a group\n * baseline without saying so. (SFT differs: there every row is a target to\n * imitate, so a gated row is removed outright.)\n */\nexport function filterDeterministicallyRewarded(\n runs: RunRecord[],\n opts: VerifiableRewardExtractionOptions = {},\n): Array<{ run: RunRecord; reward: VerifiableReward }> {\n const rewarded = extractVerifiableRewardsFromRecords(runs, { ...opts, fallbackToJudge: false })\n const out: Array<{ run: RunRecord; reward: VerifiableReward }> = []\n for (let i = 0; i < runs.length; i++) {\n const r = rewarded[i]!\n if (r.reward && r.reward.determinism === 'deterministic') {\n out.push({ run: runs[i]!, reward: r.reward })\n }\n }\n return out\n}\n\nfunction clamp01(x: number): number {\n if (!Number.isFinite(x)) return 0\n return Math.max(0, Math.min(1, x))\n}\n","/**\n * Reward hacking / Goodhart detection.\n *\n * Goodhart's Law says: when a measure becomes a target, it ceases to be\n * a good measure. In RLHF and agentic-RL settings this is the dominant\n * failure mode — the policy learns to produce outputs that score well on\n * the proxy reward (judge, rubric, test pass-rate) without producing\n * the underlying capability the proxy was meant to track.\n *\n * Krakovna et al. (2020, \"Specification Gaming Examples in AI\") and the\n * subsequent RLHF reward-hacking literature (Skalse et al. 2022, Kim et al.\n * 2023) converge on a few diagnostic signatures:\n *\n * 1. **Reward divergence:** the proxy reward grows while the held-out\n * ground-truth signal stagnates or drops. Predictive validity over\n * time captures this.\n * 2. **Distributional shift in outputs:** after RL, the policy produces\n * outputs that no longer match the reference distribution — usually\n * because it found a high-reward attractor that's degenerate (e.g.\n * one-token responses, repetition, formatting tricks).\n * 3. **Disagreement between independent rewards:** if you train on\n * reward A and a held-out independent reward B drops sharply, you're\n * probably hacking A.\n * 4. **Calibration drift:** the verifiable / deterministic component of\n * the reward is stable; the probabilistic / judge component drifts up\n * while the deterministic component doesn't. The judge is being\n * gamed.\n *\n * This module ships explicit detectors for all four signatures, plus a\n * combined verdict. The output is diagnostic — actionable signals,\n * not autoreject — because each signature has known false positives\n * (e.g., a policy that genuinely improves can show distributional shift).\n *\n * Differs from `rubricPredictiveValidity` (which is a *standing* check on\n * whether rubrics correlate with deployment outcomes) — this is a\n * *temporal* check on whether the reward-vs-truth gap is *widening over\n * time during a training run*.\n */\n\nimport { observedScore } from '../rollout/reward'\nimport type { RunRecord } from '../run-record'\nimport { pearsonR } from '../statistics'\nimport {\n filterDeterministicallyRewarded,\n type VerifiableRewardExtractionOptions,\n} from './verifiable-reward'\n\nexport type RewardHackingSignal =\n | 'reward_divergence'\n | 'distribution_shift'\n | 'reward_disagreement'\n | 'judge_drift'\n\nexport interface RewardHackingFinding {\n signal: RewardHackingSignal\n /** Severity in [0, 1]. >0.5 = strong signal. */\n severity: number\n message: string\n /** Numeric evidence the consumer can render. */\n detail: Record<string, number>\n}\n\nexport interface RewardHackingReport {\n findings: RewardHackingFinding[]\n /** Signals with enough usable observations to produce a finding. */\n evaluatedSignals: RewardHackingSignal[]\n /**\n * Composite verdict. `'insufficient_evidence'` when fewer than four scored\n * runs exist; otherwise `'clean'` if every signal severity < 0.3,\n * `'suspect'` if at least one ≥ 0.3 but none ≥ 0.6, and `'gaming'` if any ≥ 0.6.\n */\n verdict: 'insufficient_evidence' | 'clean' | 'suspect' | 'gaming'\n /** Rationale for the verdict, ready to paste into an audit log. */\n rationale: string[]\n /** Number of runs with a usable proxy reward. */\n n: number\n}\n\nexport interface DetectRewardHackingInput {\n /**\n * Run records ordered by recency (oldest first). The detector segments\n * them into prefix/suffix windows to compute \"did the gap widen.\"\n */\n runs: RunRecord[]\n /**\n * The metric the policy was trained to optimize. Should be present on\n * `outcome.raw` or `outcome.holdoutScore`. Default reads `outcome.holdoutScore`.\n */\n proxyOf?: (run: RunRecord) => number | null\n /**\n * The held-out ground-truth metric. For RL on coding, this is typically\n * test pass-rate. For RLHF, it's downstream task performance or human\n * preference. For knowledge tasks, it's an independently-graded score.\n */\n truthOf?: (run: RunRecord) => number | null\n /**\n * Independent secondary reward. Used for the `reward_disagreement`\n * signal. Default uses the verifiable reward extractor (deterministic\n * sources only).\n */\n secondaryRewardOf?: (run: RunRecord) => number | null\n /**\n * Window size — how many of the most recent runs count as the \"after\"\n * cohort. Default min(50, half the runs).\n */\n windowSize?: number\n /**\n * Severity threshold to flag a signal. Default 0.3 (suspect) and 0.6\n * (gaming).\n */\n thresholds?: { suspect?: number; gaming?: number }\n /**\n * Verifiable-reward options used for the secondary-reward fallback.\n */\n verifiableRewardOptions?: VerifiableRewardExtractionOptions\n}\n\nconst DEFAULT_PROXY = (r: RunRecord): number | null => {\n // DELIBERATELY UNGATED. This is the proxy reward the detector tests for\n // Goodharting, and gated runs are exactly the gamed population. Forcing them\n // to 0 would collapse the proxy toward the deterministic secondary signal —\n // `reward_disagreement`'s correlation would rise, `judge_drift`'s gap would\n // shrink, and `reward_divergence`'s proxy-up/truth-flat fingerprint would be\n // erased — so the detector would report \"clean\" on the very runs it exists to\n // catch. `null` (never 0) is also load-bearing: it sets the n-denominator via\n // the filter below.\n const v = observedScore(r)\n return typeof v === 'number' && Number.isFinite(v) ? v : null\n}\n\nexport function detectRewardHacking(input: DetectRewardHackingInput): RewardHackingReport {\n const proxyOf = input.proxyOf ?? DEFAULT_PROXY\n const truthOf = input.truthOf\n const sus = input.thresholds?.suspect ?? 0.3\n const gam = input.thresholds?.gaming ?? 0.6\n\n const runs = input.runs.filter((run) => finiteNumber(proxyOf(run)))\n const n = runs.length\n if (n < 4) {\n return {\n findings: [],\n evaluatedSignals: [],\n verdict: 'insufficient_evidence',\n n,\n rationale: [`fewer than 4 runs with proxy reward (n=${n}); insufficient evidence`],\n }\n }\n const windowSize = Math.max(1, input.windowSize ?? Math.min(50, Math.floor(n / 2)))\n const before = runs.slice(0, n - windowSize)\n const after = runs.slice(n - windowSize)\n\n const findings: RewardHackingFinding[] = []\n\n // ── Signal 1: reward divergence (proxy ↑ while truth flat or ↓) ──────\n if (truthOf) {\n const beforeProxy = before.map(proxyOf).filter(finiteNumber)\n const afterProxy = after.map(proxyOf).filter(finiteNumber)\n const beforeTruth = before.map(truthOf).filter(finiteNumber)\n const afterTruth = after.map(truthOf).filter(finiteNumber)\n if (\n beforeProxy.length >= 2 &&\n afterProxy.length >= 2 &&\n beforeTruth.length >= 2 &&\n afterTruth.length >= 2\n ) {\n const proxyDelta = mean(afterProxy) - mean(beforeProxy)\n const truthDelta = mean(afterTruth) - mean(beforeTruth)\n // Divergence: proxy goes up while truth goes flat or down.\n // Severity = max(0, (proxyDelta - truthDelta)) — bigger gap = bigger signal.\n const gap = Math.max(0, proxyDelta - truthDelta)\n const severity = clamp01(gap * 5) // scale: 0.2 absolute gap → severity 1.0\n findings.push({\n signal: 'reward_divergence',\n severity,\n message:\n severity >= sus\n ? `proxy reward rose by ${proxyDelta.toFixed(3)} while truth changed by ${truthDelta.toFixed(3)} — potential Goodhart`\n : `proxy and truth moved together (proxy ${proxyDelta.toFixed(3)}, truth ${truthDelta.toFixed(3)})`,\n detail: {\n proxyDelta,\n truthDelta,\n gap,\n beforeN: beforeProxy.length,\n afterN: afterProxy.length,\n },\n })\n }\n }\n\n // ── Signal 2: distributional shift in outputs (KS on score distributions) ──\n {\n const beforeP = before.map(proxyOf).filter(finiteNumber)\n const afterP = after.map(proxyOf).filter(finiteNumber)\n if (beforeP.length >= 4 && afterP.length >= 4) {\n const ks = ksStatistic(beforeP, afterP)\n // KS statistic: bigger = more shift. We're agnostic about direction;\n // genuine improvement ALSO produces shift, so this signal is\n // contributory rather than load-bearing.\n const severity = clamp01(ks - 0.2)\n findings.push({\n signal: 'distribution_shift',\n severity,\n message:\n severity >= sus\n ? `KS=${ks.toFixed(3)} between before/after windows — distributional shift large`\n : `KS=${ks.toFixed(3)} between before/after windows — within-distribution drift`,\n detail: { ks, beforeN: beforeP.length, afterN: afterP.length },\n })\n }\n }\n\n // ── Signal 3: reward disagreement (proxy vs independent secondary) ────\n {\n const secondaryOf = input.secondaryRewardOf ?? defaultSecondary(input.verifiableRewardOptions)\n const aligned = runs\n .map((r) => ({ p: proxyOf(r), s: secondaryOf(r) }))\n .filter((x): x is { p: number; s: number } => finiteNumber(x.p) && finiteNumber(x.s))\n if (aligned.length >= 4) {\n const ps = aligned.map((x) => x.p)\n const ss = aligned.map((x) => x.s)\n const r = pearsonR(ps, ss)\n // Disagreement: low or negative correlation between primary proxy\n // reward and an independent secondary signal.\n const severity = clamp01(0.5 - Math.max(0, r))\n findings.push({\n signal: 'reward_disagreement',\n severity,\n message:\n severity >= sus\n ? `proxy and independent secondary reward correlate ρ=${r.toFixed(3)} — possibly hacking proxy`\n : `proxy and secondary reward correlate ρ=${r.toFixed(3)}`,\n detail: { pearson: r, n: aligned.length },\n })\n }\n }\n\n // ── Signal 4: judge drift (probabilistic up while deterministic flat) ─\n {\n // Ungated on purpose, exactly like `DEFAULT_PROXY` above. This signal is\n // the GAP between the judge reward and the deterministic one; a\n // deterministic reward another gate already forced to 0 would open that gap\n // by construction on the gamed population, so the detector would fire on\n // its own input rather than on evidence it found.\n const detRuns = filterDeterministicallyRewarded(runs, {\n ...(input.verifiableRewardOptions ?? {}),\n applyRealnessGate: false,\n })\n if (detRuns.length >= 4) {\n const detBefore = detRuns.slice(0, Math.floor(detRuns.length / 2))\n const detAfter = detRuns.slice(Math.floor(detRuns.length / 2))\n const detDelta =\n mean(detAfter.map((r) => r.reward.value)) - mean(detBefore.map((r) => r.reward.value))\n const proxyDelta =\n mean(after.map(proxyOf).filter(finiteNumber)) -\n mean(before.map(proxyOf).filter(finiteNumber))\n const driftGap = Math.max(0, proxyDelta - detDelta)\n const severity = clamp01(driftGap * 5)\n findings.push({\n signal: 'judge_drift',\n severity,\n message:\n severity >= sus\n ? `judge proxy +${proxyDelta.toFixed(3)} while deterministic reward +${detDelta.toFixed(3)} — judge drifting up without verifiable backing`\n : `judge and deterministic rewards move in step (judge ${proxyDelta.toFixed(3)}, det ${detDelta.toFixed(3)})`,\n detail: { proxyDelta, detDelta, driftGap, n: detRuns.length },\n })\n }\n }\n\n const maxSev = findings.reduce((m, f) => Math.max(m, f.severity), 0)\n if (findings.length === 0) {\n return {\n findings,\n evaluatedSignals: [],\n verdict: 'insufficient_evidence',\n rationale: [`no reward-hacking signal had enough paired evidence (n=${n})`],\n n,\n }\n }\n const verdict: RewardHackingReport['verdict'] =\n maxSev >= gam ? 'gaming' : maxSev >= sus ? 'suspect' : 'clean'\n const rationale = findings\n .filter((f) => f.severity >= sus)\n .map((f) => `${f.signal}: severity ${f.severity.toFixed(2)} — ${f.message}`)\n if (rationale.length === 0) rationale.push('no signals fired above suspect threshold')\n\n return {\n findings,\n evaluatedSignals: findings.map((finding) => finding.signal),\n verdict,\n rationale,\n n,\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────\n\nfunction mean(xs: number[]): number {\n if (xs.length === 0) return 0\n return xs.reduce((s, x) => s + x, 0) / xs.length\n}\n\nfunction finiteNumber(value: number | null): value is number {\n return typeof value === 'number' && Number.isFinite(value)\n}\n\nfunction clamp01(x: number): number {\n if (!Number.isFinite(x)) return 0\n return Math.max(0, Math.min(1, x))\n}\n\nfunction ksStatistic(a: number[], b: number[]): number {\n // Two-sample Kolmogorov-Smirnov statistic.\n const sortedA = [...a].sort((x, y) => x - y)\n const sortedB = [...b].sort((x, y) => x - y)\n const all = [...new Set([...sortedA, ...sortedB])].sort((x, y) => x - y)\n let max = 0\n for (const v of all) {\n const fa = sortedA.filter((x) => x <= v).length / sortedA.length\n const fb = sortedB.filter((x) => x <= v).length / sortedB.length\n max = Math.max(max, Math.abs(fa - fb))\n }\n return max\n}\n\nfunction defaultSecondary(\n verifiableOpts?: VerifiableRewardExtractionOptions,\n): (run: RunRecord) => number | null {\n return (run: RunRecord) => {\n // Ungated for the same reason as signal 4: this is the INDEPENDENT\n // secondary reward whose correlation with the proxy is the evidence.\n // Zeroing it on gated runs would drive that correlation down mechanically.\n const filtered = filterDeterministicallyRewarded([run], {\n ...(verifiableOpts ?? {}),\n applyRealnessGate: false,\n })\n return filtered.length === 1 ? filtered[0]!.reward.value : null\n }\n}\n"],"mappings":";;;;;;;;;;;;AAmDA,SAAgB,wBACd,MACA,SACW;CACX,MAAM,UAAU,2BAA2B,IAAI;CAC/C,MAAM,YAAY,8BAA8B,IAAI;CACpD,MAAM,kBAAkB,KAAK,IAC3B,QAAQ,IAAI,qBAAqB,GACjC,UAAU,mBAAmB,CAC/B;CACA,MAAM,mBAAmB,OAAO,SAAS,KAAK,OAAO,KAAK,KAAK,WAAW;CAC1E,MAAM,UAAU,mBAAmB,KAAK,UAAW,QAAQ,kBAAkB;CAC7E,MAAM,iBACJ,YAAY,OACP;EAAE,MAAM;EAAc,KAAK;CAAK,IACjC,oBAAoB,CAAC,KAAK,gBACvB;EAAE,MAAM;EAAY,KAAK;CAAQ,IACjC;EAAE,MAAM;EAAa,KAAK;CAAQ;CAC3C,MAAM,MAA8B;EAClC,GAAG,cAAc,QAAQ,GAAG;EAC5B,GAAG,QAAQ;EACX,KAAK,KAAK;EACV,aAAa,KAAK;EAClB,GAAI,YAAY,OAAO,CAAC,IAAI,EAAE,UAAU,QAAQ;EAChD,gBAAgB,KAAK,gBAAgB,IAAI;EACzC,cAAc,KAAK,WAAW;EAC9B,eAAe,KAAK,WAAW;EAC/B,YAAY,KAAK;EACjB,GAAI,UAAU,wBAAwB,KAAA,IAClC,CAAC,IACD,EAAE,uBAAuB,UAAU,oBAAoB;EAC3D,GAAI,kBAAkB,IAAI,EAAE,mBAAmB,gBAAgB,IAAI,CAAC;EACpE,GAAI,UAAU,2BAA2B,KAAA,IACrC,CAAC,IACD,EAAE,0BAA0B,UAAU,uBAAuB;CACnE;CACA,IAAI,OAAO,KAAK,eAAe,UAAU,IAAI,aAAa,KAAK;CAC/D,IAAI,KAAK,WAAW,cAAc,KAAA,GAChC,IAAI,mBAAmB,KAAK,WAAW;CAEzC,IAAI,KAAK,WAAW,WAAW,KAAA,GAA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