@tangle-network/agent-eval 0.172.0 → 0.173.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.
- package/CHANGELOG.md +49 -0
- package/README.md +17 -2
- package/dist/adapters/http.d.ts +2 -2
- package/dist/analyst/index.d.ts +13 -13
- package/dist/analyst/index.js +7 -6
- package/dist/analyst/index.js.map +1 -1
- package/dist/{attestation-CJBGmMVh.d.ts → attestation-c1QvaBdX.d.ts} +2 -2
- package/dist/{attestation-CJBGmMVh.d.ts.map → attestation-c1QvaBdX.d.ts.map} +1 -1
- package/dist/{backend-integrity-e79K3UPD.d.ts → backend-integrity-CeuTgqsd.d.ts} +3 -4
- package/dist/backend-integrity-CeuTgqsd.d.ts.map +1 -0
- package/dist/{benchmark-h-h4bfqj.d.ts → benchmark-BjLGkfnN.d.ts} +3 -3
- package/dist/{benchmark-h-h4bfqj.d.ts.map → benchmark-BjLGkfnN.d.ts.map} +1 -1
- package/dist/{benchmark-command-DoFcisuM.js → benchmark-command-9S20PRel.js} +9 -9
- package/dist/{benchmark-command-DoFcisuM.js.map → benchmark-command-9S20PRel.js.map} +1 -1
- package/dist/benchmarks/index.d.ts +5 -5
- package/dist/benchmarks/index.js +3 -3
- package/dist/{bounded-process-CVOC_D3H.js → bounded-process-BBZob7vl.js} +64 -10
- package/dist/bounded-process-BBZob7vl.js.map +1 -0
- package/dist/builder-eval/index.d.ts +3 -3
- package/dist/builder-eval/index.js +2 -2
- package/dist/campaign/index.d.ts +9 -9
- package/dist/campaign/index.js +6 -6
- package/dist/{campaign-Dp35pBbS.js → campaign-pxS0wmo4.js} +8 -8
- package/dist/{campaign-Dp35pBbS.js.map → campaign-pxS0wmo4.js.map} +1 -1
- package/dist/chat-client-Db4bqYfA.js +115 -0
- package/dist/chat-client-Db4bqYfA.js.map +1 -0
- package/dist/{chat-json-call-5Jxna-aV.js → chat-json-call-C26igCih.js} +16 -6
- package/dist/chat-json-call-C26igCih.js.map +1 -0
- package/dist/cli.js +31 -17
- package/dist/cli.js.map +1 -1
- package/dist/{client-BvwNkIRN.js → client-BlLY6o2w.js} +2 -2
- package/dist/{client-BvwNkIRN.js.map → client-BlLY6o2w.js.map} +1 -1
- package/dist/{client-Df7wdslk.d.ts → client-DlqdbM7n.d.ts} +4 -4
- package/dist/{client-Df7wdslk.d.ts.map → client-DlqdbM7n.d.ts.map} +1 -1
- package/dist/contract/index.d.ts +13 -13
- package/dist/contract/index.js +202 -10
- package/dist/contract/index.js.map +1 -1
- package/dist/{counterfactual-Bee5_BIn.d.ts → counterfactual-CLgrwhkY.d.ts} +4 -4
- package/dist/{counterfactual-Bee5_BIn.d.ts.map → counterfactual-CLgrwhkY.d.ts.map} +1 -1
- package/dist/{chat-client-DI79OPye.js → default-registry-B0bKikCb.js} +3 -39
- package/dist/default-registry-B0bKikCb.js.map +1 -0
- package/dist/{default-registry-XxedTLwu.d.ts → default-registry-BKwc8bN5.d.ts} +6 -6
- package/dist/{default-registry-XxedTLwu.d.ts.map → default-registry-BKwc8bN5.d.ts.map} +1 -1
- package/dist/{define-agent-eval-0wW7gFhr.d.ts → define-agent-eval-CY6qdlGV.d.ts} +6 -6
- package/dist/{define-agent-eval-0wW7gFhr.d.ts.map → define-agent-eval-CY6qdlGV.d.ts.map} +1 -1
- package/dist/{define-agent-eval-jS8xj_Q_.js → define-agent-eval-D_i_s69h.js} +7 -7
- package/dist/{define-agent-eval-jS8xj_Q_.js.map → define-agent-eval-D_i_s69h.js.map} +1 -1
- package/dist/{dspy-rlm-engine-CS3qcCEk.js → dspy-rlm-engine-D5byiHn9.js} +5 -6
- package/dist/dspy-rlm-engine-D5byiHn9.js.map +1 -0
- package/dist/{emitter-Bvnu0VzL.d.ts → emitter-Cs0egaFd.d.ts} +3 -3
- package/dist/{emitter-Bvnu0VzL.d.ts.map → emitter-Cs0egaFd.d.ts.map} +1 -1
- package/dist/{engine-BfRay1qD.d.ts → engine-DhFir3Ys.d.ts} +23 -8
- package/dist/{engine-BfRay1qD.d.ts.map → engine-DhFir3Ys.d.ts.map} +1 -1
- package/dist/{eval-campaign-JDTeE6Pl.js → eval-campaign-BeAjdhzC.js} +2 -2
- package/dist/{eval-campaign-JDTeE6Pl.js.map → eval-campaign-BeAjdhzC.js.map} +1 -1
- package/dist/{exact-types-BEecmnWm.d.ts → exact-types-BKOEILRP.d.ts} +2 -2
- package/dist/{exact-types-BEecmnWm.d.ts.map → exact-types-BKOEILRP.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +4 -4
- package/dist/{external-optimizer-contracts-szBJ_1vh.d.ts → external-optimizer-contracts-CQCpyrIL.d.ts} +2 -2
- package/dist/{external-optimizer-contracts-szBJ_1vh.d.ts.map → external-optimizer-contracts-CQCpyrIL.d.ts.map} +1 -1
- package/dist/{external-optimizer-process-CQxylYeG.js → external-optimizer-process-Cq_Pg15r.js} +2 -2
- package/dist/{external-optimizer-process-CQxylYeG.js.map → external-optimizer-process-Cq_Pg15r.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-Cex8Da2i.js → external-optimizer-subprocess-DgNebftP.js} +2 -2
- package/dist/{external-optimizer-subprocess-Cex8Da2i.js.map → external-optimizer-subprocess-DgNebftP.js.map} +1 -1
- package/dist/failure-cluster-OldNRoAt.d.ts +154 -0
- package/dist/failure-cluster-OldNRoAt.d.ts.map +1 -0
- package/dist/{feedback-trajectory-DIqpCyF0.d.ts → feedback-trajectory-CMnv_uYs.d.ts} +6 -6
- package/dist/{feedback-trajectory-DIqpCyF0.d.ts.map → feedback-trajectory-CMnv_uYs.d.ts.map} +1 -1
- package/dist/{heldout-gate-JgNRDZwZ.d.ts → heldout-gate-Df5hsqmm.d.ts} +7 -7
- package/dist/{heldout-gate-JgNRDZwZ.d.ts.map → heldout-gate-Df5hsqmm.d.ts.map} +1 -1
- package/dist/hosted/index.d.ts +2 -2
- package/dist/hosted/index.js +1 -1
- package/dist/{index-DnglhM0A.d.ts → index-BQqOjerE.d.ts} +94 -13
- package/dist/index-BQqOjerE.d.ts.map +1 -0
- package/dist/{index-_vPrVMRX.d.ts → index-CFDffsKz.d.ts} +11 -11
- package/dist/{index-_vPrVMRX.d.ts.map → index-CFDffsKz.d.ts.map} +1 -1
- package/dist/{index-DDAPhUJJ.d.ts → index-D0Db5X-4.d.ts} +45 -9
- package/dist/index-D0Db5X-4.d.ts.map +1 -0
- package/dist/{index-DMoxLG8P.d.ts → index-e7LXeRVa.d.ts} +3 -3
- package/dist/{index-DMoxLG8P.d.ts.map → index-e7LXeRVa.d.ts.map} +1 -1
- package/dist/index.d.ts +172 -46
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +64 -41
- package/dist/index.js.map +1 -1
- package/dist/{insight-report-08F022xN.d.ts → insight-report-DETqPc_A.d.ts} +4 -4
- package/dist/{insight-report-08F022xN.d.ts.map → insight-report-DETqPc_A.d.ts.map} +1 -1
- package/dist/{integrity-B_EDELom.d.ts → integrity-BKTcA-HP.d.ts} +3 -3
- package/dist/{integrity-B_EDELom.d.ts.map → integrity-BKTcA-HP.d.ts.map} +1 -1
- package/dist/{kind-factory-DMeEoMQZ.js → kind-factory-gP6lDySe.js} +164 -149
- package/dist/kind-factory-gP6lDySe.js.map +1 -0
- package/dist/{llm-client-BFMRpmqb.js → llm-client-CxQtdtd6.js} +12 -5
- package/dist/llm-client-CxQtdtd6.js.map +1 -0
- package/dist/{llm-judge-aQHIk5_-.js → llm-judge-B2YxbAJb.js} +81 -7
- package/dist/{llm-judge-aQHIk5_-.js.map → llm-judge-B2YxbAJb.js.map} +1 -1
- package/dist/{matrix-Ch8JO1pG.d.ts → matrix-DGu8KhSs.d.ts} +2 -2
- package/dist/{matrix-Ch8JO1pG.d.ts.map → matrix-DGu8KhSs.d.ts.map} +1 -1
- package/dist/meta-eval/index.d.ts +100 -5
- package/dist/meta-eval/index.d.ts.map +1 -1
- package/dist/meta-eval/index.js +200 -2
- package/dist/meta-eval/index.js.map +1 -1
- package/dist/{mint-DjfDUMHr.js → mint-vWOdD8Ae.js} +2 -2
- package/dist/{mint-DjfDUMHr.js.map → mint-vWOdD8Ae.js.map} +1 -1
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +2 -2
- package/dist/openapi.json +1 -1
- package/dist/pipelines/index.d.ts +5 -5
- package/dist/pipelines/index.js +3 -3
- package/dist/{pre-registration-DHz6P_6f.d.ts → pre-registration-BoI4ucR3.d.ts} +2 -2
- package/dist/{pre-registration-DHz6P_6f.d.ts.map → pre-registration-BoI4ucR3.d.ts.map} +1 -1
- package/dist/{produced-state-CxmbFxFd.js → produced-state-7VYDwtkk.js} +3 -3
- package/dist/{produced-state-CxmbFxFd.js.map → produced-state-7VYDwtkk.js.map} +1 -1
- package/dist/{promotion-policy-BBBcz5_3.d.ts → promotion-policy-CvMda3kU.d.ts} +2 -2
- package/dist/{promotion-policy-BBBcz5_3.d.ts.map → promotion-policy-CvMda3kU.d.ts.map} +1 -1
- package/dist/{provenance-Dp-vvyrU.d.ts → provenance-CRY67X50.d.ts} +39 -165
- package/dist/provenance-CRY67X50.d.ts.map +1 -0
- package/dist/{query-BPGMVlbM.js → query-D1nLIKt7.js} +2 -2
- package/dist/{query-BPGMVlbM.js.map → query-D1nLIKt7.js.map} +1 -1
- package/dist/{query-Na5gEIGd.d.ts → query-D6W6MaGx.d.ts} +3 -3
- package/dist/{query-Na5gEIGd.d.ts.map → query-D6W6MaGx.d.ts.map} +1 -1
- package/dist/{registry-xEb_xfns.d.ts → registry-7pOUBrtX.d.ts} +4 -4
- package/dist/{registry-xEb_xfns.d.ts.map → registry-7pOUBrtX.d.ts.map} +1 -1
- package/dist/{release-confidence-D6lQw_o7.d.ts → release-confidence-BAcNYOf1.d.ts} +4 -4
- package/dist/{release-confidence-D6lQw_o7.d.ts.map → release-confidence-BAcNYOf1.d.ts.map} +1 -1
- package/dist/{release-confidence-CzUHc4z4.js → release-confidence-BsGEg_xg.js} +3 -3
- package/dist/{release-confidence-CzUHc4z4.js.map → release-confidence-BsGEg_xg.js.map} +1 -1
- package/dist/reporting.d.ts +3 -3
- package/dist/reporting.js +1 -1
- package/dist/{researcher-CMUTQXD7.d.ts → researcher-jsW1X94L.d.ts} +7 -8
- package/dist/researcher-jsW1X94L.d.ts.map +1 -0
- package/dist/{reward-hacking-SkxYgT0x.js → reward-hacking-CKW4teig.js} +2 -2
- package/dist/{reward-hacking-SkxYgT0x.js.map → reward-hacking-CKW4teig.js.map} +1 -1
- package/dist/{reward-hacking-CgPRUesA.d.ts → reward-hacking-ZXEi9VCq.d.ts} +2 -2
- package/dist/{reward-hacking-CgPRUesA.d.ts.map → reward-hacking-ZXEi9VCq.d.ts.map} +1 -1
- package/dist/rl.d.ts +7 -7
- package/dist/rl.js +4 -4
- package/dist/rollout/index.d.ts +1 -1
- package/dist/rollout/index.js +2 -2
- package/dist/{rollout-Crypdx8s.js → rollout-C-znbbYg.js} +2 -2
- package/dist/{rollout-Crypdx8s.js.map → rollout-C-znbbYg.js.map} +1 -1
- package/dist/{rubric-predictive-validity-DluJLCKQ.d.ts → rubric-predictive-validity-Dl1dvKCv.d.ts} +2 -2
- package/dist/{rubric-predictive-validity-DluJLCKQ.d.ts.map → rubric-predictive-validity-Dl1dvKCv.d.ts.map} +1 -1
- package/dist/{run-record-DQjRcYwA.d.ts → run-record-DTv1MdjK.d.ts} +2 -2
- package/dist/{run-record-DQjRcYwA.d.ts.map → run-record-DTv1MdjK.d.ts.map} +1 -1
- package/dist/{run-record-DLORoL7t.js → run-record-ZIsR9Fif.js} +2 -2
- package/dist/{run-record-DLORoL7t.js.map → run-record-ZIsR9Fif.js.map} +1 -1
- package/dist/{schema-DID1Cqct.d.ts → schema-CR5cpjQ3.d.ts} +57 -2
- package/dist/{schema-DID1Cqct.d.ts.map → schema-CR5cpjQ3.d.ts.map} +1 -1
- package/dist/{schema-CdIX2aHu.js → schema-CSf6qWgZ.js} +35 -1
- package/dist/{schema-CdIX2aHu.js.map → schema-CSf6qWgZ.js.map} +1 -1
- package/dist/semantic-concept-judge-Ct3QU7t5.js +780 -0
- package/dist/semantic-concept-judge-Ct3QU7t5.js.map +1 -0
- package/dist/{series-convergence-D9WgpXGi.d.ts → series-convergence-DeG33RpC.d.ts} +2 -2
- package/dist/{series-convergence-D9WgpXGi.d.ts.map → series-convergence-DeG33RpC.d.ts.map} +1 -1
- package/dist/{server-CCEnywOR.js → server-BR6onwZB.js} +2 -2
- package/dist/{server-CCEnywOR.js.map → server-BR6onwZB.js.map} +1 -1
- package/dist/{skillopt-optimization-method-LHi02MzH.js → skillopt-optimization-method-BzdphODy.js} +6 -6
- package/dist/{skillopt-optimization-method-LHi02MzH.js.map → skillopt-optimization-method-BzdphODy.js.map} +1 -1
- package/dist/{statistical-heldout-Yldkntvy.d.ts → statistical-heldout-DTyB_6-1.d.ts} +3 -3
- package/dist/{statistical-heldout-Yldkntvy.d.ts.map → statistical-heldout-DTyB_6-1.d.ts.map} +1 -1
- package/dist/{store-Cq9oOrI1.d.ts → store-BErPvYBr.d.ts} +2 -2
- package/dist/{store-Cq9oOrI1.d.ts.map → store-BErPvYBr.d.ts.map} +1 -1
- package/dist/{store-otlp-CHjBvWQY.js → store-otlp-Dow0pk_5.js} +2 -2
- package/dist/{store-otlp-CHjBvWQY.js.map → store-otlp-Dow0pk_5.js.map} +1 -1
- package/dist/{store-tool-spans-BvdUbeOB.d.ts → store-tool-spans-CCZNsihA.d.ts} +8 -8
- package/dist/{store-tool-spans-BvdUbeOB.d.ts.map → store-tool-spans-CCZNsihA.d.ts.map} +1 -1
- package/dist/{store-tool-spans-B9o6tU8f.js → store-tool-spans-CeNj_m2L.js} +3 -3
- package/dist/{store-tool-spans-B9o6tU8f.js.map → store-tool-spans-CeNj_m2L.js.map} +1 -1
- package/dist/storyboard/index.d.ts +1 -1
- package/dist/{summary-report-DRstQNBX.d.ts → summary-report-gMrbYawB.d.ts} +3 -3
- package/dist/{summary-report-DRstQNBX.d.ts.map → summary-report-gMrbYawB.d.ts.map} +1 -1
- package/dist/{task-failure-attributes-CBGtLS_H.js → task-failure-attributes-CZjZeBsY.js} +3 -3
- package/dist/{task-failure-attributes-CBGtLS_H.js.map → task-failure-attributes-CZjZeBsY.js.map} +1 -1
- package/dist/{tool-groups-DjwlMBvW.d.ts → tool-groups-Cp4Xdzrp.d.ts} +3 -3
- package/dist/tool-groups-Cp4Xdzrp.d.ts.map +1 -0
- package/dist/{tool-waste-CwGHzBzX.js → tool-waste-B9tdWV6g.js} +253 -6
- package/dist/tool-waste-B9tdWV6g.js.map +1 -0
- package/dist/{tool-waste-BrmLKxMw.d.ts → tool-waste-D23I0zWm.d.ts} +4 -4
- package/dist/{tool-waste-BrmLKxMw.d.ts.map → tool-waste-D23I0zWm.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +2 -2
- package/dist/traces.d.ts +10 -10
- package/dist/traces.js +7 -7
- package/dist/{trajectory-r1bQqvBQ.d.ts → trajectory-D7qrNvaN.d.ts} +3 -3
- package/dist/{trajectory-r1bQqvBQ.d.ts.map → trajectory-D7qrNvaN.d.ts.map} +1 -1
- package/dist/trajectory-replay/index.d.ts +3 -3
- package/dist/{types-CCZ34qmV.d.ts → types-BDV4PiMR.d.ts} +3 -3
- package/dist/{types-CCZ34qmV.d.ts.map → types-BDV4PiMR.d.ts.map} +1 -1
- package/dist/{types-nokrtr7M.d.ts → types-Ba5UQyVD.d.ts} +4 -4
- package/dist/{types-nokrtr7M.d.ts.map → types-Ba5UQyVD.d.ts.map} +1 -1
- package/dist/{types-DMoNFDWi.d.ts → types-DN2WdT5S.d.ts} +3 -3
- package/dist/{types-DMoNFDWi.d.ts.map → types-DN2WdT5S.d.ts.map} +1 -1
- package/dist/types-gvRsyJLh.d.ts +831 -0
- package/dist/types-gvRsyJLh.d.ts.map +1 -0
- package/dist/wire/index.d.ts +3 -3
- package/dist/wire/index.js +1 -1
- package/docs/plants.md +69 -1
- package/docs/public-api.md +6 -4
- package/docs/trace-analysis.md +55 -8
- package/package.json +1 -1
- package/dist/backend-integrity-e79K3UPD.d.ts.map +0 -1
- package/dist/bounded-process-CVOC_D3H.js.map +0 -1
- package/dist/chat-client-DI79OPye.js.map +0 -1
- package/dist/chat-json-call-5Jxna-aV.js.map +0 -1
- package/dist/dspy-rlm-engine-CS3qcCEk.js.map +0 -1
- package/dist/failure-cluster-6YSvsKlp.d.ts +0 -58
- package/dist/failure-cluster-6YSvsKlp.d.ts.map +0 -1
- package/dist/index-DDAPhUJJ.d.ts.map +0 -1
- package/dist/index-DnglhM0A.d.ts.map +0 -1
- package/dist/kind-factory-DMeEoMQZ.js.map +0 -1
- package/dist/llm-client-BFMRpmqb.js.map +0 -1
- package/dist/provenance-Dp-vvyrU.d.ts.map +0 -1
- package/dist/raw-provider-sink-BU29Sh8h.d.ts +0 -134
- package/dist/raw-provider-sink-BU29Sh8h.d.ts.map +0 -1
- package/dist/researcher-CMUTQXD7.d.ts.map +0 -1
- package/dist/semantic-concept-judge-I36eejJx.js +0 -382
- package/dist/semantic-concept-judge-I36eejJx.js.map +0 -1
- package/dist/tool-groups-DjwlMBvW.d.ts.map +0 -1
- package/dist/tool-waste-CwGHzBzX.js.map +0 -1
- package/dist/types-Bfk0uxRj.d.ts +0 -443
- package/dist/types-Bfk0uxRj.d.ts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kind-factory-gP6lDySe.js","names":[],"sources":["../src/analyst/exact-types.ts","../src/trace/otlp-attributes.ts","../src/analyst/engine.ts","../src/analyst/finding-subject.ts","../src/analyst/parse-tolerant.ts","../src/analyst/finding-signature.ts","../src/trace-analyst/otlp-span.ts","../src/trace-analyst/errors.ts","../src/trace-analyst/store-contract.ts","../src/trace-analyst/types.ts","../src/trace-analyst/store-bounds.ts","../src/trace-analyst/store-schemas.ts","../src/trace-analyst/store-boundary.ts","../src/trace-analyst/tools.ts","../src/analyst/tool-groups.ts","../src/analyst/kind-factory.ts"],"sourcesContent":["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","/** Canonical OpenInference-over-OTLP attribute vocabulary used at the trace boundary. */\n\nimport {\n INPUT_VALUE,\n LLM_MODEL_ATTR_KEYS,\n OUTPUT_VALUE,\n SPAN_KIND_ATTR_KEYS,\n TOOL_ARGS_CAPTURED,\n TOOL_LATENCY_MS,\n TOOL_NAME,\n TOOL_NAME_ATTR_KEYS,\n} from './attribute-vocabulary'\nimport type { ToolSpan } from './schema'\n\nexport * from './attribute-vocabulary'\n\nconst TOOL_SPAN_ATTRIBUTE_KEYS = [\n TOOL_NAME,\n TOOL_ARGS_CAPTURED,\n TOOL_LATENCY_MS,\n INPUT_VALUE,\n OUTPUT_VALUE,\n] as const\n\nexport type ToolSpanOtlpInput = Pick<\n ToolSpan,\n 'toolName' | 'args' | 'argsCaptured' | 'result' | 'latencyMs'\n>\n\nexport type OtlpSpanRole =\n | 'AGENT'\n | 'CHAIN'\n | 'EVALUATOR'\n | 'GUARDRAIL'\n | 'LLM'\n | 'SPAN'\n | 'TOOL'\n | 'UNKNOWN'\n\nexport interface OtlpSpanRoleInput {\n name: string\n attributes: Record<string, unknown>\n kind?: string | null\n}\n\nconst EXPLICIT_SPAN_ROLES = new Set<OtlpSpanRole>([\n 'AGENT',\n 'CHAIN',\n 'EVALUATOR',\n 'GUARDRAIL',\n 'LLM',\n 'SPAN',\n 'TOOL',\n])\n\n/**\n * Classify a span once for both measurement and error accounting.\n * An explicit OpenInference kind wins; untyped spans use the same tool and\n * model signals in online and offline intake.\n */\nexport function classifyOtlpSpanRole(input: OtlpSpanRoleInput): OtlpSpanRole {\n const explicitKind = input.kind ?? firstStringAttribute(input.attributes, SPAN_KIND_ATTR_KEYS)\n if (explicitKind) {\n const normalized = explicitKind.toUpperCase() as OtlpSpanRole\n if (EXPLICIT_SPAN_ROLES.has(normalized)) return normalized\n }\n\n if (\n firstStringAttribute(input.attributes, TOOL_NAME_ATTR_KEYS) !== undefined ||\n /^(?:function|tool)[.:/]/i.test(input.name)\n ) {\n return 'TOOL'\n }\n\n const spanType = input.attributes['span.type']\n if (\n (typeof spanType === 'string' && spanType.toLowerCase() === 'llm_request') ||\n /(?:^|[.:/_-])(?:chat[._-]?completions?|llm)(?:$|[.:/_-])/i.test(input.name) ||\n firstStringAttribute(input.attributes, LLM_MODEL_ATTR_KEYS) !== undefined ||\n typeof input.attributes['gen_ai.operation.name'] === 'string'\n ) {\n return 'LLM'\n }\n\n return 'UNKNOWN'\n}\n\nexport function isOtlpModelCall(input: OtlpSpanRoleInput): boolean {\n return classifyOtlpSpanRole(input) === 'LLM'\n}\n\nfunction toolSpanOtlpAttributes(\n span: ToolSpanOtlpInput,\n): Record<string, string | number | boolean> {\n const argsCaptured = span.argsCaptured !== false\n const attributes: Record<string, string | number | boolean> = {\n [TOOL_NAME]: span.toolName,\n [TOOL_ARGS_CAPTURED]: argsCaptured,\n }\n if (span.latencyMs !== undefined) attributes[TOOL_LATENCY_MS] = span.latencyMs\n if (argsCaptured) attributes[INPUT_VALUE] = stringifyTraceValue(span.args)\n if (span.result !== undefined) attributes[OUTPUT_VALUE] = stringifyTraceValue(span.result)\n return attributes\n}\n\nexport function applyToolSpanOtlpAttributes(\n attributes: Record<string, unknown>,\n span: ToolSpanOtlpInput,\n): void {\n for (const key of TOOL_SPAN_ATTRIBUTE_KEYS) delete attributes[key]\n Object.assign(attributes, toolSpanOtlpAttributes(span))\n}\n\nexport function traceSpanKindToOpenInferenceKind(kind: string): string {\n switch (kind) {\n case 'llm':\n return 'LLM'\n case 'tool':\n return 'TOOL'\n case 'retrieval':\n return 'CHAIN'\n case 'judge':\n return 'EVALUATOR'\n case 'sandbox':\n return 'CHAIN'\n case 'agent':\n return 'AGENT'\n default:\n return 'SPAN'\n }\n}\n\nfunction firstStringAttribute(\n attributes: Record<string, unknown>,\n keys: readonly string[],\n): string | undefined {\n for (const key of keys) {\n const value = attributes[key]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return undefined\n}\n\nfunction stringifyTraceValue(value: unknown): string {\n if (value === undefined) return 'null'\n if (typeof value === 'string') return value\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n","import type { CostLedgerHandle } from '../cost-ledger'\nimport type { TraceAnalysisToolDescriptor } from '../trace-analyst/tools'\nimport type { RawAnalystFinding } from './finding-signature'\n\n/** Hard limits for one recursive trace investigation. */\nexport interface TraceAnalystLimits {\n /** Maximum controller iterations. */\n maxIterations: number\n /** Maximum recursive model queries issued from the controller program. */\n maxLlmCalls: number\n /** Maximum trace-store reads. */\n maxToolCalls: number\n /** Maximum controller output retained between iterations. */\n maxOutputChars: number\n}\n\nconst DEFAULT_TRACE_ANALYST_LIMITS: Readonly<TraceAnalystLimits> = {\n maxIterations: 12,\n maxLlmCalls: 8,\n maxToolCalls: 48,\n maxOutputChars: 10_000,\n}\n\n/**\n * Completion cap one engine turn asks for when the caller names none.\n *\n * Shared by every engine because the number is load-bearing and has one\n * failure story, not two: 4096 is below what current coding models emit for a\n * full findings array — glm-5.2 through an OpenAI-compatible gateway returns\n * 8192 and the request is rejected outright (`502 — provider reported 8192\n * completion tokens, exceeding requested limit 4096`), which failed 2 of 2\n * smoke cases before any analysis ran. Two engines holding private copies of\n * this would have to move in lockstep or diverge on spend behaviour silently.\n *\n * The cap exists to bound a single response, not to bound spend: the cost\n * ledger does that directly, so this starts above what a real report needs.\n */\nexport const DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS = 16_384\n\nexport interface TraceAnalysisEngineRequest {\n analystId: string\n question: string\n instructions: string\n tools: readonly TraceAnalysisToolDescriptor[]\n /**\n * Task material delivered as structured input instead of fetched through\n * tools, for a subject that lives outside any trace store.\n *\n * An engine with a code environment binds these as variables, which is what\n * lets a typed program read the subject with code rather than parse it back\n * out of prompt text. An engine that cannot honour them must throw: dropping\n * them silently would answer a question about material the caller never\n * delivered.\n */\n taskInputs?: Readonly<Record<string, unknown>>\n limits: TraceAnalystLimits\n costLedger: CostLedgerHandle\n costPhase: string\n costTags?: Record<string, string>\n signal?: AbortSignal\n log?: (message: string, fields?: Record<string, unknown>) => void\n}\n\n/** Complete result of one recursive investigation, before registry adaptation. */\nexport interface TraceAnalysisEngineResult {\n answer: string\n findings: RawAnalystFinding[]\n /** Engine-native steps retained for audit and debugging. */\n trajectory: readonly unknown[]\n /**\n * Successful model completions used by the engine.\n * The usage receipt may contain more provider attempts when a request fails.\n */\n modelCalls: number\n /** Trace-tool requests admitted for execution, including a tool that later fails. */\n toolCalls: number\n runtime: Record<string, unknown>\n}\n\n/**\n * A recursive research engine that can inspect traces with bounded tools.\n *\n * Implementations may use DSPy RLM, HALO, another upstream engine, or a\n * caller-owned implementation. The analyst definition and finding contract do\n * not change when the engine changes.\n */\nexport interface TraceAnalysisEngine {\n readonly id: string\n readonly description: string\n readonly model?: string\n /** Implementation version. Changes whenever execution behavior changes. */\n readonly version: string\n /**\n * Canonical JSON for every effective engine knob not already bound by\n * `version` — endpoint, budgets, timeouts, whether a credential was supplied.\n * Sealed into the exact-run execution plan, so two engines pointed at\n * different providers must not produce the same value. Never carries a\n * secret: a credential is recorded as a boolean.\n */\n readonly executionConfig: Readonly<Record<string, unknown>>\n analyze(request: TraceAnalysisEngineRequest): Promise<TraceAnalysisEngineResult>\n}\n\nexport function resolveTraceAnalystLimits(\n limits: Partial<TraceAnalystLimits> | undefined,\n): TraceAnalystLimits {\n const resolved = { ...DEFAULT_TRACE_ANALYST_LIMITS, ...limits }\n for (const [name, value] of Object.entries(resolved)) {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new TypeError(`trace analyst ${name} must be a positive safe integer`)\n }\n }\n return resolved\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\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// ── acceptance grammar ────────────────────────────────────────────────\n\n/**\n * The subject grammar as pure acceptance patterns, in the parser's own order.\n *\n * `parseFindingSubject` below decides acceptance AND extracts typed\n * components; only acceptance can cross a process boundary, because the typed\n * components are consumed by TypeScript adapters. These patterns are the\n * portable half: `scripts/emit-finding-contract.mjs` writes them into the\n * contract the Python client validates against, so one grammar governs both\n * sides. `finding-subject.test.ts` proves the table and the parser agree on\n * every kind's valid and invalid forms — a branch added to one and not the\n * other fails there.\n */\nexport const FINDING_SUBJECT_PATTERNS: ReadonlyArray<{\n readonly kind: FindingSubjectKind\n readonly pattern: string\n}> = [\n {\n kind: 'knowledge.wiki',\n pattern: '^agent-knowledge:wiki:[a-z0-9][a-z0-9-]*(?:#[a-z0-9][a-z0-9-]*)?$',\n },\n { kind: 'knowledge.claim', pattern: '^agent-knowledge:claim:\\\\s*\\\\S[\\\\s\\\\S]*$' },\n { kind: 'knowledge.raw', pattern: '^agent-knowledge:raw:\\\\s*\\\\S[\\\\s\\\\S]*$' },\n { kind: 'knowledge.stale', pattern: '^agent-knowledge:stale:[a-z0-9][a-z0-9-]*$' },\n { kind: 'system-prompt', pattern: '^system-prompt:\\\\s*\\\\S[\\\\s\\\\S]*$' },\n { kind: 'skill', pattern: '^skill:[a-z0-9][a-z0-9_.-]*$' },\n { kind: 'tool-doc', pattern: '^tool-doc:[a-z0-9][a-z0-9_-]*(?::\\\\s*\\\\S[\\\\s\\\\S]*)?$' },\n { kind: 'new-tool', pattern: '^new-tool:[a-z0-9][a-z0-9_-]*$' },\n { kind: 'mcp', pattern: '^mcp:[a-z0-9][a-z0-9_.-]*(?::[a-z0-9][a-z0-9_.-]*)?$' },\n { kind: 'hook', pattern: '^hook:[a-z0-9][a-z0-9_.-]*$' },\n { kind: 'subagent', pattern: '^subagent:[a-z0-9][a-z0-9_.-]*$' },\n { kind: 'workflow', pattern: '^workflow:[a-z0-9][a-z0-9_.-]*$' },\n { kind: 'rollout-policy', pattern: '^rollout-policy:\\\\s*\\\\S[\\\\s\\\\S]*$' },\n { kind: 'agent-profile', pattern: '^agent-profile:\\\\s*\\\\S[\\\\s\\\\S]*$' },\n { kind: 'code', pattern: '^code:\\\\s*\\\\S[\\\\s\\\\S]*$' },\n { kind: 'rag', pattern: '^rag:[a-z0-9][a-z0-9_-]*:\\\\s*\\\\S[\\\\s\\\\S]*$' },\n { kind: 'memory', pattern: '^memory:\\\\s*\\\\S[\\\\s\\\\S]*$' },\n { kind: 'scaffolding', pattern: '^scaffolding:\\\\s*\\\\S[\\\\s\\\\S]*$' },\n { kind: 'output-schema', pattern: '^output-schema:\\\\s*\\\\S[\\\\s\\\\S]*$' },\n { kind: 'websearch.outdated', pattern: '^websearch:outdated:\\\\s*\\\\S[\\\\s\\\\S]*$' },\n { kind: 'prior-run-summary', pattern: '^prior-run-summary:\\\\s*\\\\S[\\\\s\\\\S]*$' },\n { kind: 'cluster', pattern: '^[a-z0-9][a-z0-9._-]{0,79}$' },\n]\n\n/** True when `subject` matches the grammar. The portable half of the parser:\n * the same decision the Python client makes from the emitted contract. */\nexport function isFindingSubject(subject: string): boolean {\n const trimmed = subject.trim()\n if (trimmed.length === 0) return false\n return FINDING_SUBJECT_PATTERNS.some((entry) => new RegExp(entry.pattern).test(trimmed))\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\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 // Two loci in one set, split by who was wrong. A divergence the agent\n // caused is fixed on a behavior surface (instructions, skill, tool-doc,\n // workflow, hook, memory, profile); a divergence the user's own ambiguous\n // request caused is fixed by a clarifying-question or checkpoint policy,\n // which is `scaffolding`. Every entry is already an `improvement` locus, so\n // this kind adds no `FindingSubject` variant and needs no adapter routing\n // it does not already have.\n 'intent-divergence': [\n 'system-prompt',\n 'skill',\n 'tool-doc',\n 'workflow',\n 'hook',\n 'scaffolding',\n 'memory',\n 'agent-profile',\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 * 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 * Engine-neutral structured output for trace-analyst findings.\n *\n * Every recursive engine returns this shape. The TypeScript boundary validates\n * it before a finding can enter a registry or benchmark.\n */\n\nimport { z } from 'zod'\nimport { parseFindingSubject } from './finding-subject'\nimport { coerceJson } from './parse-tolerant'\nimport { ANALYST_SEVERITIES, type EvidenceRef } from './types'\n\nconst 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 trace://<URL-encoded-trace-id>/span/<URL-encoded-span-id> for trace evidence or finding://<finding-id> for supplied prior findings. URL encoding means percent encoding, never base64. 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 === undefined ? {} : { 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 (parseTraceSpanEvidenceUri(uri)) return 'span'\n if (uri.startsWith('finding://')) return 'finding'\n return 'artifact'\n}\n\nexport function parseTraceSpanEvidenceUri(uri: string): { traceId: string; spanId: string } | null {\n const match = /^trace:\\/\\/([^/]+)\\/span\\/([^/]+)$/.exec(uri)\n if (!match) return null\n try {\n const traceId = decodeURIComponent(match[1]!)\n const spanId = decodeURIComponent(match[2]!)\n return traceId && spanId ? { traceId, spanId } : null\n } catch {\n return null\n }\n}\n","/**\n * Canonical OTLP-flat-line readers shared by every consumer of the\n * OTLP-JSONL wire shape (one OTLP span per line; the form\n * `flattenOtlpExportToNdjson` produces and the form AppWorld / HALO\n * emit via their OpenInference OTLP exporter).\n *\n * `OtlpFileTraceStore` indexes spans with these; `otlpToRunRecords`\n * aggregates spans into `RunRecord`s with the same readers. One parser,\n * one vocabulary — a divergence between the analyst's view of a trace and\n * the RunRecord projected from it is a class of bug this consolidation\n * removes by construction.\n *\n * Vocabulary. The readers understand BOTH dialects that appear in the\n * wild:\n * - the substrate's own `llm.*` / `tool.*` / `span.kind` attributes\n * (`flattenSpanAttributes` in `trace/otel.ts`), and\n * - the OpenInference / inference-export attributes AppWorld / HALO\n * emit (`openinference.span.kind`, `inference.observation_kind`,\n * `inference.llm.input_tokens`, `llm.token_count.prompt`, …).\n *\n * Pure, no I/O.\n */\n\nimport {\n LLM_MODEL_ATTR_KEYS,\n SPAN_KIND_ATTR_KEYS,\n TOOL_NAME_ATTR_KEYS,\n} from '../trace/otlp-attributes'\nimport type { TraceAnalystSpanKind, TraceAnalystSpanStatus } from './types'\n\n/**\n * The structural fields a flat OTLP-JSONL line projects to. `attributes`\n * is the merged resource+span attribute map (span overrides resource);\n * the named fields are the pivots every reader of a trace needs without\n * paying the full attribute materialisation.\n */\nexport interface ProjectedOtlpSpan {\n trace_id: string\n span_id: string\n parent_span_id: string | null\n name: string\n kind: TraceAnalystSpanKind\n start_time: string\n end_time: string\n duration_ms: number\n status: TraceAnalystSpanStatus\n status_message: string | undefined\n service_name: string | null\n agent_name: string | null\n model_name: string | null\n tool_name: string | null\n /** Merged resource + span attributes, span winning on overlap. */\n attributes: Record<string, unknown>\n}\n\n/**\n * Project one parsed OTLP-JSONL object to `ProjectedOtlpSpan`, or `null`\n * when the line is missing the mandatory `trace_id` + `span_id`.\n */\nexport function projectOtlpFlatLine(raw: Record<string, unknown>): ProjectedOtlpSpan | null {\n const trace_id = stringField(raw, 'trace_id') ?? stringField(raw, 'traceId')\n const span_id = stringField(raw, 'span_id') ?? stringField(raw, 'spanId')\n if (!trace_id || !span_id) return null\n\n const rawParentId = stringField(raw, 'parent_span_id') ?? stringField(raw, 'parentSpanId') ?? null\n const parent_id = normalizeParentSpanId(trace_id, span_id, rawParentId)\n const name = stringField(raw, 'name') ?? 'unknown'\n const start_time = stringField(raw, 'start_time') ?? stringField(raw, 'startTime') ?? ''\n const end_time = stringField(raw, 'end_time') ?? stringField(raw, 'endTime') ?? start_time\n\n const status = readOtlpStatus(raw)\n const attributes = extractOtlpAttributes(raw)\n\n const service_name =\n asString(attributes['service.name']) ??\n asString(attributes['resource.attributes.service.name']) ??\n null\n const agent_name =\n asString(attributes['agent.name']) ??\n asString(attributes['inference.agent.name']) ??\n asString(attributes['inference.agent_name']) ??\n null\n const model_name = firstStringAttr(attributes, LLM_MODEL_ATTR_KEYS)\n const tool_name = firstStringAttr(attributes, TOOL_NAME_ATTR_KEYS)\n\n const kind = inferOtlpKind(attributes)\n\n let duration_ms = 0\n if (start_time && end_time) {\n const a = spanEpochMillis(start_time)\n const b = spanEpochMillis(end_time)\n if (a !== null && b !== null) duration_ms = Math.max(0, b - a)\n }\n\n return {\n trace_id,\n span_id,\n parent_span_id: parent_id && parent_id.length > 0 ? parent_id : null,\n name,\n kind,\n start_time,\n end_time,\n duration_ms,\n status: status.code,\n status_message: status.message,\n service_name,\n agent_name,\n model_name,\n tool_name,\n attributes,\n }\n}\n\nfunction normalizeParentSpanId(\n traceId: string,\n spanId: string,\n parentId: string | null,\n): string | null {\n if (!parentId) return null\n const prefix = `${traceId}:`\n return spanId.startsWith(prefix) && !parentId.startsWith(prefix)\n ? `${prefix}${parentId}`\n : parentId\n}\n\nfunction readOtlpStatus(raw: Record<string, unknown>): {\n code: TraceAnalystSpanStatus\n message: string | undefined\n} {\n const status = raw.status\n if (status && typeof status === 'object' && !Array.isArray(status)) {\n const codeRaw = (status as Record<string, unknown>).code\n const code: TraceAnalystSpanStatus =\n codeRaw === 'STATUS_CODE_OK' || codeRaw === 'OK'\n ? 'OK'\n : codeRaw === 'STATUS_CODE_ERROR' || codeRaw === 'ERROR'\n ? 'ERROR'\n : 'UNSET'\n const messageRaw = (status as Record<string, unknown>).message\n const message = typeof messageRaw === 'string' && messageRaw.length > 0 ? messageRaw : undefined\n return { code, message }\n }\n return { code: 'UNSET', message: undefined }\n}\n\nfunction inferOtlpKind(attrs: Record<string, unknown>): TraceAnalystSpanKind {\n const opik = firstStringAttr(attrs, SPAN_KIND_ATTR_KEYS)\n if (opik) {\n const upper = opik.toUpperCase()\n if (\n upper === 'AGENT' ||\n upper === 'LLM' ||\n upper === 'TOOL' ||\n upper === 'CHAIN' ||\n upper === 'EVALUATOR' ||\n upper === 'GUARDRAIL' ||\n upper === 'SPAN'\n ) {\n return upper as TraceAnalystSpanKind\n }\n }\n return 'UNKNOWN'\n}\n\n/**\n * Flatten OTLP `attributes` + `resource.attributes` into a single\n * dotted-key map. Span attributes override resource attributes when keys\n * overlap. Nested objects/arrays are preserved as-is.\n */\nexport function extractOtlpAttributes(raw: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n const resource = raw.resource\n if (resource && typeof resource === 'object' && !Array.isArray(resource)) {\n const ra = (resource as Record<string, unknown>).attributes\n if (ra && typeof ra === 'object' && !Array.isArray(ra)) {\n for (const [k, v] of Object.entries(ra as Record<string, unknown>)) {\n out[k] = v\n }\n }\n }\n const spanAttrs = raw.attributes\n if (spanAttrs && typeof spanAttrs === 'object' && !Array.isArray(spanAttrs)) {\n for (const [k, v] of Object.entries(spanAttrs as Record<string, unknown>)) {\n out[k] = v\n }\n }\n return out\n}\n\nexport function stringField(raw: Record<string, unknown>, key: string): string | undefined {\n const v = raw[key]\n return typeof v === 'string' ? v : undefined\n}\n\nexport function asString(v: unknown): string | null {\n return typeof v === 'string' && v.length > 0 ? v : null\n}\n\n/** First non-empty string value across a list of candidate attribute keys. */\nexport function firstStringAttr(\n attrs: Record<string, unknown>,\n keys: readonly string[],\n): string | null {\n for (const k of keys) {\n const s = asString(attrs[k])\n if (s !== null) return s\n }\n return null\n}\n\n/**\n * Parse a span timestamp to epoch millis, or null when empty/unparseable. The\n * OTLP readers accept BOTH ISO-8601 and epoch-millis-string dialects, so raw\n * string comparison (`<`, `localeCompare`) mis-orders across dialects and\n * `Date.parse` returns NaN for a bare epoch-millis string.\n */\nexport function spanEpochMillis(ts: string | undefined | null): number | null {\n if (!ts) return null\n if (/^\\d+$/.test(ts)) return Number(ts)\n const n = Date.parse(ts)\n return Number.isNaN(n) ? null : n\n}\n\n/**\n * Order comparator for span timestamps across mixed ISO/epoch dialects.\n * Unparseable timestamps sort as epoch 0 (earliest), never NaN (which would\n * make the sort non-deterministic).\n */\nexport function compareSpanTime(a: string, b: string): number {\n return (spanEpochMillis(a) ?? 0) - (spanEpochMillis(b) ?? 0)\n}\n","import {\n AgentEvalError,\n CaptureIntegrityError,\n LimitExceededError,\n NotFoundError,\n ValidationError,\n} from '../errors'\n\n/** Invalid trace-tool arguments, including malformed filters and regexes. */\nexport class TraceAnalysisValidationError extends ValidationError {\n declare readonly code: 'validation'\n}\n\n/** A trace read cannot fit within a documented count or byte limit. */\nexport class TraceAnalysisLimitError extends LimitExceededError {\n declare readonly code: 'limit_exceeded'\n readonly operation: string\n readonly actual: number\n readonly limit: number\n\n constructor(operation: string, actual: number, limit: number, message?: string) {\n super(message ?? `${operation} produced ${actual}, over the limit of ${limit}`)\n this.operation = operation\n this.actual = actual\n this.limit = limit\n }\n}\n\n/** A supplied store returned a shape that violates the trace read contract. */\nexport class TraceAnalysisStoreContractError extends AgentEvalError {\n declare readonly code: 'backend_integrity'\n readonly operation: string\n\n constructor(operation: string, message: string, options?: { cause?: unknown }) {\n super('backend_integrity', `${operation}: ${message}`, options)\n this.operation = operation\n }\n}\n\nexport class TraceFileMissingError extends NotFoundError {\n declare readonly code: 'not_found'\n readonly path: string\n\n constructor(path: string) {\n super(`trace file not found: ${path}`)\n this.path = path\n }\n}\n\nexport class TraceFileTooLargeError extends TraceAnalysisLimitError {\n readonly path: string\n readonly size_bytes: number\n readonly max_bytes: number\n\n constructor(path: string, size_bytes: number, max_bytes: number) {\n super(\n 'OtlpFileTraceStore.readBuffer',\n size_bytes,\n max_bytes,\n `trace file ${path} is ${size_bytes} bytes, over the ${max_bytes}-byte limit; ` +\n 'raise OtlpFileTraceStoreOptions.maxFileBytes or pre-split the file',\n )\n this.path = path\n this.size_bytes = size_bytes\n this.max_bytes = max_bytes\n }\n}\n\nexport class TraceFileMalformedError extends CaptureIntegrityError {\n readonly path: string\n readonly line_number: number\n readonly byte_offset: number\n\n constructor(path: string, line_number: number, byte_offset: number, cause?: unknown) {\n super(`malformed trace row in ${path} at line ${line_number}, byte ${byte_offset}`, { cause })\n this.path = path\n this.line_number = line_number\n this.byte_offset = byte_offset\n }\n}\n\nexport class TraceNotFoundError extends NotFoundError {\n declare readonly code: 'not_found'\n readonly trace_id: string\n\n constructor(trace_id: string) {\n super(`trace not found: ${trace_id}`)\n this.trace_id = trace_id\n }\n}\n\nexport class SpanNotFoundError extends NotFoundError {\n declare readonly code: 'not_found'\n readonly trace_id: string\n readonly span_id: string\n\n constructor(trace_id: string, span_id: string) {\n super(`span ${span_id} not found in trace ${trace_id}`)\n this.trace_id = trace_id\n this.span_id = span_id\n }\n}\n","import type {\n DatasetOverview,\n QueryTracesPage,\n SearchSpanResult,\n SearchTraceResult,\n TraceAnalystByteBudgets,\n TraceAnalystFilters,\n ViewSpansResult,\n ViewTraceResult,\n} from './types'\n\nexport const TRACE_ANALYSIS_LIMITS = {\n sampleTraceIds: 20,\n queryTraces: 200,\n viewSpans: 100,\n searchMatches: 500,\n filterValues: 100,\n identifierCharacters: 256,\n regexCharacters: 4_096,\n minimumTextBudget: 64,\n} as const\n\nexport interface TraceAnalysisStoreContext {\n signal?: AbortSignal\n}\n\n/**\n * Storage adapter for trace reads.\n *\n * Bind third-party implementations with `createBoundedTraceAnalysisStore()`.\n * The binding validates every input and result, applies byte limits, and\n * forwards one cancellation signal through existence checks and reads.\n */\nexport interface TraceAnalysisStore {\n hasTrace(trace_id: string, context?: TraceAnalysisStoreContext): Promise<boolean>\n\n hasSpans(\n input: { trace_id: string; span_ids: readonly string[] },\n context?: TraceAnalysisStoreContext,\n ): Promise<string[]>\n\n getOverview(\n filters?: TraceAnalystFilters,\n context?: TraceAnalysisStoreContext,\n ): Promise<DatasetOverview>\n\n queryTraces(\n input: { filters?: TraceAnalystFilters; limit: number; offset?: number },\n context?: TraceAnalysisStoreContext,\n ): Promise<QueryTracesPage>\n\n countTraces(filters?: TraceAnalystFilters, context?: TraceAnalysisStoreContext): Promise<number>\n\n viewTrace(\n input: {\n trace_id: string\n per_attribute_byte_cap?: number\n },\n context?: TraceAnalysisStoreContext,\n ): Promise<ViewTraceResult>\n\n viewSpans(\n input: {\n trace_id: string\n span_ids: readonly string[]\n per_attribute_byte_cap?: number\n },\n context?: TraceAnalysisStoreContext,\n ): Promise<ViewSpansResult>\n\n searchTrace(\n input: {\n trace_id: string\n regex_pattern: string\n max_matches?: number\n },\n context?: TraceAnalysisStoreContext,\n ): Promise<SearchTraceResult>\n\n searchSpan(\n input: {\n trace_id: string\n span_id: string\n regex_pattern: string\n max_matches?: number\n },\n context?: TraceAnalysisStoreContext,\n ): Promise<SearchSpanResult>\n}\n\nexport interface BoundedTraceAnalysisStoreOptions {\n budgets?: Partial<TraceAnalystByteBudgets>\n}\n","/**\n * Shared types for the trace-analyst module.\n *\n * Wire format. The store interface speaks `OtlpSpanLike` rows — one JSONL\n * line per span, OTLP-shaped. We do NOT depend on a specific tracing\n * vendor at the type level. Adapter\n * layers map upstream shapes onto this interface.\n *\n * Design constraint. Every read operation that can return arbitrary\n * payload must carry a byte budget so the agent's tool result stays\n * bounded regardless of input trace size. Oversized responses\n * substitute a deterministic summary instead of bytes — see\n * `ViewTraceOversized`.\n */\n\n/** OTLP span kind (subset we actually use). */\nexport type TraceAnalystSpanKind =\n | 'AGENT'\n | 'LLM'\n | 'TOOL'\n | 'CHAIN'\n | 'EVALUATOR'\n | 'GUARDRAIL'\n | 'SPAN'\n | 'UNKNOWN'\n\nexport type TraceAnalystSpanStatus = 'OK' | 'ERROR' | 'UNSET'\n\n/** Subset of OTLP span fields the analyst exposes to the agent. The\n * store's job is to project upstream's full span shape down to this\n * view — the analyst never sees vendor extensions directly. */\nexport interface TraceAnalystSpan {\n trace_id: string\n span_id: string\n parent_span_id: string | null\n name: string\n kind: TraceAnalystSpanKind\n start_time: string\n end_time: string\n duration_ms: number\n status: TraceAnalystSpanStatus\n status_message?: string\n service_name: string | null\n agent_name: string | null\n model_name: string | null\n tool_name: string | null\n /** Raw JSON-serialisable attribute map. May contain large strings;\n * callers must respect the per-attribute byte cap. */\n attributes: Record<string, unknown>\n}\n\nexport interface TraceAnalystTraceSummary {\n trace_id: string\n service_name: string | null\n agent_name: string | null\n span_count: number\n has_errors: boolean\n start_time: string\n end_time: string\n duration_ms: number\n raw_jsonl_bytes: number\n models: string[]\n tools: string[]\n}\n\nexport interface TraceAnalystFilters {\n /** Restrict to traces that contain at least one error span. */\n has_errors?: boolean\n /** Match if any span's `service.name` is in this list. */\n service_names?: string[]\n /** Match if any span's `agent.name` is in this list. */\n agent_names?: string[]\n /** Match if any LLM span's `llm.model_name` is in this list. */\n model_names?: string[]\n /** Match if any tool span's `tool.name` is in this list. */\n tool_names?: string[]\n /** ISO-8601 lower bound on the trace's earliest start time. */\n start_time_after?: string\n /** ISO-8601 upper bound on the trace's earliest start time. */\n start_time_before?: string\n /** Single regex applied to raw JSONL bytes for the trace. Opt-in;\n * expensive on large datasets. Use the indexed filters above first. */\n regex_pattern?: string\n}\n\n/** One distinct error signature across the dataset — the deterministic unit of\n * failure coverage. Signatures normalize volatile tokens (digits, hex/uuids,\n * paths, durations) out of the span `status_message` so semantically identical\n * failures collapse into one cluster. An analyst that accounts for every\n * cluster has, by construction, covered every distinct failure mode. */\nexport interface ErrorCluster {\n /** Normalized status_message — the cluster key. */\n signature: string\n /** A verbatim, un-normalized exemplar message (for exact-string citation). */\n status_message_sample: string\n /** The span name that most often carries this signature, if any. */\n span_name: string | null\n /** The tool that most often carries this signature, if any. */\n tool_name: string | null\n trace_count: number\n span_count: number\n /** trace_count / total error traces in the matched set (0..1). */\n prevalence: number\n /** Real trace ids carrying this signature (capped), passable to view/search. */\n exemplar_trace_ids: string[]\n /** Real span ids carrying this signature (capped). */\n exemplar_span_ids: string[]\n}\n\nexport interface DatasetOverview {\n total_traces: number\n raw_jsonl_bytes: number\n services: string[]\n agents: string[]\n models: string[]\n tool_names: string[]\n /** Up to 20 real trace ids the agent may pass to view/search tools. */\n sample_trace_ids: string[]\n errors: { trace_count: number; span_count: number }\n /** The COMPLETE deterministic error-signature population, sorted by\n * trace_count desc. This is the failure-coverage checklist: an analysis is\n * complete only when every cluster here is accounted for. Empty when the\n * matched set has no error spans. */\n error_clusters: ErrorCluster[]\n time_range: { earliest: string; latest: string } | null\n}\n\nexport interface QueryTracesPage {\n traces: TraceAnalystTraceSummary[]\n total: number\n has_more: boolean\n}\n\n/** Full-trace view. When the response would exceed the per-call byte\n * budget, `oversized` is populated INSTEAD of `spans` so the agent\n * knows to switch to `searchTrace` / `viewSpans`. */\nexport interface ViewTraceResult {\n trace_id: string\n spans?: TraceAnalystSpan[]\n oversized?: ViewTraceOversized\n}\n\nexport interface ViewTraceOversized {\n span_count: number\n /** Names with their counts, sorted desc. Capped at 20 entries. */\n top_span_names: Array<[string, number]>\n /** Largest single span body (bytes after attribute-cap projection). */\n span_response_bytes_max: number\n error_span_count: number\n}\n\nexport interface ViewSpansResult {\n trace_id: string\n spans: TraceAnalystSpan[]\n /** Number of requested span ids that were not found in the trace. */\n missing_span_ids: string[]\n /** Requested span ids that exist but did not fit in this response. */\n omitted_span_ids: string[]\n /** True exactly when `omitted_span_ids` contains continuation work. */\n has_more: boolean\n /** Number of attribute fields truncated to fit the per-attribute cap. */\n truncated_attribute_count: number\n}\n\nexport interface SpanMatchRecord {\n trace_id: string\n span_id: string\n span_name: string\n span_kind: TraceAnalystSpanKind\n /** JSON pointer-style path to the matched value, e.g.\n * `attributes.\"llm.input_messages\"[2].content`. */\n attribute_path: string\n matched_text: string\n context_before: string\n context_after: string\n match_offset: number\n}\n\nexport interface SearchTraceResult {\n trace_id: string\n hits: SpanMatchRecord[]\n has_more: boolean\n}\n\nexport interface SearchSpanResult {\n trace_id: string\n span_id: string\n hits: SpanMatchRecord[]\n has_more: boolean\n}\n\n/** Tunable byte budgets for bounded RLM tool output. */\nexport interface TraceAnalystByteBudgets {\n /** Max bytes any single tool response may emit. Hard ceiling enforced\n * by the store; oversized → summary. Default 150_000. */\n perCallByteCeiling: number\n /** Per-attribute string truncation cap on `viewTrace` (discovery scan).\n * Default 4096. */\n perAttributeViewBudget: number\n /** Per-attribute string truncation cap on `viewSpans` (surgical reads).\n * Default 16384. */\n perAttributeSpanBudget: number\n /** Per-attribute cap on a single match record's `matched_text` and\n * context window. Default 1024. */\n perMatchTextBudget: number\n}\n\nexport const DEFAULT_TRACE_ANALYST_BUDGETS: TraceAnalystByteBudgets = {\n perCallByteCeiling: 150_000,\n perAttributeViewBudget: 4_096,\n perAttributeSpanBudget: 16_384,\n perMatchTextBudget: 1_024,\n}\n\n/** Marker substituted in place of truncated string payloads. Callers\n * parsing tool output can detect it deterministically. */\nexport const TRACE_ANALYST_TRUNCATION_MARKER_PREFIX = '[trace-analyst truncated:'\n","import { RE2JS } from 're2js'\n\nimport {\n TraceAnalysisLimitError,\n TraceAnalysisStoreContractError,\n TraceAnalysisValidationError,\n} from './errors'\nimport { TRACE_ANALYSIS_LIMITS } from './store-contract'\nimport type {\n DatasetOverview,\n QueryTracesPage,\n SearchSpanResult,\n SearchTraceResult,\n SpanMatchRecord,\n TraceAnalystByteBudgets,\n TraceAnalystSpan,\n ViewSpansResult,\n ViewTraceOversized,\n ViewTraceResult,\n} from './types'\nimport { DEFAULT_TRACE_ANALYST_BUDGETS } from './types'\n\nexport function resolveTraceBudgets(\n overrides: Partial<TraceAnalystByteBudgets> | undefined,\n): TraceAnalystByteBudgets {\n const budgets = { ...DEFAULT_TRACE_ANALYST_BUDGETS, ...overrides }\n validateInteger(budgets.perCallByteCeiling, 'perCallByteCeiling', 1)\n for (const name of [\n 'perAttributeViewBudget',\n 'perAttributeSpanBudget',\n 'perMatchTextBudget',\n ] as const) {\n validateInteger(budgets[name], name, TRACE_ANALYSIS_LIMITS.minimumTextBudget)\n }\n return budgets\n}\n\nexport function boundOverview(result: DatasetOverview, byteCeiling: number): DatasetOverview {\n if (result.sample_trace_ids.length > result.total_traces) {\n throw contractError('getOverview', 'sample_trace_ids contains more entries than total_traces')\n }\n if (result.errors.trace_count > result.total_traces) {\n throw contractError('getOverview', 'errors.trace_count exceeds total_traces')\n }\n return withinByteCeiling('getOverview', result, byteCeiling)\n}\n\nexport function boundTracePage(\n result: QueryTracesPage,\n input: { limit: number; offset: number },\n byteCeiling: number,\n): QueryTracesPage {\n if (result.traces.length > input.limit) {\n throw contractError(\n 'queryTraces',\n `store returned ${result.traces.length} traces for limit ${input.limit}`,\n )\n }\n if (result.total < input.offset + result.traces.length) {\n throw contractError(\n 'queryTraces',\n `total ${result.total} is smaller than the returned page ending at ${\n input.offset + result.traces.length\n }`,\n )\n }\n if (result.has_more !== input.offset + result.traces.length < result.total) {\n throw contractError(\n 'queryTraces',\n 'has_more does not match the returned page position and total',\n )\n }\n if (result.has_more && result.traces.length === 0) {\n throw contractError('queryTraces', 'store reported more traces without returning any progress')\n }\n\n const traces: QueryTracesPage['traces'] = []\n for (const trace of result.traces) {\n const candidate = { traces: [...traces, trace], total: result.total, has_more: true }\n if (encodedBytes('queryTraces', candidate) > byteCeiling) break\n traces.push(trace)\n }\n if (result.traces.length > 0 && traces.length === 0) {\n throw responseItemTooLarge(\n 'queryTraces',\n { traces: [result.traces[0]], total: result.total, has_more: true },\n byteCeiling,\n )\n }\n return withinByteCeiling(\n 'queryTraces',\n {\n traces,\n total: result.total,\n has_more: result.has_more || traces.length < result.traces.length,\n },\n byteCeiling,\n )\n}\n\nexport function boundTraceView(\n result: ViewTraceResult,\n expectedTraceId: string,\n perAttributeCap: number,\n byteCeiling: number,\n): ViewTraceResult {\n requireEqual('viewTrace', 'trace_id', result.trace_id, expectedTraceId)\n if (result.oversized) {\n return withinByteCeiling('viewTrace', result, byteCeiling)\n }\n\n const spans = result.spans!.map((span) => {\n requireEqual('viewTrace', 'span.trace_id', span.trace_id, expectedTraceId)\n return truncateSpanAttributes('viewTrace', span, perAttributeCap).span\n })\n const full = { trace_id: expectedTraceId, spans }\n if (encodedBytes('viewTrace', full) <= byteCeiling) return full\n return withinByteCeiling(\n 'viewTrace',\n { trace_id: expectedTraceId, oversized: oversizedFromSpans(spans) },\n byteCeiling,\n )\n}\n\nexport function boundSpansView(\n result: ViewSpansResult,\n expectedTraceId: string,\n requested: readonly string[],\n existingSpanIds: ReadonlySet<string>,\n perAttributeCap: number,\n byteCeiling: number,\n): ViewSpansResult {\n requireEqual('viewSpans', 'trace_id', result.trace_id, expectedTraceId)\n const requestedSet = new Set(requested)\n const missing = checkedAccountingIds('missing_span_ids', result.missing_span_ids, requestedSet)\n const omitted = checkedAccountingIds('omitted_span_ids', result.omitted_span_ids, requestedSet)\n const missingSet = new Set(missing)\n const omittedSet = new Set(omitted)\n const expectedMissing = requested.filter((id) => !existingSpanIds.has(id))\n if (\n expectedMissing.length !== missing.length ||\n expectedMissing.some((id) => !missingSet.has(id))\n ) {\n throw contractError('viewSpans', 'missing_span_ids does not match the store existence checks')\n }\n if (result.has_more !== omitted.length > 0) {\n throw contractError(\n 'viewSpans',\n 'has_more must be true exactly when omitted_span_ids is non-empty',\n )\n }\n if (\n result.spans.length === 0 &&\n requested.some((id) => existingSpanIds.has(id) && omittedSet.has(id))\n ) {\n throw contractError(\n 'viewSpans',\n 'store omitted every existing requested span instead of returning progress or throwing a size error',\n )\n }\n\n const projected = new Map<string, { span: TraceAnalystSpan; truncations: number }>()\n for (const span of result.spans) {\n requireEqual('viewSpans', 'span.trace_id', span.trace_id, expectedTraceId)\n if (!requestedSet.has(span.span_id)) {\n throw contractError(\n 'viewSpans',\n `store returned unrequested span ${JSON.stringify(span.span_id)}`,\n )\n }\n if (missingSet.has(span.span_id) || omittedSet.has(span.span_id)) {\n throw contractError(\n 'viewSpans',\n `span ${JSON.stringify(span.span_id)} is both returned and unavailable`,\n )\n }\n if (projected.has(span.span_id)) {\n throw contractError(\n 'viewSpans',\n `store returned duplicate span ${JSON.stringify(span.span_id)}`,\n )\n }\n projected.set(span.span_id, truncateSpanAttributes('viewSpans', span, perAttributeCap))\n }\n for (const id of requested) {\n if (!missingSet.has(id) && !omittedSet.has(id) && !projected.has(id)) {\n throw contractError(\n 'viewSpans',\n `store did not account for requested span ${JSON.stringify(id)}`,\n )\n }\n }\n\n const spans: TraceAnalystSpan[] = []\n let addedTruncations = 0\n const build = (): ViewSpansResult => ({\n trace_id: expectedTraceId,\n spans,\n missing_span_ids: requested.filter((id) => missingSet.has(id)),\n omitted_span_ids: requested.filter((id) => omittedSet.has(id)),\n has_more: omittedSet.size > 0,\n truncated_attribute_count: result.truncated_attribute_count + addedTruncations,\n })\n withinByteCeiling('viewSpans', build(), byteCeiling)\n for (const id of requested) {\n const item = projected.get(id)\n if (!item) continue\n spans.push(item.span)\n omittedSet.delete(id)\n addedTruncations += item.truncations\n if (encodedBytes('viewSpans', build()) <= byteCeiling) continue\n spans.pop()\n omittedSet.add(id)\n addedTruncations -= item.truncations\n }\n if (projected.size > 0 && spans.length === 0) {\n const first = projected.values().next().value\n if (first) {\n throw responseItemTooLarge(\n 'viewSpans',\n {\n trace_id: expectedTraceId,\n spans: [first.span],\n missing_span_ids: [],\n omitted_span_ids: [],\n has_more: false,\n truncated_attribute_count: result.truncated_attribute_count + first.truncations,\n },\n byteCeiling,\n )\n }\n }\n return withinByteCeiling('viewSpans', build(), byteCeiling)\n}\n\nexport function boundTraceSearch(\n result: SearchTraceResult,\n expectedTraceId: string,\n maxMatches: number,\n budgets: TraceAnalystByteBudgets,\n): SearchTraceResult {\n requireEqual('searchTrace', 'trace_id', result.trace_id, expectedTraceId)\n const bounded = boundSearchHits('searchTrace', result, maxMatches, budgets, (hit) => {\n requireEqual('searchTrace', 'hit.trace_id', hit.trace_id, expectedTraceId)\n })\n return { trace_id: expectedTraceId, ...bounded }\n}\n\nexport function boundSpanSearch(\n result: SearchSpanResult,\n expectedTraceId: string,\n expectedSpanId: string,\n maxMatches: number,\n budgets: TraceAnalystByteBudgets,\n): SearchSpanResult {\n requireEqual('searchSpan', 'trace_id', result.trace_id, expectedTraceId)\n requireEqual('searchSpan', 'span_id', result.span_id, expectedSpanId)\n const bounded = boundSearchHits('searchSpan', result, maxMatches, budgets, (hit) => {\n requireEqual('searchSpan', 'hit.trace_id', hit.trace_id, expectedTraceId)\n requireEqual('searchSpan', 'hit.span_id', hit.span_id, expectedSpanId)\n })\n return { trace_id: expectedTraceId, span_id: expectedSpanId, ...bounded }\n}\n\nfunction boundSearchHits(\n operation: 'searchTrace' | 'searchSpan',\n result: Pick<SearchTraceResult, 'hits' | 'has_more'>,\n maxMatches: number,\n budgets: TraceAnalystByteBudgets,\n validateHit: (hit: SpanMatchRecord) => void,\n): Pick<SearchTraceResult, 'hits' | 'has_more'> {\n if (result.hits.length > maxMatches) {\n throw contractError(\n operation,\n `store returned ${result.hits.length} hits for max_matches ${maxMatches}`,\n )\n }\n if (result.has_more && result.hits.length === 0) {\n throw contractError(operation, 'store reported more matches without returning any progress')\n }\n\n const hits: SpanMatchRecord[] = []\n for (const raw of result.hits) {\n validateHit(raw)\n const hit = truncateMatchRecord(raw, budgets.perMatchTextBudget)\n const candidate = {\n hits: [...hits, hit],\n has_more: true,\n }\n if (encodedBytes(operation, candidate) > budgets.perCallByteCeiling) break\n hits.push(hit)\n }\n if (result.hits.length > 0 && hits.length === 0) {\n throw responseItemTooLarge(\n operation,\n {\n hits: [truncateMatchRecord(result.hits[0]!, budgets.perMatchTextBudget)],\n has_more: true,\n },\n budgets.perCallByteCeiling,\n )\n }\n return withinByteCeiling(\n operation,\n {\n hits,\n has_more: result.has_more || hits.length < result.hits.length,\n },\n budgets.perCallByteCeiling,\n )\n}\n\nfunction checkedAccountingIds(\n label: string,\n ids: readonly string[],\n requested: ReadonlySet<string>,\n): string[] {\n const seen = new Set<string>()\n for (const id of ids) {\n if (!requested.has(id)) {\n throw contractError('viewSpans', `${label} contains unrequested id ${JSON.stringify(id)}`)\n }\n if (seen.has(id)) {\n throw contractError('viewSpans', `${label} contains duplicate id ${JSON.stringify(id)}`)\n }\n seen.add(id)\n }\n return [...ids]\n}\n\nfunction truncateMatchRecord(record: SpanMatchRecord, cap: number): SpanMatchRecord {\n return {\n ...record,\n span_name: truncateForBudget(record.span_name, cap),\n attribute_path: truncateForBudget(record.attribute_path, cap),\n matched_text: truncateForBudget(record.matched_text, cap),\n context_before: truncateForBudget(record.context_before, cap),\n context_after: truncateForBudget(record.context_after, cap),\n }\n}\n\nfunction truncateSpanAttributes(\n operation: string,\n span: TraceAnalystSpan,\n cap: number,\n): { span: TraceAnalystSpan; truncations: number } {\n const attributes: Record<string, unknown> = {}\n let truncations = 0\n for (const [key, value] of Object.entries(span.attributes)) {\n if (typeof value === 'string') {\n const truncated = truncateForBudget(value, cap)\n if (truncated !== value) truncations += 1\n attributes[key] = truncated\n continue\n }\n if (value !== null && typeof value === 'object') {\n let json: string\n try {\n json = JSON.stringify(value)\n } catch (cause) {\n throw new TraceAnalysisStoreContractError(\n operation,\n `span attribute ${JSON.stringify(key)} is not JSON-serializable`,\n { cause },\n )\n }\n const truncated = truncateForBudget(json, cap)\n if (truncated !== json) {\n truncations += 1\n attributes[key] = truncated\n } else {\n attributes[key] = value\n }\n continue\n }\n attributes[key] = value\n }\n return { span: { ...span, attributes }, truncations }\n}\n\nfunction oversizedFromSpans(spans: readonly TraceAnalystSpan[]): ViewTraceOversized {\n const names = new Map<string, number>()\n let maxBytes = 0\n let errors = 0\n for (const span of spans) {\n names.set(span.name, (names.get(span.name) ?? 0) + 1)\n maxBytes = Math.max(maxBytes, encodedBytes('viewTrace', span))\n if (span.status === 'ERROR') errors += 1\n }\n return {\n span_count: spans.length,\n top_span_names: [...names.entries()]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .slice(0, 20),\n span_response_bytes_max: maxBytes,\n error_span_count: errors,\n }\n}\n\nexport function compileSearchRegex(pattern: string): RE2JS {\n if (typeof pattern !== 'string' || pattern.length === 0) {\n throw new TraceAnalysisValidationError('regex_pattern must be a non-empty string')\n }\n let source = pattern\n let flags = RE2JS.MULTILINE\n if (source.startsWith('(?i)')) {\n source = source.slice(4)\n flags |= RE2JS.CASE_INSENSITIVE\n }\n try {\n return RE2JS.compile(source, flags)\n } catch (cause) {\n throw new TraceAnalysisValidationError(\n `regex_pattern is invalid: ${cause instanceof Error ? cause.message : String(cause)}`,\n { cause },\n )\n }\n}\n\nexport function truncateForBudget(value: string, byteCap: number): string {\n validateInteger(byteCap, 'byteCap', TRACE_ANALYSIS_LIMITS.minimumTextBudget)\n const original = Buffer.byteLength(value, 'utf8')\n if (original <= byteCap) return value\n\n const marker = `\\n[trace-analyst truncated: original ${original} bytes]`\n const contentCap = byteCap - Buffer.byteLength(marker, 'utf8')\n let cut = Math.max(0, Math.floor((value.length * contentCap) / original))\n while (cut > 0 && Buffer.byteLength(value.slice(0, cut), 'utf8') > contentCap) cut -= 1\n return `${value.slice(0, cut)}${marker}`\n}\n\nexport function validateInteger(\n value: unknown,\n label: string,\n minimum: number,\n maximum = Number.MAX_SAFE_INTEGER,\n): number {\n if (\n typeof value !== 'number' ||\n !Number.isSafeInteger(value) ||\n value < minimum ||\n value > maximum\n ) {\n throw new TraceAnalysisValidationError(\n `${label} must be an integer ${minimum}..${maximum}, got ${String(value)}`,\n )\n }\n return value\n}\n\nfunction requireEqual(operation: string, label: string, actual: string, expected: string): void {\n if (actual !== expected) {\n throw contractError(\n operation,\n `${label} ${JSON.stringify(actual)} does not match ${JSON.stringify(expected)}`,\n )\n }\n}\n\nfunction encodedBytes(operation: string, value: unknown): number {\n try {\n const encoded = JSON.stringify(value)\n if (encoded === undefined) throw new TypeError('JSON.stringify returned undefined')\n return Buffer.byteLength(encoded, 'utf8')\n } catch (cause) {\n if (cause instanceof TraceAnalysisStoreContractError) throw cause\n throw new TraceAnalysisStoreContractError(operation, 'store result is not JSON-serializable', {\n cause,\n })\n }\n}\n\nfunction withinByteCeiling<T>(operation: string, value: T, ceiling: number): T {\n const actual = encodedBytes(operation, value)\n if (actual > ceiling) {\n throw new TraceAnalysisLimitError(\n operation,\n actual,\n ceiling,\n `${operation} metadata requires ${actual} bytes, over the ${ceiling}-byte response limit`,\n )\n }\n return value\n}\n\nfunction responseItemTooLarge(\n operation: string,\n value: unknown,\n ceiling: number,\n): TraceAnalysisLimitError {\n const actual = encodedBytes(operation, value)\n return new TraceAnalysisLimitError(\n operation,\n actual,\n ceiling,\n `${operation} cannot fit one result item in the ${ceiling}-byte response limit`,\n )\n}\n\nfunction contractError(operation: string, message: string): TraceAnalysisStoreContractError {\n return new TraceAnalysisStoreContractError(operation, message)\n}\n","import { z } from 'zod'\nimport { TraceAnalysisStoreContractError, TraceAnalysisValidationError } from './errors'\nimport { TRACE_ANALYSIS_LIMITS } from './store-contract'\n\nconst identifier = z.string().min(1).max(TRACE_ANALYSIS_LIMITS.identifierCharacters)\nconst timestamp = z.iso.datetime({ offset: true })\nconst nonNegativeInteger = z.number().int().nonnegative()\nconst nonNegativeNumber = z.number().nonnegative()\nconst nullableString = z.string().nullable()\nconst nullableIdentifier = identifier.nullable()\nconst stringArray = z.array(z.string())\nconst filterValues = z.array(identifier).max(TRACE_ANALYSIS_LIMITS.filterValues)\n\nexport const traceFiltersSchema = z\n .object({\n has_errors: z.boolean().optional(),\n service_names: filterValues.optional(),\n agent_names: filterValues.optional(),\n model_names: filterValues.optional(),\n tool_names: filterValues.optional(),\n start_time_after: timestamp.optional(),\n start_time_before: timestamp.optional(),\n regex_pattern: z.string().min(1).max(TRACE_ANALYSIS_LIMITS.regexCharacters).optional(),\n })\n .strict()\n\nconst byteCap = z.number().int().min(TRACE_ANALYSIS_LIMITS.minimumTextBudget)\nconst searchPattern = z.string().min(1).max(TRACE_ANALYSIS_LIMITS.regexCharacters)\n\nexport const traceStoreInputSchemas = {\n hasTrace: z.object({ trace_id: identifier }).strict(),\n hasSpans: z\n .object({\n trace_id: identifier,\n span_ids: z.array(identifier).min(1).max(TRACE_ANALYSIS_LIMITS.viewSpans),\n })\n .strict(),\n getOverview: z.object({ filters: traceFiltersSchema.optional() }).strict(),\n queryTraces: z\n .object({\n filters: traceFiltersSchema.optional(),\n limit: z.number().int().min(1).max(TRACE_ANALYSIS_LIMITS.queryTraces),\n offset: z.number().int().nonnegative().optional(),\n })\n .strict(),\n countTraces: z.object({ filters: traceFiltersSchema.optional() }).strict(),\n viewTrace: z\n .object({\n trace_id: identifier,\n per_attribute_byte_cap: byteCap.optional(),\n })\n .strict(),\n viewSpans: z\n .object({\n trace_id: identifier,\n span_ids: z.array(identifier).min(1).max(TRACE_ANALYSIS_LIMITS.viewSpans),\n per_attribute_byte_cap: byteCap.optional(),\n })\n .strict(),\n searchTrace: z\n .object({\n trace_id: identifier,\n regex_pattern: searchPattern,\n max_matches: z.number().int().min(1).max(TRACE_ANALYSIS_LIMITS.searchMatches).default(50),\n })\n .strict(),\n searchSpan: z\n .object({\n trace_id: identifier,\n span_id: identifier,\n regex_pattern: searchPattern,\n max_matches: z.number().int().min(1).max(TRACE_ANALYSIS_LIMITS.searchMatches).default(50),\n })\n .strict(),\n} as const\n\nconst spanKind = z.enum([\n 'AGENT',\n 'LLM',\n 'TOOL',\n 'CHAIN',\n 'EVALUATOR',\n 'GUARDRAIL',\n 'SPAN',\n 'UNKNOWN',\n])\nconst spanStatus = z.enum(['OK', 'ERROR', 'UNSET'])\n\nconst traceSpan = z\n .object({\n trace_id: identifier,\n span_id: identifier,\n parent_span_id: nullableIdentifier,\n name: z.string(),\n kind: spanKind,\n start_time: timestamp,\n end_time: timestamp,\n duration_ms: nonNegativeNumber,\n status: spanStatus,\n status_message: z.string().optional(),\n service_name: nullableString,\n agent_name: nullableString,\n model_name: nullableString,\n tool_name: nullableString,\n attributes: z.record(z.string(), z.json()),\n })\n .strict()\n\nconst traceSummary = z\n .object({\n trace_id: identifier,\n service_name: nullableString,\n agent_name: nullableString,\n span_count: nonNegativeInteger,\n has_errors: z.boolean(),\n start_time: timestamp,\n end_time: timestamp,\n duration_ms: nonNegativeNumber,\n raw_jsonl_bytes: nonNegativeInteger,\n models: stringArray,\n tools: stringArray,\n })\n .strict()\n\nconst errorCluster = z\n .object({\n signature: z.string(),\n status_message_sample: z.string(),\n span_name: nullableString,\n tool_name: nullableString,\n trace_count: nonNegativeInteger,\n span_count: nonNegativeInteger,\n prevalence: z.number().min(0).max(1),\n exemplar_trace_ids: z.array(identifier),\n exemplar_span_ids: z.array(identifier),\n })\n .strict()\n\nconst overview = z\n .object({\n total_traces: nonNegativeInteger,\n raw_jsonl_bytes: nonNegativeInteger,\n services: stringArray,\n agents: stringArray,\n models: stringArray,\n tool_names: stringArray,\n sample_trace_ids: z.array(identifier).max(TRACE_ANALYSIS_LIMITS.sampleTraceIds),\n errors: z\n .object({\n trace_count: nonNegativeInteger,\n span_count: nonNegativeInteger,\n })\n .strict(),\n error_clusters: z.array(errorCluster),\n time_range: z\n .object({\n earliest: timestamp,\n latest: timestamp,\n })\n .strict()\n .nullable(),\n })\n .strict()\n\nconst tracePage = z\n .object({\n traces: z.array(traceSummary),\n total: nonNegativeInteger,\n has_more: z.boolean(),\n })\n .strict()\n\nconst oversizedTrace = z\n .object({\n span_count: nonNegativeInteger,\n top_span_names: z.array(z.tuple([z.string(), nonNegativeInteger])).max(20),\n span_response_bytes_max: nonNegativeInteger,\n error_span_count: nonNegativeInteger,\n })\n .strict()\n\nconst traceView = z\n .object({\n trace_id: identifier,\n spans: z.array(traceSpan).optional(),\n oversized: oversizedTrace.optional(),\n })\n .strict()\n .refine((value) => (value.spans === undefined) !== (value.oversized === undefined), {\n message: 'exactly one of spans or oversized is required',\n })\n\nconst spansView = z\n .object({\n trace_id: identifier,\n spans: z.array(traceSpan),\n missing_span_ids: z.array(identifier),\n omitted_span_ids: z.array(identifier),\n has_more: z.boolean(),\n truncated_attribute_count: nonNegativeInteger,\n })\n .strict()\n\nconst matchRecord = z\n .object({\n trace_id: identifier,\n span_id: identifier,\n span_name: z.string(),\n span_kind: spanKind,\n attribute_path: z.string(),\n matched_text: z.string(),\n context_before: z.string(),\n context_after: z.string(),\n match_offset: nonNegativeInteger,\n })\n .strict()\n\nconst traceSearch = z\n .object({\n trace_id: identifier,\n hits: z.array(matchRecord),\n has_more: z.boolean(),\n })\n .strict()\n\nconst spanSearch = traceSearch\n .extend({\n span_id: identifier,\n })\n .strict()\n\nexport const traceStoreOutputSchemas = {\n hasTrace: z.boolean(),\n hasSpans: z.array(identifier).max(TRACE_ANALYSIS_LIMITS.viewSpans),\n getOverview: overview,\n queryTraces: tracePage,\n countTraces: nonNegativeInteger,\n viewTrace: traceView,\n viewSpans: spansView,\n searchTrace: traceSearch,\n searchSpan: spanSearch,\n} as const\n\nexport function parseTraceInput<T extends z.ZodType>(\n operation: string,\n schema: T,\n value: unknown,\n): z.output<T> {\n try {\n return schema.parse(value)\n } catch (cause) {\n const detail = cause instanceof z.ZodError ? z.prettifyError(cause) : String(cause)\n throw new TraceAnalysisValidationError(`${operation}: invalid arguments: ${detail}`, { cause })\n }\n}\n\nexport function parseStoreOutput<T extends z.ZodType>(\n operation: string,\n schema: T,\n value: unknown,\n): z.output<T> {\n try {\n return schema.parse(value)\n } catch (cause) {\n const detail = cause instanceof z.ZodError ? z.prettifyError(cause) : String(cause)\n throw new TraceAnalysisStoreContractError(operation, `invalid store result: ${detail}`, {\n cause,\n })\n }\n}\n\nexport function toTraceJsonSchema(schema: z.ZodType): Record<string, unknown> {\n return z.toJSONSchema(schema, { target: 'draft-7' }) as Record<string, unknown>\n}\n","import {\n SpanNotFoundError,\n TraceAnalysisStoreContractError,\n TraceAnalysisValidationError,\n TraceNotFoundError,\n} from './errors'\nimport {\n boundOverview,\n boundSpanSearch,\n boundSpansView,\n boundTracePage,\n boundTraceSearch,\n boundTraceView,\n compileSearchRegex,\n resolveTraceBudgets,\n} from './store-bounds'\nimport type {\n BoundedTraceAnalysisStoreOptions,\n TraceAnalysisStore,\n TraceAnalysisStoreContext,\n} from './store-contract'\nimport {\n parseStoreOutput,\n parseTraceInput,\n traceStoreInputSchemas,\n traceStoreOutputSchemas,\n} from './store-schemas'\n\n/** Apply the public validation, cancellation, not-found, and size rules to any adapter. */\nexport function createBoundedTraceAnalysisStore(\n source: TraceAnalysisStore,\n options: BoundedTraceAnalysisStoreOptions = {},\n): TraceAnalysisStore {\n const budgets = resolveTraceBudgets(options.budgets)\n\n return {\n async hasTrace(traceId, context) {\n throwIfAborted(context)\n const { trace_id } = parseTraceInput('hasTrace', traceStoreInputSchemas.hasTrace, {\n trace_id: traceId,\n })\n const result = await source.hasTrace(trace_id, context)\n throwIfAborted(context)\n return parseStoreOutput('hasTrace', traceStoreOutputSchemas.hasTrace, result)\n },\n\n async hasSpans(input, context) {\n throwIfAborted(context)\n const parsed = parseTraceInput('hasSpans', traceStoreInputSchemas.hasSpans, input)\n assertUniqueIds(parsed.span_ids, 'hasSpans.span_ids')\n const result = await source.hasSpans(parsed, context)\n throwIfAborted(context)\n return validateExistingSpanIds(\n parseStoreOutput('hasSpans', traceStoreOutputSchemas.hasSpans, result),\n parsed.span_ids,\n )\n },\n\n async getOverview(filters, context) {\n throwIfAborted(context)\n const input = parseTraceInput('getOverview', traceStoreInputSchemas.getOverview, { filters })\n const result = await source.getOverview(input.filters, context)\n throwIfAborted(context)\n return boundOverview(\n parseStoreOutput('getOverview', traceStoreOutputSchemas.getOverview, result),\n budgets.perCallByteCeiling,\n )\n },\n\n async queryTraces(input, context) {\n throwIfAborted(context)\n const parsed = parseTraceInput('queryTraces', traceStoreInputSchemas.queryTraces, input)\n const offset = parsed.offset ?? 0\n const result = await source.queryTraces({ ...parsed, offset }, context)\n throwIfAborted(context)\n return boundTracePage(\n parseStoreOutput('queryTraces', traceStoreOutputSchemas.queryTraces, result),\n { limit: parsed.limit, offset },\n budgets.perCallByteCeiling,\n )\n },\n\n async countTraces(filters, context) {\n throwIfAborted(context)\n const input = parseTraceInput('countTraces', traceStoreInputSchemas.countTraces, { filters })\n const result = await source.countTraces(input.filters, context)\n throwIfAborted(context)\n return parseStoreOutput('countTraces', traceStoreOutputSchemas.countTraces, result)\n },\n\n async viewTrace(input, context) {\n throwIfAborted(context)\n const parsed = parseTraceInput('viewTrace', traceStoreInputSchemas.viewTrace, input)\n await requireTrace(source, parsed.trace_id, context)\n const perAttributeCap = parsed.per_attribute_byte_cap ?? budgets.perAttributeViewBudget\n const result = await source.viewTrace(\n { ...parsed, per_attribute_byte_cap: perAttributeCap },\n context,\n )\n throwIfAborted(context)\n return boundTraceView(\n parseStoreOutput('viewTrace', traceStoreOutputSchemas.viewTrace, result),\n parsed.trace_id,\n perAttributeCap,\n budgets.perCallByteCeiling,\n )\n },\n\n async viewSpans(input, context) {\n throwIfAborted(context)\n const parsed = parseTraceInput('viewSpans', traceStoreInputSchemas.viewSpans, input)\n assertUniqueIds(parsed.span_ids, 'viewSpans.span_ids')\n await requireTrace(source, parsed.trace_id, context)\n const existingSpanIds = new Set(\n validateExistingSpanIds(\n parseStoreOutput(\n 'hasSpans',\n traceStoreOutputSchemas.hasSpans,\n await source.hasSpans(\n { trace_id: parsed.trace_id, span_ids: parsed.span_ids },\n context,\n ),\n ),\n parsed.span_ids,\n ),\n )\n throwIfAborted(context)\n const perAttributeCap = parsed.per_attribute_byte_cap ?? budgets.perAttributeSpanBudget\n const result = await source.viewSpans(\n { ...parsed, per_attribute_byte_cap: perAttributeCap },\n context,\n )\n throwIfAborted(context)\n return boundSpansView(\n parseStoreOutput('viewSpans', traceStoreOutputSchemas.viewSpans, result),\n parsed.trace_id,\n parsed.span_ids,\n existingSpanIds,\n perAttributeCap,\n budgets.perCallByteCeiling,\n )\n },\n\n async searchTrace(input, context) {\n throwIfAborted(context)\n const parsed = parseTraceInput('searchTrace', traceStoreInputSchemas.searchTrace, input)\n compileSearchRegex(parsed.regex_pattern)\n await requireTrace(source, parsed.trace_id, context)\n const result = await source.searchTrace(parsed, context)\n throwIfAborted(context)\n return boundTraceSearch(\n parseStoreOutput('searchTrace', traceStoreOutputSchemas.searchTrace, result),\n parsed.trace_id,\n parsed.max_matches,\n budgets,\n )\n },\n\n async searchSpan(input, context) {\n throwIfAborted(context)\n const parsed = parseTraceInput('searchSpan', traceStoreInputSchemas.searchSpan, input)\n compileSearchRegex(parsed.regex_pattern)\n await requireTrace(source, parsed.trace_id, context)\n await requireSpan(source, parsed.trace_id, parsed.span_id, context)\n const result = await source.searchSpan(parsed, context)\n throwIfAborted(context)\n return boundSpanSearch(\n parseStoreOutput('searchSpan', traceStoreOutputSchemas.searchSpan, result),\n parsed.trace_id,\n parsed.span_id,\n parsed.max_matches,\n budgets,\n )\n },\n }\n}\n\nasync function requireTrace(\n source: TraceAnalysisStore,\n traceId: string,\n context: TraceAnalysisStoreContext | undefined,\n): Promise<void> {\n throwIfAborted(context)\n const exists = await source.hasTrace(traceId, context)\n throwIfAborted(context)\n if (!parseStoreOutput('hasTrace', traceStoreOutputSchemas.hasTrace, exists)) {\n throw new TraceNotFoundError(traceId)\n }\n}\n\nasync function requireSpan(\n source: TraceAnalysisStore,\n traceId: string,\n spanId: string,\n context: TraceAnalysisStoreContext | undefined,\n): Promise<void> {\n throwIfAborted(context)\n const existing = await source.hasSpans({ trace_id: traceId, span_ids: [spanId] }, context)\n throwIfAborted(context)\n const found = validateExistingSpanIds(\n parseStoreOutput('hasSpans', traceStoreOutputSchemas.hasSpans, existing),\n [spanId],\n )\n if (found.length === 0) {\n throw new SpanNotFoundError(traceId, spanId)\n }\n}\n\nfunction validateExistingSpanIds(found: readonly string[], requested: readonly string[]): string[] {\n const requestedSet = new Set(requested)\n const seen = new Set<string>()\n for (const id of found) {\n if (!requestedSet.has(id)) {\n throw new TraceAnalysisStoreContractError(\n 'hasSpans',\n `hasSpans returned unrequested span id ${JSON.stringify(id)}`,\n )\n }\n if (seen.has(id)) {\n throw new TraceAnalysisStoreContractError(\n 'hasSpans',\n `hasSpans returned duplicate span id ${JSON.stringify(id)}`,\n )\n }\n seen.add(id)\n }\n return [...found]\n}\n\nfunction assertUniqueIds(ids: readonly string[], label: string): void {\n if (new Set(ids).size !== ids.length) {\n throw new TraceAnalysisValidationError(`${label} must not contain duplicates`)\n }\n}\n\nfunction throwIfAborted(context: TraceAnalysisStoreContext | undefined): void {\n context?.signal?.throwIfAborted()\n}\n","/**\n * Canonical transport-neutral trace tools. Schemas and handlers originate\n * here; recursive engines only translate calls across their process boundary.\n */\n\nimport type { EvalToolDef } from '../eval-tools'\nimport {\n type BoundedTraceAnalysisStoreOptions,\n createBoundedTraceAnalysisStore,\n TRACE_ANALYSIS_LIMITS,\n type TraceAnalysisStore,\n} from './store'\nimport { parseTraceInput, toTraceJsonSchema, traceStoreInputSchemas } from './store-schemas'\n\nexport const TRACE_ANALYST_TOOL_NAMESPACE = 'traces' as const\n\nexport interface BuildTraceAnalysisToolsOptions extends BoundedTraceAnalysisStoreOptions {\n store: TraceAnalysisStore\n}\n\nexport interface TraceAnalysisToolDescriptor extends EvalToolDef {\n namespace: typeof TRACE_ANALYST_TOOL_NAMESPACE\n}\n\n/** Bind all seven trace reads without exposing an agent framework type. */\nexport function buildTraceAnalysisToolDescriptors(\n options: BuildTraceAnalysisToolsOptions,\n): TraceAnalysisToolDescriptor[] {\n const store = createBoundedTraceAnalysisStore(options.store, { budgets: options.budgets })\n\n return [\n {\n namespace: TRACE_ANALYST_TOOL_NAMESPACE,\n name: 'getDatasetOverview',\n description:\n 'Dataset rollup: total traces, raw_jsonl_bytes, services, agents, models, tools, ' +\n 'and sample_trace_ids. Always call this first without a regex_pattern.',\n parameters: toTraceJsonSchema(traceStoreInputSchemas.getOverview),\n handler: async (args, context) => {\n const { filters } = parseTraceInput(\n 'getDatasetOverview',\n traceStoreInputSchemas.getOverview,\n args ?? {},\n )\n return store.getOverview(filters, context)\n },\n },\n {\n namespace: TRACE_ANALYST_TOOL_NAMESPACE,\n name: 'queryTraces',\n description:\n `Paginated trace summaries, at most ${TRACE_ANALYSIS_LIMITS.queryTraces} per call. ` +\n 'Each summary carries raw_jsonl_bytes; narrow with indexed filters before regex_pattern.',\n parameters: toTraceJsonSchema(traceStoreInputSchemas.queryTraces),\n handler: async (args, context) => {\n const input = parseTraceInput('queryTraces', traceStoreInputSchemas.queryTraces, args)\n return store.queryTraces(input, context)\n },\n },\n {\n namespace: TRACE_ANALYST_TOOL_NAMESPACE,\n name: 'countTraces',\n description:\n 'Count traces matching filters. Use as a cheap pre-flight before a regex_pattern scan.',\n parameters: toTraceJsonSchema(traceStoreInputSchemas.countTraces),\n handler: async (args, context) => {\n const { filters } = parseTraceInput(\n 'countTraces',\n traceStoreInputSchemas.countTraces,\n args ?? {},\n )\n return store.countTraces(filters, context)\n },\n },\n {\n namespace: TRACE_ANALYST_TOOL_NAMESPACE,\n name: 'viewTrace',\n description:\n 'Return all spans for one trace with bounded attributes. Oversized responses carry ' +\n 'an oversized summary instead of spans; continue with searchTrace or viewSpans.',\n parameters: toTraceJsonSchema(\n traceStoreInputSchemas.viewTrace.omit({\n per_attribute_byte_cap: true,\n }),\n ),\n handler: async (args, context) => {\n const input = parseTraceInput(\n 'viewTrace',\n traceStoreInputSchemas.viewTrace.omit({ per_attribute_byte_cap: true }),\n args,\n )\n return store.viewTrace(input, context)\n },\n },\n {\n namespace: TRACE_ANALYST_TOOL_NAMESPACE,\n name: 'viewSpans',\n description:\n `Read 1..${TRACE_ANALYSIS_LIMITS.viewSpans} specific spans. Every requested id is ` +\n 'accounted for in spans, missing_span_ids, or omitted_span_ids; retry omitted ids.',\n parameters: toTraceJsonSchema(\n traceStoreInputSchemas.viewSpans.omit({\n per_attribute_byte_cap: true,\n }),\n ),\n handler: async (args, context) => {\n const input = parseTraceInput(\n 'viewSpans',\n traceStoreInputSchemas.viewSpans.omit({ per_attribute_byte_cap: true }),\n args,\n )\n return store.viewSpans(input, context)\n },\n },\n {\n namespace: TRACE_ANALYST_TOOL_NAMESPACE,\n name: 'searchTrace',\n description:\n `Regex search across one trace, bounded to ${TRACE_ANALYSIS_LIMITS.searchMatches} hits. ` +\n 'When has_more is true, refine the regex instead of treating the result as complete.',\n parameters: toTraceJsonSchema(traceStoreInputSchemas.searchTrace),\n handler: async (args, context) => {\n const input = parseTraceInput('searchTrace', traceStoreInputSchemas.searchTrace, args)\n return store.searchTrace(input, context)\n },\n },\n {\n namespace: TRACE_ANALYST_TOOL_NAMESPACE,\n name: 'searchSpan',\n description:\n `Regex search inside one span, bounded to ${TRACE_ANALYSIS_LIMITS.searchMatches} hits. ` +\n 'Use after viewSpans omits or truncates a large span payload.',\n parameters: toTraceJsonSchema(traceStoreInputSchemas.searchSpan),\n handler: async (args, context) => {\n const input = parseTraceInput('searchSpan', traceStoreInputSchemas.searchSpan, args)\n return store.searchSpan(input, context)\n },\n },\n ]\n}\n\nexport function traceAnalystFunctionGroup(options: BuildTraceAnalysisToolsOptions): {\n namespace: string\n title: string\n selectionCriteria: string\n description: string\n functions: TraceAnalysisToolDescriptor[]\n} {\n return {\n namespace: TRACE_ANALYST_TOOL_NAMESPACE,\n title: 'Trace Analysis',\n selectionCriteria: 'Use for any inspection of OTLP-shaped trace data.',\n description:\n 'Discovery, narrowing, and bounded deep reads over a JSONL trace dataset. ' +\n 'Always call getDatasetOverview first.',\n functions: buildTraceAnalysisToolDescriptors(options),\n }\n}\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`, schema, handler, and\n * description from `buildTraceAnalysisToolDescriptors`.\n */\n\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport {\n buildTraceAnalysisToolDescriptors,\n type TraceAnalysisToolDescriptor,\n} 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 the canonical descriptors\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): TraceAnalysisToolDescriptor[] {\n const all = buildTraceAnalysisToolDescriptors({ 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.name))\n}\n","import { CostLedger } from '../cost-ledger'\nimport { hashCanonical } from '../ledger-core/canonical'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { TraceAnalysisEngine, TraceAnalysisEngineResult, TraceAnalystLimits } from './engine'\nimport { resolveTraceAnalystLimits } from './engine'\nimport { type ExactCapableAnalyst, snapshotExactExecutionComponentIdentity } from './exact-types'\nimport {\n evidenceRefsFromRawFinding,\n parseRawFinding,\n parseTraceSpanEvidenceUri,\n RAW_FINDING_SCHEMA_PROMPT,\n type RawAnalystFinding,\n} from './finding-signature'\nimport { KIND_EXPECTED_SUBJECTS, parseFindingSubject } from './finding-subject'\nimport { buildTraceToolsForGroup, type TraceToolGroupName } from './tool-groups'\nimport type { AnalystContext, AnalystFinding } from './types'\nimport { makeFinding } from './types'\nimport { settleUsageReceiptFromCostLedger, validateUsageSettlementTimeout } from './usage-receipt'\n\n/** A named research question independent of the recursive engine that runs it. */\nexport interface TraceAnalystDefinition {\n id: string\n description: string\n area: string\n version: string\n /** User-facing question. A function may derive it from run context. */\n question?: string | ((context: AnalystContext) => string)\n /** Research policy, evidence rules, and domain-specific instructions. */\n instructions: string\n /** Smallest trace-tool set that can answer the question. */\n toolGroup: TraceToolGroupName\n /** Optional bounded context assembled deterministically before the investigation. */\n prepareContext?: (\n store: TraceAnalysisStore,\n context: AnalystContext,\n ) => string | undefined | Promise<string | undefined>\n limits?: Partial<TraceAnalystLimits>\n postProcess?: (row: RawAnalystFinding, context: AnalystContext) => RawAnalystFinding | null\n minimumEvidenceCitations?: number\n requireStructuredFindings?: boolean\n}\n\nexport interface CreateTraceAnalystOptions {\n engine: TraceAnalysisEngine\n /** Override the definition's `version` (e.g. when an optimizer has fitted new instructions). */\n versionSuffix?: string\n settlementTimeoutMs?: number\n}\n\n/** Run one definition and retain its answer, findings, and full investigation record. */\nexport async function runTraceAnalyst(args: {\n definition: TraceAnalystDefinition\n engine: TraceAnalysisEngine\n store: TraceAnalysisStore\n context: AnalystContext\n settlementTimeoutMs?: number\n}): Promise<TraceAnalysisEngineResult> {\n const { definition, context } = args\n validateDefinition(definition)\n const minimumEvidenceCitations = definition.minimumEvidenceCitations ?? 1\n const settlementTimeoutMs = validateUsageSettlementTimeout(args.settlementTimeoutMs)\n const costLedger = context.costLedger ?? new CostLedger(context.budgetUsd)\n const costTags = {\n ...(context.tags ?? {}),\n analystId: definition.id,\n ...(context.correlationId ? { analystRunId: context.correlationId } : {}),\n }\n\n try {\n const preparedContext = await definition.prepareContext?.(args.store, context)\n if (preparedContext !== undefined && typeof preparedContext !== 'string') {\n throw new TypeError(`trace analyst '${definition.id}' prepareContext must return a string`)\n }\n const instructions = [\n definition.instructions.trim(),\n renderPriorFindings(context.priorFindings),\n renderUpstreamFindings(context.upstreamFindings),\n RAW_FINDING_SCHEMA_PROMPT,\n minimumEvidenceCitations > 1\n ? `Every finding requires at least ${minimumEvidenceCitations} distinct evidence citations.`\n : '',\n preparedContext ? `PREPARED CONTEXT:\\n${preparedContext}` : '',\n 'Return a direct prose answer and a strict findings array. Use trace tools to investigate. Do not infer trace facts from the question alone.',\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n const completed = await args.engine.analyze({\n analystId: definition.id,\n question: deriveQuestion(context, definition),\n instructions,\n tools: buildTraceToolsForGroup(definition.toolGroup, args.store),\n limits: resolveTraceAnalystLimits(definition.limits),\n costLedger,\n costPhase: context.costPhase ?? 'trace-analysis',\n costTags,\n ...(context.signal ? { signal: context.signal } : {}),\n ...(context.log ? { log: context.log } : {}),\n })\n const findings = await acceptFindings(\n definition,\n completed.findings,\n args.store,\n context,\n minimumEvidenceCitations,\n )\n if (definition.requireStructuredFindings && findings.length === 0) {\n throw new Error(\n `trace analyst '${definition.id}' returned no valid structured findings: ${truncateForContext(completed.answer, 600)}`,\n )\n }\n context.log?.(`trace analyst ${definition.id} completed`, {\n engine: args.engine.id,\n model_calls: completed.modelCalls,\n tool_calls: completed.toolCalls,\n submitted_findings: completed.findings.length,\n accepted_findings: findings.length,\n })\n return { ...completed, findings }\n } finally {\n const usage = await settleUsageReceiptFromCostLedger(costLedger, {\n channel: 'analyst',\n tags: costTags,\n timeoutMs: settlementTimeoutMs,\n })\n if (!usage.settled) {\n context.log?.(`trace analyst ${definition.id} provider settlement timed out`, {\n pending_calls: usage.pendingCalls,\n timeout_ms: settlementTimeoutMs,\n })\n }\n context.recordUsage?.(usage.receipt)\n }\n}\n\n/** Adapt a research definition to the common Analyst registry contract. */\nexport function createTraceAnalyst(\n definition: TraceAnalystDefinition,\n options: CreateTraceAnalystOptions,\n): ExactCapableAnalyst<TraceAnalysisStore> {\n validateDefinition(definition)\n const version = options.versionSuffix\n ? `${definition.version}+${options.versionSuffix}`\n : definition.version\n const settlementTimeoutMs = validateUsageSettlementTimeout(options.settlementTimeoutMs)\n // Resolve once: the sealed digest and the executed request must not drift.\n const limits = resolveTraceAnalystLimits(definition.limits)\n const engineIdentity = snapshotExactExecutionComponentIdentity(\n {\n id: options.engine.id,\n version: options.engine.version,\n config: options.engine.executionConfig,\n },\n 'createTraceAnalyst engine',\n )\n return {\n id: definition.id,\n description: definition.description,\n inputKind: 'trace-store',\n cost: {\n kind: 'llm',\n ...(options.engine.model ? { models: [options.engine.model] } : {}),\n settlement_timeout_ms: settlementTimeoutMs,\n },\n version,\n executionConfig: {\n kind: 'trace-analyst',\n model: options.engine.model ?? null,\n engine: options.engine.id,\n engine_identity: engineIdentity,\n instructions_digest: hashCanonical(definition.instructions.trim()),\n question:\n typeof definition.question === 'string'\n ? hashCanonical(definition.question.trim())\n : definition.question === undefined\n ? 'context-derived'\n : 'version-bound',\n tool_group: definition.toolGroup,\n max_iterations: limits.maxIterations,\n max_llm_calls: limits.maxLlmCalls,\n max_tool_calls: limits.maxToolCalls,\n max_output_chars: limits.maxOutputChars,\n minimum_evidence_citations: definition.minimumEvidenceCitations ?? 1,\n require_structured_findings: definition.requireStructuredFindings ?? false,\n prepare_context: definition.prepareContext === undefined ? 'disabled' : 'version-bound',\n post_process: definition.postProcess === undefined ? 'disabled' : 'version-bound',\n evidence_verification: EVIDENCE_VERIFICATION_VERSION,\n settlement_timeout_ms: settlementTimeoutMs,\n },\n async analyze(store, context) {\n const completed = await runTraceAnalyst({\n definition,\n engine: options.engine,\n store,\n context,\n settlementTimeoutMs: options.settlementTimeoutMs,\n })\n return completed.findings.map((finding) =>\n toAnalystFinding(definition, version, finding, {\n analysis_engine: options.engine.id,\n ...(options.engine.model === undefined ? {} : { analysis_model: options.engine.model }),\n analysis_model_calls: completed.modelCalls,\n analysis_tool_calls: completed.toolCalls,\n analysis_runtime: completed.runtime,\n }),\n )\n },\n }\n}\n\nasync function acceptFindings(\n definition: TraceAnalystDefinition,\n submitted: readonly unknown[],\n store: TraceAnalysisStore,\n context: AnalystContext,\n minimumEvidenceCitations: number,\n): Promise<RawAnalystFinding[]> {\n const expectedSubjects = KIND_EXPECTED_SUBJECTS[definition.id]\n const accepted: RawAnalystFinding[] = []\n for (const row of submitted) {\n const parsed = parseRawFinding(row, context.log)\n if (!parsed) continue\n const processed = definition.postProcess ? definition.postProcess(parsed, context) : parsed\n if (!processed) continue\n const validated = parseRawFinding(processed, context.log)\n if (!validated) continue\n if (expectedSubjects && validated.subject !== undefined) {\n const subject = parseFindingSubject(validated.subject)\n if (subject === null || !expectedSubjects.includes(subject.kind)) {\n context.log?.('finding rejected: subject is not valid for analyst', {\n analyst_id: definition.id,\n subject: validated.subject,\n allowed: expectedSubjects,\n })\n continue\n }\n }\n const distinctEvidence = new Set(validated.evidence.map((citation) => citation.uri.trim())).size\n if (distinctEvidence < minimumEvidenceCitations) {\n context.log?.('finding rejected: insufficient evidence citations', {\n analyst_id: definition.id,\n required: minimumEvidenceCitations,\n distinct: distinctEvidence,\n })\n continue\n }\n if (!(await evidenceIsResolvable(validated, store, context))) continue\n accepted.push(validated)\n }\n return accepted\n}\n\nasync function evidenceIsResolvable(\n finding: RawAnalystFinding,\n store: TraceAnalysisStore,\n context: AnalystContext,\n): Promise<boolean> {\n const knownFindings = new Map(\n [...(context.priorFindings ?? []), ...(context.upstreamFindings ?? [])].map((entry) => [\n entry.finding_id,\n entry,\n ]),\n )\n for (const citation of finding.evidence) {\n if (citation.excerpt !== undefined && citation.excerpt.trim().length < MINIMUM_EXCERPT_LENGTH) {\n rejectEvidence(context, citation.uri, 'excerpt is too short to verify')\n return false\n }\n const traceLocation = parseTraceSpanEvidenceUri(citation.uri)\n if (traceLocation) {\n const storeContext = context.signal ? { signal: context.signal } : undefined\n const existing = await store.hasSpans(\n {\n trace_id: traceLocation.traceId,\n span_ids: [traceLocation.spanId],\n },\n storeContext,\n )\n if (!existing.includes(traceLocation.spanId)) {\n rejectEvidence(context, citation.uri, 'trace span does not exist')\n return false\n }\n if (citation.excerpt !== undefined) {\n const viewed = await store.viewSpans(\n {\n trace_id: traceLocation.traceId,\n span_ids: [traceLocation.spanId],\n },\n storeContext,\n )\n const span = viewed.spans.find((entry) => entry.span_id === traceLocation.spanId)\n if (!span || !containsExactText([span.attributes, span.status_message], citation.excerpt)) {\n rejectEvidence(context, citation.uri, 'excerpt is not present in the cited span content')\n return false\n }\n }\n continue\n }\n\n const findingId = parseFindingEvidenceUri(citation.uri)\n const referenced = findingId ? knownFindings.get(findingId) : undefined\n if (!referenced) {\n rejectEvidence(context, citation.uri, 'citation is not a supplied finding or trace span')\n return false\n }\n if (\n citation.excerpt !== undefined &&\n !containsExactText(\n [\n referenced.claim,\n referenced.rationale,\n referenced.recommended_action,\n referenced.validation_plan,\n referenced.evidence_refs?.map((evidence) => evidence.excerpt),\n ],\n citation.excerpt,\n )\n ) {\n rejectEvidence(context, citation.uri, 'excerpt is not present in the cited finding content')\n return false\n }\n }\n return true\n}\n\nfunction parseFindingEvidenceUri(uri: string): string | null {\n const match = /^finding:\\/\\/([^/?#]+)$/.exec(uri)\n if (!match) return null\n try {\n return decodeURIComponent(match[1]!) || null\n } catch {\n return null\n }\n}\n\n/** Excerpts must quote enough content to be checkable evidence, not an\n * incidental substring of an id, status, or timestamp. */\nconst MINIMUM_EXCERPT_LENGTH = 8\n\n/** Bumped whenever the evidence-acceptance rules change, so two differently\n * strict builds cannot seal identical execution plans. */\nconst EVIDENCE_VERIFICATION_VERSION = 'resolvable-excerpt-v1'\n\n/** Matches only within the passed content-bearing values — callers must not\n * hand this whole spans or findings, or identifier fields become quotable. */\nfunction containsExactText(value: unknown, expected: string, depth = 0): boolean {\n if (!expected || depth > 20) return false\n if (typeof value === 'string') return value.includes(expected)\n if (Array.isArray(value)) {\n return value.some((entry) => containsExactText(entry, expected, depth + 1))\n }\n if (typeof value === 'object' && value !== null) {\n return Object.values(value).some((entry) => containsExactText(entry, expected, depth + 1))\n }\n return false\n}\n\nfunction rejectEvidence(context: AnalystContext, uri: string, reason: string): void {\n context.log?.('finding rejected: unresolved evidence', { uri, reason })\n}\n\nfunction validateDefinition(definition: TraceAnalystDefinition): void {\n for (const [name, value] of [\n ['id', definition.id],\n ['description', definition.description],\n ['area', definition.area],\n ['version', definition.version],\n ['instructions', definition.instructions],\n ] as const) {\n if (typeof value !== 'string' || !value.trim()) {\n throw new TypeError(`trace analyst ${name} must be a non-empty string`)\n }\n }\n const minimumEvidenceCitations = definition.minimumEvidenceCitations ?? 1\n if (!Number.isSafeInteger(minimumEvidenceCitations) || minimumEvidenceCitations < 1) {\n throw new TypeError('minimumEvidenceCitations must be a positive safe integer')\n }\n resolveTraceAnalystLimits(definition.limits)\n}\n\nfunction deriveQuestion(context: AnalystContext, definition: TraceAnalystDefinition): string {\n const supplied =\n typeof definition.question === 'function' ? definition.question(context) : definition.question\n const base =\n supplied?.trim() ||\n `Analyze this trace dataset and report ${definition.area} findings. ${definition.description}`\n const focus = context.tags?.focus?.trim()\n return focus ? `${base}\\nFocus: ${focus}` : base\n}\n\nfunction toAnalystFinding(\n definition: TraceAnalystDefinition,\n version: string,\n raw: RawAnalystFinding,\n metadata: Record<string, unknown>,\n): AnalystFinding {\n return makeFinding({\n analyst_id: definition.id,\n area: definition.area,\n claim: raw.claim,\n severity: raw.severity,\n confidence: raw.confidence,\n evidence_refs: evidenceRefsFromRawFinding(raw),\n ...(raw.subject === undefined ? {} : { subject: raw.subject }),\n ...(raw.rationale === undefined ? {} : { rationale: raw.rationale }),\n ...(raw.recommended_action === undefined ? {} : { recommended_action: raw.recommended_action }),\n metadata: { definition_version: version, ...metadata },\n })\n}\n\nexport function renderPriorFindings(prior: AnalystContext['priorFindings']): string {\n if (!prior || prior.length === 0) return ''\n const maxRows = 40\n const rows = prior.slice(0, maxRows).map((finding) => {\n const subject = finding.subject ? ` [${finding.subject}]` : ''\n return `- id=${finding.finding_id} ${finding.severity}${subject} ${truncateForContext(finding.claim, 160)}`\n })\n if (prior.length > maxRows) rows.push(`- ${prior.length - maxRows} older findings omitted`)\n return [\n 'PRIOR FINDINGS:',\n 'Reuse a matching finding id through id_basis and raise confidence only when current evidence confirms recurrence.',\n ...rows,\n ].join('\\n')\n}\n\nfunction renderUpstreamFindings(upstream: AnalystContext['upstreamFindings']): string {\n if (!upstream || upstream.length === 0) return ''\n const maxRows = 40\n const rows = upstream.slice(0, maxRows).map((finding) => {\n const subject = finding.subject ? ` [${finding.subject}]` : ''\n const evidence = finding.evidence_refs[0]?.uri\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)}${evidence}`\n })\n if (upstream.length > maxRows) {\n rows.push(`- ${upstream.length - maxRows} additional upstream findings omitted`)\n }\n return [\n 'UPSTREAM FINDINGS:',\n 'Build on these findings instead of repeating them. Cite dependencies as finding://<id>.',\n ...rows,\n ].join('\\n')\n}\n\nfunction truncateForContext(value: string, max: number): string {\n if (value.length <= max) return value\n return `${value.slice(0, max - 3).trimEnd()}...`\n}\n"],"mappings":";;;;;;;;;AAmCA,SAAgB,wCACd,OACA,SACiC;CACjC,IAAI;CACJ,IAAI;EACF,WAAW,KAAK,MAAM,gBAAgB,KAAK,CAAC;CAC9C,SAAS,OAAO;EACd,MAAM,IAAI,UAAU,GAAG,QAAQ,6CAA6C,EAAE,MAAM,CAAC;CACvF;CACA,MAAM,SAAS,wBAAwB,UAAU,QAAQ;CACzD,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,UAAU,GAAG,QAAQ,iDAAiD;CAElF,OAAO,wBAAwB;EAC7B,IAAI,OAAO,KAAK;EAChB,SAAS,OAAO,KAAK;EACrB,eAAe,cAAc,OAAO,KAAK,MAAM;CACjD,CAAC;AACH;AAyCA,MAAM,iBAAiB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;AACvC,MAAM,SAAS,EAAE,OAAO,CAAC,CAAC,MAAM,uBAAuB;AACvD,MAAM,oBAAoB,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,YAAY;AAC1D,MAAM,yBAAyB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,OAAO,gBAAgB;AAClF,MAAM,kBAAkB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,IAAI,UAAa;AAErE,MAAM,0BAA0B,EAAE,aAAa;CAC7C,IAAI;CACJ,SAAS;CACT,eAAe;AACjB,CAAC;AACD,MAAM,0BAA0B,EAAE,aAAa;CAC7C,IAAI;CACJ,SAAS;CACT,QAAQ,EAAE,OAAO,EAA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AU,KAAK,QAAQ,QAAQ,KAAK;EAC5D,OAAO,QAAQ,QAAQ,WAAW,GAAG,QAAQ,WAAW,QAAQ,GAAG,mBAAmB,QAAQ,OAAO,GAAG;CAC1G,CAAC;CACD,IAAI,MAAM,SAAS,SAAS,KAAK,KAAK,KAAK,MAAM,SAAS,QAAQ,wBAAwB;CAC1F,OAAO;EACL;EACA;EACA,GAAG;CACL,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAAS,uBAAuB,UAAsD;CACpF,IAAI,CAAC,YAAY,SAAS,WAAW,GAAG,OAAO;CAC/C,MAAM,UAAU;CAChB,MAAM,OAAO,SAAS,MAAM,GAAG,OAAO,CAAC,CAAC,KAAK,YAAY;EACvD,MAAM,UAAU,QAAQ,UAAU,KAAK,QAAQ,QAAQ,KAAK;EAC5D,MAAM,WAAW,QAAQ,cAAc,EAAE,EAAE,MACvC,aAAa,mBAAmB,QAAQ,cAAc,EAAE,CAAC,KAAK,GAAG,MACjE;EACJ,OAAO,QAAQ,QAAQ,WAAW,UAAU,QAAQ,WAAW,GAAG,QAAQ,WAAW,QAAQ,SAAS,mBAAmB,QAAQ,OAAO,GAAG,IAAI;CACjJ,CAAC;CACD,IAAI,SAAS,SAAS,SACpB,KAAK,KAAK,KAAK,SAAS,SAAS,QAAQ,sCAAsC;CAEjF,OAAO;EACL;EACA;EACA,GAAG;CACL,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAAS,mBAAmB,OAAe,KAAqB;CAC9D,IAAI,MAAM,UAAU,KAAK,OAAO;CAChC,OAAO,GAAG,MAAM,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,QAAQ,EAAE;AAC9C"}
|
|
@@ -277,11 +277,18 @@ function assertCrossFamilyServed(pairs, opts = {}) {
|
|
|
277
277
|
//#endregion
|
|
278
278
|
//#region src/llm-client.ts
|
|
279
279
|
/**
|
|
280
|
-
*
|
|
280
|
+
* OpenAI-compatible client. The CLASS is internal; one transport now drives it
|
|
281
|
+
* for public callers.
|
|
281
282
|
*
|
|
282
|
-
* agent-eval
|
|
283
|
-
*
|
|
284
|
-
*
|
|
283
|
+
* agent-eval never goes looking for a credential — it reads no environment
|
|
284
|
+
* variable to find one — and this module is still not reachable through any
|
|
285
|
+
* export subpath. What reaches a consumer is `createChatClient({ transport:
|
|
286
|
+
* 'openai-compatible', baseUrl, apiKey })`, the sanctioned public route, which
|
|
287
|
+
* constructs this client from an endpoint and a credential the caller passed as
|
|
288
|
+
* values. Anything richer than that transport's options stays in-repo.
|
|
289
|
+
*
|
|
290
|
+
* Three in-repo callers hold the class directly:
|
|
291
|
+
* - `src/analyst/chat-client.ts`, the public transport above;
|
|
285
292
|
* - the `agent-eval` binary (`src/cli-config.ts`), a deployed server whose
|
|
286
293
|
* caller is a JSON-RPC client in another language and which therefore
|
|
287
294
|
* configures its own endpoint from its own environment;
|
|
@@ -973,4 +980,4 @@ var LlmClient = class {
|
|
|
973
980
|
//#endregion
|
|
974
981
|
export { judgeFamily as S, assertServedModels as _, callLlmJson as a, CrossFamilyError as b, extractJsonPayload as c, stripFencedJson as d, ModelSubstitutionError as f, assertServedModelPolicy as g, assertServedModel as h, backoffMs as i, isTransientLlmError as l, assertCrossFamilyServed as m, LlmClient as n, costReceiptFromLlm as o, ServedCrossFamilyError as p, LlmResponseError as r, costReceiptFromLlmError as s, LlmCallError as t, maximumChargeForLlmRequest as u, checkServedModel as v, assertCrossFamily as x, servedModelAcceptable as y };
|
|
975
982
|
|
|
976
|
-
//# sourceMappingURL=llm-client-
|
|
983
|
+
//# sourceMappingURL=llm-client-CxQtdtd6.js.map
|