@tangle-network/agent-eval 0.138.0 → 0.139.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 (164) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +2 -1
  3. package/dist/analyst/index.d.ts +41 -94
  4. package/dist/analyst/index.d.ts.map +1 -1
  5. package/dist/analyst/index.js +9 -24
  6. package/dist/analyst/index.js.map +1 -1
  7. package/dist/{benchmark-D8dkki-J.js → benchmark-CYtcIF2V.js} +2 -2
  8. package/dist/{benchmark-D8dkki-J.js.map → benchmark-CYtcIF2V.js.map} +1 -1
  9. package/dist/{benchmark-DlQgU_XI.d.ts → benchmark-DDVdWcwA.d.ts} +3 -3
  10. package/dist/{benchmark-DlQgU_XI.d.ts.map → benchmark-DDVdWcwA.d.ts.map} +1 -1
  11. package/dist/{benchmark-command-CMqVqReF.js → benchmark-command-BKfjOBJ5.js} +243 -38
  12. package/dist/benchmark-command-BKfjOBJ5.js.map +1 -0
  13. package/dist/benchmarks/index.d.ts +1 -1
  14. package/dist/benchmarks/index.js +1 -1
  15. package/dist/{benchmarks-BJ_xK5rQ.js → benchmarks-zxhy1QV3.js} +4 -4
  16. package/dist/{benchmarks-BJ_xK5rQ.js.map → benchmarks-zxhy1QV3.js.map} +1 -1
  17. package/dist/campaign/index.d.ts +5 -5
  18. package/dist/campaign/index.js +4 -3
  19. package/dist/{campaign-BIBS-NHV.js → campaign-DrS6_hLd.js} +10 -9
  20. package/dist/campaign-DrS6_hLd.js.map +1 -0
  21. package/dist/canonical-D011XM8r.js +86 -0
  22. package/dist/canonical-D011XM8r.js.map +1 -0
  23. package/dist/cli.js +3 -3
  24. package/dist/{client-BwPKohkJ.d.ts → client-BohnDFBq.d.ts} +4 -4
  25. package/dist/{client-BwPKohkJ.d.ts.map → client-BohnDFBq.d.ts.map} +1 -1
  26. package/dist/{completion-verifier-B4-IMYcS.d.ts → completion-verifier-IPoP4fQO.d.ts} +178 -4
  27. package/dist/completion-verifier-IPoP4fQO.d.ts.map +1 -0
  28. package/dist/contract/index.d.ts +10 -10
  29. package/dist/contract/index.js +8 -7
  30. package/dist/contract/index.js.map +1 -1
  31. package/dist/control.d.ts +2 -2
  32. package/dist/{cost-ledger-CHDLA0Ss.js → cost-ledger-CZ9diLxY.js} +7 -7
  33. package/dist/cost-ledger-CZ9diLxY.js.map +1 -0
  34. package/dist/{cost-ledger-B1D3COAc.d.ts → cost-ledger-DKgyIWRj.d.ts} +5 -2
  35. package/dist/cost-ledger-DKgyIWRj.d.ts.map +1 -0
  36. package/dist/default-registry-B8vf7Rmf.d.ts +118 -0
  37. package/dist/default-registry-B8vf7Rmf.d.ts.map +1 -0
  38. package/dist/{default-registry-lp5R0lve.js → default-registry-BgJJItGr.js} +57 -1532
  39. package/dist/default-registry-BgJJItGr.js.map +1 -0
  40. package/dist/dspy-rlm-engine-DTkVyDX-.js +344 -0
  41. package/dist/dspy-rlm-engine-DTkVyDX-.js.map +1 -0
  42. package/dist/{eval-campaign-9MozgKL7.js → eval-campaign-BmptJj50.js} +2 -2
  43. package/dist/{eval-campaign-9MozgKL7.js.map → eval-campaign-BmptJj50.js.map} +1 -1
  44. package/dist/{exact-types-Dpw2LeHA.d.ts → exact-types-MaaFcllV.d.ts} +2 -2
  45. package/dist/{exact-types-Dpw2LeHA.d.ts.map → exact-types-MaaFcllV.d.ts.map} +1 -1
  46. package/dist/external-optimizer-contracts-BrxY2Sli.d.ts +32 -0
  47. package/dist/external-optimizer-contracts-BrxY2Sli.d.ts.map +1 -0
  48. package/dist/{extract-usage-CS391dOE.js → extract-usage-DZs601Va.js} +2 -2
  49. package/dist/{extract-usage-CS391dOE.js.map → extract-usage-DZs601Va.js.map} +1 -1
  50. package/dist/{feedback-trajectory-CoNep7rl.d.ts → feedback-trajectory-BJUWOkJM.d.ts} +3 -3
  51. package/dist/{feedback-trajectory-CoNep7rl.d.ts.map → feedback-trajectory-BJUWOkJM.d.ts.map} +1 -1
  52. package/dist/fuzz.d.ts +1 -1
  53. package/dist/fuzz.js +1 -1
  54. package/dist/{hf-dataset-DBJXXoY1.js → hf-dataset-XggBupCr.js} +2 -2
  55. package/dist/{hf-dataset-DBJXXoY1.js.map → hf-dataset-XggBupCr.js.map} +1 -1
  56. package/dist/hosted/index.d.ts +3 -3
  57. package/dist/{index-D0cxAdaV.d.ts → index-BTm_P9aC.d.ts} +11 -11
  58. package/dist/{index-D0cxAdaV.d.ts.map → index-BTm_P9aC.d.ts.map} +1 -1
  59. package/dist/{index-B2-IxCMB.d.ts → index-CWOPCJiw.d.ts} +2 -2
  60. package/dist/{index-B2-IxCMB.d.ts.map → index-CWOPCJiw.d.ts.map} +1 -1
  61. package/dist/{index-sMN_hI4E.d.ts → index-CtR1xh4V.d.ts} +3 -3
  62. package/dist/{index-sMN_hI4E.d.ts.map → index-CtR1xh4V.d.ts.map} +1 -1
  63. package/dist/{index-CjVYlVBK.d.ts → index-_66rVpwN.d.ts} +5 -5
  64. package/dist/{index-CjVYlVBK.d.ts.map → index-_66rVpwN.d.ts.map} +1 -1
  65. package/dist/index.d.ts +35 -56
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +51 -176
  68. package/dist/index.js.map +1 -1
  69. package/dist/{insight-report-CXd8VBDR.d.ts → insight-report-Bu5Wi9tG.d.ts} +4 -4
  70. package/dist/{insight-report-CXd8VBDR.d.ts.map → insight-report-Bu5Wi9tG.d.ts.map} +1 -1
  71. package/dist/{integrity-B-MLFz0I.d.ts → integrity-COTh3DTH.d.ts} +2 -2
  72. package/dist/{integrity-B-MLFz0I.d.ts.map → integrity-COTh3DTH.d.ts.map} +1 -1
  73. package/dist/kind-factory-CFxA0JQX.js +2133 -0
  74. package/dist/kind-factory-CFxA0JQX.js.map +1 -0
  75. package/dist/ledger-core/index.js +2 -1
  76. package/dist/{ledger-core-C0Yx1I14.js → ledger-core-Dxz0Rkwa.js} +3 -85
  77. package/dist/ledger-core-Dxz0Rkwa.js.map +1 -0
  78. package/dist/{llm-client-Cj3c7PEm.js → llm-client-bkztEfIx.js} +2 -2
  79. package/dist/{llm-client-Cj3c7PEm.js.map → llm-client-bkztEfIx.js.map} +1 -1
  80. package/dist/meta-eval/index.d.ts +2 -2
  81. package/dist/multishot/index.d.ts +2 -2
  82. package/dist/openapi.json +1 -1
  83. package/dist/{release-report-CoyvyLBs.d.ts → release-report-fZarvIm-.d.ts} +3 -3
  84. package/dist/{release-report-CoyvyLBs.d.ts.map → release-report-fZarvIm-.d.ts.map} +1 -1
  85. package/dist/{replay-DbIYwso6.d.ts → replay-DjG4IG60.d.ts} +34 -143
  86. package/dist/replay-DjG4IG60.d.ts.map +1 -0
  87. package/dist/{replay-Cb-4Vf0k.js → replay-SA4OB7O7.js} +48 -137
  88. package/dist/replay-SA4OB7O7.js.map +1 -0
  89. package/dist/reporting.d.ts +4 -4
  90. package/dist/{researcher-BCeOEjtR.d.ts → researcher-BxhtGfKa.d.ts} +5 -5
  91. package/dist/{researcher-BCeOEjtR.d.ts.map → researcher-BxhtGfKa.d.ts.map} +1 -1
  92. package/dist/{reward-hacking-sE2l_NV6.d.ts → reward-hacking-CqSLiV51.d.ts} +2 -2
  93. package/dist/{reward-hacking-sE2l_NV6.d.ts.map → reward-hacking-CqSLiV51.d.ts.map} +1 -1
  94. package/dist/rl.d.ts +5 -5
  95. package/dist/rl.js +1 -1
  96. package/dist/rollout/index.d.ts +1 -1
  97. package/dist/rollout/index.js +2 -2
  98. package/dist/{rollout-DQFl0UXA.js → rollout-8nj3mYvx.js} +2 -2
  99. package/dist/{rollout-DQFl0UXA.js.map → rollout-8nj3mYvx.js.map} +1 -1
  100. package/dist/{rubric-predictive-validity-w2klGv1u.d.ts → rubric-predictive-validity-DQBQj6uV.d.ts} +2 -2
  101. package/dist/{rubric-predictive-validity-w2klGv1u.d.ts.map → rubric-predictive-validity-DQBQj6uV.d.ts.map} +1 -1
  102. package/dist/{run-evidence-CbE0A8Xg.d.ts → run-evidence-C4RcRQT5.d.ts} +3 -3
  103. package/dist/{run-evidence-CbE0A8Xg.d.ts.map → run-evidence-C4RcRQT5.d.ts.map} +1 -1
  104. package/dist/{run-record-DwHMk1Ai.d.ts → run-record-CztDMXVF.d.ts} +2 -2
  105. package/dist/{run-record-DwHMk1Ai.d.ts.map → run-record-CztDMXVF.d.ts.map} +1 -1
  106. package/dist/{semantic-concept-judge-DYXDPZW0.js → semantic-concept-judge-BuIJ9IfB.js} +43 -6
  107. package/dist/semantic-concept-judge-BuIJ9IfB.js.map +1 -0
  108. package/dist/{server-DLEvyW2z.js → server-DaCpLfi0.js} +3 -3
  109. package/dist/{server-DLEvyW2z.js.map → server-DaCpLfi0.js.map} +1 -1
  110. package/dist/single-run-lock-BTTtPZ9N.js +989 -0
  111. package/dist/single-run-lock-BTTtPZ9N.js.map +1 -0
  112. package/dist/{skill-usage-Bv3G4VkA.d.ts → skill-usage-B-BFS8M2.d.ts} +54 -39
  113. package/dist/skill-usage-B-BFS8M2.d.ts.map +1 -0
  114. package/dist/{skillopt-optimization-method-CjKMZy0d.js → skillopt-optimization-method-BbGnCC53.js} +18 -802
  115. package/dist/skillopt-optimization-method-BbGnCC53.js.map +1 -0
  116. package/dist/{skillopt-optimization-method-CzfnA8O-.d.ts → skillopt-optimization-method-_s0Tub7Y.d.ts} +11 -39
  117. package/dist/skillopt-optimization-method-_s0Tub7Y.d.ts.map +1 -0
  118. package/dist/{statistics-mf70aXKp.d.ts → statistics-B5d0Zd-z.d.ts} +2 -2
  119. package/dist/{statistics-mf70aXKp.d.ts.map → statistics-B5d0Zd-z.d.ts.map} +1 -1
  120. package/dist/store-otlp-DX4fGIcf.js +757 -0
  121. package/dist/store-otlp-DX4fGIcf.js.map +1 -0
  122. package/dist/{summary-report-BKinV4yD.d.ts → summary-report-Cg7BifAM.d.ts} +3 -3
  123. package/dist/{summary-report-BKinV4yD.d.ts.map → summary-report-Cg7BifAM.d.ts.map} +1 -1
  124. package/dist/tool-groups-CdYq22lX.d.ts +258 -0
  125. package/dist/tool-groups-CdYq22lX.d.ts.map +1 -0
  126. package/dist/traces.d.ts +7 -6
  127. package/dist/traces.js +5 -5
  128. package/dist/{types-zFYez3PK.d.ts → types-BBFNHxSK.d.ts} +5 -5
  129. package/dist/{types-zFYez3PK.d.ts.map → types-BBFNHxSK.d.ts.map} +1 -1
  130. package/dist/{types-BtJhn8v6.d.ts → types-DoEYskCd.d.ts} +5 -5
  131. package/dist/{types-BtJhn8v6.d.ts.map → types-DoEYskCd.d.ts.map} +1 -1
  132. package/dist/{types-5q2T25iW.d.ts → types-uPrS6mD-.d.ts} +2 -2
  133. package/dist/{types-5q2T25iW.d.ts.map → types-uPrS6mD-.d.ts.map} +1 -1
  134. package/dist/usage-receipt-CgxMEBZq.js +134 -0
  135. package/dist/usage-receipt-CgxMEBZq.js.map +1 -0
  136. package/dist/wire/index.d.ts +3 -3
  137. package/dist/wire/index.js +1 -1
  138. package/docs/trace-analysis.md +170 -484
  139. package/package.json +1 -2
  140. package/dist/analyze-runs-CPYxfPWT.d.ts +0 -72
  141. package/dist/analyze-runs-CPYxfPWT.d.ts.map +0 -1
  142. package/dist/benchmark-command-CMqVqReF.js.map +0 -1
  143. package/dist/campaign-BIBS-NHV.js.map +0 -1
  144. package/dist/completion-verifier-B4-IMYcS.d.ts.map +0 -1
  145. package/dist/cost-ledger-B1D3COAc.d.ts.map +0 -1
  146. package/dist/cost-ledger-CHDLA0Ss.js.map +0 -1
  147. package/dist/default-registry-PUhIVRWz.d.ts +0 -215
  148. package/dist/default-registry-PUhIVRWz.d.ts.map +0 -1
  149. package/dist/default-registry-lp5R0lve.js.map +0 -1
  150. package/dist/ledger-core-C0Yx1I14.js.map +0 -1
  151. package/dist/registry-C4yJTza7.d.ts +0 -178
  152. package/dist/registry-C4yJTza7.d.ts.map +0 -1
  153. package/dist/replay-Cb-4Vf0k.js.map +0 -1
  154. package/dist/replay-DbIYwso6.d.ts.map +0 -1
  155. package/dist/semantic-concept-judge-DYXDPZW0.js.map +0 -1
  156. package/dist/single-run-lock-D_bS5xhj.js +0 -318
  157. package/dist/single-run-lock-D_bS5xhj.js.map +0 -1
  158. package/dist/skill-usage-Bv3G4VkA.d.ts.map +0 -1
  159. package/dist/skillopt-optimization-method-CjKMZy0d.js.map +0 -1
  160. package/dist/skillopt-optimization-method-CzfnA8O-.d.ts.map +0 -1
  161. package/dist/store-otlp-BenKynPE.js +0 -1688
  162. package/dist/store-otlp-BenKynPE.js.map +0 -1
  163. package/dist/tools-DZGdROtG.js +0 -255
  164. package/dist/tools-DZGdROtG.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"default-registry-lp5R0lve.js","names":["ANALYST_ID","finiteNonnegative","nonnegativeSafeInteger","ACTOR_PROMPT","ACTOR_PROMPT","ACTOR_PROMPT"],"sources":["../src/analyst/ax-service.ts","../src/analyst/chat-client.ts","../src/trace-analyst/behavioral-metrics.ts","../src/analyst/behavioral-analyst.ts","../src/analyst/ax-cost-service.ts","../src/ledger-core/deep-freeze.ts","../src/analyst/exact-types.ts","../src/analyst/finding-subject.ts","../src/analyst/parse-tolerant.ts","../src/analyst/finding-signature.ts","../src/analyst/structure-findings.ts","../src/analyst/kind-factory.ts","../src/analyst/kinds/control-integrity.ts","../src/analyst/tool-groups.ts","../src/analyst/kinds/failure-mode.ts","../src/analyst/kinds/improvement.ts","../src/analyst/kinds/knowledge-gap.ts","../src/analyst/kinds/knowledge-poisoning.ts","../src/analyst/kinds/index.ts","../src/feedback-trajectory-review.ts","../src/analyst/registry.ts","../src/analyst/default-registry.ts"],"sourcesContent":["import type { AxAIArgs, AxAIService } from '@ax-llm/ax'\nimport { ai } from '@ax-llm/ax'\n\nconst configuredModels = new WeakMap<object, string>()\n\nexport interface CreateAnalystAiConfig {\n /** OpenAI-compatible API key forwarded as `Authorization: Bearer`.\n * cli-bridge ignores the value on loopback but Ax requires a non-empty string. */\n apiKey: string\n /** OpenAI-compatible base URL — e.g. `https://router.tangle.tools/v1` or a\n * cli-bridge loopback. */\n baseUrl?: string\n /** Additional headers required by the gateway, such as tenant or execution policy. */\n headers?: Record<string, string>\n /** Model id forwarded to analyst calls. */\n model: string\n /** Ax provider name. Defaults to the OpenAI-compatible client. */\n provider?: AxAIArgs<unknown>['name']\n}\n\n/**\n * Construct the `AxAIService` an analyst kind calls through\n * (`createTraceAnalystKind({ ai })`).\n *\n * Ax's `ai()` pins `config.model` to the OpenAI catalog enum, but every\n * OpenAI-compatible router an analyst points at (router.tangle.tools,\n * cli-bridge) accepts arbitrary model ids (claude-code/sonnet, openai/gpt-5.4,\n * …). Consumers were each re-rolling `ai({ name, apiKey, apiURL, config })`\n * behind an `as (a: any) => any` cast to dodge the enum; this is the one\n * canonical constructor so they don't have to — and don't take a direct\n * `@ax-llm/ax` dependency for it.\n */\nexport function createAnalystAi(config: CreateAnalystAiConfig): AxAIService {\n const model = config.model.trim()\n if (!model) throw new TypeError('createAnalystAi: model must be a non-empty string')\n const args = {\n name: config.provider ?? 'openai',\n apiKey: config.apiKey,\n ...(config.baseUrl ? { apiURL: config.baseUrl } : {}),\n ...(config.headers ? { headers: config.headers } : {}),\n config: { model },\n } as unknown as AxAIArgs<unknown>\n const service = ai(args)\n configuredModels.set(service as object, model)\n return service\n}\n\nexport function getConfiguredAnalystModel(service: AxAIService): string | undefined {\n return configuredModels.get(service as object)\n}\n\n/** Resolve the model before paid work so every request can be bounded and attributed. */\nexport function resolveAnalystModel(service: AxAIService, override?: string): string {\n if (override !== undefined) {\n const model = override.trim()\n if (!model) throw new TypeError('createTraceAnalystKind: model must be a non-empty string')\n return model\n }\n const model = getConfiguredAnalystModel(service)?.trim()\n if (!model) {\n throw new TypeError(\n 'createTraceAnalystKind: model is required for Ax services not created by createAnalystAi()',\n )\n }\n return model\n}\n","/**\n * Provider-neutral chat contract for every model call made by agent-eval.\n *\n * Callers choose the transport at the package boundary with `createChatClient`.\n * Evaluation code receives canonical requests and results without importing a\n * provider SDK.\n */\n\nimport {\n type LlmCallRequest,\n type LlmCallResult,\n LlmClient,\n type LlmClientOptions,\n} from '../llm-client'\n\n/**\n * Unified chat interface using the package's canonical LLM request and result.\n */\nexport interface ChatClient {\n /** Display name of the bound transport, included in telemetry. */\n readonly transport: ChatTransport\n /** Default model when the caller omits one. */\n readonly defaultModel?: string\n /** Total provider attempts this transport can make for one chat call. */\n readonly maximumAttempts?: number\n\n /** Implementations must enforce `req.maxTokens` when it is present. */\n chat(req: ChatRequest, opts?: ChatCallOpts): Promise<ChatResponse>\n}\n\nexport type ChatTransport =\n | 'router' // router.tangle.tools — production paid models\n | 'sandbox-sdk' // box.streamPrompt() — chat completion via sandbox SDK\n | 'cli-bridge' // local cli-bridge for dev / local-only runs\n | 'direct-provider' // direct OpenAI / Anthropic / etc. — bypass router\n | 'custom' // caller-adapted SDK or transport\n | 'mock' // test-time injection\n\nexport interface ChatRequest extends Omit<LlmCallRequest, 'model'> {\n /** Optional — falls back to ChatClient.defaultModel. */\n model?: string\n}\n\nexport type ChatResponse = LlmCallResult\n\nexport interface ChatCallOpts {\n /** Cancel the in-flight request. */\n signal?: AbortSignal\n /** Hard USD ceiling for this single call (informational; the underlying transport may not enforce). */\n maxCostUsd?: number\n /** Correlation tag carried into request headers when the transport allows. */\n correlationId?: string\n /** Stable provider idempotency key for retries/redrives of one paid call. */\n idempotencyKey?: string\n}\n\n// ── Factory ─────────────────────────────────────────────────────────\n\nexport type CreateChatClientOpts =\n | RouterTransportOpts\n | CliBridgeTransportOpts\n | DirectProviderTransportOpts\n | SandboxSdkTransportOpts\n | CustomTransportOpts\n | MockTransportOpts\n\ninterface BaseTransportOpts {\n defaultModel?: string\n /** Total provider attempts. Required for opaque transports used in capped runs. */\n maximumAttempts?: number\n}\n\nexport interface RouterTransportOpts extends BaseTransportOpts {\n transport: 'router'\n baseUrl?: string\n apiKey: string\n}\n\nexport interface CliBridgeTransportOpts extends BaseTransportOpts {\n transport: 'cli-bridge'\n baseUrl?: string\n bearer?: string\n}\n\nexport interface DirectProviderTransportOpts extends BaseTransportOpts {\n transport: 'direct-provider'\n baseUrl: string\n apiKey: string\n}\n\n/**\n * Sandbox-SDK transport. The caller supplies a canonical chat function for an\n * already-configured Sandbox handle, so agent-eval does not import the SDK.\n */\nexport interface SandboxSdkTransportOpts extends BaseTransportOpts {\n transport: 'sandbox-sdk'\n chat: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/** Caller-adapted SDK or transport returning the canonical ChatResponse shape. */\nexport interface CustomTransportOpts extends BaseTransportOpts {\n transport: 'custom'\n chat: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/**\n * Mock transport for tests. The handler receives the request and returns\n * whatever the test wants. No retries, no JSON-schema degrade.\n */\nexport interface MockTransportOpts extends BaseTransportOpts {\n transport: 'mock'\n handler: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/**\n * Build a ChatClient bound to a specific transport. The returned client\n * is safe to share across analysts in a single registry run.\n */\nexport function createChatClient(opts: CreateChatClientOpts): ChatClient {\n switch (opts.transport) {\n case 'router':\n return wrapLlmClient(\n opts.transport,\n opts.defaultModel,\n new LlmClient({\n baseUrl: opts.baseUrl ?? 'https://router.tangle.tools/v1',\n apiKey: opts.apiKey,\n maximumAttempts: opts.maximumAttempts,\n } as LlmClientOptions),\n )\n case 'cli-bridge':\n return wrapLlmClient(\n opts.transport,\n opts.defaultModel,\n new LlmClient({\n baseUrl: opts.baseUrl ?? 'http://127.0.0.1:3344/v1',\n apiKey: opts.bearer ?? '',\n maximumAttempts: opts.maximumAttempts,\n } as LlmClientOptions),\n )\n case 'direct-provider':\n return wrapLlmClient(\n opts.transport,\n opts.defaultModel,\n new LlmClient({\n baseUrl: opts.baseUrl,\n apiKey: opts.apiKey,\n maximumAttempts: opts.maximumAttempts,\n } as LlmClientOptions),\n )\n case 'sandbox-sdk':\n return {\n transport: 'sandbox-sdk',\n defaultModel: opts.defaultModel,\n maximumAttempts: opts.maximumAttempts,\n chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts),\n }\n case 'custom':\n return {\n transport: 'custom',\n defaultModel: opts.defaultModel,\n maximumAttempts: opts.maximumAttempts,\n chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts),\n }\n case 'mock':\n return {\n transport: 'mock',\n defaultModel: opts.defaultModel,\n maximumAttempts: 1,\n chat: async (req, callOpts) => opts.handler(resolveModel(req, opts.defaultModel), callOpts),\n }\n }\n}\n\nfunction wrapLlmClient(\n transport: ChatTransport,\n defaultModel: string | undefined,\n inner: LlmClient,\n): ChatClient {\n return {\n transport,\n defaultModel,\n maximumAttempts: inner.maximumAttempts,\n chat: (req, callOpts) => {\n const resolved = resolveModel(req, defaultModel)\n const request: LlmCallRequest = {\n model: resolved.model!,\n messages: req.messages,\n jsonMode: req.jsonMode,\n jsonSchema: req.jsonSchema,\n temperature: req.temperature,\n maxTokens: req.maxTokens,\n thinking: req.thinking,\n timeoutMs: req.timeoutMs,\n }\n return inner.call(request, {\n signal: callOpts?.signal,\n idempotencyKey: callOpts?.idempotencyKey,\n })\n },\n }\n}\n\nfunction resolveModel(req: ChatRequest, defaultModel: string | undefined): ChatRequest {\n if (req.model) return req\n if (!defaultModel) {\n throw new Error(\n 'ChatClient.chat: no model on request and no defaultModel on the client. ' +\n 'Either pass req.model or bind defaultModel at createChatClient().',\n )\n }\n return { ...req, model: defaultModel }\n}\n","/**\n * Deterministic behavioral metrics over OTLP spans — pure arithmetic, no LLM.\n *\n * It computes token growth, output decay, tool monoculture, and missing\n * self-verification once in TypeScript with no model judgment.\n *\n * General, not trace-specific: the detectors key off token trajectories and\n * tool usage present in any agentic OTLP trace, not any one benchmark.\n */\n\nimport { LLM_CONTEXT_TOKENS } from '../trace/attribute-vocabulary'\nimport { executionTrackByLane } from '../trace/execution-tracks'\nimport {\n LLM_INPUT_TOKEN_ATTR_KEYS,\n LLM_OUTPUT_TOKEN_ATTR_KEYS,\n TOOL_NAME_ATTR_KEYS,\n} from '../trace/otlp-attributes'\nimport { spanEpochMillis } from './otlp-span'\nimport type { TraceAnalystSpan } from './types'\n\nexport type SuboptimalCode =\n | 'monotonic-input-growth'\n | 'output-length-decay'\n | 'single-tool-dependency'\n | 'no-self-verification'\n\nexport interface SuboptimalSignal {\n code: SuboptimalCode\n severity: 'high' | 'medium' | 'low'\n /** Human-readable claim, with the backing numbers inlined. */\n detail: string\n /** The exact figures the detector fired on — auditable, no model in the loop. */\n evidence: Record<string, number | string | boolean>\n}\n\nexport interface BehavioralMetrics {\n /** The only trace represented by these metrics; null when spans are empty. */\n traceId: string | null\n llmCallCount: number\n /** Causally serial LLM timelines. Parallel branches are never joined. */\n tokenSequences: BehavioralTokenSequence[]\n /** Token values from the longest serial timeline, retained for convenience. */\n inputTokenTrajectory: number[]\n outputTokenTrajectory: number[]\n toolHistogram: Record<string, number>\n totalToolCalls: number\n distinctTools: number\n /** distinct/total tool calls; 1.0 when there are no tool calls. */\n toolDiversityRatio: number\n hasSelfVerification: boolean\n signals: SuboptimalSignal[]\n}\n\nexport interface BehavioralTokenSequence {\n scopeId: string\n spanIds: string[]\n inputTokenTrajectory: Array<number | null>\n outputTokenTrajectory: Array<number | null>\n}\n\ninterface TokenSample {\n span: TraceAnalystSpan\n input: number | null\n output: number | null\n step: number | null\n}\n\n/** ≥ this input-token growth ratio across a run, with no compression, fires. */\nconst INPUT_GROWTH_FACTOR = 3\n/** Tool-usage signals need at least this many calls to be meaningful. */\nconst MIN_TOOL_CALLS = 3\n/** Tool names that read or check state count as self-verification, not mutation.\n * Covers the inspect verbs plus the read/search tools real harnesses use to\n * verify (Claude Code Read/Grep/Glob, codex read_file/ls/cat, git status/diff,\n * test/lint). A pure shell tool (Bash/exec_command) is intentionally NOT matched\n * — its name can't tell a `pytest` from an `rm`. */\nconst VERIFY_RE =\n /verif|eval|inspect|check|assert|validat|review|confirm|read|grep|glob|search|view|\\blist\\b|\\bls\\b|\\bcat\\b|\\bfind\\b|diff|status|\\btest|lint|typecheck/i\n\nfunction num(v: unknown): number | null {\n return typeof v === 'number' && Number.isFinite(v) ? v : null\n}\nfunction numAttr(attrs: Record<string, unknown>, keys: readonly string[]): number | null {\n for (const key of keys) {\n const value = num(attrs[key])\n if (value !== null) return value\n }\n return null\n}\nfunction inputTokensOf(s: TraceAnalystSpan): number | null {\n const exactContext = num(s.attributes[LLM_CONTEXT_TOKENS])\n if (exactContext !== null) return exactContext\n // Foreign producers disagree on whether prompt includes cached tokens.\n // Without an exact total, retain the reported prompt instead of guessing.\n return (\n numAttr(s.attributes, LLM_INPUT_TOKEN_ATTR_KEYS) ?? num(s.attributes['llm.usage.input_tokens'])\n )\n}\nfunction outputTokensOf(s: TraceAnalystSpan): number | null {\n return (\n numAttr(s.attributes, LLM_OUTPUT_TOKEN_ATTR_KEYS) ??\n num(s.attributes['llm.usage.output_tokens'])\n )\n}\nfunction stepOf(s: TraceAnalystSpan): number | null {\n return num(s.attributes.step)\n}\nfunction toolNameOf(s: TraceAnalystSpan): string | null {\n if (s.tool_name) return s.tool_name\n for (const key of TOOL_NAME_ATTR_KEYS) {\n const t = s.attributes[key]\n if (typeof t === 'string' && t.length > 0) return t\n }\n return null\n}\n\n/**\n * Reduce a span list to behavioral metrics + fired suboptimality signals.\n * Pure + deterministic: same spans → same output, on any machine, no model.\n */\nexport function computeTraceMetrics(spans: readonly TraceAnalystSpan[]): BehavioralMetrics {\n const traceIds = new Set(spans.map((span) => span.trace_id))\n if (traceIds.size > 1) {\n throw new Error(\n `computeTraceMetrics: expected spans from one trace, received ${traceIds.size} traces`,\n )\n }\n const traceId = traceIds.values().next().value ?? null\n\n const samples: TokenSample[] = spans.map((span) => ({\n span,\n input: inputTokensOf(span),\n output: outputTokensOf(span),\n step: stepOf(span),\n }))\n const llmSamples = samples.filter((sample) => sample.span.kind === 'LLM')\n const tokenSamples =\n llmSamples.length > 0\n ? llmSamples\n : samples.filter((sample) => sample.input !== null || sample.output !== null)\n const tokenSequences = buildTokenSequences(tokenSamples, spans)\n const primarySequence = tokenSequences[0]\n const inputTokenTrajectory =\n primarySequence?.inputTokenTrajectory.filter((value): value is number => value !== null) ?? []\n const outputTokenTrajectory =\n primarySequence?.outputTokenTrajectory.filter((value): value is number => value !== null) ?? []\n const toolHistogram: Record<string, number> = {}\n let hasSelfVerification = false\n\n for (const s of spans) {\n const tool = toolNameOf(s)\n if (tool) {\n toolHistogram[tool] = (toolHistogram[tool] ?? 0) + 1\n if (VERIFY_RE.test(tool)) hasSelfVerification = true\n }\n }\n\n const totalToolCalls = Object.values(toolHistogram).reduce((a, b) => a + b, 0)\n const distinctTools = Object.keys(toolHistogram).length\n const toolDiversityRatio = totalToolCalls === 0 ? 1 : distinctTools / totalToolCalls\n\n const signals: SuboptimalSignal[] = []\n const seenTokenSignals = new Set<SuboptimalCode>()\n for (const sequence of tokenSequences) {\n for (const signal of tokenSignals(sequence)) {\n if (seenTokenSignals.has(signal.code)) continue\n seenTokenSignals.add(signal.code)\n signals.push(signal)\n }\n }\n\n if (totalToolCalls >= MIN_TOOL_CALLS && distinctTools === 1) {\n const only = Object.keys(toolHistogram)[0]!\n signals.push({\n code: 'single-tool-dependency',\n severity: 'medium',\n detail: `All ${totalToolCalls} observed tool calls are \\`${only}\\`; no alternate tool call was observed.`,\n evidence: { tool: only, calls: totalToolCalls, distinct_tools: 1 },\n })\n }\n\n if (totalToolCalls >= MIN_TOOL_CALLS && !hasSelfVerification) {\n signals.push({\n code: 'no-self-verification',\n severity: 'medium',\n detail: `${totalToolCalls} tool calls were observed without a verification-named tool call.`,\n evidence: { tool_calls: totalToolCalls, verification_calls: 0 },\n })\n }\n\n return {\n traceId,\n llmCallCount: tokenSamples.length,\n tokenSequences,\n inputTokenTrajectory,\n outputTokenTrajectory,\n toolHistogram,\n totalToolCalls,\n distinctTools,\n toolDiversityRatio,\n hasSelfVerification,\n signals,\n }\n}\n\nfunction buildTokenSequences(\n samples: readonly TokenSample[],\n spans: readonly TraceAnalystSpan[],\n): BehavioralTokenSequence[] {\n const spansById = new Map(spans.map((span) => [span.span_id, span]))\n const executionScopeFor = createTokenExecutionScopeResolver(spansById)\n const scopedSamples = samples.map((sample) => ({\n sample,\n ...executionScopeFor(sample.span),\n }))\n const trackByLane = executionTrackByLane(scopedSamples)\n const byTrack = new Map<string, { scopeId: string; samples: TokenSample[] }>()\n for (const scoped of scopedSamples) {\n const trackId = trackByLane.get(scoped.key)!\n const track = byTrack.get(trackId) ?? { scopeId: scoped.scopeId, samples: [] }\n track.samples.push(scoped.sample)\n byTrack.set(trackId, track)\n }\n\n const sequences: BehavioralTokenSequence[] = []\n for (const { scopeId, samples: tracked } of byTrack.values()) {\n const runs = serialTokenRuns([...tracked].sort(compareTokenSamples))\n runs.forEach((run, index) => {\n sequences.push({\n scopeId: runs.length === 1 ? scopeId : `${scopeId}#${index + 1}`,\n spanIds: run.map((sample) => sample.span.span_id),\n inputTokenTrajectory: run.map((sample) => sample.input),\n outputTokenTrajectory: run.map((sample) => sample.output),\n })\n })\n }\n\n return sequences.sort(\n (a, b) =>\n b.spanIds.length - a.spanIds.length ||\n a.scopeId.localeCompare(b.scopeId) ||\n a.spanIds[0]!.localeCompare(b.spanIds[0]!),\n )\n}\n\ninterface AncestorScope {\n agentId: string | null\n rootId: string | null\n missingParentId: string | null\n laneSpanId: string | null\n}\n\nfunction createTokenExecutionScopeResolver(spansById: ReadonlyMap<string, TraceAnalystSpan>): (\n span: TraceAnalystSpan,\n) => {\n key: string\n scopeKey: string\n scopeId: string\n start: number | null\n end: number | null\n} {\n const cache = new Map<string, AncestorScope>()\n return (span) => {\n const ancestry = resolveAncestorScope(span.parent_span_id, spansById, cache)\n const rootId = ancestry.rootId\n const scopeId = ancestry.agentId\n ? `span:${ancestry.agentId}`\n : ancestry.missingParentId\n ? `parent:${ancestry.missingParentId}`\n : rootId\n ? `root:${rootId}`\n : span.agent_name\n ? `agent:${span.agent_name}`\n : `trace:${span.trace_id}`\n const scopeSpanId = ancestry.agentId ?? ancestry.missingParentId ?? rootId\n const laneSpan = ancestry.laneSpanId ? spansById.get(ancestry.laneSpanId) : undefined\n const direct = scopeSpanId === null || ancestry.laneSpanId === scopeSpanId\n const timedSpan = direct ? span : laneSpan\n return {\n key: JSON.stringify([scopeId, direct ? span.span_id : ancestry.laneSpanId]),\n scopeKey: scopeId,\n scopeId,\n start: timedSpan ? spanEpochMillis(timedSpan.start_time) : null,\n end: timedSpan ? spanEpochMillis(timedSpan.end_time) : null,\n }\n }\n}\n\nfunction resolveAncestorScope(\n startId: string | null,\n spansById: ReadonlyMap<string, TraceAnalystSpan>,\n cache: Map<string, AncestorScope>,\n): AncestorScope {\n const empty: AncestorScope = {\n agentId: null,\n rootId: null,\n missingParentId: null,\n laneSpanId: null,\n }\n if (!startId) return empty\n\n const path: string[] = []\n const pathIndex = new Map<string, number>()\n let currentId: string | null = startId\n let resolved = empty\n while (currentId) {\n const cached = cache.get(currentId)\n if (cached) {\n resolved = cached\n break\n }\n const cycleStart = pathIndex.get(currentId)\n if (cycleStart !== undefined) {\n resolved = {\n agentId: null,\n rootId: [...path.slice(cycleStart)].sort()[0]!,\n missingParentId: null,\n laneSpanId: [...path.slice(cycleStart)].sort()[0]!,\n }\n break\n }\n const current = spansById.get(currentId)\n if (!current) {\n resolved = {\n agentId: null,\n rootId: null,\n missingParentId: currentId,\n laneSpanId: currentId,\n }\n break\n }\n if (current.kind === 'AGENT') {\n resolved = {\n agentId: current.span_id,\n rootId: null,\n missingParentId: null,\n laneSpanId: current.span_id,\n }\n break\n }\n pathIndex.set(currentId, path.length)\n path.push(currentId)\n currentId = current.parent_span_id\n }\n\n for (let index = path.length - 1; index >= 0; index -= 1) {\n if (resolved.agentId === null && resolved.rootId === null) {\n resolved = { ...resolved, rootId: path[index]!, laneSpanId: path[index]! }\n } else if (\n resolved.laneSpanId === (resolved.agentId ?? resolved.missingParentId ?? resolved.rootId)\n ) {\n resolved = { ...resolved, laneSpanId: path[index]! }\n }\n cache.set(path[index]!, resolved)\n }\n return resolved\n}\n\nfunction compareTokenSamples(a: TokenSample, b: TokenSample): number {\n const aStart = spanEpochMillis(a.span.start_time)\n const bStart = spanEpochMillis(b.span.start_time)\n if (aStart === null && bStart !== null) return 1\n if (aStart !== null && bStart === null) return -1\n if (aStart !== null && bStart !== null && aStart !== bStart) return aStart - bStart\n if (a.step !== null && b.step !== null && a.step !== b.step) return a.step - b.step\n return a.span.span_id.localeCompare(b.span.span_id)\n}\n\nfunction serialTokenRuns(ordered: readonly TokenSample[]): TokenSample[][] {\n const runs: TokenSample[][] = []\n let serial: TokenSample[] = []\n let overlap: TokenSample[] = []\n let overlapEnd = Number.NEGATIVE_INFINITY\n\n const flushSerial = () => {\n if (serial.length > 0) runs.push(serial)\n serial = []\n }\n const flushOverlap = () => {\n if (overlap.length === 1) {\n serial.push(overlap[0]!)\n } else if (overlap.length > 1) {\n flushSerial()\n for (const sample of overlap) runs.push([sample])\n }\n overlap = []\n overlapEnd = Number.NEGATIVE_INFINITY\n }\n\n for (const sample of ordered) {\n const start = spanEpochMillis(sample.span.start_time)\n const end = spanEpochMillis(sample.span.end_time)\n if (start === null || end === null || sample.span.duration_ms <= 0 || end < start) {\n flushOverlap()\n flushSerial()\n runs.push([sample])\n continue\n }\n if (overlap.length > 0 && start >= overlapEnd) flushOverlap()\n overlap.push(sample)\n overlapEnd = Math.max(overlapEnd, end)\n }\n flushOverlap()\n flushSerial()\n return runs\n}\n\nfunction tokenSignals(sequence: BehavioralTokenSequence): SuboptimalSignal[] {\n const signals: SuboptimalSignal[] = []\n const inputs = sequence.inputTokenTrajectory\n const outputs = sequence.outputTokenTrajectory\n if (inputs.length >= 3 && inputs.every((value): value is number => value !== null)) {\n const first = inputs[0]!\n const last = inputs[inputs.length - 1]!\n const isMonotonic = everyAdjacent(inputs, (previous, current) => current >= previous)\n const growthFromZero = first === 0 && last > 0\n const growth = growthFromZero ? Infinity : first > 0 ? last / first : 0\n if (isMonotonic && last > first && growth >= INPUT_GROWTH_FACTOR) {\n const growthLabel = growthFromZero ? '0→nonzero (unbounded)' : `${growth.toFixed(1)}x`\n signals.push({\n code: 'monotonic-input-growth',\n severity: 'high',\n detail: `LLM input tokens grew ${growthLabel} (${first}→${last}) across ${inputs.length} serial calls without an intervening decrease.`,\n evidence: {\n first,\n last,\n growth_x: growthFromZero ? 'unbounded' : Number(growth.toFixed(2)),\n calls: inputs.length,\n scope: sequence.scopeId,\n first_span_id: sequence.spanIds[0]!,\n last_span_id: sequence.spanIds[sequence.spanIds.length - 1]!,\n },\n })\n }\n }\n\n if (\n inputs.length >= 3 &&\n inputs.length === outputs.length &&\n inputs.every((value): value is number => value !== null) &&\n outputs.every((value): value is number => value !== null)\n ) {\n const first = outputs[0]!\n const last = outputs[outputs.length - 1]!\n const inputIsMonotonic = everyAdjacent(inputs, (previous, current) => current >= previous)\n const outputIsMonotonic = everyAdjacent(outputs, (previous, current) => current <= previous)\n const inputGrew = inputs[inputs.length - 1]! > inputs[0]!\n if (inputIsMonotonic && inputGrew && outputIsMonotonic && last < first) {\n signals.push({\n code: 'output-length-decay',\n severity: 'medium',\n detail: `LLM output tokens shrank ${first}→${last} over ${outputs.length} serial calls while input tokens increased monotonically.`,\n evidence: {\n first,\n last,\n calls: outputs.length,\n scope: sequence.scopeId,\n first_span_id: sequence.spanIds[0]!,\n last_span_id: sequence.spanIds[sequence.spanIds.length - 1]!,\n },\n })\n }\n }\n return signals\n}\n\nfunction everyAdjacent(\n values: readonly number[],\n predicate: (previous: number, current: number) => boolean,\n): boolean {\n return values.slice(1).every((current, index) => predicate(values[index]!, current))\n}\n","/**\n * Deterministic behavioral analysis over arithmetic in trace spans.\n * This pass is cheap and repeatable; semantic analysis remains the job of\n * model-backed analysts. Relative quality requires a labeled comparison.\n */\n\nimport {\n type BehavioralMetrics,\n computeTraceMetrics,\n type SuboptimalCode,\n} from '../trace-analyst/behavioral-metrics'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { ExactCapableAnalyst } from './exact-types'\nimport { type AnalystFinding, makeFinding } from './types'\n\nconst RECOMMENDED_ACTION: Record<SuboptimalCode, string> = {\n 'monotonic-input-growth':\n 'Inspect context assembly; if prior history is repeatedly included, summarize completed work before the next model call.',\n 'output-length-decay':\n 'Check late-step completeness; if shorter responses omit required work, add explicit completion criteria to the agent instructions.',\n 'single-tool-dependency':\n 'Test whether an inspect or verification tool improves outcomes after the repeated call fails or returns no progress.',\n 'no-self-verification':\n 'After state-changing actions, require an observable check before the agent proceeds.',\n}\n\nconst ANALYST_ID = 'efficiency-behavioral'\nconst DEFAULT_MAX_TRACES = 1_000\nconst DEFAULT_MAX_EVIDENCE_REFS = 20\nconst TRACE_PAGE_SIZE = 200\n\nexport interface BehavioralAnalystOptions {\n /** Refuse larger unfiltered datasets instead of sampling them silently. Default 1,000. */\n maxTraces?: number\n /** Evidence locations retained per finding. Counts still cover every analyzed trace. Default 20. */\n maxEvidenceRefsPerFinding?: number\n}\n\nconst AGGREGATE_CLAIM: Record<SuboptimalCode, (observed: number, analyzed: number) => string> = {\n 'monotonic-input-growth': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces showed input tokens grow from zero to nonzero or to at least 3x their initial value across at least 3 serial model calls without a decrease.`,\n 'output-length-decay': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces showed output tokens decrease while input tokens increased monotonically across at least 3 serial model calls.`,\n 'single-tool-dependency': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces used only one named tool across at least 3 tool calls.`,\n 'no-self-verification': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces had at least 3 tool calls without a verification-named tool call.`,\n}\n\nasync function listTraceIds(\n store: TraceAnalysisStore,\n maxTraces: number,\n signal?: AbortSignal,\n): Promise<string[]> {\n const traceIds = new Set<string>()\n let offset = 0\n let expectedTotal: number | undefined\n\n while (true) {\n signal?.throwIfAborted()\n const page = await store.queryTraces({ limit: TRACE_PAGE_SIZE, offset })\n if (expectedTotal === undefined) expectedTotal = page.total\n if (page.total !== expectedTotal) {\n throw new Error(\n `behavioralAnalyst: trace count changed during pagination (${expectedTotal} to ${page.total})`,\n )\n }\n if (page.total > maxTraces) {\n throw new RangeError(\n `behavioralAnalyst: ${page.total} traces exceed maxTraces=${maxTraces}; filter the store or raise the explicit limit`,\n )\n }\n for (const trace of page.traces) traceIds.add(trace.trace_id)\n if (traceIds.size > maxTraces) {\n throw new RangeError(\n `behavioralAnalyst: more than maxTraces=${maxTraces} unique traces were returned`,\n )\n }\n if (!page.has_more) break\n if (page.traces.length === 0) {\n throw new Error('behavioralAnalyst: trace store returned an empty page with has_more=true')\n }\n offset += page.traces.length\n }\n\n if (traceIds.size !== expectedTotal) {\n throw new Error(\n `behavioralAnalyst: pagination returned ${traceIds.size}/${expectedTotal ?? 0} unique traces`,\n )\n }\n\n return [...traceIds].sort()\n}\n\n/**\n * Map computed signals → structured AnalystFindings. Pure: no LLM, no clock\n * dependence beyond `produced_at` (overridable for deterministic tests).\n */\nexport function deriveEfficiencyFindings(\n metrics: BehavioralMetrics,\n opts: { analystId?: string; producedAt?: string } = {},\n): AnalystFinding[] {\n const analystId = opts.analystId ?? ANALYST_ID\n const traceId = metrics.traceId\n return metrics.signals.map((sig) =>\n makeFinding({\n analyst_id: analystId,\n area: 'efficiency',\n subject: sig.code,\n claim: sig.detail,\n severity: sig.severity,\n // Deterministic arithmetic over spans, not a model judgment → certain.\n confidence: 1,\n evidence_refs: [\n {\n kind: 'metric',\n uri: traceId\n ? `metric://trace/${encodeURIComponent(traceId)}/efficiency/${sig.code}`\n : `metric://efficiency/${sig.code}`,\n excerpt: JSON.stringify(sig.evidence),\n },\n ],\n recommended_action: RECOMMENDED_ACTION[sig.code],\n metadata: {\n deterministic: true,\n evidence: sig.evidence,\n ...(traceId ? { trace_id: traceId } : {}),\n },\n id_basis: sig.code,\n ...(opts.producedAt ? { produced_at: opts.producedAt } : {}),\n }),\n )\n}\n\n/** The deterministic behavioral/efficiency analyst (no LLM, any-model). */\nexport function behavioralAnalyst(\n options: BehavioralAnalystOptions = {},\n): ExactCapableAnalyst<TraceAnalysisStore> {\n const maxTraces = positiveInteger(options.maxTraces ?? DEFAULT_MAX_TRACES, 'maxTraces')\n const maxEvidenceRefsPerFinding = positiveInteger(\n options.maxEvidenceRefsPerFinding ?? DEFAULT_MAX_EVIDENCE_REFS,\n 'maxEvidenceRefsPerFinding',\n )\n return {\n id: ANALYST_ID,\n description:\n 'Deterministic behavioral/efficiency findings over OTLP spans — token-growth, output-decay, tool-monoculture, missing self-verification. Zero LLM; model-agnostic by construction.',\n inputKind: 'trace-store',\n cost: { kind: 'deterministic' },\n version: '2.0.0',\n executionConfig: {\n kind: 'behavioral-efficiency',\n max_traces: maxTraces,\n max_evidence_refs_per_finding: maxEvidenceRefsPerFinding,\n },\n async analyze(store, context) {\n const analyzedTraceIds = await listTraceIds(store, maxTraces, context.signal)\n const findingsById = new Map<\n string,\n {\n finding: AnalystFinding\n observedTraceCount: number\n evidenceTraceIds: string[]\n evidence: AnalystFinding['evidence_refs']\n }\n >()\n for (const traceId of analyzedTraceIds) {\n context.signal?.throwIfAborted()\n const viewed = await store.viewTrace({ trace_id: traceId })\n if (viewed.trace_id !== traceId) {\n throw new Error(\n `behavioralAnalyst: requested trace '${traceId}', received '${viewed.trace_id}'`,\n )\n }\n if (!viewed.spans) {\n throw new Error(\n `behavioralAnalyst: trace '${traceId}' is oversized; complete spans are required`,\n )\n }\n const metrics = computeTraceMetrics(viewed.spans)\n if (metrics.traceId !== null && metrics.traceId !== traceId) {\n throw new Error(\n `behavioralAnalyst: requested trace '${traceId}', received '${metrics.traceId}'`,\n )\n }\n for (const finding of deriveEfficiencyFindings(metrics)) {\n const current = findingsById.get(finding.finding_id)\n if (!current) {\n findingsById.set(finding.finding_id, {\n finding,\n observedTraceCount: 1,\n evidenceTraceIds: [traceId],\n evidence: [...finding.evidence_refs],\n })\n continue\n }\n current.observedTraceCount += 1\n if (current.evidence.length < maxEvidenceRefsPerFinding) {\n current.evidenceTraceIds.push(traceId)\n current.evidence.push(...finding.evidence_refs)\n }\n }\n }\n return [...findingsById.values()].map(\n ({ finding, observedTraceCount, evidenceTraceIds, evidence }) => ({\n ...finding,\n claim: AGGREGATE_CLAIM[finding.subject as SuboptimalCode](\n observedTraceCount,\n analyzedTraceIds.length,\n ),\n rationale: `${observedTraceCount}/${analyzedTraceIds.length} analyzed traces exhibited this pattern.`,\n evidence_refs: evidence,\n metadata: {\n deterministic: true,\n evidence_trace_ids: evidenceTraceIds,\n omitted_evidence_trace_count: observedTraceCount - evidenceTraceIds.length,\n observed_trace_count: observedTraceCount,\n analyzed_trace_count: analyzedTraceIds.length,\n },\n }),\n )\n },\n }\n}\n\nfunction positiveInteger(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new RangeError(`behavioralAnalyst: ${name} must be a positive safe integer`)\n }\n return value\n}\n","import type { AxAIService, AxChatRequest, AxChatResponse } from '@ax-llm/ax'\nimport type { CostLedgerHandle, CostReceiptInput, MaximumCharge } from '../cost-ledger'\n\ninterface MeterAxChatServiceOptions {\n ledger: CostLedgerHandle\n actor: string\n /** Hard output limit applied to every Ax chat call. */\n maxOutputTokens: number\n /** Model configured on the Ax service when requests omit an override. */\n defaultModel?: string\n phase?: string\n tags?: Record<string, string>\n signal?: AbortSignal\n}\n\ninterface AxChatCallOptions {\n abortSignal?: AbortSignal\n stream?: boolean\n showThoughts?: boolean\n thinkingTokenBudget?: 'minimal' | 'low' | 'medium' | 'high' | 'highest' | 'none'\n retry?: { maxRetries?: number; [key: string]: unknown }\n [key: string]: unknown\n}\n\ninterface AxChatService {\n chat(\n request: Readonly<AxChatRequest>,\n options?: Readonly<AxChatCallOptions>,\n ): Promise<AxChatResponse | ReadableStream<AxChatResponse>>\n}\n\n/**\n * Meter every chat call an Ax program makes through the shared paid-call ledger.\n * The wrapper disables provider streaming because a stream has no complete usage\n * receipt until it is consumed, while Ax's analyst output is not streamed to users.\n */\nexport function meterAxChatService(\n ai: AxAIService,\n options: MeterAxChatServiceOptions,\n): AxAIService & AxChatService {\n assertPositiveInteger(options.maxOutputTokens, 'maxOutputTokens')\n const source = ai as AxAIService & Partial<AxChatService>\n if (typeof source.chat !== 'function') {\n throw new TypeError('meterAxChatService: Ax service must implement chat()')\n }\n const providerChat = source.chat.bind(ai)\n\n const chat: AxChatService['chat'] = async (request, callOptions = {}) => {\n const boundedRequest = boundOutputTokens(request, options.maxOutputTokens)\n const model = modelName(boundedRequest.model) || options.defaultModel || ''\n const canTurnOffThinking = canDisableThinking(ai, model)\n const combined = combineSignals(options.signal, callOptions.abortSignal)\n try {\n const paid = await options.ledger.runPaidCall<AxChatResponse>({\n channel: 'analyst',\n phase: options.phase ?? 'analyst.ax.chat',\n actor: options.actor,\n model,\n tags: options.tags,\n signal: combined.signal,\n maximumCharge: maximumChargeForAxChatRequest(boundedRequest, model),\n execute: async (executionSignal) => {\n const providerOptions: AxChatCallOptions = {\n ...callOptions,\n abortSignal: executionSignal,\n retry: { ...callOptions.retry, maxRetries: 0 },\n stream: false,\n showThoughts: false,\n }\n if (canTurnOffThinking) providerOptions.thinkingTokenBudget = 'none'\n else Reflect.deleteProperty(providerOptions, 'thinkingTokenBudget')\n const response = await providerChat(boundedRequest, providerOptions)\n if (response instanceof ReadableStream) {\n throw new Error('meterAxChatService: provider returned a stream after stream:false')\n }\n return response\n },\n receipt: (response) => costReceiptFromAxResponse(response, model),\n })\n if (!paid.succeeded) throw paid.error\n return paid.value\n } finally {\n combined.dispose()\n }\n }\n\n return new Proxy(ai as AxAIService & AxChatService, {\n get(target, property) {\n if (property === 'chat') return chat\n const value = Reflect.get(target, property, target)\n return typeof value === 'function' ? value.bind(target) : value\n },\n })\n}\n\n/** Conservative priced bound for one Ax text chat request. */\nexport function maximumChargeForAxChatRequest(\n request: Readonly<AxChatRequest<unknown>>,\n defaultModel?: string,\n): MaximumCharge | undefined {\n const model = modelName(request.model) || defaultModel || ''\n const maxTokens = request.modelConfig?.maxTokens\n const completions = request.modelConfig?.n\n if (!model || maxTokens === undefined || completions === undefined) return undefined\n assertPositiveInteger(maxTokens, 'request.modelConfig.maxTokens')\n assertPositiveInteger(completions, 'request.modelConfig.n')\n const maximumOutputTokens = maxTokens * completions\n assertPositiveInteger(maximumOutputTokens, 'maximum output tokens')\n if (containsUnboundedOrCacheableContent(request)) return undefined\n let inputTokens: number\n try {\n const pricedRequest = request.model === undefined ? { ...request, model } : request\n inputTokens = new TextEncoder().encode(JSON.stringify(pricedRequest)).byteLength * completions\n } catch {\n return undefined\n }\n assertPositiveInteger(inputTokens, 'maximum input tokens')\n return { model, inputTokens, outputTokens: maximumOutputTokens }\n}\n\nfunction boundOutputTokens<TModel>(\n request: Readonly<AxChatRequest<TModel>>,\n limit: number,\n): AxChatRequest<TModel> {\n const requested = request.modelConfig?.maxTokens\n if (requested !== undefined) {\n assertPositiveInteger(requested, 'request.modelConfig.maxTokens')\n }\n const completions = request.modelConfig?.n ?? 1\n assertPositiveInteger(completions, 'request.modelConfig.n')\n const maxTokens = requested === undefined ? limit : Math.min(requested, limit)\n return {\n ...request,\n ...(request.functionCall === undefined && !request.functions?.length\n ? { functionCall: 'none' as const }\n : {}),\n modelConfig: { ...request.modelConfig, maxTokens, n: completions },\n }\n}\n\nfunction costReceiptFromAxResponse(\n response: AxChatResponse,\n fallbackModel: string,\n): CostReceiptInput {\n const usage = response.modelUsage\n const tokens = usage?.tokens\n const model = usage?.model || fallbackModel\n if (\n !tokens ||\n !validUsage(tokens.promptTokens) ||\n !validUsage(tokens.completionTokens) ||\n !validUsage(tokens.totalTokens) ||\n tokens.totalTokens < tokens.promptTokens + tokens.completionTokens ||\n !validOptionalUsage(tokens.cacheReadTokens) ||\n !validOptionalUsage(tokens.cacheCreationTokens) ||\n !validOptionalUsage(tokens.reasoningTokens) ||\n !validOptionalUsage(tokens.thoughtsTokens)\n ) {\n return {\n model,\n inputTokens: 0,\n outputTokens: 0,\n usageUnknown: true,\n }\n }\n const cacheReadTokens = validUsage(tokens.cacheReadTokens) ? tokens.cacheReadTokens : 0\n const cacheCreationTokens = validUsage(tokens.cacheCreationTokens)\n ? tokens.cacheCreationTokens\n : 0\n const totalCacheTokens = cacheReadTokens + cacheCreationTokens\n const thoughtsTokens = validUsage(tokens.thoughtsTokens) ? tokens.thoughtsTokens : 0\n const reasoningTokens = Math.max(\n validUsage(tokens.reasoningTokens) ? tokens.reasoningTokens : 0,\n thoughtsTokens,\n )\n // OpenAI includes reasoning in completionTokens, while other Ax providers may\n // report hidden output separately. Only add reasoning when it cannot be a\n // subset of completionTokens; thoughts are always separately billed output.\n const separateReasoningTokens = reasoningTokens > tokens.completionTokens ? reasoningTokens : 0\n const additionalOutputTokens = Math.max(thoughtsTokens, separateReasoningTokens)\n const outputTokens = tokens.completionTokens + additionalOutputTokens\n const directTotal = tokens.promptTokens + tokens.completionTokens\n const validTotals = new Set([\n directTotal,\n directTotal + totalCacheTokens,\n directTotal + additionalOutputTokens,\n directTotal + totalCacheTokens + additionalOutputTokens,\n ])\n if (!validTotals.has(tokens.totalTokens)) {\n return {\n model,\n inputTokens: 0,\n outputTokens: 0,\n usageUnknown: true,\n }\n }\n return {\n model,\n inputTokens: tokens.promptTokens,\n outputTokens,\n ...(reasoningTokens > 0 ? { reasoningTokens } : {}),\n ...(cacheReadTokens > 0 ? { cachedTokens: cacheReadTokens } : {}),\n ...(cacheCreationTokens > 0 ? { cacheWriteTokens: cacheCreationTokens } : {}),\n }\n}\n\nfunction combineSignals(\n first: AbortSignal | undefined,\n second: AbortSignal | undefined,\n): { signal: AbortSignal | undefined; dispose(): void } {\n if (!first) return { signal: second, dispose: () => {} }\n if (!second || first === second) return { signal: first, dispose: () => {} }\n if (typeof AbortSignal.any === 'function') {\n return { signal: AbortSignal.any([first, second]), dispose: () => {} }\n }\n\n const controller = new AbortController()\n const dispose = (): void => {\n first.removeEventListener('abort', abortFromFirst)\n second.removeEventListener('abort', abortFromSecond)\n }\n const abortFrom = (source: AbortSignal): void => {\n if (!controller.signal.aborted) controller.abort(source.reason)\n dispose()\n }\n const abortFromFirst = (): void => abortFrom(first)\n const abortFromSecond = (): void => abortFrom(second)\n if (first.aborted) abortFrom(first)\n else if (second.aborted) abortFrom(second)\n else {\n first.addEventListener('abort', abortFromFirst, { once: true })\n second.addEventListener('abort', abortFromSecond, { once: true })\n }\n return { signal: controller.signal, dispose }\n}\n\nfunction containsUnboundedOrCacheableContent(request: Readonly<AxChatRequest<unknown>>): boolean {\n if (request.functions?.some((fn) => fn.cache === true)) return true\n return request.chatPrompt.some((message) => {\n if (message.cache === true) return true\n if (!('content' in message) || !Array.isArray(message.content)) return false\n return message.content.some((part) => part.cache === true || part.type !== 'text')\n })\n}\n\nfunction modelName(value: unknown): string {\n return typeof value === 'string' ? value : ''\n}\n\nfunction canDisableThinking(ai: AxAIService, model: string): boolean {\n // Ax maps \"none\" to a Gemini 3 thinking level, which cannot coexist with maxTokens.\n const namedAi = ai as { getName?: () => string }\n const serviceName = typeof namedAi.getName === 'function' ? namedAi.getName() : ''\n const modelId = model.slice(model.lastIndexOf('/') + 1)\n return serviceName !== 'GoogleGeminiAI' || !/^gemini-3(?:[.-]|$)/i.test(modelId)\n}\n\nfunction validUsage(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n}\n\nfunction validOptionalUsage(value: unknown): boolean {\n return value === undefined || validUsage(value)\n}\n\nfunction assertPositiveInteger(value: number, field: string): void {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new RangeError(`meterAxChatService: ${field} must be a positive integer`)\n }\n}\n","/** Freeze a detached canonical-JSON graph. Canonicalization has already ruled out cycles.\n *\n * Lives outside canonical.ts so the analyst-benchmark implementation digest,\n * which covers canonical.ts, stays bound to the published benchmark evidence. */\nexport function deepFreezeCanonicalJson<T>(value: T): T {\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n Object.freeze(value)\n for (const nested of Object.values(value)) deepFreezeCanonicalJson(nested)\n }\n return value\n}\n","import { z } from 'zod'\nimport { canonicalString, hashCanonical } from '../ledger-core/canonical'\nimport { deepFreezeCanonicalJson } from '../ledger-core/deep-freeze'\nimport type { Analyst, AnalystRunEvent, AnalystRunResult, AnalystRunSummary } from './types'\n\n/** Analyst metadata required before the exact registry path will execute it. */\nexport interface ExactCapableAnalyst<TInput = unknown> extends Analyst<TInput> {\n /** Canonical JSON for every effective behavior knob not already bound by `version`. */\n readonly executionConfig: Readonly<Record<string, unknown>>\n}\n\ntype DeepReadonly<T> = T extends readonly (infer Item)[]\n ? readonly DeepReadonly<Item>[]\n : T extends object\n ? { readonly [Key in keyof T]: DeepReadonly<T[Key]> }\n : T\n\nexport type ExactAnalystSnapshot = DeepReadonly<z.infer<typeof analystSnapshotSchema>>\nexport type ExactAnalystBudgetSnapshot = DeepReadonly<z.infer<typeof budgetSnapshotSchema>>\n\n/** Caller-provided identity for a component used by an exact run. */\nexport interface ExactExecutionComponentIdentity {\n id: string\n version: string\n config: Readonly<Record<string, unknown>>\n}\n\n/** Persisted identity; configuration is bound by digest and never stored raw. */\nexport interface ExactExecutionComponentSnapshot {\n id: string\n version: string\n config_digest: string\n}\n\n/** Canonical identity for any live component admitted to an exact run. */\nexport function snapshotExactExecutionComponentIdentity(\n value: ExactExecutionComponentIdentity,\n context: string,\n): ExactExecutionComponentSnapshot {\n let detached: unknown\n try {\n detached = JSON.parse(canonicalString(value)) as unknown\n } catch (cause) {\n throw new TypeError(`${context} must have a canonical JSON representation`, { cause })\n }\n const parsed = componentIdentitySchema.safeParse(detached)\n if (!parsed.success) {\n throw new TypeError(`${context} requires non-empty id/version and object config`)\n }\n return deepFreezeCanonicalJson({\n id: parsed.data.id,\n version: parsed.data.version,\n config_digest: hashCanonical(parsed.data.config),\n })\n}\n\nexport type ExactAnalystRunPolicySnapshot = DeepReadonly<z.infer<typeof exactRunPolicySchema>>\nexport type ExactAnalystExecutionPlanSnapshot = DeepReadonly<\n z.infer<typeof exactExecutionPlanSchema>\n>\n\nexport type ExactAnalystRunSummary = AnalystRunSummary & {\n /** Effective caller-owned budget; null means uncapped. Skipped work has no allocation. */\n allocated_budget_usd?: number | null\n}\n\nexport type ExactAnalystRunCompletion =\n | { status: 'complete' }\n | {\n status: 'failed'\n error: { class: string; message: string }\n }\n\nexport interface ExactAnalystRunResult extends AnalystRunResult {\n per_analyst: ExactAnalystRunSummary[]\n execution_plan: ExactAnalystExecutionPlanSnapshot\n completion: ExactAnalystRunCompletion\n}\n\n/** Exact events are detached immutable snapshots of the shared serial execution stream. */\nexport type ExactAnalystRunEvent =\n | (Extract<AnalystRunEvent, { type: 'run-started' }> & {\n execution_plan: ExactAnalystExecutionPlanSnapshot\n })\n | (Omit<Extract<AnalystRunEvent, { type: 'analyst-skipped' }>, 'summary'> & {\n summary: ExactAnalystRunSummary\n })\n | Extract<AnalystRunEvent, { type: 'analyst-started' }>\n | (Omit<Extract<AnalystRunEvent, { type: 'analyst-completed' }>, 'summary'> & {\n summary: ExactAnalystRunSummary\n })\n | (Omit<Extract<AnalystRunEvent, { type: 'run-completed' }>, 'result'> & {\n result: ExactAnalystRunResult\n })\n\nconst nonEmptyString = z.string().min(1)\nconst digest = z.string().regex(/^sha256:[a-f0-9]{64}$/)\nconst finiteNonnegative = z.number().finite().nonnegative()\nconst nonnegativeSafeInteger = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER)\nconst positiveTimeout = z.number().int().positive().max(2_147_483_647)\n\nconst componentSnapshotSchema = z.strictObject({\n id: nonEmptyString,\n version: nonEmptyString,\n config_digest: digest,\n})\nconst componentIdentitySchema = z.strictObject({\n id: nonEmptyString,\n version: nonEmptyString,\n config: z.record(z.string(), z.unknown()),\n})\n\nconst deterministicCostSchema = z.strictObject({\n kind: z.literal('deterministic'),\n est_usd_per_run: finiteNonnegative.optional(),\n models: z.array(nonEmptyString).optional(),\n})\n\nconst llmCostSchema = z.strictObject({\n kind: z.literal('llm'),\n est_usd_per_run: finiteNonnegative.optional(),\n models: z.array(nonEmptyString).optional(),\n settlement_timeout_ms: nonnegativeSafeInteger.optional(),\n})\n\nconst requirementsSchema = z\n .strictObject({\n min_shots: nonnegativeSafeInteger.optional(),\n capabilities: z.array(nonEmptyString).optional(),\n })\n .nullable()\n\nconst analystSnapshotSchema = z.strictObject({\n id: nonEmptyString,\n version: nonEmptyString,\n input_kind: z.enum(['trace-store', 'artifact-dir', 'run-record', 'judge-input', 'custom']),\n cost: z.discriminatedUnion('kind', [deterministicCostSchema, llmCostSchema]),\n requirements: requirementsSchema,\n execution_config_digest: digest,\n})\n\nconst allocationsSchema = z.record(nonEmptyString, z.union([finiteNonnegative, z.null()]))\nconst weightsSchema = z.record(nonEmptyString, finiteNonnegative)\nconst budgetSnapshotSchema = z.discriminatedUnion('kind', [\n z.strictObject({ kind: z.literal('none') }),\n z.strictObject({\n kind: z.literal('equal'),\n total_usd: finiteNonnegative,\n allocations_usd: allocationsSchema,\n }),\n z.strictObject({\n kind: z.literal('weighted'),\n total_usd: finiteNonnegative,\n weights: weightsSchema,\n allocations_usd: allocationsSchema,\n }),\n])\n\nconst priorFindingsSchema = z.discriminatedUnion('kind', [\n z.strictObject({ kind: z.literal('none') }),\n z.strictObject({\n kind: z.literal('ordered'),\n count: nonnegativeSafeInteger,\n digest,\n }),\n z.strictObject({\n kind: z.literal('by_analyst'),\n keys: z.array(nonEmptyString),\n count: nonnegativeSafeInteger,\n digest,\n }),\n])\n\nconst exactRunPolicySchema = z.strictObject({\n budget: budgetSnapshotSchema,\n total_timeout_ms: positiveTimeout.nullable(),\n signal_provided: z.boolean(),\n cost_ledger: componentSnapshotSchema.nullable(),\n cost_phase: nonEmptyString.nullable(),\n tags: z.record(z.string(), z.string()).nullable(),\n prior_findings: priorFindingsSchema,\n chain_findings: z.boolean(),\n missing_input_mode: z.enum(['skip', 'abort']),\n registry_hooks: componentSnapshotSchema.nullable(),\n registry_chat: componentSnapshotSchema.nullable(),\n})\n\nconst exactExecutionPlanSchema = z\n .strictObject({\n schema_version: z.literal('1.0.0'),\n analysts: z.array(analystSnapshotSchema).min(1),\n policy: exactRunPolicySchema,\n digest,\n })\n .superRefine((plan, context) => {\n const issue = (path: PropertyKey[], message: string): void =>\n context.addIssue({ code: 'custom', path, message })\n const analystIds = plan.analysts.map((analyst) => analyst.id)\n if (new Set(analystIds).size !== analystIds.length) {\n issue(['analysts'], 'analyst ids must be unique')\n }\n if (plan.policy.cost_ledger === null && plan.policy.cost_phase !== null) {\n issue(['policy', 'cost_phase'], 'cost phase requires a cost ledger')\n }\n if (\n plan.policy.prior_findings.kind === 'by_analyst' &&\n plan.policy.prior_findings.keys.some(\n (key, index, keys) => index > 0 && key <= keys[index - 1]!,\n )\n ) {\n issue(['policy', 'prior_findings', 'keys'], 'keys must be sorted and unique')\n }\n\n const budget = plan.policy.budget\n if (budget.kind === 'none') return\n const allocationIds = Object.keys(budget.allocations_usd).sort()\n const selectedIds = [...analystIds].sort()\n if (\n allocationIds.length !== selectedIds.length ||\n allocationIds.some((id, index) => id !== selectedIds[index])\n ) {\n issue(\n ['policy', 'budget', 'allocations_usd'],\n 'allocations must name every analyst and no others',\n )\n return\n }\n const runnableIds = analystIds.filter((id) => budget.allocations_usd[id] !== null)\n const epsilon = Math.max(1, budget.total_usd) * Number.EPSILON * 8\n if (runnableIds.length === 0) return\n\n if (budget.kind === 'weighted') {\n const weightIds = Object.keys(budget.weights).sort()\n if (\n weightIds.length !== selectedIds.length ||\n weightIds.some((id, index) => id !== selectedIds[index])\n ) {\n issue(['policy', 'budget', 'weights'], 'weights must name every analyst and no others')\n return\n }\n const totalWeight = runnableIds.reduce((sum, id) => sum + (budget.weights[id] ?? 0), 0)\n if (totalWeight === 0) {\n issue(['policy', 'budget', 'weights'], 'runnable analysts must have positive total weight')\n return\n }\n for (const id of runnableIds) {\n const expected = (budget.total_usd * (budget.weights[id] ?? 0)) / totalWeight\n if (Math.abs((budget.allocations_usd[id] ?? 0) - expected) > epsilon) {\n issue(\n ['policy', 'budget', 'allocations_usd', id],\n 'allocation does not match the weighted policy',\n )\n }\n }\n return\n }\n\n const expected = budget.total_usd / runnableIds.length\n for (const id of runnableIds) {\n if (Math.abs((budget.allocations_usd[id] ?? 0) - expected) > epsilon) {\n issue(\n ['policy', 'budget', 'allocations_usd', id],\n 'allocation does not match the equal policy',\n )\n }\n }\n })\n\n/**\n * Canonicalize and validate the one exact-plan representation shared by execution and archival.\n * Unknown fields fail at every level; the returned graph is detached and deeply frozen.\n */\nexport function snapshotExactExecutionPlan(\n value: unknown,\n context = 'exact analyst execution plan',\n): ExactAnalystExecutionPlanSnapshot {\n let detached: unknown\n try {\n detached = JSON.parse(canonicalString(value)) as unknown\n } catch (cause) {\n throw new TypeError(`${context} must have a canonical JSON representation`, { cause })\n }\n const parsed = exactExecutionPlanSchema.safeParse(detached)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n const path = issue?.path.length ? ` ${issue.path.join('.')}` : ''\n throw new TypeError(`${context}${path}: ${issue?.message ?? 'is invalid'}`)\n }\n const expectedDigest = hashCanonical({\n schema_version: parsed.data.schema_version,\n analysts: parsed.data.analysts,\n policy: parsed.data.policy,\n })\n if (parsed.data.digest !== expectedDigest) {\n throw new TypeError(`${context} digest does not match its content`)\n }\n return deepFreezeCanonicalJson(parsed.data as ExactAnalystExecutionPlanSnapshot)\n}\n","/**\n * Typed `FindingSubject` — the canonical grammar every analyst kind emits.\n *\n * Background: kind actor prompts have always documented a subject grammar\n * (e.g. `system-prompt:<section>`, `agent-knowledge:wiki:<slug>`) but the\n * LLM was unconstrained — it could emit `subject: \"fix the prompt\"`\n * (prose) and downstream adapters routed on `startsWith(...)` would\n * silently skip it. Every per-vertical `ImprovementAdapter` had a\n * routing table that mostly caught nothing.\n *\n * This module fixes that:\n * - `parseFindingSubject(raw)` — returns the typed `FindingSubject`\n * when `raw` matches the grammar, else `null`. Used at the\n * `RawAnalystFindingSchema` boundary so malformed subjects are\n * rejected loudly instead of silently lifted into the registry.\n * - `FindingSubjectKind` — the union of valid locus categories. Each\n * variant carries the typed components downstream adapters resolve\n * against the agent's surface manifest (no string parsing in the\n * adapter).\n * - `FINDING_SUBJECT_GRAMMAR_PROMPT` — single source of truth for the\n * grammar string embedded in kind actor prompts. Drift between\n * prompt and parser is impossible if every kind imports this.\n *\n * The grammar is intentionally NARROW — only loci the substrate's\n * default `ImprovementAdapter` / `KnowledgeAdapter` can act on. A\n * finding with a subject outside this set fails the parser; the kind\n * author either extends the grammar here (and adds adapter routing)\n * or rephrases the prompt to map onto an existing variant.\n *\n * `failure-mode` is the one exception — its subjects are free-form\n * cluster labels, not loci. The schema preserves them as\n * `{ kind: 'cluster', label }` and the adapters skip them (cluster\n * findings are evidence, not actionable mutations).\n */\n\nimport { z } from 'zod'\n\n// ── canonical grammar ─────────────────────────────────────────────────\n\n/**\n * Discriminated union of every locus the substrate can route findings to.\n *\n * Adapters narrow on `kind` and use the typed components (no string\n * parsing). Adding a variant here REQUIRES updating the parser, the\n * grammar prompt, and at least one adapter — by design.\n */\nexport type FindingSubject =\n // ── agent-knowledge:* — routed to the KnowledgeAdapter ──\n | { kind: 'knowledge.wiki'; slug: string; heading?: string }\n | { kind: 'knowledge.claim'; topic: string }\n | { kind: 'knowledge.raw'; sourceId: string }\n | { kind: 'knowledge.stale'; slug: string }\n // ── system-prompt / tool / new-tool / rag / memory / scaffolding / output-schema ──\n // routed to the ImprovementAdapter\n | { kind: 'system-prompt'; section: string }\n | { kind: 'skill'; name: string }\n | { kind: 'tool-doc'; tool: string; aspect?: string }\n | { kind: 'new-tool'; name: string }\n | { kind: 'mcp'; server: string; tool?: string }\n | { kind: 'hook'; name: string }\n | { kind: 'subagent'; name: string }\n | { kind: 'workflow'; name: string }\n | { kind: 'rollout-policy'; field: string }\n | { kind: 'agent-profile'; field: string }\n | { kind: 'code'; path: string }\n | { kind: 'rag'; corpus: string; docId: string }\n | { kind: 'memory'; key: string }\n | { kind: 'scaffolding'; concern: string }\n | { kind: 'output-schema'; field: string }\n // ── websearch / prior-run-summary — routed to the KnowledgeAdapter as stale signals\n | { kind: 'websearch.outdated'; topic: string }\n | { kind: 'prior-run-summary'; topic: string }\n // ── failure-mode cluster label — preserved verbatim, not routed\n | { kind: 'cluster'; label: string }\n\nexport type FindingSubjectKind = FindingSubject['kind']\n\nexport const FINDING_SUBJECT_KINDS: ReadonlyArray<FindingSubjectKind> = [\n 'knowledge.wiki',\n 'knowledge.claim',\n 'knowledge.raw',\n 'knowledge.stale',\n 'system-prompt',\n 'skill',\n 'tool-doc',\n 'new-tool',\n 'mcp',\n 'hook',\n 'subagent',\n 'workflow',\n 'rollout-policy',\n 'agent-profile',\n 'code',\n 'rag',\n 'memory',\n 'scaffolding',\n 'output-schema',\n 'websearch.outdated',\n 'prior-run-summary',\n 'cluster',\n]\n\n// ── parser ────────────────────────────────────────────────────────────\n\n/**\n * Parse a raw subject string emitted by an analyst kind's actor.\n *\n * Returns the typed `FindingSubject` when `raw` matches the grammar,\n * else `null`. Callers use the `null` return as a signal to either\n * (a) reject the finding at parse time (kinds that emit typed loci —\n * knowledge-gap, improvement, knowledge-poisoning) or (b) lift it as\n * a cluster label (failure-mode).\n *\n * Slugs are constrained to `[a-z0-9-]+` (lowercase kebab) to keep file\n * paths sane downstream. Topics / keys / sections allow any non-empty\n * string (free-form for the LLM's voice) but get trimmed.\n *\n * Empty / whitespace-only inputs return `null`. `undefined` returns\n * `null`. Both are surfaced by the caller as a rejected subject.\n */\nexport function parseFindingSubject(raw: string | null | undefined): FindingSubject | null {\n if (raw === null || raw === undefined) return null\n const trimmed = raw.trim()\n if (trimmed.length === 0) return null\n\n // agent-knowledge:wiki:<slug>[#<heading>]\n const wiki = trimmed.match(\n /^agent-knowledge:wiki:([a-z0-9][a-z0-9-]*)(?:#([a-z0-9][a-z0-9-]*))?$/,\n )\n if (wiki)\n return { kind: 'knowledge.wiki', slug: wiki[1]!, ...(wiki[2] ? { heading: wiki[2] } : {}) }\n\n // agent-knowledge:claim:<topic>\n const claim = trimmed.match(/^agent-knowledge:claim:(.+)$/)\n if (claim && claim[1]!.trim().length > 0)\n return { kind: 'knowledge.claim', topic: claim[1]!.trim() }\n\n // agent-knowledge:raw:<source-id>\n const raw_ = trimmed.match(/^agent-knowledge:raw:(.+)$/)\n if (raw_ && raw_[1]!.trim().length > 0)\n return { kind: 'knowledge.raw', sourceId: raw_[1]!.trim() }\n\n // agent-knowledge:stale:<slug>\n const stale = trimmed.match(/^agent-knowledge:stale:([a-z0-9][a-z0-9-]*)$/)\n if (stale) return { kind: 'knowledge.stale', slug: stale[1]! }\n\n // system-prompt:<section>\n const sp = trimmed.match(/^system-prompt:(.+)$/)\n if (sp && sp[1]!.trim().length > 0) return { kind: 'system-prompt', section: sp[1]!.trim() }\n\n // skill:<name>\n const skill = trimmed.match(/^skill:([a-z0-9][a-z0-9_.-]*)$/)\n if (skill) return { kind: 'skill', name: skill[1]! }\n\n // tool-doc:<tool>[:<aspect>]\n const tdAspect = trimmed.match(/^tool-doc:([a-z0-9][a-z0-9_-]*):(.+)$/)\n if (tdAspect && tdAspect[2]!.trim().length > 0) {\n return { kind: 'tool-doc', tool: tdAspect[1]!, aspect: tdAspect[2]!.trim() }\n }\n const td = trimmed.match(/^tool-doc:([a-z0-9][a-z0-9_-]*)$/)\n if (td) return { kind: 'tool-doc', tool: td[1]! }\n\n // new-tool:<name>\n const nt = trimmed.match(/^new-tool:([a-z0-9][a-z0-9_-]*)$/)\n if (nt) return { kind: 'new-tool', name: nt[1]! }\n\n // mcp:<server>[:<tool>]\n const mcp = trimmed.match(/^mcp:([a-z0-9][a-z0-9_.-]*)(?::([a-z0-9][a-z0-9_.-]*))?$/)\n if (mcp) {\n return { kind: 'mcp', server: mcp[1]!, ...(mcp[2] ? { tool: mcp[2] } : {}) }\n }\n\n // hook / subagent / workflow:<name>\n const hook = trimmed.match(/^hook:([a-z0-9][a-z0-9_.-]*)$/)\n if (hook) return { kind: 'hook', name: hook[1]! }\n const subagent = trimmed.match(/^subagent:([a-z0-9][a-z0-9_.-]*)$/)\n if (subagent) return { kind: 'subagent', name: subagent[1]! }\n const workflow = trimmed.match(/^workflow:([a-z0-9][a-z0-9_.-]*)$/)\n if (workflow) return { kind: 'workflow', name: workflow[1]! }\n\n // rollout-policy / agent-profile:<field>\n const rolloutPolicy = trimmed.match(/^rollout-policy:(.+)$/)\n if (rolloutPolicy && rolloutPolicy[1]!.trim().length > 0) {\n return { kind: 'rollout-policy', field: rolloutPolicy[1]!.trim() }\n }\n const agentProfile = trimmed.match(/^agent-profile:(.+)$/)\n if (agentProfile && agentProfile[1]!.trim().length > 0) {\n return { kind: 'agent-profile', field: agentProfile[1]!.trim() }\n }\n\n // code:<path>\n const code = trimmed.match(/^code:(.+)$/)\n if (code && code[1]!.trim().length > 0) return { kind: 'code', path: code[1]!.trim() }\n\n // rag:<corpus>:<doc-id>\n const rag = trimmed.match(/^rag:([a-z0-9][a-z0-9_-]*):(.+)$/)\n if (rag && rag[2]!.trim().length > 0) {\n return { kind: 'rag', corpus: rag[1]!, docId: rag[2]!.trim() }\n }\n\n // memory:<key>\n const mem = trimmed.match(/^memory:(.+)$/)\n if (mem && mem[1]!.trim().length > 0) return { kind: 'memory', key: mem[1]!.trim() }\n\n // scaffolding:<concern>\n const sc = trimmed.match(/^scaffolding:(.+)$/)\n if (sc && sc[1]!.trim().length > 0) return { kind: 'scaffolding', concern: sc[1]!.trim() }\n\n // output-schema:<field>\n const os = trimmed.match(/^output-schema:(.+)$/)\n if (os && os[1]!.trim().length > 0) return { kind: 'output-schema', field: os[1]!.trim() }\n\n // websearch:outdated:<topic>\n const ws = trimmed.match(/^websearch:outdated:(.+)$/)\n if (ws && ws[1]!.trim().length > 0) return { kind: 'websearch.outdated', topic: ws[1]!.trim() }\n\n // prior-run-summary:<topic>\n const prs = trimmed.match(/^prior-run-summary:(.+)$/)\n if (prs && prs[1]!.trim().length > 0) return { kind: 'prior-run-summary', topic: prs[1]!.trim() }\n\n // cluster (no prefix — a free-form evidence label, never a routed locus, so\n // it admits dotted/underscored identifiers like `appworld.task.530b157_1`.\n // ':' stays excluded so it cannot collide with the prefixed grammars above.)\n if (/^[a-z0-9][a-z0-9._-]*$/.test(trimmed) && trimmed.length <= 80) {\n return { kind: 'cluster', label: trimmed }\n }\n\n return null\n}\n\n/**\n * Render the parsed subject back to its canonical string form. Inverse\n * of `parseFindingSubject`; useful when the substrate constructs new\n * findings programmatically (e.g. for tests, replays, or\n * `id_basis` carry-forward).\n */\nexport function renderFindingSubject(s: FindingSubject): string {\n switch (s.kind) {\n case 'knowledge.wiki':\n return s.heading\n ? `agent-knowledge:wiki:${s.slug}#${s.heading}`\n : `agent-knowledge:wiki:${s.slug}`\n case 'knowledge.claim':\n return `agent-knowledge:claim:${s.topic}`\n case 'knowledge.raw':\n return `agent-knowledge:raw:${s.sourceId}`\n case 'knowledge.stale':\n return `agent-knowledge:stale:${s.slug}`\n case 'system-prompt':\n return `system-prompt:${s.section}`\n case 'skill':\n return `skill:${s.name}`\n case 'tool-doc':\n return s.aspect ? `tool-doc:${s.tool}:${s.aspect}` : `tool-doc:${s.tool}`\n case 'new-tool':\n return `new-tool:${s.name}`\n case 'mcp':\n return s.tool ? `mcp:${s.server}:${s.tool}` : `mcp:${s.server}`\n case 'hook':\n return `hook:${s.name}`\n case 'subagent':\n return `subagent:${s.name}`\n case 'workflow':\n return `workflow:${s.name}`\n case 'rollout-policy':\n return `rollout-policy:${s.field}`\n case 'agent-profile':\n return `agent-profile:${s.field}`\n case 'code':\n return `code:${s.path}`\n case 'rag':\n return `rag:${s.corpus}:${s.docId}`\n case 'memory':\n return `memory:${s.key}`\n case 'scaffolding':\n return `scaffolding:${s.concern}`\n case 'output-schema':\n return `output-schema:${s.field}`\n case 'websearch.outdated':\n return `websearch:outdated:${s.topic}`\n case 'prior-run-summary':\n return `prior-run-summary:${s.topic}`\n case 'cluster':\n return s.label\n }\n}\n\n// ── grammar prompt — single source of truth for actor instructions ──\n\n/**\n * The grammar text embedded into kind actor prompts. Kinds opt into\n * the subset of variants they emit (e.g. `improvement` excludes the\n * cluster variant; `failure-mode` includes ONLY the cluster variant).\n *\n * Drift between prompt and parser is impossible: every kind imports\n * this constant + the matching `expects` set, and the unit tests below\n * lock the table to the parser.\n */\nexport const FINDING_SUBJECT_SYNTAX: Readonly<Record<FindingSubjectKind, string>> = {\n 'knowledge.wiki': 'agent-knowledge:wiki:<slug>[#<heading>]',\n 'knowledge.claim': 'agent-knowledge:claim:<topic>',\n 'knowledge.raw': 'agent-knowledge:raw:<source-id>',\n 'knowledge.stale': 'agent-knowledge:stale:<slug>',\n 'system-prompt': 'system-prompt:<section>',\n skill: 'skill:<name>',\n 'tool-doc': 'tool-doc:<tool>[:<aspect>]',\n 'new-tool': 'new-tool:<name>',\n mcp: 'mcp:<server>[:<tool>]',\n hook: 'hook:<name>',\n subagent: 'subagent:<name>',\n workflow: 'workflow:<name>',\n 'rollout-policy': 'rollout-policy:<field>',\n 'agent-profile': 'agent-profile:<field>',\n code: 'code:<path>',\n rag: 'rag:<corpus>:<doc-id>',\n memory: 'memory:<key>',\n scaffolding: 'scaffolding:<concern>',\n 'output-schema': 'output-schema:<field>',\n 'websearch.outdated': 'websearch:outdated:<topic>',\n 'prior-run-summary': 'prior-run-summary:<topic>',\n cluster: '<lowercase-cluster-label>',\n}\n\nconst FINDING_SUBJECT_PURPOSE: Readonly<Record<FindingSubjectKind, string>> = {\n 'knowledge.wiki': 'create or update a wiki page',\n 'knowledge.claim': 'draft a claim or relation',\n 'knowledge.raw': 'curate a raw source',\n 'knowledge.stale': 'mark a stale page',\n 'system-prompt': 'revise a system-prompt section',\n skill: 'create or revise a skill',\n 'tool-doc': 'revise a tool contract',\n 'new-tool': 'propose a new tool',\n mcp: 'revise an MCP server or tool',\n hook: 'revise a lifecycle hook',\n subagent: 'revise a delegated agent',\n workflow: 'revise an orchestration workflow',\n 'rollout-policy': 'revise budget, sampling, or stop policy',\n 'agent-profile': 'revise another AgentProfile field',\n code: 'revise an implementation path',\n rag: 'ingest or correct a RAG document',\n memory: 'invalidate or set memory',\n scaffolding: 'revise preconditions, retries, or verification',\n 'output-schema': 'constrain the output shape',\n 'websearch.outdated': 'identify a stale web result',\n 'prior-run-summary': 'identify a stale prior-run summary',\n cluster: 'name one failure cluster',\n}\n\nfunction renderFindingSubjectGrammar(kinds: ReadonlyArray<FindingSubjectKind>): string {\n return [\n 'Subjects MUST match one of these forms — anything else is rejected at parse time:',\n ...kinds.map((kind) => ` ${FINDING_SUBJECT_SYNTAX[kind]} — ${FINDING_SUBJECT_PURPOSE[kind]}`),\n 'Runtime ids are lowercase [a-z0-9_.-]+. Topics, keys, paths, and sections are free-form and trimmed.',\n ].join('\\n')\n}\n\nexport const FINDING_SUBJECT_GRAMMAR_PROMPT = renderFindingSubjectGrammar(FINDING_SUBJECT_KINDS)\n\n// ── kind expects sets ─────────────────────────────────────────────────\n\n/**\n * The variants each kind is allowed to emit. Used at the kind factory\n * boundary so a knowledge-gap finding can't sneak in a `system-prompt:*`\n * subject (the improvement-analyst's job) and vice versa.\n *\n * `failure-mode` is restricted to `cluster` — the only kind that emits\n * a non-locus subject.\n */\nexport const KIND_EXPECTED_SUBJECTS: Record<string, ReadonlyArray<FindingSubjectKind>> = {\n 'failure-mode': ['cluster'],\n 'knowledge-gap': [\n 'knowledge.wiki',\n 'knowledge.claim',\n 'knowledge.raw',\n 'knowledge.stale',\n 'tool-doc',\n 'system-prompt',\n 'skill',\n 'mcp',\n 'subagent',\n 'workflow',\n 'memory',\n 'websearch.outdated',\n 'prior-run-summary',\n ],\n 'knowledge-poisoning': [\n 'knowledge.wiki',\n 'knowledge.claim',\n 'knowledge.raw',\n 'tool-doc',\n 'system-prompt',\n 'skill',\n 'mcp',\n 'hook',\n 'memory',\n 'websearch.outdated',\n 'prior-run-summary',\n ],\n improvement: [\n 'system-prompt',\n 'skill',\n 'tool-doc',\n 'new-tool',\n 'mcp',\n 'hook',\n 'subagent',\n 'workflow',\n 'rollout-policy',\n 'agent-profile',\n 'code',\n 'rag',\n 'memory',\n 'scaffolding',\n 'output-schema',\n 'knowledge.wiki',\n 'knowledge.claim',\n ],\n}\n\n/** Render only the subject forms one analyst kind is permitted to emit. */\nexport function findingSubjectGrammarPromptFor(kindId: string): string {\n const kinds = KIND_EXPECTED_SUBJECTS[kindId]\n if (!kinds) throw new Error(`unknown analyst kind: ${kindId}`)\n return renderFindingSubjectGrammar(kinds)\n}\n\n// ── Zod schema for boundary validation ───────────────────────────────\n\n/**\n * Zod schema that validates a raw subject string and returns the parsed\n * `FindingSubject`. Embedded in `RawAnalystFindingSchema` via\n * `transform`, so `subject` arrives at the kind factory either as a\n * typed locus or as a parse error attached to a single Zod issue.\n *\n * Optionality is preserved: subjects ARE optional on the wire (some\n * findings are descriptive, not actionable). When present, they MUST\n * parse — emitting a malformed subject is a contract violation, not a\n * soft signal.\n */\nexport const FindingSubjectStringSchema = z\n .string()\n .refine((s) => parseFindingSubject(s) !== null, {\n message: 'subject does not match the finding-subject grammar',\n })\n","/**\n * Forgiving pre-parse for analyst findings. Weak models routinely emit\n * schema-correct content in an unusable wrapper — fenced ```json blocks, a\n * single object where an array is expected, trailing commas. Measured: GPT-4o\n * drops to 0% usable output purely from markdown-fence wrapping\n * (arXiv:2605.02363). A five-line de-fence recovers most of it. This module is\n * the de-fence/coerce step that runs BEFORE Zod, so a recoverable finding is\n * repaired, not dropped.\n *\n * Pure + deterministic. No model, no network.\n */\n\n/** Strip a ```lang ... ``` (or bare ``` ... ```) code fence, if the string is one. */\nexport function stripCodeFences(text: string): string {\n const t = text.trim()\n const fence = /^```[a-zA-Z0-9]*\\s*\\n?([\\s\\S]*?)\\n?```$/\n const m = t.match(fence)\n return m ? m[1]!.trim() : t\n}\n\n/** Remove trailing commas before } or ] — the most common near-JSON defect. */\nfunction dropTrailingCommas(s: string): string {\n return s.replace(/,(\\s*[}\\]])/g, '$1')\n}\n\n/**\n * Best-effort parse of a string into JSON. De-fences, drops trailing commas,\n * then `JSON.parse`. Returns `undefined` (never throws) when unrecoverable.\n */\nexport function coerceJson(text: string): unknown {\n const candidate = dropTrailingCommas(stripCodeFences(text))\n try {\n return JSON.parse(candidate)\n } catch {\n return undefined\n }\n}\n\n/**\n * Coerce arbitrary actor/structurer output into an array of candidate finding\n * rows: a JSON string → parse; a single object → 1-element array; an array →\n * as-is; anything else → []. Callers still run each row through Zod\n * (`parseRawFinding`) — this only fixes the shape and never invents fields.\n */\nexport function coerceToFindingRows(raw: unknown): unknown[] {\n let value = raw\n if (typeof value === 'string') {\n const parsed = coerceJson(value)\n if (parsed === undefined) return []\n value = parsed\n }\n if (Array.isArray(value)) return value\n if (value && typeof value === 'object') {\n // Some models wrap the array as { findings: [...] } — unwrap that one case.\n const inner = (value as Record<string, unknown>).findings\n if (Array.isArray(inner)) return inner\n return [value]\n }\n return []\n}\n","/**\n * Typed Ax output for analyst findings.\n *\n * Ax binds the field as `findings:json[]` so the provider emits native\n * structured output. At the kind-factory boundary every row is validated\n * before it becomes an `AnalystFinding`.\n *\n * Why not `f.object().array()` directly in the signature? The Ax\n * signature string `question:string -> findings:json[]` already lets\n * the provider emit JSON arrays. A Zod boundary is required either\n * way (the provider can return any JSON), and Zod gives us a single\n * validation surface independent of which Ax version is installed.\n */\n\nimport { z } from 'zod'\nimport { parseFindingSubject } from './finding-subject'\nimport { coerceJson } from './parse-tolerant'\nimport type { EvidenceRef } from './types'\n\nexport const ANALYST_SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'] as const\n\nexport const RawAnalystEvidenceSchema = z\n .object({\n uri: z.string().trim().min(1).max(2000),\n excerpt: z.string().max(2000).optional(),\n })\n .strict()\n\nexport type RawAnalystEvidence = z.infer<typeof RawAnalystEvidenceSchema>\n\nconst RawAnalystFindingBaseShape = {\n severity: z.enum(ANALYST_SEVERITIES),\n claim: z.string().min(1).max(2000),\n subject: z\n .string()\n .max(400)\n .refine((subject) => parseFindingSubject(subject) !== null, {\n message: 'subject does not match the finding-subject grammar',\n })\n .optional(),\n confidence: z.number().min(0).max(1),\n rationale: z.string().max(4000).optional(),\n recommended_action: z.string().max(2000).optional(),\n}\n\nexport const RawAnalystFindingSchema = z\n .object({\n ...RawAnalystFindingBaseShape,\n evidence: z.array(RawAnalystEvidenceSchema).min(1),\n })\n .strict()\n\nexport type RawAnalystFinding = z.infer<typeof RawAnalystFindingSchema>\n\n/**\n * Description embedded into the actor prompt so the LLM knows what\n * shape to emit. Kept here so kinds share one source of truth rather\n * than restating the schema in every prompt.\n */\nexport const RAW_FINDING_SCHEMA_PROMPT = `Each finding MUST be a strict JSON object with:\n - severity: \"critical\" | \"high\" | \"medium\" | \"low\" | \"info\"\n - claim: one-sentence statement (max 2000 chars)\n - subject?: one exact subject form listed by this kind; omit rather than guess\n - evidence: REQUIRED non-empty array of {\"uri\": string, \"excerpt\"?: string}. Use real identifiers with span://, event://, artifact://, metric://, or finding://. Include a short exact quote in excerpt when available. If nothing is citable, do not emit the finding.\n - confidence: number 0..1 (0.9+ exact evidence; 0.6-0.8 inferred pattern; <0.5 speculative)\n - rationale?: one or two reasoning sentences\n - recommended_action?: concrete imperative change; omit for descriptive findings\n\nUnknown fields are rejected. Do not emit area; the factory assigns it. Emit [] when there are no findings. Never fabricate evidence.`\n\n/** Convert raw citations into the public finding evidence envelope. */\nexport function evidenceRefsFromRawFinding(finding: RawAnalystFinding): EvidenceRef[] {\n return finding.evidence.map(({ uri, excerpt }) => ({\n kind: evidenceKindFromUri(uri),\n uri,\n excerpt,\n }))\n}\n\nexport function parseRawFinding(\n row: unknown,\n log?: (msg: string, fields?: Record<string, unknown>) => void,\n): RawAnalystFinding | null {\n return parseFindingWithSchema(RawAnalystFindingSchema, row, log)\n}\n\nfunction parseFindingWithSchema<T>(\n schema: z.ZodType<T>,\n row: unknown,\n log?: (msg: string, fields?: Record<string, unknown>) => void,\n): T | null {\n const result = schema.safeParse(row)\n if (result.success) return result.data\n // A schema-correct finding in an unusable wrapper (a JSON string, a fenced\n // block) should be repaired, not dropped. Coerce the shape and retry ONCE.\n if (typeof row === 'string') {\n const coerced = coerceJson(row)\n if (coerced !== undefined) {\n const retry = schema.safeParse(coerced)\n if (retry.success) return retry.data\n }\n }\n log?.('finding rejected: schema failure', {\n issues: result.error.issues.map((i) => ({\n path: i.path.join('.'),\n code: i.code,\n message: i.message,\n })),\n })\n return null\n}\n\nfunction evidenceKindFromUri(uri: string): EvidenceRef['kind'] {\n if (uri.startsWith('span://')) return 'span'\n if (/^trace:\\/\\/[^/]+\\/span\\/[^/]+$/.test(uri)) return 'span'\n if (uri.startsWith('event://')) return 'event'\n if (uri.startsWith('finding://')) return 'finding'\n if (uri.startsWith('metric://')) return 'metric'\n return 'artifact'\n}\n","/**\n * `structureFindings` — the deferred structuring pass (DSPy TwoStepAdapter /\n * HALO `synthesize_traces` analog). The agentic actor reasons FREE-FORM and\n * emits a prose `report` (which any model does reliably); this separate, cheap\n * call's ONLY job is to turn that report into `AnalystFinding[]`. Decoupling\n * reasoning from structuring is what makes the SEMANTIC findings model-agnostic\n * — the reasoning model never has to satisfy a strict typed-array contract\n * while it diagnoses.\n *\n * Forgiving: the response runs through `coerceToFindingRows` (de-fence, lift\n * single→array) before Zod, and on a zero-finding extraction from a substantive\n * report it reasks ONCE with the schema restated. Returns a typed outcome so a\n * legitimate \"nothing to report\" is distinguishable from a failed extraction\n * (no silent empty).\n */\n\nimport { CostLedger, type CostLedgerHandle } from '../cost-ledger'\nimport {\n callLlm,\n costReceiptFromLlm,\n costReceiptFromLlmError,\n type LlmCallRequest,\n type LlmClientOptions,\n maximumChargeForLlmRequest,\n} from '../llm-client'\nimport {\n evidenceRefsFromRawFinding,\n parseRawFinding,\n RAW_FINDING_SCHEMA_PROMPT,\n type RawAnalystFinding,\n} from './finding-signature'\nimport { coerceToFindingRows } from './parse-tolerant'\nimport { type AnalystFinding, makeFinding } from './types'\n\nexport interface StructureFindingsOptions {\n /** The actor's free-form diagnosis prose. */\n report: string\n analystId: string\n /** Coarse classification stamped on every extracted finding. */\n area: string\n model: string\n baseUrl: string\n apiKey?: string\n /** Optional ledger for direct use. */\n costLedger?: CostLedgerHandle\n costPhase?: string\n costTags?: Record<string, string>\n maxTokens?: number\n signal?: AbortSignal\n /** Max reask attempts after a zero/invalid extraction. Default 1. */\n maxReasks?: number\n /** Apply the caller's normal finding rules before a recovered row is lifted. */\n processRow?: (row: RawAnalystFinding) => RawAnalystFinding | null\n /** Provenance copied onto every recovered finding. */\n findingMetadata?: Record<string, unknown>\n /** Test seam: inject a fetch (no network in unit tests). */\n fetchImpl?: LlmClientOptions['fetch']\n}\n\nexport interface StructureFindingsResult {\n findings: AnalystFinding[]\n outcome: 'ok' | 'extraction_failed'\n}\n\nconst SYSTEM = [\n 'You convert a free-form trace-analysis report into a STRICT JSON array of findings.',\n 'Output ONLY the JSON array — no prose, no code fences.',\n RAW_FINDING_SCHEMA_PROMPT,\n 'Omit subject when the report does not contain an exact valid locus.',\n 'If the report asserts NO problems, output exactly [].',\n].join(' ')\n\nfunction buildRows(raw: unknown, opts: StructureFindingsOptions): AnalystFinding[] {\n const rows = coerceToFindingRows(raw)\n const out: AnalystFinding[] = []\n for (const row of rows) {\n const parsed = parseRawFinding(row)\n if (!parsed) continue\n const callbackResult = opts.processRow ? opts.processRow(parsed) : parsed\n if (!callbackResult) continue\n const processed = parseRawFinding(callbackResult)\n if (!processed) continue\n out.push(\n makeFinding({\n analyst_id: opts.analystId,\n area: opts.area,\n subject: processed.subject,\n claim: processed.claim,\n rationale: processed.rationale,\n severity: processed.severity,\n confidence: processed.confidence,\n evidence_refs: evidenceRefsFromRawFinding(processed),\n recommended_action: processed.recommended_action,\n ...(opts.findingMetadata ? { metadata: { ...opts.findingMetadata } } : {}),\n }),\n )\n }\n return out\n}\n\nexport async function structureFindings(\n opts: StructureFindingsOptions,\n): Promise<StructureFindingsResult> {\n const maxReasks = opts.maxReasks ?? 1\n if (!Number.isSafeInteger(maxReasks) || maxReasks < 0) {\n throw new RangeError('structureFindings: maxReasks must be a non-negative safe integer')\n }\n const llm = { baseUrl: opts.baseUrl, apiKey: opts.apiKey, fetch: opts.fetchImpl }\n const costLedger = opts.costLedger ?? new CostLedger()\n let user = `TRACE-ANALYSIS REPORT:\\n${opts.report}\\n\\nReturn the findings JSON array.`\n\n for (let attempt = 0; attempt <= maxReasks; attempt++) {\n const request: LlmCallRequest = {\n model: opts.model,\n messages: [\n { role: 'system', content: SYSTEM },\n { role: 'user', content: user },\n ],\n maxTokens: opts.maxTokens ?? 2_000,\n }\n const paid = await costLedger.runPaidCall({\n channel: 'analyst',\n phase: opts.costPhase ?? 'analyst.structure-findings',\n actor: 'structure-findings',\n model: opts.model,\n signal: opts.signal,\n maximumCharge: maximumChargeForLlmRequest(request, llm),\n tags: { ...opts.costTags, analystId: opts.analystId, attempt: String(attempt) },\n execute: (signal, callId) => callLlm(request, { ...llm, signal, idempotencyKey: callId }),\n receipt: costReceiptFromLlm,\n receiptFromError: costReceiptFromLlmError,\n })\n if (!paid.succeeded) throw paid.error\n const res = paid.value\n const text = res.content.trim()\n const findings = buildRows(text, opts)\n if (findings.length > 0) return { findings, outcome: 'ok' }\n // A report that asserts nothing is a legitimate empty — only reask when the\n // report is substantive (the extraction, not the diagnosis, likely failed).\n if (opts.report.trim().length < 200) return { findings: [], outcome: 'ok' }\n user = `${user}\\n\\nThat produced no valid findings. The report DOES describe issues — re-extract them as the strict JSON array described in the system prompt. Output ONLY the array.`\n }\n return { findings: [], outcome: 'extraction_failed' }\n}\n","/**\n * Analyst-kind factory — the typed way to define trace analysts.\n *\n * A \"kind\" is a specialized analyst whose actor prompt, tool subset,\n * and bounded Ax subqueries target one failure-mode lens (failure-mode\n * classification, knowledge gap discovery, knowledge poisoning,\n * self-improvement, ...). Kinds emit findings in the typed\n * `RawAnalystFinding` shape via a JSON-array Ax output; the factory\n * validates each row with Zod and lifts it into `AnalystFinding[]`.\n *\n * Composition rules:\n * - Each kind owns its actor description. No generic \"answer this\n * question\" prompt — the prompt names the failure lens.\n * - Each kind picks a narrow tool subset from `ANALYST_TOOL_GROUPS`.\n * A kind that never needs full-trace dumps can drop `viewTrace` /\n * `viewSpans` and stay cheap.\n * - Each kind declares its subquery + parallelism budget. Discovery-heavy\n * kinds can fan out more bounded semantic questions than narrow lenses.\n *\n * Evaluate prompt changes through `runAnalystBenchmark`, where labels include\n * exact evidence locations and clean cases instead of output-string overlap.\n */\n\nimport type { AxAIService, AxFunction } from '@ax-llm/ax'\nimport { CostLedger } from '../cost-ledger'\nimport { hashCanonical } from '../ledger-core/canonical'\nimport { runTraceAnalysisLoop } from '../trace-analyst/loop'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport { meterAxChatService } from './ax-cost-service'\nimport { resolveAnalystModel } from './ax-service'\nimport {\n type ExactCapableAnalyst,\n type ExactExecutionComponentIdentity,\n snapshotExactExecutionComponentIdentity,\n} from './exact-types'\nimport {\n evidenceRefsFromRawFinding,\n parseRawFinding,\n RAW_FINDING_SCHEMA_PROMPT,\n type RawAnalystFinding,\n} from './finding-signature'\nimport { KIND_EXPECTED_SUBJECTS, parseFindingSubject } from './finding-subject'\nimport { structureFindings } from './structure-findings'\nimport type { AnalystContext, AnalystCost, AnalystFinding } from './types'\nimport { makeFinding } from './types'\nimport { settleUsageReceiptFromCostLedger, validateUsageSettlementTimeout } from './usage-receipt'\n\n/**\n * Per-kind specification. The factory turns this into a regular\n * `Analyst<TraceAnalysisStore>` ready for `AnalystRegistry.register()`.\n */\nexport interface TraceAnalystKindSpec {\n /** Stable id. Appears in finding_id, telemetry, and registry exclusions. */\n id: string\n /** One-sentence description shown in `registry.list()`. */\n description: string\n /** Coarse classification stamped on every emitted finding (`failure-mode`, `knowledge-gap`, ...). */\n area: string\n /** Bump on any breaking change to the actor prompt or output schema. */\n version: string\n /** Actor system prompt. Must instruct the LLM to emit `findings` per the schema. */\n actorDescription: string\n /** Tool functions the actor may call. Pick narrow subsets via `ANALYST_TOOL_GROUPS`. */\n buildTools: (store: TraceAnalysisStore) => AxFunction[]\n /**\n * Deterministically prepare one bounded context value before model work.\n * Returning a string uses Ax's long-context path without tools. Returning\n * undefined keeps the normal tool-driven path.\n */\n prepareContext?: (\n store: TraceAnalysisStore,\n ctx: AnalystContext,\n ) => string | undefined | Promise<string | undefined>\n /** Bounded semantic subqueries. `maxCalls: 0` disables model fan-out. */\n subqueries?: { maxCalls: number; maxParallel?: number }\n /** Actor turn cap. Default 12. */\n maxTurns?: number\n /** Runtime char cap. Default 6000. */\n maxRuntimeChars?: number\n /** Maximum output tokens for every actor and subquery model call. Default 4096. */\n maxOutputTokens?: number\n /** Cost classification surfaced in `registry.list()` and budget enforcement. */\n cost: AnalystCost\n /** Per-finding-row hook — kinds may reject / rewrite before lifting. */\n postProcess?: (row: RawAnalystFinding, ctx: AnalystContext) => RawAnalystFinding | null\n /** Minimum citations per finding. Default 1; rows below it are rejected. */\n minimumEvidenceCitations?: number\n /** Reject a substantive report when no structured finding survives validation. */\n requireStructuredFindings?: boolean\n}\n\nexport interface CreateTraceAnalystKindOpts {\n /** AxAIService bound at registration time. */\n ai: AxAIService\n /** Required when this analyst is used by `runExact`; binds the effective AI service. */\n aiIdentity?: ExactExecutionComponentIdentity\n /** Required unless `ai` was created by {@link createAnalystAi}. */\n model?: string\n /** Override the spec's `version` (e.g. when an optimizer has fitted a new prompt). */\n versionSuffix?: string\n /**\n * Optional two-phase recovery: when the agentic harvest is empty but the\n * actor produced a substantive free-form `report`, extract findings from that\n * prose via a tolerant chat-completions pass (`structureFindings`) — no\n * strict-emission contract, so it works on weak models. Omit to leave the\n * actor's harvest as-is (the report is still surfaced fail-loud either way).\n */\n recovery?: { baseUrl: string; apiKey?: string; model?: string; fetchImpl?: typeof fetch }\n /** Maximum post-cancellation wait for a provider receipt. Default 5 seconds. */\n settlementTimeoutMs?: number\n}\n\n/**\n * Build an `Analyst<TraceAnalysisStore>` from a kind spec.\n *\n * Lifts the Ax pipeline once at registration time so the registry\n * gets a stateless analyst. The Ax agent is freshly constructed per\n * `analyze()` call (the agent carries chat-log + usage state we don't\n * want shared across analyst runs).\n */\nexport function createTraceAnalystKind(\n spec: TraceAnalystKindSpec,\n opts: CreateTraceAnalystKindOpts,\n): ExactCapableAnalyst<TraceAnalysisStore> {\n rejectRemovedKindOptions(spec)\n const version = opts.versionSuffix ? `${spec.version}+${opts.versionSuffix}` : spec.version\n const model = resolveAnalystModel(opts.ai, opts.model)\n const minimumEvidenceCitations = spec.minimumEvidenceCitations ?? 1\n if (!Number.isInteger(minimumEvidenceCitations) || minimumEvidenceCitations < 1) {\n throw new TypeError('minimumEvidenceCitations must be a positive integer')\n }\n const settlementTimeoutMs = validateUsageSettlementTimeout(opts.settlementTimeoutMs)\n const maxOutputTokens = spec.maxOutputTokens ?? 4096\n const aiIdentity =\n opts.aiIdentity === undefined\n ? null\n : snapshotExactExecutionComponentIdentity(\n opts.aiIdentity,\n 'createTraceAnalystKind aiIdentity',\n )\n return {\n id: spec.id,\n description: spec.description,\n inputKind: 'trace-store',\n cost: { ...spec.cost, settlement_timeout_ms: settlementTimeoutMs },\n version,\n executionConfig: {\n kind: 'trace-analyst',\n model,\n ai_identity: aiIdentity,\n actor_description_digest: hashCanonical(spec.actorDescription.trim()),\n max_subqueries: spec.subqueries?.maxCalls ?? 0,\n max_parallel_subqueries: spec.subqueries?.maxParallel ?? 2,\n max_turns: spec.maxTurns ?? 12,\n max_runtime_chars: spec.maxRuntimeChars ?? 6000,\n max_output_tokens: maxOutputTokens,\n minimum_evidence_citations: minimumEvidenceCitations,\n require_structured_findings: spec.requireStructuredFindings ?? false,\n prepare_context: spec.prepareContext === undefined ? 'disabled' : 'version-bound',\n post_process: spec.postProcess === undefined ? 'disabled' : 'version-bound',\n recovery:\n opts.recovery === undefined\n ? null\n : {\n base_url: opts.recovery.baseUrl,\n model: opts.recovery.model ?? model,\n api_key_provided: opts.recovery.apiKey !== undefined,\n fetch_implementation:\n opts.recovery.fetchImpl === undefined ? 'global' : 'version-bound',\n },\n settlement_timeout_ms: settlementTimeoutMs,\n },\n async analyze(store, ctx) {\n const costLedger = ctx.costLedger ?? new CostLedger(ctx.budgetUsd)\n const costTags = {\n ...(ctx.tags ?? {}),\n analystId: spec.id,\n ...(ctx.correlationId ? { analystRunId: ctx.correlationId } : {}),\n }\n const meteredAi = meterAxChatService(opts.ai, {\n ledger: costLedger,\n actor: spec.id,\n maxOutputTokens,\n defaultModel: model,\n phase: ctx.costPhase,\n signal: ctx.signal,\n tags: costTags,\n })\n try {\n const preparedContext = await spec.prepareContext?.(store, ctx)\n if (preparedContext !== undefined && typeof preparedContext !== 'string') {\n throw new TypeError(`Trace analyst '${spec.id}' prepareContext must return a string`)\n }\n const tools = preparedContext === undefined ? spec.buildTools(store) : []\n const analysisMode = preparedContext === undefined ? 'tool-loop' : 'prepared-context'\n const maxSubqueries = spec.subqueries?.maxCalls ?? 0\n const maxParallel = spec.subqueries?.maxParallel ?? 2\n const priorContext = renderPriorFindings(ctx.priorFindings)\n const upstreamContext = renderUpstreamFindings(ctx.upstreamFindings)\n const actorDescription =\n spec.actorDescription.trim() +\n priorContext +\n upstreamContext +\n '\\n\\n' +\n RAW_FINDING_SCHEMA_PROMPT +\n (minimumEvidenceCitations > 1\n ? `\\n\\nThis kind requires at least ${minimumEvidenceCitations} evidence citations per finding; rows with fewer are rejected.`\n : '') +\n '\\n\\nFirst write `report`: a concise free-form prose diagnosis of what ' +\n 'the traces show — what succeeded, what was suboptimal or failed — with ' +\n 'concrete trace ids and numbers. THEN return the structured `findings` ' +\n 'array (it MAY be empty when there is nothing to report).'\n\n ctx.log?.(`analyst.kind ${spec.id} forward`, {\n max_subqueries: maxSubqueries,\n tool_count: tools.length,\n analysis_mode: analysisMode,\n prepared_context_chars: preparedContext?.length ?? 0,\n tags: ctx.tags,\n })\n\n const completed = await runTraceAnalysisLoop({\n id: spec.id,\n description: spec.description,\n prompt: actorDescription,\n question: deriveQuestion(ctx, spec),\n ai: meteredAi,\n model,\n tools,\n findingType: 'object',\n maxSubqueries,\n maxParallelSubqueries: maxParallel,\n maxTurns: spec.maxTurns ?? 12,\n maxRuntimeChars: spec.maxRuntimeChars ?? 6000,\n ...(preparedContext !== undefined ? { context: preparedContext } : {}),\n ...(ctx.signal ? { signal: ctx.signal } : {}),\n })\n const { report, findings: submittedFindings } = completed\n\n const expectedSubjects = KIND_EXPECTED_SUBJECTS[spec.id]\n const out: AnalystFinding[] = []\n const rawRows = submittedFindings\n let rejectedWrongKind = 0\n let rejectedInsufficientEvidence = 0\n const processRow = (parsed: RawAnalystFinding): RawAnalystFinding | null => {\n const callbackResult = spec.postProcess ? spec.postProcess(parsed, ctx) : parsed\n if (!callbackResult) return null\n const postProcessed = parseRawFinding(callbackResult, ctx.log)\n if (!postProcessed) return null\n if (expectedSubjects && postProcessed.subject !== undefined) {\n const parsedSubject = parseFindingSubject(postProcessed.subject)\n if (parsedSubject === null) {\n ctx.log?.('finding rejected: subject failed to parse', {\n kind: spec.id,\n subject: postProcessed.subject,\n })\n rejectedWrongKind += 1\n return null\n }\n if (!expectedSubjects.includes(parsedSubject.kind)) {\n ctx.log?.('finding rejected: subject variant not allowed for this kind', {\n kind: spec.id,\n subject_kind: parsedSubject.kind,\n subject: postProcessed.subject,\n allowed: expectedSubjects,\n })\n rejectedWrongKind += 1\n return null\n }\n }\n const distinctEvidenceCitations = new Set(\n postProcessed.evidence.map((citation) => citation.uri.trim()),\n ).size\n if (distinctEvidenceCitations < minimumEvidenceCitations) {\n ctx.log?.('finding rejected: insufficient evidence citations', {\n kind: spec.id,\n required: minimumEvidenceCitations,\n received: postProcessed.evidence.length,\n distinct: distinctEvidenceCitations,\n })\n rejectedInsufficientEvidence += 1\n return null\n }\n return postProcessed\n }\n for (const row of rawRows) {\n const parsed = parseRawFinding(row, ctx.log)\n if (!parsed) continue\n const postProcessed = processRow(parsed)\n if (!postProcessed) continue\n out.push(\n toAnalystFinding(spec, version, postProcessed, {\n analysis_mode: analysisMode,\n analysis_turn_count: completed.turnCount,\n }),\n )\n }\n\n ctx.log?.(`analyst.kind ${spec.id} done`, {\n emitted: rawRows.length,\n accepted: out.length,\n rejected_wrong_subject: rejectedWrongKind,\n rejected_insufficient_evidence: rejectedInsufficientEvidence,\n })\n\n // Two-phase recovery / fail-loud. The actor reasons free-form (the\n // `report`); a weak model often produces a sound diagnosis but fails the\n // strict findings emission (or the rows get rejected). If the harvest is\n // empty but the report is substantive, recover findings from the prose\n // via the tolerant structuring pass (opt-in), and — either way — surface\n // the report as a visible info finding so an empty harvest is never a\n // silent zero. A genuinely empty diagnosis (short/no report) stays empty.\n if (out.length === 0 && report.trim().length >= 200) {\n if (opts.recovery) {\n const wrongKindBefore = rejectedWrongKind\n const insufficientEvidenceBefore = rejectedInsufficientEvidence\n const recovered = await structureFindings({\n report,\n analystId: spec.id,\n area: spec.area,\n model: opts.recovery.model ?? model,\n baseUrl: opts.recovery.baseUrl,\n apiKey: opts.recovery.apiKey,\n fetchImpl: opts.recovery.fetchImpl,\n costLedger,\n costPhase: ctx.costPhase,\n costTags,\n signal: ctx.signal,\n maxTokens: Math.min(maxOutputTokens, 2_000),\n processRow,\n findingMetadata: { kind_version: version },\n })\n out.push(...recovered.findings)\n ctx.log?.(`analyst.kind ${spec.id} recovery`, {\n outcome: recovered.outcome,\n recovered: recovered.findings.length,\n rejected_wrong_subject: rejectedWrongKind - wrongKindBefore,\n rejected_insufficient_evidence:\n rejectedInsufficientEvidence - insufficientEvidenceBefore,\n })\n }\n if (out.length === 0) {\n if (spec.requireStructuredFindings) {\n throw new Error(\n `Trace analyst '${spec.id}' produced no valid structured findings after ${completed.turnCount} turns: ${truncateForContext(report, 600)}`,\n )\n }\n const fallback = processRow({\n claim: 'Analyst produced a diagnosis but no structured findings — see report.',\n rationale: report.slice(0, 1500),\n severity: 'info',\n confidence: 0.3,\n evidence: [{ uri: 'report://summary', excerpt: report.slice(0, 2000) }],\n })\n if (fallback) {\n out.push(\n toAnalystFinding(spec, version, fallback, {\n analysis_mode: analysisMode,\n analysis_turn_count: completed.turnCount,\n outcome: 'extraction_failed',\n }),\n )\n } else {\n throw new Error(\n `Trace analyst '${spec.id}' produced a substantive report, but no finding satisfied its acceptance rules`,\n )\n }\n }\n }\n return out\n } finally {\n const usage = await settleUsageReceiptFromCostLedger(costLedger, {\n tags: {\n analystId: spec.id,\n ...(ctx.correlationId ? { analystRunId: ctx.correlationId } : {}),\n },\n timeoutMs: settlementTimeoutMs,\n })\n if (!usage.settled) {\n ctx.log?.(`analyst.kind ${spec.id} provider settlement timed out`, {\n pending_calls: usage.pendingCalls,\n timeout_ms: settlementTimeoutMs,\n })\n }\n ctx.recordUsage?.(usage.receipt)\n }\n },\n }\n}\n\nfunction rejectRemovedKindOptions(spec: TraceAnalystKindSpec): void {\n const supplied = spec as unknown as Record<string, unknown>\n const migrations = [\n ['recursion', 'subqueries'],\n ['responderDescription', 'actorDescription'],\n ['maxDepth', 'subqueries'],\n ['maxParallelSubagents', 'subqueries.maxParallel'],\n ['subagentDescription', 'actorDescription'],\n ] as const\n for (const [removed, replacement] of migrations) {\n if (removed in supplied) {\n throw new TypeError(\n `createTraceAnalystKind: '${removed}' is unsupported; use '${replacement}'`,\n )\n }\n }\n}\n\nfunction deriveQuestion(ctx: AnalystContext, spec: TraceAnalystKindSpec): string {\n // The actor's user message must orient it at the task, not echo the kind id.\n // A bare id like \"failure-mode\" gives the actor nothing to act on, so it\n // spends turns inspecting the input instead of reading traces. Operators can\n // still steer with `tags.focus = \"leaf-X\"`, appended to the task directive.\n const focus = ctx.tags?.focus?.trim()\n const task = `Analyze this trace dataset with the available tools and report ${spec.area} findings. ${spec.description}`\n return focus ? `${task} Focus: ${focus}.` : task\n}\n\nfunction toAnalystFinding(\n spec: TraceAnalystKindSpec,\n version: string,\n raw: RawAnalystFinding,\n metadata: Record<string, unknown> = {},\n): AnalystFinding {\n return makeFinding({\n analyst_id: spec.id,\n area: spec.area,\n subject: raw.subject,\n claim: raw.claim,\n rationale: raw.rationale,\n severity: raw.severity,\n confidence: raw.confidence,\n evidence_refs: evidenceRefsFromRawFinding(raw),\n recommended_action: raw.recommended_action,\n metadata: { kind_version: version, ...metadata },\n })\n}\n\n/**\n * Render a compact prior-findings block the actor reads alongside its\n * brief. Each row is one line so the actor can scan dozens cheaply.\n * The kind's prompt instructs the actor to (a) check whether a new\n * cluster matches a prior `finding_id` (carry the id forward via\n * `id_basis` to keep diffs stable) and (b) raise severity / confidence\n * when a prior finding has reappeared without remediation.\n *\n * Returns the empty string when there are no prior findings — most\n * runs are \"first-of-its-kind\" and the prompt stays unchanged.\n *\n * Exported for tests + for consumers that build their own actor\n * prompts (e.g. specialized analysts living outside the default kinds).\n */\nexport function renderPriorFindings(prior: AnalystContext['priorFindings']): string {\n if (!prior || prior.length === 0) return ''\n const MAX_ROWS = 40 // keep the block under ~2KB; older history is summarized externally\n const rows = prior.slice(0, MAX_ROWS).map((f) => {\n const subject = f.subject ? ` [${f.subject}]` : ''\n return ` - id=${f.finding_id} ${f.severity}${subject} ${truncateForContext(f.claim, 160)}`\n })\n const overflow =\n prior.length > MAX_ROWS\n ? `\\n ... +${prior.length - MAX_ROWS} more prior findings (older history truncated)`\n : ''\n return [\n '',\n '',\n 'PRIOR FINDINGS (from a previous run on related data):',\n 'When the work you do now matches a row below, REUSE the `finding_id` (pass it as `id_basis`) so the cross-run diff stays stable.',\n 'A finding that reappears with no remediation evidence SHOULD raise its `confidence` and may justify a higher `severity`.',\n ...rows,\n overflow,\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\n/** Render findings produced earlier in this same registry run. */\nexport function renderUpstreamFindings(upstream: AnalystContext['upstreamFindings']): string {\n if (!upstream || upstream.length === 0) return ''\n const MAX_ROWS = 40\n const rows = upstream.slice(0, MAX_ROWS).map((finding) => {\n const subject = finding.subject ? ` [${finding.subject}]` : ''\n const action = finding.recommended_action\n ? ` action=${truncateForContext(finding.recommended_action, 120)}`\n : ''\n const evidence = finding.evidence_refs[0]\n ? ` evidence=${truncateForContext(finding.evidence_refs[0].uri, 120)}`\n : ''\n return ` - id=${finding.finding_id} source=${finding.analyst_id} ${finding.severity}${subject} claim=${truncateForContext(finding.claim, 160)}${action}${evidence}`\n })\n const overflow =\n upstream.length > MAX_ROWS\n ? `\\n ... +${upstream.length - MAX_ROWS} more upstream findings (truncated)`\n : ''\n return [\n '',\n '',\n 'UPSTREAM FINDINGS (produced earlier in this same registry run):',\n 'Use these as intermediate evidence. Build on them instead of repeating the same diagnosis, and cite a dependency with `finding://<id>`.',\n ...rows,\n overflow,\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\nfunction truncateForContext(s: string, max: number): string {\n if (s.length <= max) return s\n return `${s.slice(0, max - 1).trimEnd()}…`\n}\n","import {\n analyzeSupervisorRunIntegrity,\n type SupervisorRunIntegrityEvidence,\n} from '../../supervisor-run/integrity'\nimport type { SupervisorRunSources, SupervisorRunTree } from '../../supervisor-run/types'\nimport type { ExactCapableAnalyst } from '../exact-types'\nimport { type AnalystContext, type AnalystFinding, type EvidenceRef, makeFinding } from '../types'\n\nconst ANALYST_ID = 'control-integrity'\n\nfunction shown(value: unknown): string {\n if (value === undefined) return '<absent>'\n const encoded = JSON.stringify(value)\n return encoded === undefined ? String(value) : encoded\n}\n\nfunction evidenceRef(namespace: string, value: SupervisorRunIntegrityEvidence): EvidenceRef {\n return {\n kind: 'metric',\n uri: `supervisor-run://${encodeURIComponent(namespace)}/${value.path}`,\n excerpt: shown(value.value),\n }\n}\n\n/** Translate typed supervisor-run integrity issues into the shared analyst envelope. */\nexport function emitControlIntegrityFindings(\n input: SupervisorRunSources | SupervisorRunTree,\n producedAt: string,\n): AnalystFinding[] {\n const report = analyzeSupervisorRunIntegrity(input, { capturedAt: producedAt })\n return report.issues.map((issue) =>\n makeFinding({\n analyst_id: ANALYST_ID,\n produced_at: producedAt,\n area: issue.area,\n severity: issue.severity,\n subject: `${report.runRef}/${issue.subject}`,\n claim: issue.claim,\n rationale: issue.detail,\n evidence_refs: issue.evidence.map((value) => evidenceRef(report.runRef, value)),\n recommended_action: issue.recommendedAction,\n validation_plan:\n 'Re-run this deterministic analyst on the retained SupervisorRunSources or SupervisorRunTree after correcting the producer.',\n confidence: 1,\n metadata: {\n integrity_code: issue.code,\n integrity_input: report.input,\n integrity_run_ref: report.runRef,\n integrity_subject: issue.subject,\n ...issue.metadata,\n },\n }),\n )\n}\n\n/** Deterministic Analyst adapter for `SupervisorRunSources | SupervisorRunTree`. */\nexport class ControlIntegrityAnalyst\n implements ExactCapableAnalyst<SupervisorRunSources | SupervisorRunTree>\n{\n readonly id = ANALYST_ID\n readonly description =\n 'Deterministic supervisor-run integrity checks with explicit unavailable evidence.'\n readonly inputKind = 'custom' as const\n readonly cost = { kind: 'deterministic' as const, est_usd_per_run: 0 }\n readonly version = '2.0.0'\n readonly executionConfig = {\n kind: 'control-integrity',\n produced_at_source: 'tags.producedAt-or-system-clock',\n } as const\n\n async analyze(\n input: SupervisorRunSources | SupervisorRunTree,\n ctx: AnalystContext,\n ): Promise<AnalystFinding[]> {\n const producedAt = ctx.tags?.producedAt ?? new Date().toISOString()\n const findings = emitControlIntegrityFindings(input, producedAt)\n ctx.log?.(`control-integrity: ${findings.length} finding(s)`, {\n input: 'nodes' in input ? 'SupervisorRunTree' : 'SupervisorRunSources',\n })\n return findings\n }\n}\n\nexport const CONTROL_INTEGRITY_ANALYST = new ControlIntegrityAnalyst()\n","/**\n * Pre-curated tool subsets for analyst kinds.\n *\n * The full trace-analyst tool set is seven functions. Most kinds only\n * need three or four. Picking from named groups instead of importing\n * the whole bundle keeps every kind's actor-context budget tight and\n * makes \"what can this analyst see?\" obvious at registration time.\n *\n * Each function in the group keeps its full `name`/`description` from\n * `buildTraceAnalystTools` — we filter, we don't re-implement.\n */\n\nimport type { AxFunction } from '@ax-llm/ax'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport { buildTraceAnalystTools } from '../trace-analyst/tools'\n\n/** Named tool sets. Kinds pass `tools: TRACE_TOOL_GROUPS.failureForensics` etc. */\nexport type TraceToolGroupName =\n /** All seven tools. Use for open-ended discovery kinds. */\n | 'all'\n /** Overview + paginated query + count. No deep reads. Cheap. */\n | 'discovery'\n /** Discovery + viewTrace + viewSpans. Deep-read but no regex search. */\n | 'discoveryAndRead'\n /** Discovery + search tools. For pattern-matching across many traces. */\n | 'discoveryAndSearch'\n /** Discovery + viewSpans + searchSpan. Targeted-span work after another kind narrows down. */\n | 'targeted'\n /** One known-small trace: overview, bounded reads, and in-trace search. */\n | 'singleTrace'\n\nconst TOOL_NAMES_BY_GROUP: Record<TraceToolGroupName, ReadonlySet<string>> = {\n all: new Set(),\n discovery: new Set(['getDatasetOverview', 'queryTraces', 'countTraces']),\n discoveryAndRead: new Set([\n 'getDatasetOverview',\n 'queryTraces',\n 'countTraces',\n 'viewTrace',\n 'viewSpans',\n ]),\n discoveryAndSearch: new Set([\n 'getDatasetOverview',\n 'queryTraces',\n 'countTraces',\n 'searchTrace',\n 'searchSpan',\n ]),\n targeted: new Set(['getDatasetOverview', 'queryTraces', 'viewSpans', 'searchSpan']),\n singleTrace: new Set([\n 'getDatasetOverview',\n 'viewTrace',\n 'viewSpans',\n 'searchTrace',\n 'searchSpan',\n ]),\n}\n\n/**\n * Build the tool set for a named group bound to a specific trace store.\n *\n * `all` returns every tool. Other groups filter `buildTraceAnalystTools`\n * by name to the documented subset. An unrecognised group name throws —\n * silently returning all tools would defeat the cost-control point.\n */\nexport function buildTraceToolsForGroup(\n group: TraceToolGroupName,\n store: TraceAnalysisStore,\n): AxFunction[] {\n const all = buildTraceAnalystTools({ store })\n if (group === 'all') return all\n const allow = TOOL_NAMES_BY_GROUP[group]\n if (!allow) throw new Error(`unknown trace tool group: ${group}`)\n return all.filter((tool) => allow.has((tool as { name: string }).name))\n}\n","/**\n * Failure-mode analyst — classifies what went wrong and why.\n *\n * Brief: read the trace dataset, identify the top failure modes across\n * runs, classify each with severity + evidence, and surface them as\n * findings. The actor's job is *taxonomy + evidence*, not fix-design —\n * that's the improvement-analyst's job.\n *\n * Eight bounded model subqueries let the actor compare candidate\n * clusters in parallel after it has loaded representative evidence.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystKindSpec } from '../kind-factory'\nimport { buildTraceToolsForGroup } from '../tool-groups'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('failure-mode')\n\nconst ACTOR_PROMPT = `You are a failure-mode classifier for an OTLP trace dataset. Your job is to identify the **distinct ways agents failed** in this dataset, not to grade individual runs.\n\n${subjectGrammar}\n\nDISCOVERY → CLUSTER → CITE protocol:\n\n1. Call \\`traces.getDatasetOverview({})\\` first. Use \\`has_errors\\`, \\`models\\`, \\`agent_names\\`, \\`tools\\`, and \\`sample_trace_ids\\` to size the failure surface.\n2. Use \\`traces.queryTraces({ filters: { has_errors: true }, limit })\\` to pull error-bearing traces. Combine with \\`traces.countTraces\\` to see what fraction of the dataset failed.\n3. For each candidate failure cluster, use \\`traces.searchTrace\\` with regex like \\`STATUS_CODE_ERROR\\`, \\`MaxTurnsExceeded\\`, \\`assertion\\`, \\`unauthorized\\`, \\`timeout\\`, \\`429\\`, \\`5\\\\d\\\\d\\`, the agent's specific error strings, or the names of its tools. Pull one or two representative traces per cluster, **not all** of them.\n4. **Cluster, do not enumerate.** Two failures with the same root cause should be ONE finding citing both traces, not two findings. The point of this analyst is to compress N runs into K modes.\n5. For each defensible cluster, emit ONE finding. Use a lowercase cluster label matching the subject grammar (\"tool-call-loop\", \"auth-revoked-mid-run\", ...). Rate it critical when it blocks the run, high when the run finishes degraded, and medium when it slows convergence. Cite representative spans and include exact error, payload, or contradictory-output quotes. Use confidence 0.85+ when multiple traces show the same shape, 0.6-0.8 for a single-trace inference, and <0.5 for speculation. Keep the imperative fix idea short; the improvement analyst expands it.\n\nIf the dataset has no failures, return an empty findings array — do NOT pad with low-confidence speculation.\n\n**Use subqueries over loaded evidence.** After the first scan, load representative span excerpts for each candidate cluster. Then send one bounded \\`llmQuery\\` per cluster in one batch, including the exact excerpts and asking it to classify the root cause. Subqueries cannot call trace tools. Merge or split clusters yourself from their classifications and the cited source evidence.\n\nOBSERVABILITY rules:\n- Each non-final turn must emit at least one \\`console.log\\` for evidence.\n- Reuse runtime variables across turns; don't recompute.`\n\nexport const FAILURE_MODE_KIND_SPEC: TraceAnalystKindSpec = {\n id: 'failure-mode',\n description:\n 'Clusters trace-dataset failures into distinct failure modes with cited evidence and a short recommended action.',\n area: 'failure-mode',\n version: '1.2.0',\n actorDescription: ACTOR_PROMPT,\n buildTools: (store) => buildTraceToolsForGroup('all', store),\n subqueries: { maxCalls: 8, maxParallel: 4 },\n maxTurns: 24,\n cost: { kind: 'llm' },\n}\n","/**\n * Improvement analyst — actionable self-improvement findings.\n *\n * Brief: read findings from upstream analysts (failure-mode,\n * knowledge-gap, knowledge-poisoning) AND the trace dataset itself,\n * then propose **concrete edits** to the agent's runtime: prompt\n * additions, RAG documents to ingest, tool descriptions to rewrite,\n * scaffolding changes to make, memory entries to invalidate. Each\n * finding is one proposed edit with the locus, the diff, and the\n * expected effect.\n *\n * This is the self-improvement loop's last mile: the prior\n * kinds describe *what's wrong*; this kind describes *what to change*.\n *\n * Eight bounded model subqueries let the actor compare competing fix\n * directions over the same cited evidence before recommending one.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystKindSpec } from '../kind-factory'\nimport { buildTraceToolsForGroup } from '../tool-groups'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('improvement')\n\nconst ACTOR_PROMPT = `You are a self-improvement analyst. Your job is to propose **concrete, locus-named edits** the agent's runtime should adopt to fix the failure modes, knowledge gaps, and poisonings present in this dataset.\n\nUpstream analysts have already classified the problems. Your job is to convert each problem into a *change to make* and grade its expected leverage. Each finding is one proposed edit.\n\n${subjectGrammar}\n\nDISCOVERY → CANDIDATE-FIXES → COMPETE → CITE protocol:\n\n1. \\`traces.getDatasetOverview({})\\` first. Note the agents, tools, and any system-prompt fingerprints (look for the prompt text echoed in early spans).\n2. For each high-severity failure pattern, generate 2-3 candidate fixes. Real candidate axes:\n - **System-prompt edit** — add an instruction, remove a misleading one, restructure precedence\n - **Tool description edit** — rewrite a tool's description so the agent picks it correctly / passes valid args\n - **New tool** — add a tool the agent kept emulating in code\n - **RAG ingestion** — add a document or correct a stale one\n - **Memory invalidation** — clear cached prior-run decisions that no longer apply\n - **Scaffolding** — add a precondition check, a retry policy, a turn budget, a verification step\n - **Output schema** — narrow the agent's output to forbid the failure shape\n - **Skill / MCP / hook / subagent** — change the reusable profile component responsible for the behavior\n - **Workflow / rollout policy** — change orchestration, budget, sampling, or stopping behavior\n - **Code** — change an implementation path when profile edits cannot repair the behavior\n3. **Compare candidate fixes with bounded subqueries.** Load the representative failure excerpts, then send one \\`llmQuery\\` per candidate-fix axis the same evidence. Ask for likely effect, side effects, and implementation scope. Subqueries cannot call trace tools; trace ids alone are insufficient context.\n4. After the comparisons return, **pick the winning candidate per cluster** based on expected effect and risk, then emit ONE finding. Keep the alternatives and rejection reasons in the rationale so the recommendation is auditable.\n5. **Cross-reference upstream findings.** Cite prior failure-mode or knowledge-gap findings as \\`finding://<prior-finding-id>\\`. This builds the dependency graph that lets the dashboard show \"fix #X resolves failure modes A, B, C.\"\n\nFor each winning recommendation, emit ONE finding. Use one exact locus from the subject grammar and state the edit in one sentence. Match leverage to the source failure's severity; use medium for quality-of-life changes and info for cleanup with no behavioral effect. Cite the targeted \\`finding://<id>\\` when available and the most representative span when useful. Quote the problem being fixed. Use confidence 0.85+ for a mechanical fix to a well-evidenced failure, 0.6-0.8 when judgment is required, and <0.5 for speculation. Explain in at most two sentences why this candidate beat its alternatives. The recommended action must be the literal diff, quoted replacement, tool description, or setting change.\n\nIf no upstream failure findings exist in this run, derive your own from the trace dataset using the failure-mode protocol inline (\\`searchTrace\\` for STATUS_CODE_ERROR / MaxTurnsExceeded / etc.). But prefer to consume upstream findings when present — the kinds are designed to chain.\n\nDo NOT propose a fix you cannot defend with evidence. \"Tighten the prompt\" is not a finding; \"Add 'When the user asks for X, always Y' to the system prompt section \"request-classification\"\" is.\n\nOBSERVABILITY rules:\n- Each non-final turn must emit at least one \\`console.log\\` for evidence.`\n\nexport const IMPROVEMENT_KIND_SPEC: TraceAnalystKindSpec = {\n id: 'improvement',\n description:\n 'Converts upstream failure / gap / poisoning findings into concrete locus-named edits (prompt, tool-doc, RAG, scaffolding) with leverage grades.',\n area: 'improvement',\n version: '1.2.0',\n actorDescription: ACTOR_PROMPT,\n buildTools: (store) => buildTraceToolsForGroup('all', store),\n subqueries: { maxCalls: 8, maxParallel: 4 },\n maxTurns: 30,\n maxRuntimeChars: 12000,\n cost: { kind: 'llm' },\n}\n","/**\n * Knowledge-gap analyst — what did the agent NOT know that it needed?\n *\n * Brief: find moments in the trace where the agent had to guess, ask\n * the user to fill in context, recover from a wrong assumption, or\n * loop on a retrieval. Each finding names a *missing or outdated piece\n * of knowledge* the agent's curated knowledge base should have held —\n * or a downstream lookup (web, docs, tool description) that surfaced\n * stale or outdated information.\n *\n * The primary expected store is `@tangle-network/agent-knowledge`: a\n * Karpathy-style wiki the agent maintains with raw ↔ curated pages,\n * source anchors, and claim/relation triples. A gap is anything the\n * agent had to discover at run-time that should already have lived\n * there. Secondary loci: web-search results that returned outdated\n * pages, tool descriptions that omitted critical behavior, system-\n * prompt sections that didn't cover the case.\n *\n * Distinct from failure-mode: failure-mode classifies *how* it broke;\n * knowledge-gap names the *information* whose absence (or staleness)\n * caused the break. One failure-mode often maps to several gaps.\n *\n * Five bounded model subqueries let the actor compare candidate gaps\n * across source layers after it has loaded the relevant excerpts.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystKindSpec } from '../kind-factory'\nimport { buildTraceToolsForGroup } from '../tool-groups'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('knowledge-gap')\n\nconst ACTOR_PROMPT = `You are a knowledge-gap analyst for an OTLP trace dataset. Your job is to identify the **specific pieces of information the agent lacked, or that were stale**, that caused poor decisions.\n\nThe agent under analysis maintains a curated knowledge base via \\`@tangle-network/agent-knowledge\\` — a wiki of \\`KnowledgePage\\`s with raw source anchors, claims, and relations. The primary expected store of agent-knowable facts IS that wiki. A \"knowledge gap\" is anything the agent had to discover or guess at run-time that the wiki should have held — or an outdated/contradictory fact the agent picked up from a non-wiki source.\n\n${subjectGrammar}\n\nDISCOVERY → ATTRIBUTE-TO-LAYER → CITE protocol:\n\n1. \\`traces.getDatasetOverview({})\\` first. Note which agents, tools, and models appear.\n2. Pull traces where the agent shows gap signals. The strongest signals are:\n - Self-correction turns (\"I assumed X but…\", \"let me re-check\", \"actually,\")\n - Clarifying-question turns where the agent asked the user something the runtime should have surfaced\n - Repeated retrieval / lookup calls for the same artifact with slightly varied queries\n - Tool errors that name a missing argument or unknown resource\n - Web-search calls returning pages dated before a known cutoff for content that changes (versioned APIs, schemas, policies)\n - Agent quoting a tool's docs / system prompt incorrectly because the actual text was insufficient\n - Fabricated identifiers that don't appear in dataset \\`sample_trace_ids\\`\n Use \\`traces.searchTrace\\` with patterns like \\`I (don.?t|do not) know\\`, \\`assumed\\`, \\`unclear\\`, \\`could you (clarify|tell me|provide)\\`, \\`not found\\`, \\`undefined\\`, \\`unknown\\`, \\`null\\`, dates older than the analysis window, or the agent's specific clarification phrases.\n3. For each gap, identify the **layer of the runtime that should have prevented it** and use its exact locus from the subject grammar above.\n4. For each defensible gap, emit ONE finding. Use an exact locus from the subject grammar and name the missing or stale knowledge (for example, \"wiki has no page on invoice line-item shape; agent re-derived it from raw spans\"). Rate it high when it caused failure or a clarifying question, medium for unnecessary turns, and low for minor inefficiency. Cite the span where the question, correction, retrieval miss, or stale result surfaced and quote it exactly. Use confidence 0.85+ when the agent articulated the gap and 0.6-0.8 when inferred. Recommend a concrete wiki edit for an agent-knowledge locus or a prompt/tool-description edit otherwise.\n\n**Compare layers over loaded evidence.** After the first scan, load the exact excerpts behind candidates across \\`agent-knowledge:*\\`, \\`websearch:outdated\\`, \\`tool-doc:*\\`, \\`system-prompt:*\\`, and \\`memory:*\\`. Use one bounded \\`llmQuery\\` per layer to classify those excerpts. Subqueries cannot call trace tools. Merge their classifications into the final finding set only when the source excerpts support them.\n\nDo NOT report a gap that the agent later recovered from cleanly within the same turn — that's resilience, not a gap. Cite the *non-recovery* version when both exist.\n\nOBSERVABILITY rules:\n- Each non-final turn must emit at least one \\`console.log\\` for evidence.`\n\nexport const KNOWLEDGE_GAP_KIND_SPEC: TraceAnalystKindSpec = {\n id: 'knowledge-gap',\n description:\n 'Identifies missing or stale pieces of knowledge — primarily against the agent-knowledge wiki — and attributes each to the runtime layer (wiki page, claim, raw source, websearch, tool-doc, system-prompt, memory) that should have held it.',\n area: 'knowledge-gap',\n version: '1.2.0',\n actorDescription: ACTOR_PROMPT,\n buildTools: (store) => buildTraceToolsForGroup('discoveryAndSearch', store),\n subqueries: { maxCalls: 5, maxParallel: 4 },\n maxTurns: 18,\n cost: { kind: 'llm' },\n}\n","/**\n * Knowledge-poisoning analyst — what FALSE information misled the agent?\n *\n * Brief: find moments where the agent acted on information that was\n * *wrong* — stale memory, RAG documents that contradicted ground truth,\n * tool descriptions that lied about return shapes, system-prompt\n * instructions that no longer matched reality, prior-run summaries that\n * cached a wrong decision.\n *\n * Distinct from knowledge-gap: a gap is \"the agent didn't know X\"; a\n * poisoning is \"the agent confidently used X, but X was wrong.\" Gaps\n * surface as questions / self-correction; poisonings surface as\n * confident-but-wrong actions that downstream evidence contradicts.\n *\n * Eight bounded model subqueries let the actor independently assess\n * the action and contradiction excerpts for candidate poisonings.\n */\n\nimport { findingSubjectGrammarPromptFor } from '../finding-subject'\nimport type { TraceAnalystKindSpec } from '../kind-factory'\nimport { buildTraceToolsForGroup } from '../tool-groups'\n\nconst subjectGrammar = findingSubjectGrammarPromptFor('knowledge-poisoning')\n\nconst ACTOR_PROMPT = `You are a knowledge-poisoning analyst for an OTLP trace dataset. Your job is to identify cases where the agent **confidently used wrong information** — not where it lacked information (that's the knowledge-gap analyst).\n\n${subjectGrammar}\n\nDISCOVERY → DUAL-VERIFY → CITE protocol:\n\n1. \\`traces.getDatasetOverview({})\\` first. Identify the agents, models, and tools.\n2. Pull traces where the agent's confident action was later contradicted. Strongest signals:\n - Agent stated a fact in one span; a later span surfaced contradictory evidence; the agent then proceeded anyway or fabricated reconciliation.\n - Tool call with stale arguments (an id that no longer exists, an API shape that changed).\n - Agent cited an \\`agent-knowledge\\` wiki page or claim whose content contradicts the trace's own evidence — the wiki itself drifted.\n - Web-search result the agent cited that returned an outdated page; agent treated it as canonical.\n - System-prompt instruction the agent followed that ground-truth evidence in the trace contradicts (e.g. prompt says \"use endpoint A\"; tool reply says \"endpoint A deprecated, use B\").\n - Repeated wrong-shape parsing despite the tool's actual output proving the shape.\n3. Use \\`traces.searchTrace\\` with regex on phrases like \\`actually\\`, \\`turns out\\`, \\`previously assumed\\`, \\`old version\\`, \\`deprecated\\`, \\`updated to\\`, \\`now uses\\`, or specific entity names you suspect have changed.\n4. For each candidate poisoning, **DUAL-VERIFY**:\n - Confirm the agent actually acted on the false belief (cite the span where it did)\n - Confirm the belief is actually false in this trace's own evidence (cite the span that contradicts it)\n Only emit a finding when both halves are nailed down. If you can only nail one, drop it — single-evidence poisoning findings are too speculative to be useful.\n\n**Independently assess both halves.** Load the action excerpt and contradicting excerpt yourself, then send bounded \\`llmQuery\\` calls the exact evidence for \"did the agent act?\" and \"does the trace contradict the belief?\" Subqueries cannot call trace tools. Accept a poisoning only when both assessments and the source excerpts support it.\n\nFor each confirmed poisoning, emit ONE finding. Use the source of the false belief as the exact subject. State \"agent believed X (from source S); trace evidence shows X is false.\" Rate it critical for a wrong user-visible action, high when caught internally after significant waste, and medium for inefficiency. Cite BOTH the action span and the contradicting span with exact quotes. Use confidence 0.85+ when both halves have exact quotes and 0.6-0.8 when one half is inferred. Recommend the literal source correction: update the wiki claim, invalidate and re-curate the raw source, or replace the stale prompt/tool instruction.\n\nDo NOT report a finding if the agent caught and corrected the false belief in the same turn — that's the system working. Reserve poisoning for cases where the false belief shaped downstream action.\n\nOBSERVABILITY rules:\n- Each non-final turn must emit at least one \\`console.log\\` for evidence.`\n\nexport const KNOWLEDGE_POISONING_KIND_SPEC: TraceAnalystKindSpec = {\n id: 'knowledge-poisoning',\n description:\n 'Identifies confident-but-wrong actions caused by stale memory, contradicting RAG, deprecated tool docs, or outdated system-prompt instructions.',\n area: 'knowledge-poisoning',\n version: '1.2.0',\n actorDescription: ACTOR_PROMPT,\n buildTools: (store) => buildTraceToolsForGroup('all', store),\n subqueries: { maxCalls: 8, maxParallel: 4 },\n maxTurns: 20,\n minimumEvidenceCitations: 2,\n cost: { kind: 'llm' },\n}\n","/**\n * Default analyst kinds focused on agent failure + recursive\n * self-improvement.\n *\n * The four kinds chain: failure-mode classifies; knowledge-gap and\n * knowledge-poisoning explain *why* in two orthogonal ways; improvement\n * proposes concrete edits. Register all four against the same trace\n * store in this order and run the registry with `chainFindings: true`\n * to pass each completed kind's findings to the kinds that follow it.\n */\n\nexport {\n CONTROL_INTEGRITY_ANALYST,\n ControlIntegrityAnalyst,\n emitControlIntegrityFindings,\n} from './control-integrity'\nexport { FAILURE_MODE_KIND_SPEC } from './failure-mode'\nexport { IMPROVEMENT_KIND_SPEC } from './improvement'\nexport { KNOWLEDGE_GAP_KIND_SPEC } from './knowledge-gap'\nexport { KNOWLEDGE_POISONING_KIND_SPEC } from './knowledge-poisoning'\n\nimport type { TraceAnalystKindSpec } from '../kind-factory'\nimport { FAILURE_MODE_KIND_SPEC } from './failure-mode'\nimport { IMPROVEMENT_KIND_SPEC } from './improvement'\nimport { KNOWLEDGE_GAP_KIND_SPEC } from './knowledge-gap'\nimport { KNOWLEDGE_POISONING_KIND_SPEC } from './knowledge-poisoning'\n\n/**\n * The default kind suite. Order is the run order operators should\n * use: failure-mode first (no upstream deps), gap + poisoning next\n * (both depend on failures), improvement last (chains all three).\n */\nexport const DEFAULT_TRACE_ANALYST_KINDS: readonly TraceAnalystKindSpec[] = [\n FAILURE_MODE_KIND_SPEC,\n KNOWLEDGE_GAP_KIND_SPEC,\n KNOWLEDGE_POISONING_KIND_SPEC,\n IMPROVEMENT_KIND_SPEC,\n] as const\n","import { type ExactAnalystRunResult, snapshotExactExecutionPlan } from './analyst/exact-types'\nimport type {\n AnalystFinding,\n AnalystRunResult,\n AnalystUsageReceipt,\n EvidenceRef,\n} from './analyst/types'\nimport { assertValidAnalystUsageReceipt } from './analyst/usage-receipt'\nimport type { FeedbackLabelSource, FeedbackTrajectory } from './feedback-trajectory'\nimport { canonicalString, hashCanonical } from './ledger-core/canonical'\nimport { deepFreezeCanonicalJson } from './ledger-core/deep-freeze'\n\nexport type AnalystReviewSource = Exclude<FeedbackLabelSource, 'system'>\nexport type AnalystFindingDigest = `sha256:${string}`\nexport type AnalystRunDigest = `sha256:${string}`\n\nexport interface AnalystMissedIssue {\n id: string\n reason: string\n evidence?: EvidenceRef[]\n}\n\ninterface AnalystReviewDecisionBase {\n runDigest: AnalystRunDigest\n source: AnalystReviewSource\n reviewerId: string\n reviewId: string\n reason: string\n decidedAt: string\n}\n\nexport type AnalystReviewDecision =\n | (AnalystReviewDecisionBase & {\n findingId: string\n findingDigest: AnalystFindingDigest\n verdict: 'confirmed' | 'rejected'\n missedIssues?: never\n })\n | (AnalystReviewDecisionBase & {\n verdict: 'completeness_assessed'\n missedIssues: AnalystMissedIssue[]\n findingId?: never\n findingDigest?: never\n })\n\nexport interface AnalystReviewCounts {\n emitted: number\n confirmed: number\n rejected: number\n missed: number\n}\n\nexport interface AnalystReviewQuality {\n precision: number\n recall: number\n f1: number\n counts: AnalystReviewCounts\n}\n\nexport interface StoredAnalystReview {\n runId: string\n runDigest: AnalystRunDigest\n findings: AnalystFinding[]\n findingIds: string[]\n analystIds: string[]\n reviewDecisions: AnalystReviewDecision[]\n}\n\n/** Bind an analyst finding's complete canonical JSON content to a stable digest. */\nexport function analystFindingDigest(finding: AnalystFinding): AnalystFindingDigest {\n return hashCanonical(snapshotAnalystFinding(finding, 'analyst finding'))\n}\n\n/** Bind the complete analyst result to one immutable review target. */\nexport function analystRunDigest(run: AnalystRunResult): AnalystRunDigest {\n return hashCanonical(snapshotAnalystRun(run, 'analyst run'))\n}\n\nexport function snapshotAnalystRun(value: unknown, context = 'analyst run'): AnalystRunResult {\n const snapshot = snapshotAnalystRunRecord(value, context)\n if (snapshot.execution_plan !== undefined) {\n return sealExactAnalystRunReceipt(snapshot, context)\n }\n if (snapshot.completion !== undefined) {\n throw new TypeError(`${context} completion is valid only for an exact run`)\n }\n return snapshot as unknown as AnalystRunResult\n}\n\n/** Canonicalize, validate, and deeply freeze one complete or failed exact-run receipt. */\nexport function snapshotExactAnalystRunReceipt(\n value: unknown,\n context = 'exact analyst run receipt',\n): ExactAnalystRunResult {\n return sealExactAnalystRunReceipt(snapshotAnalystRunRecord(value, context), context)\n}\n\nfunction snapshotAnalystRunRecord(value: unknown, context: string): Record<string, unknown> {\n let snapshot: unknown\n try {\n snapshot = JSON.parse(canonicalString(value)) as unknown\n } catch (cause) {\n throw new TypeError(`${context} must have a canonical JSON representation`, { cause })\n }\n if (!isRecord(snapshot)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(\n snapshot,\n [\n 'run_id',\n 'correlation_id',\n 'started_at',\n 'ended_at',\n 'findings',\n 'per_analyst',\n 'total_cost_usd',\n 'total_cost_provenance',\n 'execution_plan',\n 'completion',\n ],\n context,\n )\n requiredString(snapshot.run_id, `${context} run_id`)\n requiredString(snapshot.correlation_id, `${context} correlation_id`)\n canonicalTimestamp(snapshot.started_at, `${context} started_at`)\n canonicalTimestamp(snapshot.ended_at, `${context} ended_at`)\n snapshot.findings = snapshotAnalystFindings(snapshot.findings, `${context} findings`)\n if (!Array.isArray(snapshot.per_analyst)) {\n throw new TypeError(`${context} per_analyst must be an array`)\n }\n for (const [index, summary] of snapshot.per_analyst.entries()) {\n assertAnalystRunSummary(summary, `${context} per_analyst ${index}`)\n }\n if (\n typeof snapshot.total_cost_usd !== 'number' ||\n !Number.isFinite(snapshot.total_cost_usd) ||\n snapshot.total_cost_usd < 0\n ) {\n throw new TypeError(`${context} total_cost_usd must be a finite non-negative number`)\n }\n if (snapshot.total_cost_provenance !== undefined) {\n assertCostProvenance(snapshot.total_cost_provenance, `${context} total_cost_provenance`)\n }\n return snapshot\n}\n\nfunction assertAnalystRunSummary(value: unknown, context: string): void {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(\n value,\n [\n 'analyst_id',\n 'status',\n 'reason',\n 'findings_count',\n 'latency_ms',\n 'usage',\n 'allocated_budget_usd',\n 'error',\n ],\n context,\n )\n requiredString(value.analyst_id, `${context} analyst_id`)\n if (value.status !== 'ok' && value.status !== 'skipped' && value.status !== 'failed') {\n throw new TypeError(`${context} status is invalid`)\n }\n if (value.reason !== undefined) requiredString(value.reason, `${context} reason`)\n if (value.status === 'skipped' && value.reason === undefined) {\n throw new TypeError(`${context} skipped summary requires reason`)\n }\n nonnegativeSafeInteger(value.findings_count, `${context} findings_count`)\n finiteNonnegative(value.latency_ms, `${context} latency_ms`)\n assertAnalystUsageReceipt(value.usage, `${context} usage`)\n if (value.allocated_budget_usd !== undefined && value.allocated_budget_usd !== null) {\n finiteNonnegative(value.allocated_budget_usd, `${context} allocated_budget_usd`)\n }\n if (value.error !== undefined) {\n if (value.status !== 'failed' || !isRecord(value.error)) {\n throw new TypeError(`${context} error is valid only for failed summaries`)\n }\n assertOnlyKeys(value.error, ['class', 'message'], `${context} error`)\n requiredString(value.error.class, `${context} error class`)\n requiredString(value.error.message, `${context} error message`)\n } else if (value.status === 'failed') {\n throw new TypeError(`${context} failed summary requires error`)\n }\n}\n\nfunction assertAnalystUsageReceipt(value: unknown, context: string): void {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(value, ['calls', 'tokens', 'cost', 'knownCostUsd'], context)\n for (const field of ['calls', 'tokens', 'cost'] as const) {\n if (!Object.hasOwn(value, field)) {\n throw new TypeError(`${context} ${field} is required`)\n }\n }\n if (value.tokens !== null) {\n if (!isRecord(value.tokens)) throw new TypeError(`${context} tokens must be an object or null`)\n assertOnlyKeys(\n value.tokens,\n ['input', 'output', 'reasoning', 'cached', 'cacheWrite'],\n `${context} tokens`,\n )\n }\n assertCostProvenance(value.cost, `${context} cost`)\n assertValidAnalystUsageReceipt(value as unknown as AnalystUsageReceipt, context)\n}\n\nfunction assertCostProvenance(value: unknown, context: string): void {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(value, ['kind', 'usd'], context)\n if (value.kind === 'uncaptured') {\n if (value.usd !== null) throw new TypeError(`${context} uncaptured usd must be null`)\n return\n }\n if (value.kind !== 'observed' && value.kind !== 'estimated') {\n throw new TypeError(`${context} kind is invalid`)\n }\n finiteNonnegative(value.usd, `${context} usd`)\n}\n\nfunction sealExactAnalystRunReceipt(\n run: Record<string, unknown>,\n context: string,\n): ExactAnalystRunResult {\n if (run.execution_plan === undefined) {\n throw new TypeError(`${context} exact run requires execution_plan`)\n }\n const plan = snapshotExactExecutionPlan(run.execution_plan, `${context} execution_plan`)\n const completion = snapshotExactRunCompletion(run.completion, `${context} completion`)\n run.execution_plan = plan\n run.completion = completion\n const summaries = run.per_analyst as Array<{\n analyst_id: string\n status: 'ok' | 'skipped' | 'failed'\n findings_count: number\n usage: { cost: { kind: string; usd: number | null }; knownCostUsd?: number }\n allocated_budget_usd?: number | null\n }>\n const findings = run.findings as AnalystFinding[]\n const planned = plan.analysts.map((analyst) => analyst.id)\n const completed = summaries.map((summary) => summary.analyst_id)\n const ordered = completed.every((analystId, index) => analystId === planned[index])\n if (!ordered || (completion.status === 'complete' && completed.length !== planned.length)) {\n throw new TypeError(\n completion.status === 'complete'\n ? `${context} complete receipt must contain every execution_plan analyst in exact order`\n : `${context} failed receipt per_analyst must be an execution_plan prefix`,\n )\n }\n const completedIds = new Set(completed)\n for (const finding of findings) {\n if (!completedIds.has(finding.analyst_id)) {\n throw new TypeError(`${context} finding names an analyst absent from per_analyst`)\n }\n }\n for (const summary of summaries) {\n const actual = findings.filter((finding) => finding.analyst_id === summary.analyst_id).length\n if (summary.findings_count !== actual) {\n throw new TypeError(\n `${context} findings_count does not match findings for \"${summary.analyst_id}\"`,\n )\n }\n const hasAllocation = Object.hasOwn(summary, 'allocated_budget_usd')\n if (summary.status === 'skipped') {\n if (hasAllocation) {\n throw new TypeError(\n `${context} skipped summary \"${summary.analyst_id}\" cannot report an allocated budget`,\n )\n }\n continue\n }\n const allocation = summary.allocated_budget_usd\n const validAllocation =\n hasAllocation &&\n (plan.policy.budget.kind === 'none'\n ? allocation === null\n : typeof allocation === 'number' &&\n plan.policy.budget.allocations_usd[summary.analyst_id] !== null &&\n plan.policy.budget.allocations_usd[summary.analyst_id] !== undefined &&\n allocation <= plan.policy.budget.allocations_usd[summary.analyst_id]!)\n if (!validAllocation) {\n throw new TypeError(\n `${context} summary \"${summary.analyst_id}\" allocation does not match its execution plan`,\n )\n }\n }\n let knownCost = 0\n for (const summary of summaries) {\n const amount =\n summary.usage.cost.kind === 'uncaptured'\n ? (summary.usage.knownCostUsd ?? 0)\n : (summary.usage.cost.usd ?? 0)\n knownCost = finiteNonnegative(knownCost + amount, `${context} aggregate known cost`)\n }\n if (run.total_cost_usd !== knownCost) {\n throw new TypeError(`${context} total_cost_usd does not match per_analyst usage`)\n }\n if (run.total_cost_provenance === undefined) {\n throw new TypeError(`${context} exact run requires total_cost_provenance`)\n }\n const costs = summaries.map((summary) => summary.usage.cost)\n const expectedProvenance = costs.some((cost) => cost.kind === 'uncaptured')\n ? { kind: 'uncaptured', usd: null }\n : {\n kind: costs.some((cost) => cost.kind === 'estimated') ? 'estimated' : 'observed',\n usd: costs.reduce(\n (sum, cost) =>\n finiteNonnegative(sum + (cost.usd ?? 0), `${context} aggregate captured cost`),\n 0,\n ),\n }\n if (hashCanonical(run.total_cost_provenance) !== hashCanonical(expectedProvenance)) {\n throw new TypeError(`${context} total_cost_provenance does not match per_analyst usage`)\n }\n return deepFreezeCanonicalJson(run as unknown as ExactAnalystRunResult)\n}\n\nfunction snapshotExactRunCompletion(\n value: unknown,\n context: string,\n): ExactAnalystRunResult['completion'] {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n if (value.status === 'complete') {\n assertOnlyKeys(value, ['status'], context)\n return value as ExactAnalystRunResult['completion']\n }\n if (value.status !== 'failed') {\n throw new TypeError(`${context} status must be complete or failed`)\n }\n assertOnlyKeys(value, ['status', 'error'], context)\n if (!isRecord(value.error)) throw new TypeError(`${context} failed receipt requires error`)\n assertOnlyKeys(value.error, ['class', 'message'], `${context} error`)\n requiredString(value.error.class, `${context} error class`)\n requiredString(value.error.message, `${context} error message`)\n return value as unknown as ExactAnalystRunResult['completion']\n}\n\nfunction finiteNonnegative(value: unknown, context: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new TypeError(`${context} must be a non-negative finite number`)\n }\n return value\n}\n\nfunction nonnegativeSafeInteger(value: unknown, context: string): number {\n if (!Number.isSafeInteger(value) || (value as number) < 0) {\n throw new TypeError(`${context} must be a non-negative safe integer`)\n }\n return value as number\n}\n\nexport function snapshotAnalystFindings(\n value: unknown,\n context = 'analyst run findings',\n): AnalystFinding[] {\n if (!Array.isArray(value)) {\n throw new TypeError(`${context} must be an array`)\n }\n const findings = value.map((finding, index) =>\n snapshotAnalystFinding(finding, `${context} finding ${index}`),\n )\n assertUniqueFindingIds(findings.map((finding) => finding.finding_id))\n return findings\n}\n\nexport function readAnalystReview(trajectory: FeedbackTrajectory): StoredAnalystReview | undefined {\n const analystAttempts = trajectory.attempts.filter(\n (attempt) => isRecord(attempt.artifact) && attempt.artifact.type === 'analyst-run',\n )\n const analysis = isRecord(trajectory.metadata?.analysis)\n ? trajectory.metadata.analysis\n : undefined\n if (analystAttempts.length === 0) {\n if (analysis?.kind === 'analyst-run') {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" is missing its archived run`,\n )\n }\n return undefined\n }\n if (analystAttempts.length !== 1) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" must contain exactly one archived run`,\n )\n }\n if (analysis?.kind !== 'analyst-run') {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" is missing review state`,\n )\n }\n\n const artifact = analystAttempts[0]!.artifact\n if (!isRecord(artifact)) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" has an invalid archived run`,\n )\n }\n const runId = requiredString(\n artifact.analystRunId,\n `analyst trajectory \"${trajectory.id}\" run id`,\n )\n if (analysis.runId !== runId) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" run identity does not match its review state`,\n )\n }\n const artifactRunDigest = requiredDigest(\n artifact.runDigest,\n `analyst trajectory \"${trajectory.id}\" archived run digest`,\n )\n const storedRunDigest = requiredDigest(\n analysis.runDigest,\n `analyst trajectory \"${trajectory.id}\" review run digest`,\n )\n if (artifactRunDigest !== storedRunDigest) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" run digest does not match its review state`,\n )\n }\n const findings = snapshotAnalystFindings(\n artifact.findings,\n `analyst trajectory \"${trajectory.id}\"`,\n )\n const findingIds = findings.map((finding) => finding.finding_id)\n const analystIds = stringArray(\n artifact.analystIds,\n `analyst trajectory \"${trajectory.id}\" analyst ids`,\n )\n const attemptMetadata = analystAttempts[0]!.metadata\n if (!isRecord(attemptMetadata)) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" is missing archived run metadata`,\n )\n }\n const archivedRun = snapshotAnalystRun(\n {\n run_id: runId,\n correlation_id: artifact.correlationId,\n started_at: analysis.startedAt,\n ended_at: analysis.endedAt,\n findings,\n per_analyst: attemptMetadata.perAnalyst,\n total_cost_usd: analysis.knownCostUsd,\n ...(analysis.costProvenance === undefined\n ? {}\n : { total_cost_provenance: analysis.costProvenance }),\n ...(artifact.executionPlan === undefined\n ? {}\n : {\n execution_plan: artifact.executionPlan,\n completion: artifact.completion,\n }),\n },\n `analyst trajectory \"${trajectory.id}\" archived run`,\n )\n const knownAnalystIds = new Set(analystIds)\n for (const [index, finding] of findings.entries()) {\n if (!knownAnalystIds.has(finding.analyst_id)) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" omits generating analyst \"${finding.analyst_id}\" at finding ${index}`,\n )\n }\n }\n const reviewDecisions = validateAnalystReviewDecisions({\n runId,\n runDigest: storedRunDigest,\n findings,\n analystIds,\n decisions: analysis.reviewDecisions,\n requireComplete: true,\n })\n const expectedRunDigest = analystRunDigest(archivedRun)\n if (storedRunDigest !== expectedRunDigest) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: analyst trajectory \"${trajectory.id}\" archived run digest mismatch`,\n )\n }\n return {\n runId,\n runDigest: expectedRunDigest,\n findings,\n findingIds,\n analystIds,\n reviewDecisions,\n }\n}\n\nexport function completedAnalystReviewQuality(review: StoredAnalystReview): AnalystReviewQuality {\n const findingDecisions = review.reviewDecisions.filter(\n (decision): decision is Extract<AnalystReviewDecision, { verdict: 'confirmed' | 'rejected' }> =>\n decision.verdict !== 'completeness_assessed',\n )\n const completeness = review.reviewDecisions.filter(\n (decision): decision is Extract<AnalystReviewDecision, { verdict: 'completeness_assessed' }> =>\n decision.verdict === 'completeness_assessed',\n )\n if (completeness.length !== 1) {\n throw new TypeError(\n 'feedbackTrajectoryToOptimizerRow: analyst run requires exactly one independent completeness_assessed decision',\n )\n }\n\n const confirmed = findingDecisions.filter((decision) => decision.verdict === 'confirmed').length\n const rejected = findingDecisions.length - confirmed\n const emitted = review.findingIds.length\n const missed = completeness[0]!.missedIssues.length\n const precision = emitted === 0 ? 1 : confirmed / emitted\n const recallDenominator = confirmed + missed\n const recall = recallDenominator === 0 ? 1 : confirmed / recallDenominator\n const f1 = precision + recall === 0 ? 0 : (2 * precision * recall) / (precision + recall)\n return {\n precision,\n recall,\n f1,\n counts: { emitted, confirmed, rejected, missed },\n }\n}\n\nexport function validateAnalystReviewDecisions(input: {\n runId: string\n runDigest: AnalystRunDigest\n findings: readonly AnalystFinding[]\n analystIds: readonly string[]\n decisions: unknown\n requireComplete?: boolean\n}): AnalystReviewDecision[] {\n if (!Array.isArray(input.decisions)) {\n throw new TypeError('analyst review decisions must be an array')\n }\n const findings = snapshotAnalystFindings(input.findings)\n const expectedRunDigest = requiredDigest(input.runDigest, 'analyst review run digest')\n const findingsById = new Map(findings.map((finding) => [finding.finding_id, finding]))\n const generatingAnalystIds = new Set(input.analystIds)\n const seenFindingIds = new Set<string>()\n let completenessCount = 0\n\n const decisions = input.decisions.map((value, index): AnalystReviewDecision => {\n if (!isRecord(value)) {\n throw new TypeError(`analyst review decision ${index} must be an object`)\n }\n const source = requiredString(value.source, `analyst review decision ${index} source`)\n if (!isAnalystReviewSource(source)) {\n throw new TypeError(\n `analyst review decision ${index} source must be user, judge, environment, metric, or policy`,\n )\n }\n const reviewerId = requiredString(\n value.reviewerId,\n `analyst review decision ${index} reviewerId`,\n )\n if (generatingAnalystIds.has(reviewerId)) {\n throw new TypeError(\n `analyst review decision ${index} reviewerId must differ from the generating analyst`,\n )\n }\n const reviewId = requiredString(value.reviewId, `analyst review decision ${index} reviewId`)\n if (reviewId === input.runId) {\n throw new TypeError(\n `analyst review decision ${index} reviewId must identify an independent review`,\n )\n }\n const reason = requiredString(value.reason, `analyst review decision ${index} reason`)\n const decidedAt = canonicalTimestamp(\n value.decidedAt,\n `analyst review decision ${index} decidedAt`,\n )\n const runDigest = requiredDigest(value.runDigest, `analyst review decision ${index} runDigest`)\n if (runDigest !== expectedRunDigest) {\n throw new TypeError(`analyst review decision ${index} run digest mismatch`)\n }\n\n if (value.verdict === 'completeness_assessed') {\n assertOnlyKeys(\n value,\n [\n 'runDigest',\n 'verdict',\n 'missedIssues',\n 'source',\n 'reviewerId',\n 'reviewId',\n 'reason',\n 'decidedAt',\n ],\n `analyst review decision ${index}`,\n )\n completenessCount += 1\n if (completenessCount > 1) {\n throw new TypeError('duplicate completeness_assessed analyst review decision')\n }\n return {\n runDigest,\n verdict: 'completeness_assessed',\n missedIssues: validateMissedIssues(\n value.missedIssues,\n findingsById,\n `analyst review decision ${index}`,\n ),\n source,\n reviewerId,\n reviewId,\n reason,\n decidedAt,\n }\n }\n\n if (value.verdict !== 'confirmed' && value.verdict !== 'rejected') {\n throw new TypeError(\n `analyst review decision ${index} verdict must be confirmed, rejected, or completeness_assessed`,\n )\n }\n assertOnlyKeys(\n value,\n [\n 'runDigest',\n 'findingId',\n 'findingDigest',\n 'verdict',\n 'source',\n 'reviewerId',\n 'reviewId',\n 'reason',\n 'decidedAt',\n ],\n `analyst review decision ${index}`,\n )\n const findingId = requiredString(value.findingId, `analyst review decision ${index} findingId`)\n const finding = findingsById.get(findingId)\n if (!finding) {\n throw new TypeError(`analyst review decision references unknown finding id \"${findingId}\"`)\n }\n if (seenFindingIds.has(findingId)) {\n throw new TypeError(`duplicate analyst review decision for finding id \"${findingId}\"`)\n }\n seenFindingIds.add(findingId)\n const findingDigest = requiredString(\n value.findingDigest,\n `analyst review decision ${index} findingDigest`,\n )\n const expectedDigest = analystFindingDigest(finding)\n if (findingDigest !== expectedDigest) {\n throw new TypeError(\n `analyst review decision ${index} digest mismatch for finding id \"${findingId}\"`,\n )\n }\n return {\n runDigest,\n findingId,\n findingDigest: expectedDigest,\n verdict: value.verdict,\n source,\n reviewerId,\n reviewId,\n reason,\n decidedAt,\n }\n })\n\n if (input.requireComplete) {\n const missing = findings\n .map((finding) => finding.finding_id)\n .filter((findingId) => !seenFindingIds.has(findingId))\n if (missing.length > 0) {\n throw new TypeError(\n `feedbackTrajectoryToOptimizerRow: missing independent decisions for finding ids: ${missing.join(', ')}`,\n )\n }\n if (completenessCount !== 1) {\n throw new TypeError(\n 'feedbackTrajectoryToOptimizerRow: analyst run requires exactly one independent completeness_assessed decision',\n )\n }\n }\n return decisions\n}\n\nexport function assertUniqueFindingIds(findingIds: readonly string[]): void {\n const seen = new Set<string>()\n for (const findingId of findingIds) {\n if (findingId.trim().length === 0) throw new TypeError('analyst finding id must not be empty')\n if (seen.has(findingId)) {\n throw new TypeError(`analyst run contains duplicate finding id \"${findingId}\"`)\n }\n seen.add(findingId)\n }\n}\n\nfunction snapshotAnalystFinding(value: unknown, context: string): AnalystFinding {\n let snapshot: unknown\n try {\n snapshot = JSON.parse(canonicalString(value)) as unknown\n } catch (cause) {\n throw new TypeError(`${context} must have a canonical JSON representation`, { cause })\n }\n assertAnalystFinding(snapshot, context)\n return snapshot\n}\n\nfunction assertAnalystFinding(value: unknown, context: string): asserts value is AnalystFinding {\n if (!isRecord(value)) throw new TypeError(`${context} must be an object`)\n assertOnlyKeys(\n value,\n [\n 'schema_version',\n 'finding_id',\n 'analyst_id',\n 'produced_at',\n 'severity',\n 'area',\n 'claim',\n 'rationale',\n 'evidence_refs',\n 'recommended_action',\n 'validation_plan',\n 'confidence',\n 'subject',\n 'derived_from_judge',\n 'metadata',\n ],\n context,\n )\n if (value.schema_version !== '1.0.0') {\n throw new TypeError(`${context} schema_version must be \"1.0.0\"`)\n }\n requiredString(value.finding_id, `${context} finding_id`)\n requiredString(value.analyst_id, `${context} analyst_id`)\n canonicalTimestamp(value.produced_at, `${context} produced_at`)\n if (\n value.severity !== 'critical' &&\n value.severity !== 'high' &&\n value.severity !== 'medium' &&\n value.severity !== 'low' &&\n value.severity !== 'info'\n ) {\n throw new TypeError(`${context} severity is invalid`)\n }\n requiredString(value.area, `${context} area`)\n requiredString(value.claim, `${context} claim`)\n optionalString(value.rationale, `${context} rationale`)\n value.evidence_refs = validateEvidenceRefs(value.evidence_refs, `${context} evidence_refs`)\n optionalString(value.recommended_action, `${context} recommended_action`)\n optionalString(value.validation_plan, `${context} validation_plan`)\n if (\n typeof value.confidence !== 'number' ||\n !Number.isFinite(value.confidence) ||\n value.confidence < 0 ||\n value.confidence > 1\n ) {\n throw new TypeError(`${context} confidence must be a finite number from 0 through 1`)\n }\n optionalString(value.subject, `${context} subject`)\n if (value.derived_from_judge !== undefined && typeof value.derived_from_judge !== 'boolean') {\n throw new TypeError(`${context} derived_from_judge must be a boolean`)\n }\n if (value.metadata !== undefined && !isRecord(value.metadata)) {\n throw new TypeError(`${context} metadata must be an object`)\n }\n}\n\nfunction validateMissedIssues(\n value: unknown,\n findingsById: ReadonlyMap<string, AnalystFinding>,\n context: string,\n): AnalystMissedIssue[] {\n if (!Array.isArray(value)) {\n throw new TypeError(`${context} missedIssues must be an array`)\n }\n const seen = new Set<string>()\n return value.map((issue, index) => {\n const issueContext = `${context} missedIssues ${index}`\n if (!isRecord(issue)) throw new TypeError(`${issueContext} must be an object`)\n assertOnlyKeys(issue, ['id', 'reason', 'evidence'], issueContext)\n const id = requiredString(issue.id, `${issueContext} id`)\n if (findingsById.has(id)) {\n throw new TypeError(`${issueContext} id \"${id}\" is already an emitted finding id`)\n }\n if (seen.has(id)) {\n throw new TypeError(`duplicate missed issue id \"${id}\"`)\n }\n seen.add(id)\n const reason = requiredString(issue.reason, `${issueContext} reason`)\n return {\n id,\n reason,\n ...(issue.evidence === undefined\n ? {}\n : { evidence: validateEvidenceRefs(issue.evidence, `${issueContext} evidence`) }),\n }\n })\n}\n\nfunction validateEvidenceRefs(value: unknown, context: string): EvidenceRef[] {\n if (!Array.isArray(value)) throw new TypeError(`${context} must be an array`)\n return value.map((evidence, index) => {\n const evidenceContext = `${context} ${index}`\n if (!isRecord(evidence)) throw new TypeError(`${evidenceContext} must be an object`)\n assertOnlyKeys(evidence, ['kind', 'uri', 'excerpt'], evidenceContext)\n if (\n evidence.kind !== 'span' &&\n evidence.kind !== 'event' &&\n evidence.kind !== 'artifact' &&\n evidence.kind !== 'finding' &&\n evidence.kind !== 'metric'\n ) {\n throw new TypeError(`${evidenceContext} kind is invalid`)\n }\n const uri = requiredString(evidence.uri, `${evidenceContext} uri`)\n const excerpt = evidence.excerpt\n optionalString(excerpt, `${evidenceContext} excerpt`)\n return {\n kind: evidence.kind,\n uri,\n ...(excerpt === undefined ? {} : { excerpt: excerpt as string }),\n }\n })\n}\n\nfunction assertOnlyKeys(\n value: Record<string, unknown>,\n allowed: readonly string[],\n name: string,\n): void {\n const allowedKeys = new Set(allowed)\n const unexpected = Object.keys(value).filter((key) => !allowedKeys.has(key))\n if (unexpected.length > 0) {\n throw new TypeError(`${name} contains unknown fields: ${unexpected.sort().join(', ')}`)\n }\n}\n\nfunction stringArray(value: unknown, name: string): string[] {\n if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {\n throw new TypeError(`${name} must be an array of strings`)\n }\n const strings = value.map((item) => requiredString(item, name))\n if (new Set(strings).size !== strings.length) {\n throw new TypeError(`${name} must contain unique values`)\n }\n return strings\n}\n\nfunction requiredString(value: unknown, name: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new TypeError(`${name} must be a non-empty string`)\n }\n return value\n}\n\nfunction requiredDigest(value: unknown, name: string): AnalystRunDigest {\n const digest = requiredString(value, name)\n if (!/^sha256:[a-f0-9]{64}$/.test(digest)) {\n throw new TypeError(`${name} must be a sha256 digest`)\n }\n return digest as AnalystRunDigest\n}\n\nfunction optionalString(value: unknown, name: string): void {\n if (value !== undefined && typeof value !== 'string') {\n throw new TypeError(`${name} must be a string`)\n }\n}\n\nfunction canonicalTimestamp(value: unknown, name: string): string {\n const timestamp = requiredString(value, name)\n const parsed = new Date(timestamp)\n if (Number.isNaN(parsed.valueOf()) || parsed.toISOString() !== timestamp) {\n throw new TypeError(`${name} must be a canonical ISO 8601 UTC timestamp`)\n }\n return timestamp\n}\n\nfunction isAnalystReviewSource(value: string): value is AnalystReviewSource {\n return (\n value === 'user' ||\n value === 'judge' ||\n value === 'environment' ||\n value === 'metric' ||\n value === 'policy'\n )\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","/**\n * AnalystRegistry — orchestrate N analysts against one run.\n *\n * Owns three responsibilities and only three:\n * 1. Registration — ids must be unique; bad registrations fail loudly\n * at register-time, not run-time.\n * 2. Routing — each analyst declares its `inputKind`; the registry\n * picks the matching field from AnalystRunInputs and skips the\n * analyst with a logged reason if it's missing.\n * 3. Isolation — one analyst's exception MUST NOT stop other analysts.\n * Failed analysts produce zero findings + a 'failed' summary row.\n *\n * Cross-cutting concerns (telemetry, error → finding conversion, cost\n * ingestion, storage rotation) live in `AnalystHooks`. Budget shaping\n * (equal split vs weighted vs custom) lives in `BudgetPolicy`. Both\n * have sensible defaults; consumers override only what they need.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { z } from 'zod'\nimport { combineAbortSignals } from '../abort-signal'\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport {\n snapshotAnalystFindings,\n snapshotExactAnalystRunReceipt,\n} from '../feedback-trajectory-review'\nimport { canonicalString, hashCanonical } from '../ledger-core/canonical'\nimport { deepFreezeCanonicalJson } from '../ledger-core/deep-freeze'\nimport type { RunCostProvenance, RunTokenUsage } from '../run-record'\nimport type { ChatClient } from './chat-client'\nimport type {\n ExactAnalystExecutionPlanSnapshot,\n ExactAnalystRunEvent,\n ExactAnalystRunResult,\n ExactCapableAnalyst,\n ExactExecutionComponentIdentity,\n ExactExecutionComponentSnapshot,\n} from './exact-types'\nimport { snapshotExactExecutionComponentIdentity, snapshotExactExecutionPlan } from './exact-types'\nimport type {\n Analyst,\n AnalystContext,\n AnalystFinding,\n AnalystRunEvent,\n AnalystRunInputs,\n AnalystRunResult,\n AnalystRunSummary,\n AnalystUsageReceipt,\n} from './types'\nimport { assertValidAnalystUsageReceipt, validateUsageSettlementTimeout } from './usage-receipt'\n\n// ── Hook + policy surfaces ─────────────────────────────────────────\n\nexport interface AnalystHooks {\n /** Legacy runs may mutate ctx; exact runs provide a frozen observational context. */\n onBeforeAnalyze?(args: {\n analyst: Analyst\n ctx: AnalystContext\n runId: string\n }): void | Promise<void>\n /** After every analyst (ok | failed | skipped). Use for telemetry, ingestion, rotation. */\n onAfterAnalyze?(args: {\n analyst: Analyst\n summary: AnalystRunSummary\n findings: AnalystFinding[]\n runId: string\n }): void | Promise<void>\n /**\n * On analyst exception. Hook MAY return findings to convert the\n * error into structured findings; the summary still reports 'failed'.\n * Return void to keep the default empty-findings behavior.\n */\n onError?(args: {\n analyst: Analyst\n error: Error\n runId: string\n }): AnalystFinding[] | undefined | Promise<AnalystFinding[] | undefined>\n /** Once after registry.run() completes. Use for final aggregation, persistence. */\n onComplete?(args: { result: AnalystRunResult }): void | Promise<void>\n}\n\nexport interface BudgetPolicy {\n /** Overall USD cap across the registry.run(). */\n totalUsd?: number\n /** Per-analyst weight for the default allocator. Missing ids get weight 1. */\n weights?: Record<string, number>\n /**\n * Custom allocator — receives the analyst, remaining/total budget, and\n * the count of analysts that will run. Returns the per-analyst budget\n * (or undefined only when the run has no overall cap). Overrides weights\n * when set.\n */\n allocate?: (args: {\n analyst: Analyst\n totalUsd: number | undefined\n remainingUsd: number | undefined\n runningCount: number\n }) => number | undefined\n}\n\nexport interface AnalystRegistryOptions {\n /** Shared chat client passed to every LLM analyst via AnalystContext. */\n chat?: ChatClient\n /** Logger callback. Defaults to a no-op. */\n log?: (msg: string, fields?: Record<string, unknown>) => void\n /** Hooks invoked around analyze() — observability + customization seam. */\n hooks?: AnalystHooks\n /** Required identity/config when `runExact` applies `hooks`. */\n hooksIdentity?: ExactExecutionComponentIdentity\n /** Default budget when run() doesn't override. */\n defaultBudget?: BudgetPolicy\n /** Required identity/config when `runExact` provides `chat`. */\n chatIdentity?: ExactExecutionComponentIdentity\n}\n\nexport interface RegistryRunOpts {\n /** Restrict to a subset of registered analysts by id. */\n only?: string[]\n /** Skip these analysts even if registered. Useful for cheap iteration. */\n skip?: string[]\n /** Budget policy — totalUsd + optional weights/allocator. Falls back to options.defaultBudget. */\n budget?: BudgetPolicy\n /** Active-work cap for the complete registry run. Model receipt settlement may follow. */\n timeoutMs?: number\n /** Abort signal — forwarded into every analyst's context. */\n signal?: AbortSignal\n /** Shared paid-call account forwarded to every analyst. */\n costLedger?: CostLedgerHandle\n /** Attribution phase for calls written to `costLedger`. */\n costPhase?: string\n /** Tags echoed into AnalystContext.tags — useful for tracking environment/version in findings. */\n tags?: Record<string, string>\n /**\n * Prior-run findings made available as retrieval context to every\n * analyst via `ctx.priorFindings`. The registry forwards the slice\n * whose `analyst_id` matches each registered analyst so a kind sees\n * only its own history. Pass `{ '*': findings }` to broadcast to\n * every analyst (useful when several kinds share the same historical\n * context). For findings from this run, use `chainFindings` instead.\n */\n priorFindings?: ReadonlyArray<AnalystFinding> | Record<string, ReadonlyArray<AnalystFinding>>\n /**\n * Pass findings produced earlier in this registry run to each later analyst\n * via `ctx.upstreamFindings`. Registration order is dependency order.\n * Disabled by default because independent analyst suites must opt in.\n */\n chainFindings?: boolean\n}\n\n/** A caller-selected allocation rule for an exact analyst run. */\nexport type ExactAnalystBudgetPolicy =\n | {\n readonly kind: 'equal'\n readonly totalUsd: number\n }\n | {\n readonly kind: 'weighted'\n readonly totalUsd: number\n /** One explicit weight for every selected analyst id. */\n readonly weights: Readonly<Record<string, number>>\n }\n\n/**\n * Complete per-run analyst policy.\n *\n * Every field is required. `null` explicitly disables an optional resource or context channel.\n * `analystIds` is execution order; it is not filtered through registry insertion order.\n * Missing-input behavior is explicit so callers cannot accidentally inherit it by omission.\n * Exact runs are serial; more elaborate scheduling belongs in the caller's runtime.\n */\nexport interface ExactRegistryRunOpts {\n readonly analystIds: readonly string[]\n readonly budget: ExactAnalystBudgetPolicy | null\n readonly totalTimeoutMs: number | null\n readonly signal: AbortSignal | null\n readonly costLedger: CostLedgerHandle | null\n readonly costLedgerIdentity: ExactExecutionComponentIdentity | null\n readonly costPhase: string | null\n readonly tags: Readonly<Record<string, string>> | null\n readonly priorFindings:\n | ReadonlyArray<AnalystFinding>\n | Readonly<Record<string, ReadonlyArray<AnalystFinding>>>\n | null\n readonly chainFindings: boolean\n readonly missingInputMode: 'skip' | 'abort'\n readonly applyRegistryHooks: boolean\n readonly useRegistryChat: boolean\n}\n\ntype NormalizedBudgetPlan =\n | { readonly kind: 'none' }\n | { readonly kind: 'dynamic'; readonly policy: BudgetPolicy }\n\ninterface PreparedAnalyst {\n readonly analyst: Analyst\n readonly input:\n | { readonly kind: 'present'; readonly value: unknown }\n | { readonly kind: 'missing' }\n}\n\ninterface AnalystExecutionPlan {\n readonly runId: string\n readonly prepared: readonly PreparedAnalyst[]\n readonly budget: NormalizedBudgetPlan\n readonly totalTimeoutMs: number | null\n readonly signal: AbortSignal | null\n readonly costLedger: CostLedgerHandle | null\n readonly costPhase: string | null\n readonly tags: Readonly<Record<string, string>> | null\n readonly priorFindings:\n | ReadonlyArray<AnalystFinding>\n | Readonly<Record<string, ReadonlyArray<AnalystFinding>>>\n | null\n readonly chainFindings: boolean\n readonly hooks: AnalystHooks\n readonly chat: ChatClient | undefined\n readonly log: (msg: string, fields?: Record<string, unknown>) => void\n readonly executionSnapshot: ExactAnalystExecutionPlanSnapshot | undefined\n}\n\ntype InternalAnalystRunEvent = AnalystRunEvent\n\n/** A post-start exact-run failure; completed work remains attached for accounting and review. */\nexport class ExactAnalystRunExecutionError extends Error {\n readonly name: string = 'ExactAnalystRunExecutionError'\n readonly result: ExactAnalystRunResult\n\n constructor(message: string, result: ExactAnalystRunResult, options?: ErrorOptions) {\n super(message, options)\n const snapshot = snapshotExactAnalystRunReceipt(result, 'ExactAnalystRunExecutionError result')\n if (snapshot.completion.status !== 'failed') {\n throw new TypeError('ExactAnalystRunExecutionError result must be a failed receipt')\n }\n this.result = snapshot\n }\n}\n\nexport class AnalystRegistry {\n private readonly analysts = new Map<string, Analyst>()\n private readonly options: AnalystRegistryOptions\n\n constructor(options: AnalystRegistryOptions = {}) {\n this.options = options\n }\n\n register(analyst: Analyst): void {\n const id = analyst.id\n const version = analyst.version\n const cost = analyst.cost\n if (!id) throw new Error('AnalystRegistry.register: analyst.id is required')\n if (this.analysts.has(id)) {\n throw new Error(`AnalystRegistry.register: duplicate analyst id \"${id}\"`)\n }\n if (!version) {\n throw new Error(`AnalystRegistry.register: analyst \"${id}\" must declare a version`)\n }\n if (cost.kind === 'deterministic' && cost.settlement_timeout_ms !== undefined) {\n throw new TypeError(\n `AnalystRegistry.register: deterministic analyst \"${id}\" cannot declare settlement_timeout_ms`,\n )\n }\n if (cost.settlement_timeout_ms !== undefined) {\n validateUsageSettlementTimeout(cost.settlement_timeout_ms)\n }\n this.analysts.set(id, analyst)\n }\n\n list(): ReadonlyArray<{\n id: string\n description: string\n version: string\n cost: Analyst['cost']\n }> {\n return Array.from(this.analysts.values()).map((a) => ({\n id: a.id,\n description: a.description,\n version: a.version,\n cost: a.cost,\n }))\n }\n\n async run(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: RegistryRunOpts = {},\n ): Promise<AnalystRunResult> {\n // Thin collector over `runStream`. Both surfaces share the same\n // loop body so they cannot drift on isolation / hook order / cost.\n for await (const ev of this.runStream(runId, inputs, runOpts)) {\n if (ev.type === 'run-completed') return ev.result\n }\n throw new Error('AnalystRegistry.run: stream completed without run-completed event')\n }\n\n /** Run exactly the ordered analysts and complete policy supplied by the caller. */\n async runExact(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: ExactRegistryRunOpts,\n ): Promise<ExactAnalystRunResult> {\n for await (const ev of this.runExactStream(runId, inputs, runOpts)) {\n if (ev.type === 'run-completed') return ev.result\n }\n throw new Error('AnalystRegistry.runExact: stream completed without run-completed event')\n }\n\n /** Streaming counterpart to {@link runExact}. */\n async *runExactStream(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: ExactRegistryRunOpts,\n ): AsyncGenerator<ExactAnalystRunEvent, void, void> {\n for await (const event of this.executePlanStream(\n this.normalizeExactPlan(runId, inputs, runOpts),\n )) {\n yield event as ExactAnalystRunEvent\n }\n }\n\n /**\n * Streaming counterpart to `run()`. Emits `AnalystRunEvent` values\n * in real time — `run-started`, then per-analyst `skipped` /\n * `started` / `completed`, then a terminal `run-completed` whose\n * payload is the full `AnalystRunResult`. UIs use this to render\n * progress; persistence consumers use `run()` and read the result.\n *\n * Hooks (`onBeforeAnalyze` / `onAfterAnalyze` / `onError` /\n * `onComplete`) fire as before — streaming is additive, not a hook\n * replacement.\n */\n async *runStream(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: RegistryRunOpts = {},\n ): AsyncGenerator<AnalystRunEvent, void, void> {\n yield* this.executePlanStream(this.normalizeLegacyPlan(runId, inputs, runOpts))\n }\n\n private normalizeLegacyPlan(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: RegistryRunOpts,\n ): AnalystExecutionPlan {\n const timeoutMs = validateTimeout(runOpts.timeoutMs) ?? null\n const budget = runOpts.budget ?? this.options.defaultBudget\n validateBudgetPolicy(budget)\n const selected = this.selectAnalysts(runOpts)\n return {\n runId,\n prepared: selected.map((analyst) => ({\n analyst,\n input: this.routeInput(analyst, inputs),\n })),\n budget: budget ? { kind: 'dynamic', policy: budget } : { kind: 'none' },\n totalTimeoutMs: timeoutMs,\n signal: runOpts.signal ?? null,\n costLedger: runOpts.costLedger ?? null,\n costPhase: runOpts.costPhase ?? null,\n tags: runOpts.tags ?? null,\n priorFindings: runOpts.priorFindings ?? null,\n chainFindings: runOpts.chainFindings ?? false,\n hooks: this.options.hooks ?? {},\n chat: this.options.chat,\n log: this.options.log ?? (() => {}),\n executionSnapshot: undefined,\n }\n }\n\n private normalizeExactPlan(\n runId: string,\n inputs: AnalystRunInputs,\n runOpts: ExactRegistryRunOpts,\n ): AnalystExecutionPlan {\n const exactRunId = snapshotExactRunId(runId)\n const exact = snapshotExactRegistryRunOpts(runOpts)\n const selected = normalizeExactAnalysts(this.selectExactAnalysts(exact.analystIds))\n const registryChat = this.options.chat\n const registryChatIdentity = this.options.chatIdentity\n const registryHooks = this.options.hooks\n const registryHooksIdentity = this.options.hooksIdentity\n if (exact.useRegistryChat && registryChat === undefined) {\n throw new TypeError(\n 'ExactRegistryRunOpts.useRegistryChat is true but the registry has no chat client',\n )\n }\n if (exact.applyRegistryHooks && !hasRegistryHooks(registryHooks)) {\n throw new TypeError(\n 'ExactRegistryRunOpts.applyRegistryHooks is true but the registry has no lifecycle hooks',\n )\n }\n const inputSnapshot = snapshotAnalystRunInputChannels(inputs)\n const prepared = selected.map((analyst) => ({\n analyst,\n input: this.routeInput(analyst, inputSnapshot),\n }))\n if (exact.missingInputMode === 'abort') {\n const missing = prepared.find((candidate) => candidate.input.kind === 'missing')?.analyst\n if (missing) {\n throw new TypeError(\n `ExactRegistryRunOpts.missingInputMode abort preflight found no \"${missing.inputKind}\" input for \"${missing.id}\"`,\n )\n }\n }\n const hooksIdentity =\n exact.applyRegistryHooks && registryHooks\n ? requireExactComponentIdentity(registryHooksIdentity, 'registry hooks')\n : null\n const chatIdentity = exact.useRegistryChat\n ? requireExactComponentIdentity(registryChatIdentity, 'registry chat')\n : null\n const costLedgerIdentity =\n exact.costLedger === null\n ? null\n : requireExactComponentIdentity(exact.costLedgerIdentity ?? undefined, 'cost ledger')\n const allocations = exactFixedBudgets(\n exact.budget,\n prepared\n .filter(\n (\n candidate,\n ): candidate is {\n analyst: ExactCapableAnalyst\n input: { kind: 'present'; value: unknown }\n } => candidate.input.kind === 'present',\n )\n .map((candidate) => candidate.analyst),\n selected,\n )\n const executionSnapshot = exactExecutionSnapshot(\n selected,\n exact,\n allocations,\n costLedgerIdentity,\n hooksIdentity,\n chatIdentity,\n )\n return {\n runId: exactRunId,\n prepared,\n budget: { kind: 'none' },\n totalTimeoutMs: exact.totalTimeoutMs,\n signal: exact.signal,\n costLedger: exact.costLedger,\n costPhase: exact.costPhase,\n tags: exact.tags,\n priorFindings: exact.priorFindings,\n chainFindings: exact.chainFindings,\n hooks: exact.applyRegistryHooks && registryHooks ? snapshotHooks(registryHooks) : {},\n chat: exact.useRegistryChat && registryChat ? snapshotChat(registryChat) : undefined,\n // Exact runs expose live events and versioned hooks. An inherited logger is intentionally\n // excluded because an anonymous callback can throw, block, or mutate shared state.\n log: () => {},\n executionSnapshot,\n }\n }\n\n private async *executePlanStream(\n plan: AnalystExecutionPlan,\n ): AsyncGenerator<InternalAnalystRunEvent, void, void> {\n const exact = plan.executionSnapshot !== undefined\n if (exact && plan.signal?.aborted) throw abortReason(plan.signal)\n\n const correlationId = `ar_${randomUUID().slice(0, 12)}`\n const log = plan.log\n const startedAt = new Date().toISOString()\n const started = Date.now()\n const timeoutSignal =\n plan.totalTimeoutMs === null ? undefined : AbortSignal.timeout(plan.totalTimeoutMs)\n const runSignal = combineAbortSignals(plan.signal ?? undefined, timeoutSignal)\n const deadlineMs = plan.totalTimeoutMs === null ? undefined : started + plan.totalTimeoutMs\n const runnable = plan.prepared\n .filter(\n (\n candidate,\n ): candidate is {\n analyst: Analyst\n input: { kind: 'present'; value: unknown }\n } => candidate.input.kind === 'present',\n )\n .map((candidate) => candidate.analyst)\n let remainingUsd = plan.budget.kind === 'dynamic' ? plan.budget.policy.totalUsd : undefined\n const weights = plan.budget.kind === 'dynamic' ? plan.budget.policy.weights : undefined\n const totalWeight =\n weights &&\n plan.budget.kind === 'dynamic' &&\n plan.budget.policy.totalUsd != null &&\n !plan.budget.policy.allocate &&\n runnable.length > 0\n ? runnable.reduce((sum, analyst) => sum + analystWeight(weights, analyst.id), 0)\n : undefined\n if (totalWeight === 0) {\n throw new Error('BudgetPolicy.weights must allocate positive weight to a runnable analyst')\n }\n const upstreamFindings: AnalystFinding[] = []\n\n yield snapshotExecutionEvent(\n {\n type: 'run-started',\n run_id: plan.runId,\n correlation_id: correlationId,\n started_at: startedAt,\n analyst_ids: plan.prepared.map(({ analyst }) => analyst.id),\n ...(plan.executionSnapshot === undefined ? {} : { execution_plan: plan.executionSnapshot }),\n },\n exact,\n )\n\n const executions: AnalystExecution[] = []\n let executionFailure: unknown\n\n for (const { analyst, input } of plan.prepared) {\n const t0 = Date.now()\n if (runSignal?.aborted) {\n const summary = abortedBeforeStartSummary(analyst, runSignal)\n executions.push({ summary, findings: [], budgetDebitUsd: 0 })\n log(`[analyst] skip ${analyst.id} — run aborted`, {\n runId: plan.runId,\n reason: summary.reason,\n })\n yield snapshotExecutionEvent({ type: 'analyst-skipped', summary }, exact)\n if (exact) {\n executionFailure = abortReason(runSignal)\n break\n }\n continue\n }\n\n if (input.kind === 'missing') {\n const summary: AnalystRunSummary = {\n analyst_id: analyst.id,\n status: 'skipped',\n reason: `missing input of kind '${analyst.inputKind}'`,\n findings_count: 0,\n latency_ms: 0,\n usage: zeroUsage(),\n }\n const execution = { summary, findings: [], budgetDebitUsd: 0 } satisfies AnalystExecution\n executions.push(execution)\n log(`[analyst] skip ${analyst.id} — missing input`, {\n runId: plan.runId,\n kind: analyst.inputKind,\n })\n const hookValues = snapshotAfterHookValues(summary, [], exact)\n try {\n await waitForHook(\n plan.hooks.onAfterAnalyze\n ? () =>\n plan.hooks.onAfterAnalyze?.({\n analyst,\n summary: hookValues.summary,\n findings: hookValues.findings,\n runId: plan.runId,\n })\n : undefined,\n runSignal,\n )\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n }\n yield snapshotExecutionEvent({ type: 'analyst-skipped', summary }, exact)\n if (executionFailure !== undefined) break\n continue\n }\n\n const allocatedUsd =\n plan.executionSnapshot === undefined\n ? allocateBudget(plan.budget.kind === 'dynamic' ? plan.budget.policy : undefined, {\n analyst,\n remainingUsd,\n runningCount: runnable.length,\n totalWeight,\n })\n : exactPlannedAllocation(plan.executionSnapshot, analyst.id)\n const budgetCeilingUsd = plan.executionSnapshot === undefined ? remainingUsd : allocatedUsd\n const usageReceipts: AnalystUsageReceipt[] = []\n const contextTags = plan.tags === null ? undefined : { ...plan.tags }\n const priorFindings = selectPriorFindings(plan.priorFindings ?? undefined, analyst.id)\n const chainedFindings =\n plan.chainFindings && upstreamFindings.length > 0 ? [...upstreamFindings] : undefined\n const ctx: AnalystContext = {\n runId: plan.runId,\n correlationId,\n deadlineMs,\n budgetUsd: allocatedUsd,\n costLedger: plan.costLedger ?? undefined,\n costPhase: plan.costPhase ?? undefined,\n chat: plan.chat,\n tags: contextTags,\n log: (message, fields) =>\n log(`[${analyst.id}] ${message}`, {\n runId: plan.runId,\n correlationId,\n ...fields,\n }),\n signal: runSignal,\n priorFindings,\n upstreamFindings: chainedFindings,\n recordUsage: (receipt) => {\n if (!exact) {\n assertValidAnalystUsageReceipt(receipt)\n usageReceipts.push(receipt)\n return\n }\n usageReceipts.push(\n snapshotUsageReceiptOnce(\n receipt,\n `AnalystRegistry.runExact analyst \"${analyst.id}\" usage`,\n ),\n )\n },\n }\n if (exact) {\n if (contextTags) deepFreezeCanonicalJson(contextTags)\n if (priorFindings) deepFreezeCanonicalJson(priorFindings)\n if (chainedFindings) deepFreezeCanonicalJson(chainedFindings)\n Object.freeze(ctx)\n }\n\n try {\n await waitForHook(\n plan.hooks.onBeforeAnalyze\n ? () => plan.hooks.onBeforeAnalyze?.({ analyst, ctx, runId: plan.runId })\n : undefined,\n runSignal,\n )\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n break\n }\n if (runSignal?.aborted) {\n const summary = abortedBeforeStartSummary(analyst, runSignal, Date.now() - t0)\n executions.push({ summary, findings: [], budgetDebitUsd: 0 })\n yield snapshotExecutionEvent({ type: 'analyst-skipped', summary }, exact)\n if (exact) {\n executionFailure = abortReason(runSignal)\n break\n }\n continue\n }\n let effectiveBudget: number | undefined\n try {\n effectiveBudget = validateEffectiveBudget(ctx.budgetUsd, budgetCeilingUsd, analyst.id)\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n break\n }\n const analystContext: AnalystContext = exact ? ctx : { ...ctx }\n const executionSignal = exact ? ctx.signal : runSignal\n yield snapshotExecutionEvent(\n {\n type: 'analyst-started',\n analyst_id: analyst.id,\n started_at: new Date(t0).toISOString(),\n },\n exact,\n )\n\n let findings: AnalystFinding[]\n let summary: AnalystRunSummary\n let lifecycleFailure: unknown\n let analysisFailure: Error | undefined\n try {\n if (runSignal?.aborted) throw abortReason(runSignal)\n const analyzed = await waitForOperation(\n (analyst as Analyst<unknown>).analyze(input.value, analystContext),\n executionSignal,\n analystAbortGraceMs(analyst),\n )\n findings = snapshotExecutionFindings(\n analyzed,\n exact,\n `AnalystRegistry.runExact analyst \"${analyst.id}\" findings`,\n )\n } catch (error) {\n const cause = error instanceof Error ? error : new Error(String(error))\n analysisFailure = cause\n let hookFindings: AnalystFinding[] = []\n if (!executionSignal?.aborted) {\n try {\n const rawHookFindings =\n (await waitForHook(\n plan.hooks.onError\n ? () =>\n plan.hooks.onError?.({\n analyst,\n error: cause,\n runId: plan.runId,\n })\n : undefined,\n executionSignal,\n )) ?? []\n hookFindings = snapshotExecutionFindings(\n rawHookFindings,\n exact,\n `AnalystRegistry.runExact analyst \"${analyst.id}\" onError findings`,\n )\n } catch (error) {\n lifecycleFailure = error\n }\n }\n findings = hookFindings\n }\n\n let usage: AnalystUsageReceipt\n try {\n usage = resolveUsage(analyst, usageReceipts, exact)\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n break\n }\n if (analysisFailure === undefined) {\n summary = {\n analyst_id: analyst.id,\n status: 'ok',\n findings_count: findings.length,\n latency_ms: Date.now() - t0,\n usage,\n ...(exact ? { allocated_budget_usd: effectiveBudget ?? null } : {}),\n }\n log(`[analyst] ok ${analyst.id}`, {\n runId: plan.runId,\n findings: findings.length,\n latency_ms: summary.latency_ms,\n cost_usd: knownCostUsd(usage),\n cost_kind: usage.cost.kind,\n input_tokens: usage.tokens?.input ?? null,\n output_tokens: usage.tokens?.output ?? null,\n })\n } else {\n const errorClass = analysisFailure.constructor.name || 'Error'\n const errorMessage =\n exact && analysisFailure.message.length === 0\n ? 'Analyst failed without an error message'\n : analysisFailure.message\n summary = {\n analyst_id: analyst.id,\n status: 'failed',\n findings_count: findings.length,\n latency_ms: Date.now() - t0,\n usage,\n ...(exact ? { allocated_budget_usd: effectiveBudget ?? null } : {}),\n error: { class: errorClass, message: errorMessage },\n }\n log(`[analyst] FAIL ${analyst.id}`, {\n runId: plan.runId,\n error_class: errorClass,\n error: errorMessage,\n cost_usd: knownCostUsd(usage),\n cost_kind: usage.cost.kind,\n })\n }\n logUncapturedBudgetWarning({\n analyst,\n runId: plan.runId,\n budgetUsd: effectiveBudget,\n usage,\n log,\n })\n\n const execution = {\n summary,\n findings,\n budgetDebitUsd: budgetDebit(summary.usage, effectiveBudget),\n } satisfies AnalystExecution\n if (exact) {\n try {\n executionCost([...executions, execution], true)\n } catch (error) {\n executionFailure = error\n break\n }\n }\n executions.push(execution)\n if (plan.budget.kind === 'dynamic' && remainingUsd !== undefined) {\n remainingUsd = Math.max(0, remainingUsd - execution.budgetDebitUsd)\n }\n if (plan.chainFindings) upstreamFindings.push(...findings)\n if (lifecycleFailure !== undefined) {\n if (!exact) throw lifecycleFailure\n executionFailure = lifecycleFailure\n break\n }\n\n const hookValues = snapshotAfterHookValues(summary, findings, exact)\n try {\n await waitForHook(\n plan.hooks.onAfterAnalyze\n ? () =>\n plan.hooks.onAfterAnalyze?.({\n analyst,\n summary: hookValues.summary,\n findings: hookValues.findings,\n runId: plan.runId,\n })\n : undefined,\n executionSignal,\n )\n } catch (error) {\n if (!exact) throw error\n executionFailure = error\n break\n }\n yield snapshotExecutionEvent({ type: 'analyst-completed', summary, findings }, exact)\n if (exact && runSignal?.aborted) {\n executionFailure = abortReason(runSignal)\n break\n }\n }\n\n const summaries = executions.map(({ summary }) => summary)\n const findings = executions.flatMap((execution) => execution.findings)\n const cost = executionCost(executions, exact)\n const baseResult: AnalystRunResult = {\n run_id: plan.runId,\n correlation_id: correlationId,\n started_at: startedAt,\n ended_at: new Date().toISOString(),\n findings,\n per_analyst: summaries,\n total_cost_usd: cost.known,\n total_cost_provenance: cost.provenance,\n }\n if (plan.executionSnapshot === undefined) {\n await waitForHook(\n plan.hooks.onComplete ? () => plan.hooks.onComplete?.({ result: baseResult }) : undefined,\n runSignal,\n )\n yield { type: 'run-completed', result: baseResult }\n return\n }\n\n let completeResult: ExactAnalystRunResult | undefined\n if (executionFailure === undefined) {\n try {\n completeResult = snapshotExactAnalystRunReceipt(\n {\n ...baseResult,\n execution_plan: plan.executionSnapshot,\n completion: { status: 'complete' },\n },\n 'AnalystRegistry.runExact result',\n )\n await waitForHook(\n plan.hooks.onComplete\n ? () => plan.hooks.onComplete?.({ result: completeResult! })\n : undefined,\n runSignal,\n )\n } catch (error) {\n executionFailure = error\n }\n }\n if (runSignal?.aborted) executionFailure ??= abortReason(runSignal)\n if (executionFailure === undefined && completeResult) {\n yield snapshotExecutionEvent({ type: 'run-completed', result: completeResult }, true)\n return\n }\n\n const cause =\n executionFailure instanceof Error ? executionFailure : new Error(String(executionFailure))\n const errorClass = cause.constructor.name || 'Error'\n const errorMessage =\n cause.message.trim().length === 0\n ? 'Exact analyst run failed without a message'\n : cause.message\n throw new ExactAnalystRunExecutionError(\n `exact analyst run failed after starting: ${errorMessage}; partial result is attached`,\n {\n ...baseResult,\n execution_plan: plan.executionSnapshot,\n completion: {\n status: 'failed',\n error: { class: errorClass, message: errorMessage },\n },\n },\n { cause },\n )\n }\n\n private selectAnalysts(opts: RegistryRunOpts): Analyst[] {\n let candidates = Array.from(this.analysts.values())\n if (opts.only?.length) {\n const only = new Set(opts.only)\n candidates = candidates.filter((a) => only.has(a.id))\n }\n if (opts.skip?.length) {\n const skip = new Set(opts.skip)\n candidates = candidates.filter((a) => !skip.has(a.id))\n }\n return candidates\n }\n\n private selectExactAnalysts(\n ids: readonly string[],\n ): ReadonlyArray<{ readonly registeredId: string; readonly analyst: Analyst }> {\n return ids.map((id) => {\n const analyst = this.analysts.get(id)\n if (!analyst) throw new Error(`ExactRegistryRunOpts.analystIds names unknown analyst \"${id}\"`)\n return { registeredId: id, analyst }\n })\n }\n\n private routeInput(\n analyst: Analyst,\n inputs: AnalystRunInputs,\n ): { kind: 'present'; value: unknown } | { kind: 'missing' } {\n switch (analyst.inputKind) {\n case 'trace-store': {\n const value = inputs.traceStore\n return value ? { kind: 'present', value } : { kind: 'missing' }\n }\n case 'artifact-dir': {\n const value = inputs.artifactDir\n return value ? { kind: 'present', value } : { kind: 'missing' }\n }\n case 'run-record': {\n const value = inputs.runRecord\n return value ? { kind: 'present', value } : { kind: 'missing' }\n }\n case 'judge-input': {\n const value = inputs.judgeInput\n return value ? { kind: 'present', value } : { kind: 'missing' }\n }\n case 'custom': {\n const custom = inputs.custom\n const value = custom?.[analyst.id]\n return value !== undefined ? { kind: 'present', value } : { kind: 'missing' }\n }\n }\n }\n}\n\nconst exactRunFields = [\n 'analystIds',\n 'budget',\n 'totalTimeoutMs',\n 'signal',\n 'costLedger',\n 'costLedgerIdentity',\n 'costPhase',\n 'tags',\n 'priorFindings',\n 'chainFindings',\n 'missingInputMode',\n 'applyRegistryHooks',\n 'useRegistryChat',\n] as const\n\nconst exactNonEmptyString = z.string().min(1)\nconst exactFiniteNonnegative = z.number().finite().nonnegative()\nconst exactBudgetSchema = z.discriminatedUnion('kind', [\n z.strictObject({\n kind: z.literal('equal'),\n totalUsd: exactFiniteNonnegative,\n }),\n z.strictObject({\n kind: z.literal('weighted'),\n totalUsd: exactFiniteNonnegative,\n weights: z.record(exactNonEmptyString, exactFiniteNonnegative),\n }),\n])\nconst exactRunDataSchema = z\n .strictObject({\n analystIds: z.array(exactNonEmptyString).min(1),\n budget: exactBudgetSchema.nullable(),\n totalTimeoutMs: z.number().int().positive().max(2_147_483_647).nullable(),\n costLedgerIdentity: z.unknown().nullable(),\n costPhase: exactNonEmptyString.nullable(),\n tags: z.record(z.string(), z.string()).nullable(),\n chainFindings: z.boolean(),\n missingInputMode: z.enum(['skip', 'abort']),\n applyRegistryHooks: z.boolean(),\n useRegistryChat: z.boolean(),\n })\n .superRefine((policy, context) => {\n const issue = (path: PropertyKey[], message: string): void =>\n context.addIssue({ code: 'custom', path, message })\n if (new Set(policy.analystIds).size !== policy.analystIds.length) {\n issue(['analystIds'], 'must not contain duplicates')\n }\n if (\n policy.budget?.kind === 'weighted' &&\n Object.values(policy.budget.weights).every((weight) => weight === 0)\n ) {\n issue(['budget', 'weights'], 'must allocate positive weight to at least one analyst')\n }\n if (policy.budget?.kind === 'weighted') {\n const selected = [...policy.analystIds].sort()\n const weighted = Object.keys(policy.budget.weights).sort()\n if (\n selected.length !== weighted.length ||\n selected.some((id, index) => id !== weighted[index])\n ) {\n issue(['budget', 'weights'], 'must name every selected analyst and no others')\n }\n }\n })\n\n/** Validate the canonical exact-run policy before any analyst can start. */\nexport function assertExactRegistryRunOpts(value: unknown): asserts value is ExactRegistryRunOpts {\n void snapshotExactRegistryRunOpts(value)\n}\n\nfunction snapshotExactRunId(value: unknown): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw new TypeError('AnalystRegistry.runExact: runId must be a non-empty string')\n }\n return canonicalJsonSnapshot(value, 'AnalystRegistry.runExact runId')\n}\n\nfunction snapshotAnalystRunInputChannels(inputs: AnalystRunInputs): AnalystRunInputs {\n if (!inputs || typeof inputs !== 'object' || Array.isArray(inputs)) {\n throw new TypeError('AnalystRegistry.runExact: inputs must be an object')\n }\n const traceStore = inputs.traceStore\n const artifactDir = inputs.artifactDir\n const runRecord = inputs.runRecord\n const judgeInput = inputs.judgeInput\n const custom = inputs.custom\n return Object.freeze({\n traceStore,\n artifactDir,\n runRecord,\n judgeInput,\n custom,\n })\n}\n\n/**\n * Read the untrusted caller object once, then validate and execute only this frozen snapshot.\n * Functions and resource handles retain identity; all data fields are copied canonically.\n */\nfunction snapshotExactRegistryRunOpts(value: unknown): ExactRegistryRunOpts {\n const captured = readOwnFields(value, exactRunFields, 'ExactRegistryRunOpts')\n const missing = exactRunFields.find((field) => !Object.hasOwn(captured, field))\n if (missing) {\n throw new TypeError(`ExactRegistryRunOpts.${missing} must be supplied explicitly`)\n }\n const { signal, costLedger, priorFindings, ...rawData } = captured\n const data = canonicalJsonSnapshot(rawData, 'ExactRegistryRunOpts')\n const parsed = exactRunDataSchema.safeParse(data)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n if (issue?.code === 'unrecognized_keys' && issue.path.join('.') === 'budget') {\n const required =\n isPlainRecord(data.budget) && data.budget.kind === 'weighted'\n ? 'kind, totalUsd, weights'\n : 'kind, totalUsd'\n throw new TypeError(`ExactRegistryRunOpts.budget must contain exactly ${required}`)\n }\n const path = issue?.path.length ? `.${issue.path.join('.')}` : ''\n throw new TypeError(`ExactRegistryRunOpts${path}: ${issue?.message ?? 'is invalid'}`)\n }\n if (\n signal !== null &&\n (!signal ||\n typeof signal !== 'object' ||\n typeof (signal as AbortSignal).addEventListener !== 'function')\n ) {\n throw new TypeError('ExactRegistryRunOpts.signal must be an AbortSignal or null')\n }\n if (costLedger !== null && (!costLedger || typeof costLedger !== 'object')) {\n throw new TypeError('ExactRegistryRunOpts.costLedger must be a CostLedgerHandle or null')\n }\n if (costLedger === null && parsed.data.costLedgerIdentity !== null) {\n throw new TypeError('ExactRegistryRunOpts.costLedgerIdentity must be null without costLedger')\n }\n if (costLedger !== null && parsed.data.costLedgerIdentity === null) {\n throw new TypeError('ExactRegistryRunOpts.costLedgerIdentity is required with costLedger')\n }\n if (costLedger === null && parsed.data.costPhase !== null) {\n throw new TypeError('ExactRegistryRunOpts.costPhase requires a non-null costLedger')\n }\n return Object.freeze({\n ...deepFreezeCanonicalJson(parsed.data),\n signal: signal as AbortSignal | null,\n costLedger: costLedger as CostLedgerHandle | null,\n priorFindings: snapshotExactPriorFindings(priorFindings),\n }) as ExactRegistryRunOpts\n}\n\nfunction snapshotExactPriorFindings(value: unknown): ExactRegistryRunOpts['priorFindings'] {\n if (value === null) return null\n if (Array.isArray(value)) {\n return snapshotAnalystFindings(value, 'ExactRegistryRunOpts.priorFindings')\n }\n if (!isPlainRecord(value)) {\n throw new TypeError(\n 'ExactRegistryRunOpts.priorFindings must be an array, a findings record, or null',\n )\n }\n const result: Record<string, ReadonlyArray<AnalystFinding>> = {}\n for (const [key, findings] of Object.entries(value)) {\n if (!Array.isArray(findings)) {\n throw new TypeError(`ExactRegistryRunOpts.priorFindings.${key} must be an array`)\n }\n result[key] = snapshotAnalystFindings(findings, `ExactRegistryRunOpts.priorFindings.${key}`)\n }\n return deepFreezeCanonicalJson(result)\n}\n\nfunction normalizeExactAnalysts(\n selections: ReadonlyArray<{ readonly registeredId: string; readonly analyst: Analyst }>,\n): ExactCapableAnalyst[] {\n return selections.map(({ registeredId, analyst }) => {\n const exactAnalyst = analyst as Analyst & {\n readonly executionConfig?: Readonly<Record<string, unknown>>\n }\n const id = analyst.id\n const description = analyst.description\n const inputKind = analyst.inputKind\n const rawCostValue = analyst.cost\n const requiresValue = analyst.requires\n const version = analyst.version\n const executionConfigValue = exactAnalyst.executionConfig\n const analyzeValue = analyst.analyze\n if (id !== registeredId) {\n throw new TypeError(\n `AnalystRegistry.runExact: registered analyst \"${registeredId}\" changed id to \"${id}\"`,\n )\n }\n if (executionConfigValue === undefined) {\n throw new TypeError(`AnalystRegistry.runExact: analyst \"${id}\" must declare executionConfig`)\n }\n const executionConfig = canonicalJsonSnapshot(\n executionConfigValue,\n `AnalystRegistry.runExact analyst \"${id}\" executionConfig`,\n )\n if (!isPlainRecord(executionConfig)) {\n throw new TypeError(\n `AnalystRegistry.runExact analyst \"${id}\" executionConfig must be an object`,\n )\n }\n const rawCost = canonicalJsonSnapshot(\n rawCostValue,\n `AnalystRegistry.runExact analyst \"${id}\" cost`,\n )\n const cost =\n rawCost.kind === 'llm'\n ? Object.freeze({\n ...rawCost,\n settlement_timeout_ms: validateUsageSettlementTimeout(rawCost.settlement_timeout_ms),\n })\n : rawCost\n const requires =\n requiresValue === undefined\n ? undefined\n : canonicalJsonSnapshot(\n requiresValue,\n `AnalystRegistry.runExact analyst \"${id}\" requirements`,\n )\n const analyze = analyzeValue.bind(analyst)\n return Object.freeze({\n id,\n description,\n inputKind,\n cost,\n ...(requires === undefined ? {} : { requires }),\n version,\n executionConfig,\n analyze,\n }) satisfies ExactCapableAnalyst\n })\n}\n\nfunction hasRegistryHooks(hooks: AnalystHooks | undefined): hooks is AnalystHooks {\n return Boolean(\n hooks && (hooks.onBeforeAnalyze || hooks.onAfterAnalyze || hooks.onError || hooks.onComplete),\n )\n}\n\nfunction snapshotHooks(hooks: AnalystHooks): AnalystHooks {\n const onBeforeAnalyze = hooks.onBeforeAnalyze\n const onAfterAnalyze = hooks.onAfterAnalyze\n const onError = hooks.onError\n const onComplete = hooks.onComplete\n return Object.freeze({\n ...(onBeforeAnalyze === undefined ? {} : { onBeforeAnalyze: onBeforeAnalyze.bind(hooks) }),\n ...(onAfterAnalyze === undefined ? {} : { onAfterAnalyze: onAfterAnalyze.bind(hooks) }),\n ...(onError === undefined ? {} : { onError: onError.bind(hooks) }),\n ...(onComplete === undefined ? {} : { onComplete: onComplete.bind(hooks) }),\n })\n}\n\nfunction snapshotChat(chat: ChatClient): ChatClient {\n const transport = chat.transport\n const defaultModel = chat.defaultModel\n const maximumAttempts = chat.maximumAttempts\n const call = chat.chat\n return Object.freeze({\n transport,\n ...(defaultModel === undefined ? {} : { defaultModel }),\n ...(maximumAttempts === undefined ? {} : { maximumAttempts }),\n chat: call.bind(chat),\n })\n}\n\nfunction requireExactComponentIdentity(\n value: ExactExecutionComponentIdentity | undefined,\n label: string,\n): ExactExecutionComponentSnapshot {\n if (value === undefined) {\n throw new TypeError(`AnalystRegistry.runExact: ${label} requires a versioned identity`)\n }\n return snapshotExactExecutionComponentIdentity(\n value,\n `AnalystRegistry.runExact ${label} identity`,\n )\n}\n\nfunction exactExecutionSnapshot(\n analysts: readonly ExactCapableAnalyst[],\n opts: ExactRegistryRunOpts,\n allocations: Readonly<Record<string, number | null>>,\n costLedger: ExactExecutionComponentSnapshot | null,\n hooks: ExactExecutionComponentSnapshot | null,\n chat: ExactExecutionComponentSnapshot | null,\n): ExactAnalystExecutionPlanSnapshot {\n const priorFindings = exactPriorFindingsSnapshot(opts.priorFindings)\n const budget =\n opts.budget === null\n ? ({ kind: 'none' } as const)\n : opts.budget.kind === 'equal'\n ? ({\n kind: 'equal',\n total_usd: opts.budget.totalUsd,\n allocations_usd: { ...allocations },\n } as const)\n : ({\n kind: 'weighted',\n total_usd: opts.budget.totalUsd,\n weights: { ...opts.budget.weights },\n allocations_usd: { ...allocations },\n } as const)\n const material = {\n schema_version: '1.0.0' as const,\n analysts: analysts.map((analyst) => ({\n id: analyst.id,\n version: analyst.version,\n input_kind: analyst.inputKind,\n cost: analyst.cost,\n requirements: analyst.requires ?? null,\n execution_config_digest: hashCanonical(analyst.executionConfig),\n })),\n policy: {\n budget,\n total_timeout_ms: opts.totalTimeoutMs,\n signal_provided: opts.signal !== null,\n cost_ledger: costLedger,\n cost_phase: opts.costPhase,\n tags: opts.tags === null ? null : { ...opts.tags },\n prior_findings: priorFindings,\n chain_findings: opts.chainFindings,\n missing_input_mode: opts.missingInputMode,\n registry_hooks: hooks,\n registry_chat: chat,\n },\n }\n return snapshotExactExecutionPlan(\n { ...material, digest: hashCanonical(material) },\n 'AnalystRegistry.runExact execution plan',\n )\n}\n\nfunction exactPriorFindingsSnapshot(\n findings: ExactRegistryRunOpts['priorFindings'],\n): ExactAnalystExecutionPlanSnapshot['policy']['prior_findings'] {\n if (findings === null) return { kind: 'none' }\n if (Array.isArray(findings)) {\n return {\n kind: 'ordered',\n count: findings.length,\n digest: hashCanonical(findings),\n }\n }\n const record = findings as Readonly<Record<string, ReadonlyArray<AnalystFinding>>>\n const keys = Object.keys(record).sort()\n return {\n kind: 'by_analyst',\n keys,\n count: keys.reduce((sum, key) => sum + (record[key]?.length ?? 0), 0),\n digest: hashCanonical(record),\n }\n}\n\nfunction canonicalJsonSnapshot<T>(value: T, label: string): T {\n let snapshot: T\n try {\n snapshot = JSON.parse(canonicalString(value)) as T\n } catch (cause) {\n throw new TypeError(`${label} must be canonical JSON`, { cause })\n }\n return deepFreezeCanonicalJson(snapshot)\n}\n\nfunction snapshotUsageReceiptOnce(\n receipt: AnalystUsageReceipt,\n context: string,\n): AnalystUsageReceipt {\n const data = readOwnFields(receipt, ['calls', 'tokens', 'cost', 'knownCostUsd'], context)\n data.tokens =\n data.tokens === null\n ? null\n : readOwnFields(\n data.tokens,\n ['input', 'output', 'reasoning', 'cached', 'cacheWrite'],\n `${context} tokens`,\n )\n data.cost = readOwnFields(data.cost, ['kind', 'usd'], `${context} cost`)\n const snapshot = canonicalJsonSnapshot(data as unknown as AnalystUsageReceipt, context)\n assertValidAnalystUsageReceipt(snapshot, context)\n return snapshot\n}\n\nfunction readOwnFields(\n value: unknown,\n fields: readonly string[],\n context: string,\n): Record<string, unknown> {\n if (!isPlainRecord(value)) throw new TypeError(`${context} must be a plain object`)\n const unexpected = Object.keys(value).filter((key) => !fields.includes(key))\n if (unexpected.length > 0) {\n throw new TypeError(`${context} contains unknown fields: ${unexpected.sort().join(', ')}`)\n }\n return Object.fromEntries(\n fields.flatMap((field) => (Object.hasOwn(value, field) ? [[field, value[field]]] : [])),\n )\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const prototype = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\n\nfunction exactFixedBudgets(\n exact: ExactAnalystBudgetPolicy | null,\n runnable: readonly Analyst[],\n selected: readonly Analyst[],\n): Readonly<Record<string, number | null>> {\n if (exact === null) return {}\n const allocations: Record<string, number | null> = Object.fromEntries(\n selected.map((analyst) => [analyst.id, null]),\n )\n if (runnable.length === 0) return deepFreezeCanonicalJson(allocations)\n if (exact.kind === 'equal') {\n const each = exact.totalUsd / runnable.length\n for (const analyst of runnable) allocations[analyst.id] = each\n return deepFreezeCanonicalJson(allocations)\n }\n const totalWeight = runnable.reduce((sum, analyst) => sum + exact.weights[analyst.id]!, 0)\n if (totalWeight === 0) {\n throw new Error(\n 'ExactRegistryRunOpts weighted budget must allocate positive weight to a runnable analyst',\n )\n }\n for (const analyst of runnable) {\n allocations[analyst.id] = (exact.totalUsd * exact.weights[analyst.id]!) / totalWeight\n }\n return deepFreezeCanonicalJson(allocations)\n}\n\ninterface AnalystExecution {\n readonly summary: AnalystRunSummary\n readonly findings: AnalystFinding[]\n readonly budgetDebitUsd: number\n}\n\nfunction snapshotExecutionFindings(\n findings: AnalystFinding[],\n exact: boolean,\n context: string,\n): AnalystFinding[] {\n return exact ? deepFreezeCanonicalJson(snapshotAnalystFindings(findings, context)) : findings\n}\n\nfunction snapshotAfterHookValues(\n summary: AnalystRunSummary,\n findings: AnalystFinding[],\n exact: boolean,\n): { summary: AnalystRunSummary; findings: AnalystFinding[] } {\n if (!exact) return { summary, findings }\n return {\n summary: canonicalJsonSnapshot(summary, 'AnalystRegistry.runExact onAfterAnalyze summary'),\n findings: deepFreezeCanonicalJson(\n snapshotAnalystFindings(findings, 'AnalystRegistry.runExact onAfterAnalyze findings'),\n ),\n }\n}\n\nfunction exactPlannedAllocation(\n plan: ExactAnalystExecutionPlanSnapshot,\n analystId: string,\n): number | undefined {\n const budget = plan.policy.budget\n if (budget.kind === 'none') return undefined\n const allocated = budget.allocations_usd[analystId]\n return allocated === null ? undefined : allocated\n}\n\nfunction snapshotExecutionEvent<T extends InternalAnalystRunEvent>(event: T, exact: boolean): T {\n return exact ? canonicalJsonSnapshot(event, 'AnalystRegistry.runExact event') : event\n}\n\nfunction logUncapturedBudgetWarning(args: {\n analyst: Analyst\n runId: string\n budgetUsd: number | undefined\n usage: AnalystUsageReceipt\n log: (message: string, fields?: Record<string, unknown>) => void\n}): void {\n if (args.budgetUsd === undefined || args.usage.cost.kind !== 'uncaptured') return\n args.log(`[analyst] WARN ${args.analyst.id} — USD cost uncaptured; budget not reconciled`, {\n runId: args.runId,\n budget_usd: args.budgetUsd,\n cost_captured: false,\n })\n}\n\nfunction validateTimeout(timeoutMs: number | undefined): number | undefined {\n if (timeoutMs === undefined) return undefined\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) {\n throw new TypeError(\n 'RegistryRunOpts.timeoutMs must be a positive safe integer no greater than 2147483647',\n )\n }\n return timeoutMs\n}\n\nasync function waitForOperation<T>(\n operation: Promise<T>,\n signal: AbortSignal | undefined,\n abortGraceMs: number,\n): Promise<T> {\n if (!signal) return operation\n if (signal.aborted) {\n void operation.catch(() => {})\n throw abortReason(signal)\n }\n return new Promise<T>((resolve, reject) => {\n let settlementTimer: ReturnType<typeof setTimeout> | undefined\n const cleanup = (): void => {\n signal.removeEventListener('abort', onAbort)\n if (settlementTimer) clearTimeout(settlementTimer)\n }\n const onAbort = (): void => {\n if (abortGraceMs === 0) {\n cleanup()\n reject(abortReason(signal))\n return\n }\n settlementTimer = setTimeout(() => {\n cleanup()\n reject(abortReason(signal))\n }, abortGraceMs)\n }\n signal.addEventListener('abort', onAbort, { once: true })\n operation.then(\n (value) => {\n cleanup()\n if (signal.aborted) reject(abortReason(signal))\n else resolve(value)\n },\n (error) => {\n cleanup()\n reject(signal.aborted ? abortReason(signal) : error)\n },\n )\n })\n}\n\nasync function waitForHook<T>(\n operation: (() => T | Promise<T>) | undefined,\n signal: AbortSignal | undefined,\n): Promise<T | undefined> {\n if (operation === undefined || signal?.aborted) return undefined\n try {\n return await waitForOperation(\n Promise.resolve().then(() => {\n if (signal?.aborted) throw abortReason(signal)\n return operation()\n }),\n signal,\n 0,\n )\n } catch (error) {\n if (signal?.aborted) return undefined\n throw error\n }\n}\n\nfunction analystAbortGraceMs(analyst: Analyst): number {\n if (analyst.cost.kind === 'deterministic') return 0\n const settlementMs = validateUsageSettlementTimeout(analyst.cost.settlement_timeout_ms)\n if (settlementMs === 0) return 0\n return Math.min(settlementMs + 100, 2_147_483_647)\n}\n\nfunction abortedBeforeStartSummary(\n analyst: Analyst,\n signal: AbortSignal,\n latencyMs = 0,\n): AnalystRunSummary {\n const reason = abortReason(signal)\n return {\n analyst_id: analyst.id,\n status: 'skipped',\n reason: `${reason.name}: ${reason.message}`,\n findings_count: 0,\n latency_ms: latencyMs,\n usage: zeroUsage(),\n }\n}\n\nfunction abortReason(signal: AbortSignal): Error {\n return signal.reason instanceof Error\n ? signal.reason\n : new DOMException('The operation was aborted', 'AbortError')\n}\n\n/**\n * Default budget allocator: prefer the custom `allocate` callback if\n * provided; else weighted split when weights are set; else equal split\n * across `runningCount`. Returns undefined when no totalUsd is known.\n */\nfunction allocateBudget(\n policy: BudgetPolicy | undefined,\n args: {\n analyst: Analyst\n remainingUsd: number | undefined\n runningCount: number\n totalWeight: number | undefined\n },\n): number | undefined {\n if (!policy) return undefined\n if (policy.allocate) {\n const allocated = policy.allocate({\n analyst: args.analyst,\n totalUsd: policy.totalUsd,\n remainingUsd: args.remainingUsd,\n runningCount: args.runningCount,\n })\n if (allocated === undefined) {\n if (policy.totalUsd !== undefined) {\n throw new Error(\n `BudgetPolicy.allocate('${args.analyst.id}') cannot return undefined when totalUsd is set`,\n )\n }\n return undefined\n }\n assertBudgetAmount(allocated, `BudgetPolicy.allocate('${args.analyst.id}')`)\n return args.remainingUsd === undefined ? allocated : Math.min(allocated, args.remainingUsd)\n }\n if (policy.totalUsd == null) return undefined\n const allocated = policy.weights\n ? (policy.totalUsd * analystWeight(policy.weights, args.analyst.id)) / args.totalWeight!\n : policy.totalUsd / Math.max(1, args.runningCount)\n return args.remainingUsd === undefined ? allocated : Math.min(allocated, args.remainingUsd)\n}\n\nfunction validateBudgetPolicy(policy: BudgetPolicy | undefined): void {\n if (!policy) return\n if (policy.totalUsd !== undefined) assertBudgetAmount(policy.totalUsd, 'BudgetPolicy.totalUsd')\n for (const [analystId, weight] of Object.entries(policy.weights ?? {})) {\n assertBudgetAmount(weight, `BudgetPolicy.weights['${analystId}']`)\n }\n}\n\nfunction assertBudgetAmount(value: number, field: string): void {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${field} must be a non-negative finite number`)\n }\n}\n\nfunction validateEffectiveBudget(\n budgetUsd: number | undefined,\n remainingUsd: number | undefined,\n analystId: string,\n): number | undefined {\n if (budgetUsd !== undefined) {\n assertBudgetAmount(budgetUsd, `AnalystContext.budgetUsd for '${analystId}'`)\n }\n if (remainingUsd === undefined) return budgetUsd\n if (budgetUsd === undefined) {\n throw new Error(\n `AnalystContext.budgetUsd for '${analystId}' cannot be removed while an overall budget remains`,\n )\n }\n if (budgetUsd > remainingUsd) {\n throw new Error(\n `AnalystContext.budgetUsd for '${analystId}' (${budgetUsd}) exceeds the remaining overall budget (${remainingUsd})`,\n )\n }\n return budgetUsd\n}\n\nfunction analystWeight(weights: Record<string, number>, analystId: string): number {\n const weight = weights[analystId] ?? 1\n assertBudgetAmount(weight, `BudgetPolicy.weights['${analystId}']`)\n return weight\n}\n\nfunction zeroUsage(): AnalystUsageReceipt {\n return {\n calls: 0,\n tokens: { input: 0, output: 0 },\n cost: { kind: 'observed', usd: 0 },\n }\n}\n\nfunction resolveUsage(\n analyst: Analyst,\n receipts: ReadonlyArray<AnalystUsageReceipt>,\n exact = false,\n): AnalystUsageReceipt {\n if (receipts.length > 0) return mergeUsageReceipts(receipts, exact)\n if (analyst.cost.kind === 'deterministic') return zeroUsage()\n return { calls: null, tokens: null, cost: { kind: 'uncaptured', usd: null } }\n}\n\nfunction mergeUsageReceipts(\n receipts: ReadonlyArray<AnalystUsageReceipt>,\n exact = false,\n): AnalystUsageReceipt {\n const calls = receipts.every((receipt) => receipt.calls !== null)\n ? usageSum(\n receipts.map((receipt) => receipt.calls ?? 0),\n exact,\n 'calls',\n true,\n )\n : null\n const tokens = receipts.every((receipt) => receipt.tokens !== null)\n ? (Object.fromEntries(\n (['input', 'output', 'reasoning', 'cached', 'cacheWrite'] as const).flatMap((field) =>\n field === 'input' ||\n field === 'output' ||\n receipts.some((receipt) => receipt.tokens?.[field] !== undefined)\n ? [\n [\n field,\n usageSum(\n receipts.map((receipt) => receipt.tokens?.[field] ?? 0),\n exact,\n `tokens.${field}`,\n true,\n ),\n ],\n ]\n : [],\n ),\n ) as unknown as RunTokenUsage)\n : null\n const cost = aggregateCostProvenance(\n receipts.map((receipt) => receipt.cost),\n exact,\n )\n return {\n calls,\n tokens,\n cost,\n ...(cost.kind === 'uncaptured'\n ? {\n knownCostUsd: usageSum(receipts.map(knownCostUsd), exact, 'known cost'),\n }\n : {}),\n }\n}\n\nfunction knownCostUsd(receipt: AnalystUsageReceipt): number {\n return receipt.cost.kind === 'uncaptured' ? (receipt.knownCostUsd ?? 0) : receipt.cost.usd\n}\n\nfunction budgetDebit(receipt: AnalystUsageReceipt, allocatedUsd: number | undefined): number {\n const known = knownCostUsd(receipt)\n return receipt.cost.kind === 'uncaptured' && allocatedUsd !== undefined\n ? Math.max(known, allocatedUsd)\n : known\n}\n\nfunction aggregateCostProvenance(\n costs: ReadonlyArray<RunCostProvenance>,\n exact = false,\n): RunCostProvenance {\n if (costs.some((cost) => cost.kind === 'uncaptured')) {\n return { kind: 'uncaptured', usd: null }\n }\n const usd = usageSum(\n costs.map((cost) => cost.usd ?? 0),\n exact,\n 'captured cost',\n )\n return costs.some((cost) => cost.kind === 'estimated')\n ? { kind: 'estimated', usd }\n : { kind: 'observed', usd }\n}\n\nfunction executionCost(\n executions: ReadonlyArray<AnalystExecution>,\n exact: boolean,\n): { known: number; provenance: RunCostProvenance } {\n const usages = executions.map((execution) => execution.summary.usage)\n return {\n known: usageSum(usages.map(knownCostUsd), exact, 'run known cost'),\n provenance: aggregateCostProvenance(\n usages.map((usage) => usage.cost),\n exact,\n ),\n }\n}\n\nfunction usageSum(\n values: readonly number[],\n exact: boolean,\n field: string,\n integer = false,\n): number {\n const sum = values.reduce((total, value) => total + value, 0)\n if (exact && (integer ? !Number.isSafeInteger(sum) : !Number.isFinite(sum))) {\n throw new RangeError(\n `exact analyst usage ${field} aggregate ${integer ? 'exceeds a safe integer' : 'is not finite'}`,\n )\n }\n return sum\n}\n\n/**\n * Resolve the `priorFindings` slice an analyst sees.\n *\n * - Array form → the analyst sees only findings whose `analyst_id`\n * matches its own id, so a kind never reads\n * another kind's history by accident.\n * - Record form → the analyst gets the entry keyed by its id, with\n * the `'*'` wildcard appended (in that order). Use\n * the wildcard when several kinds should see the same\n * historical findings.\n */\nfunction selectPriorFindings(\n source: RegistryRunOpts['priorFindings'],\n analystId: string,\n): ReadonlyArray<AnalystFinding> | undefined {\n if (!source) return undefined\n if (Array.isArray(source)) {\n const own = source.filter((f) => f.analyst_id === analystId)\n return own.length > 0 ? own : undefined\n }\n const record = source as Record<string, ReadonlyArray<AnalystFinding>>\n const own = record[analystId] ?? []\n const wildcard = record['*'] ?? []\n const merged = [...own, ...wildcard]\n return merged.length > 0 ? merged : undefined\n}\n","/**\n * `buildDefaultAnalystRegistry` — the canonical analyst suite, so consumers\n * stop hand-wiring `new AnalystRegistry()` + per-kind `createTraceAnalystKind`.\n *\n * The deterministic `behavioralAnalyst` is ALWAYS registered (it needs no\n * model and is model-agnostic by construction). The agentic RLM kinds are\n * registered only when an `ai` service is supplied — so a caller with no LLM\n * still gets the full behavioral/efficiency diagnosis, and the substrate's\n * \"any model (including no model)\" guarantee holds at the suite level.\n */\n\nimport type { AxAIService } from '@ax-llm/ax'\nimport { type BehavioralAnalystOptions, behavioralAnalyst } from './behavioral-analyst'\nimport type { ExactExecutionComponentIdentity } from './exact-types'\nimport { createTraceAnalystKind, type TraceAnalystKindSpec } from './kind-factory'\nimport { DEFAULT_TRACE_ANALYST_KINDS } from './kinds'\nimport { AnalystRegistry, type AnalystRegistryOptions } from './registry'\n\nexport interface DefaultAnalystRegistryOptions {\n /** Ax service for the agentic RLM kinds. Omit → only the deterministic analyst. */\n ai?: AxAIService\n /** Required when agentic kinds will be selected by `runExact`. */\n aiIdentity?: ExactExecutionComponentIdentity\n /** Required unless `ai` was created by `createAnalystAi`. */\n model?: string\n /** Which agentic kinds to register when `ai` is present. Default = the shipped suite. */\n kinds?: readonly TraceAnalystKindSpec[]\n /** Set false to omit the deterministic behavioral analyst (default: include). */\n includeBehavioral?: boolean\n /** Bound deterministic trace scanning without changing the store. */\n behavioral?: BehavioralAnalystOptions\n /** Forwarded to the AnalystRegistry constructor (signal, tags, priorFindings). */\n registry?: AnalystRegistryOptions\n}\n\nexport function buildDefaultAnalystRegistry(\n opts: DefaultAnalystRegistryOptions = {},\n): AnalystRegistry {\n const registry = new AnalystRegistry(opts.registry)\n if (opts.includeBehavioral !== false) {\n registry.register(behavioralAnalyst(opts.behavioral))\n }\n if (opts.ai) {\n const kinds = opts.kinds ?? DEFAULT_TRACE_ANALYST_KINDS\n for (const spec of kinds) {\n registry.register(\n createTraceAnalystKind(spec, {\n ai: opts.ai,\n model: opts.model,\n aiIdentity: opts.aiIdentity,\n }),\n )\n }\n }\n return registry\n}\n"],"mappings":";;;;;;;;;;;;;;AAGA,MAAM,mCAAmB,IAAI,QAAwB;;;;;;;;;;;;;AA6BrD,SAAgB,gBAAgB,QAA4C;CAC1E,MAAM,QAAQ,OAAO,MAAM,KAAK;CAChC,IAAI,CAAC,OAAO,MAAM,IAAI,UAAU,mDAAmD;CAQnF,MAAM,UAAU,GAAG;EANjB,MAAM,OAAO,YAAY;EACzB,QAAQ,OAAO;EACf,GAAI,OAAO,UAAU,EAAE,QAAQ,OAAO,QAAQ,IAAI,CAAC;EACnD,GAAI,OAAO,UAAU,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;EACpD,QAAQ,EAAE,MAAM;CAEI,CAAC;CACvB,iBAAiB,IAAI,SAAmB,KAAK;CAC7C,OAAO;AACT;AAEA,SAAgB,0BAA0B,SAA0C;CAClF,OAAO,iBAAiB,IAAI,OAAiB;AAC/C;;AAGA,SAAgB,oBAAoB,SAAsB,UAA2B;CACnF,IAAI,aAAa,KAAA,GAAW;EAC1B,MAAM,QAAQ,SAAS,KAAK;EAC5B,IAAI,CAAC,OAAO,MAAM,IAAI,UAAU,0DAA0D;EAC1F,OAAO;CACT;CACA,MAAM,QAAQ,0BAA0B,OAAO,CAAC,EAAE,KAAK;CACvD,IAAI,CAAC,OACH,MAAM,IAAI,UACR,4FACF;CAEF,OAAO;AACT;;;;;;;;;;;;;;ACqDA,SAAgB,iBAAiB,MAAwC;CACvE,QAAQ,KAAK,WAAb;EACE,KAAK,UACH,OAAO,cACL,KAAK,WACL,KAAK,cACL,IAAI,UAAU;GACZ,SAAS,KAAK,WAAW;GACzB,QAAQ,KAAK;GACb,iBAAiB,KAAK;EACxB,CAAqB,CACvB;EACF,KAAK,cACH,OAAO,cACL,KAAK,WACL,KAAK,cACL,IAAI,UAAU;GACZ,SAAS,KAAK,WAAW;GACzB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