@tangle-network/agent-eval 0.137.0 → 0.139.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +78 -0
- package/README.md +34 -0
- package/dist/analyst/index.d.ts +485 -104
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +10 -607
- package/dist/analyst/index.js.map +1 -1
- package/dist/{benchmark-YDrpumqB.js → benchmark-CYtcIF2V.js} +299 -159
- package/dist/benchmark-CYtcIF2V.js.map +1 -0
- package/dist/{benchmark-CHX4orG7.d.ts → benchmark-DDVdWcwA.d.ts} +67 -15
- package/dist/benchmark-DDVdWcwA.d.ts.map +1 -0
- package/dist/benchmark-command-BKfjOBJ5.js +4537 -0
- package/dist/benchmark-command-BKfjOBJ5.js.map +1 -0
- package/dist/benchmarks/index.d.ts +1 -1
- package/dist/benchmarks/index.js +1 -1
- package/dist/{benchmarks-DCLkQOmc.js → benchmarks-zxhy1QV3.js} +4 -3
- package/dist/{benchmarks-DCLkQOmc.js.map → benchmarks-zxhy1QV3.js.map} +1 -1
- package/dist/campaign/index.d.ts +5 -5
- package/dist/campaign/index.js +4 -3
- package/dist/{campaign-lgObcHFC.js → campaign-DrS6_hLd.js} +19 -11
- package/dist/campaign-DrS6_hLd.js.map +1 -0
- package/dist/canonical-D011XM8r.js +86 -0
- package/dist/canonical-D011XM8r.js.map +1 -0
- package/dist/cli.js +10 -3
- package/dist/cli.js.map +1 -1
- package/dist/{client-C8L6h6Wf.d.ts → client-BohnDFBq.d.ts} +4 -4
- package/dist/{client-C8L6h6Wf.d.ts.map → client-BohnDFBq.d.ts.map} +1 -1
- package/dist/{completion-verifier-DSyRNVzU.d.ts → completion-verifier-IPoP4fQO.d.ts} +178 -4
- package/dist/completion-verifier-IPoP4fQO.d.ts.map +1 -0
- package/dist/contract/index.d.ts +10 -10
- package/dist/contract/index.js +9 -8
- package/dist/contract/index.js.map +1 -1
- package/dist/control.d.ts +2 -2
- package/dist/{cost-ledger-D-5_-dhi.js → cost-ledger-CZ9diLxY.js} +90 -45
- package/dist/cost-ledger-CZ9diLxY.js.map +1 -0
- package/dist/{cost-ledger-D2o6JOrL.d.ts → cost-ledger-DKgyIWRj.d.ts} +6 -2
- package/dist/cost-ledger-DKgyIWRj.d.ts.map +1 -0
- package/dist/default-registry-B8vf7Rmf.d.ts +118 -0
- package/dist/default-registry-B8vf7Rmf.d.ts.map +1 -0
- package/dist/default-registry-BgJJItGr.js +2364 -0
- package/dist/default-registry-BgJJItGr.js.map +1 -0
- package/dist/dspy-rlm-engine-DTkVyDX-.js +344 -0
- package/dist/dspy-rlm-engine-DTkVyDX-.js.map +1 -0
- package/dist/{eval-campaign-CHqfLnff.js → eval-campaign-BmptJj50.js} +2 -2
- package/dist/{eval-campaign-CHqfLnff.js.map → eval-campaign-BmptJj50.js.map} +1 -1
- package/dist/exact-types-MaaFcllV.d.ts +234 -0
- package/dist/exact-types-MaaFcllV.d.ts.map +1 -0
- package/dist/external-optimizer-contracts-BrxY2Sli.d.ts +32 -0
- package/dist/external-optimizer-contracts-BrxY2Sli.d.ts.map +1 -0
- package/dist/{extract-usage-p-56bh8q.js → extract-usage-DZs601Va.js} +2 -2
- package/dist/{extract-usage-p-56bh8q.js.map → extract-usage-DZs601Va.js.map} +1 -1
- package/dist/{feedback-trajectory-N_F0PwHz.d.ts → feedback-trajectory-BJUWOkJM.d.ts} +3 -2
- package/dist/feedback-trajectory-BJUWOkJM.d.ts.map +1 -0
- package/dist/fuzz.d.ts +1 -1
- package/dist/fuzz.js +1 -1
- package/dist/{hf-dataset-DBJXXoY1.js → hf-dataset-XggBupCr.js} +2 -2
- package/dist/{hf-dataset-DBJXXoY1.js.map → hf-dataset-XggBupCr.js.map} +1 -1
- package/dist/hosted/index.d.ts +3 -3
- package/dist/{index-C-Pr4OWg.d.ts → index-BTm_P9aC.d.ts} +12 -11
- package/dist/index-BTm_P9aC.d.ts.map +1 -0
- package/dist/{index-U3RHOShi.d.ts → index-CWOPCJiw.d.ts} +2 -2
- package/dist/{index-U3RHOShi.d.ts.map → index-CWOPCJiw.d.ts.map} +1 -1
- package/dist/{index-DRNl6g_N.d.ts → index-CtR1xh4V.d.ts} +3 -3
- package/dist/{index-DRNl6g_N.d.ts.map → index-CtR1xh4V.d.ts.map} +1 -1
- package/dist/index-DEb46kc6.d.ts.map +1 -1
- package/dist/{index-BnP1QJUv.d.ts → index-_66rVpwN.d.ts} +5 -5
- package/dist/{index-BnP1QJUv.d.ts.map → index-_66rVpwN.d.ts.map} +1 -1
- package/dist/index.d.ts +35 -55
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +55 -514
- package/dist/index.js.map +1 -1
- package/dist/{insight-report-B9ooYH_g.d.ts → insight-report-Bu5Wi9tG.d.ts} +4 -4
- package/dist/{insight-report-B9ooYH_g.d.ts.map → insight-report-Bu5Wi9tG.d.ts.map} +1 -1
- package/dist/{integrity-CKxosZ5Z.d.ts → integrity-COTh3DTH.d.ts} +2 -2
- package/dist/{integrity-CKxosZ5Z.d.ts.map → integrity-COTh3DTH.d.ts.map} +1 -1
- package/dist/kind-factory-CFxA0JQX.js +2133 -0
- package/dist/kind-factory-CFxA0JQX.js.map +1 -0
- package/dist/ledger-core/index.js +2 -1
- package/dist/{ledger-core-t6sItivm.js → ledger-core-Dxz0Rkwa.js} +210 -99
- package/dist/ledger-core-Dxz0Rkwa.js.map +1 -0
- package/dist/{llm-client-DKB25jV8.js → llm-client-bkztEfIx.js} +5 -5
- package/dist/llm-client-bkztEfIx.js.map +1 -0
- package/dist/meta-eval/index.d.ts +2 -2
- package/dist/multishot/index.d.ts +2 -2
- package/dist/openapi.json +1 -1
- package/dist/{proposal-findings-DCawte-y.js → proposal-findings-2GIUo1et.js} +2 -68
- package/dist/proposal-findings-2GIUo1et.js.map +1 -0
- package/dist/{release-report-CofgVNZt.d.ts → release-report-fZarvIm-.d.ts} +3 -3
- package/dist/{release-report-CofgVNZt.d.ts.map → release-report-fZarvIm-.d.ts.map} +1 -1
- package/dist/{replay-K8FaC0CB.d.ts → replay-DjG4IG60.d.ts} +34 -143
- package/dist/replay-DjG4IG60.d.ts.map +1 -0
- package/dist/{replay-Bju0T8Ls.js → replay-SA4OB7O7.js} +48 -136
- package/dist/replay-SA4OB7O7.js.map +1 -0
- package/dist/reporting.d.ts +4 -4
- package/dist/{researcher-Da0Wj-bt.d.ts → researcher-BxhtGfKa.d.ts} +5 -5
- package/dist/{researcher-Da0Wj-bt.d.ts.map → researcher-BxhtGfKa.d.ts.map} +1 -1
- package/dist/{reward-hacking-CQ3hTCO3.d.ts → reward-hacking-CqSLiV51.d.ts} +2 -2
- package/dist/{reward-hacking-CQ3hTCO3.d.ts.map → reward-hacking-CqSLiV51.d.ts.map} +1 -1
- package/dist/rl.d.ts +5 -5
- package/dist/rl.js +1 -1
- package/dist/rollout/index.d.ts +1 -1
- package/dist/rollout/index.js +2 -2
- package/dist/{rollout-DQFl0UXA.js → rollout-8nj3mYvx.js} +2 -2
- package/dist/{rollout-DQFl0UXA.js.map → rollout-8nj3mYvx.js.map} +1 -1
- package/dist/{rubric-predictive-validity-C4sztLR3.d.ts → rubric-predictive-validity-DQBQj6uV.d.ts} +2 -2
- package/dist/{rubric-predictive-validity-C4sztLR3.d.ts.map → rubric-predictive-validity-DQBQj6uV.d.ts.map} +1 -1
- package/dist/{run-evidence-BDIircdA.d.ts → run-evidence-C4RcRQT5.d.ts} +3 -3
- package/dist/{run-evidence-BDIircdA.d.ts.map → run-evidence-C4RcRQT5.d.ts.map} +1 -1
- package/dist/{run-record-BPCa2rQ8.d.ts → run-record-CztDMXVF.d.ts} +2 -2
- package/dist/{run-record-BPCa2rQ8.d.ts.map → run-record-CztDMXVF.d.ts.map} +1 -1
- package/dist/{semantic-concept-judge-Bz64IckK.js → semantic-concept-judge-BuIJ9IfB.js} +49 -6
- package/dist/semantic-concept-judge-BuIJ9IfB.js.map +1 -0
- package/dist/{server-KjXZZUDX.js → server-DaCpLfi0.js} +3 -3
- package/dist/{server-KjXZZUDX.js.map → server-DaCpLfi0.js.map} +1 -1
- package/dist/single-run-lock-BTTtPZ9N.js +989 -0
- package/dist/single-run-lock-BTTtPZ9N.js.map +1 -0
- package/dist/{skill-usage-CFDLLlhF.d.ts → skill-usage-B-BFS8M2.d.ts} +65 -40
- package/dist/skill-usage-B-BFS8M2.d.ts.map +1 -0
- package/dist/{skillopt-optimization-method-f4o9sUT4.js → skillopt-optimization-method-BbGnCC53.js} +20 -979
- package/dist/skillopt-optimization-method-BbGnCC53.js.map +1 -0
- package/dist/{skillopt-optimization-method-BpbnlvAZ.d.ts → skillopt-optimization-method-_s0Tub7Y.d.ts} +11 -39
- package/dist/skillopt-optimization-method-_s0Tub7Y.d.ts.map +1 -0
- package/dist/{statistics-_7P642CN.d.ts → statistics-B5d0Zd-z.d.ts} +2 -2
- package/dist/{statistics-_7P642CN.d.ts.map → statistics-B5d0Zd-z.d.ts.map} +1 -1
- package/dist/store-otlp-DX4fGIcf.js +757 -0
- package/dist/store-otlp-DX4fGIcf.js.map +1 -0
- package/dist/{summary-report-DHipz9Kx.d.ts → summary-report-Cg7BifAM.d.ts} +3 -3
- package/dist/{summary-report-DHipz9Kx.d.ts.map → summary-report-Cg7BifAM.d.ts.map} +1 -1
- package/dist/tool-groups-CdYq22lX.d.ts +258 -0
- package/dist/tool-groups-CdYq22lX.d.ts.map +1 -0
- package/dist/traces.d.ts +7 -6
- package/dist/traces.js +5 -4
- package/dist/{types-CTGbIm57.d.ts → types-BBFNHxSK.d.ts} +5 -5
- package/dist/{types-CTGbIm57.d.ts.map → types-BBFNHxSK.d.ts.map} +1 -1
- package/dist/{types-CKswbJGO.d.ts → types-DoEYskCd.d.ts} +5 -5
- package/dist/{types-CKswbJGO.d.ts.map → types-DoEYskCd.d.ts.map} +1 -1
- package/dist/{types-CTvKfr5F.d.ts → types-uPrS6mD-.d.ts} +2 -2
- package/dist/{types-CTvKfr5F.d.ts.map → types-uPrS6mD-.d.ts.map} +1 -1
- package/dist/usage-receipt-CgxMEBZq.js +134 -0
- package/dist/usage-receipt-CgxMEBZq.js.map +1 -0
- package/dist/wire/index.d.ts +3 -3
- package/dist/wire/index.js +1 -1
- package/docs/trace-analysis.md +191 -385
- package/package.json +5 -4
- package/dist/analyze-runs-PVtnfjvA.d.ts +0 -72
- package/dist/analyze-runs-PVtnfjvA.d.ts.map +0 -1
- package/dist/benchmark-CHX4orG7.d.ts.map +0 -1
- package/dist/benchmark-YDrpumqB.js.map +0 -1
- package/dist/campaign-lgObcHFC.js.map +0 -1
- package/dist/completion-verifier-DSyRNVzU.d.ts.map +0 -1
- package/dist/concurrency-MUjT7VjM.js +0 -109
- package/dist/concurrency-MUjT7VjM.js.map +0 -1
- package/dist/cost-ledger-D-5_-dhi.js.map +0 -1
- package/dist/cost-ledger-D2o6JOrL.d.ts.map +0 -1
- package/dist/default-registry-CLXbRt0f.js +0 -2594
- package/dist/default-registry-CLXbRt0f.js.map +0 -1
- package/dist/default-registry-Dc5D_Loc.d.ts +0 -202
- package/dist/default-registry-Dc5D_Loc.d.ts.map +0 -1
- package/dist/feedback-trajectory-N_F0PwHz.d.ts.map +0 -1
- package/dist/index-C-Pr4OWg.d.ts.map +0 -1
- package/dist/ledger-core-t6sItivm.js.map +0 -1
- package/dist/llm-client-DKB25jV8.js.map +0 -1
- package/dist/proposal-findings-DCawte-y.js.map +0 -1
- package/dist/registry-BdM7SuTr.d.ts +0 -124
- package/dist/registry-BdM7SuTr.d.ts.map +0 -1
- package/dist/replay-Bju0T8Ls.js.map +0 -1
- package/dist/replay-K8FaC0CB.d.ts.map +0 -1
- package/dist/semantic-concept-judge-Bz64IckK.js.map +0 -1
- package/dist/skill-usage-CFDLLlhF.d.ts.map +0 -1
- package/dist/skillopt-optimization-method-BpbnlvAZ.d.ts.map +0 -1
- package/dist/skillopt-optimization-method-f4o9sUT4.js.map +0 -1
- package/dist/tools-DZk2Jn64.js +0 -1876
- package/dist/tools-DZk2Jn64.js.map +0 -1
|
@@ -1,2594 +0,0 @@
|
|
|
1
|
-
import { i as CostLedger } from "./cost-ledger-D-5_-dhi.js";
|
|
2
|
-
import { f as maximumChargeForLlmRequest, l as costReceiptFromLlm, n as LlmClient, s as callLlm, u as costReceiptFromLlmError } from "./llm-client-DKB25jV8.js";
|
|
3
|
-
import { LLM_CONTEXT_TOKENS, LLM_INPUT_TOKEN_ATTR_KEYS, LLM_OUTPUT_TOKEN_ATTR_KEYS, TOOL_NAME_ATTR_KEYS } from "./trace-attributes.js";
|
|
4
|
-
import { t as executionTrackByLane } from "./execution-tracks-CpgFPpS5.js";
|
|
5
|
-
import { O as spanEpochMillis, a as runTraceAnalysisLoop, r as buildTraceAnalystTools } from "./tools-DZk2Jn64.js";
|
|
6
|
-
import { c as makeFinding, o as combineAbortSignals } from "./proposal-findings-DCawte-y.js";
|
|
7
|
-
import { t as analyzeSupervisorRunIntegrity } from "./integrity-CCXTftiL.js";
|
|
8
|
-
import { ai } from "@ax-llm/ax";
|
|
9
|
-
import { z } from "zod";
|
|
10
|
-
import { randomUUID } from "node:crypto";
|
|
11
|
-
//#region src/analyst/ax-service.ts
|
|
12
|
-
const configuredModels = /* @__PURE__ */ new WeakMap();
|
|
13
|
-
/**
|
|
14
|
-
* Construct the `AxAIService` an analyst kind calls through
|
|
15
|
-
* (`createTraceAnalystKind({ ai })`).
|
|
16
|
-
*
|
|
17
|
-
* Ax's `ai()` pins `config.model` to the OpenAI catalog enum, but every
|
|
18
|
-
* OpenAI-compatible router an analyst points at (router.tangle.tools,
|
|
19
|
-
* cli-bridge) accepts arbitrary model ids (claude-code/sonnet, openai/gpt-5.4,
|
|
20
|
-
* …). Consumers were each re-rolling `ai({ name, apiKey, apiURL, config })`
|
|
21
|
-
* behind an `as (a: any) => any` cast to dodge the enum; this is the one
|
|
22
|
-
* canonical constructor so they don't have to — and don't take a direct
|
|
23
|
-
* `@ax-llm/ax` dependency for it.
|
|
24
|
-
*/
|
|
25
|
-
function createAnalystAi(config) {
|
|
26
|
-
const model = config.model.trim();
|
|
27
|
-
if (!model) throw new TypeError("createAnalystAi: model must be a non-empty string");
|
|
28
|
-
const service = ai({
|
|
29
|
-
name: config.provider ?? "openai",
|
|
30
|
-
apiKey: config.apiKey,
|
|
31
|
-
...config.baseUrl ? { apiURL: config.baseUrl } : {},
|
|
32
|
-
...config.headers ? { headers: config.headers } : {},
|
|
33
|
-
config: { model }
|
|
34
|
-
});
|
|
35
|
-
configuredModels.set(service, model);
|
|
36
|
-
return service;
|
|
37
|
-
}
|
|
38
|
-
function getConfiguredAnalystModel(service) {
|
|
39
|
-
return configuredModels.get(service);
|
|
40
|
-
}
|
|
41
|
-
/** Resolve the model before paid work so every request can be bounded and attributed. */
|
|
42
|
-
function resolveAnalystModel(service, override) {
|
|
43
|
-
if (override !== void 0) {
|
|
44
|
-
const model = override.trim();
|
|
45
|
-
if (!model) throw new TypeError("createTraceAnalystKind: model must be a non-empty string");
|
|
46
|
-
return model;
|
|
47
|
-
}
|
|
48
|
-
const model = getConfiguredAnalystModel(service)?.trim();
|
|
49
|
-
if (!model) throw new TypeError("createTraceAnalystKind: model is required for Ax services not created by createAnalystAi()");
|
|
50
|
-
return model;
|
|
51
|
-
}
|
|
52
|
-
//#endregion
|
|
53
|
-
//#region src/analyst/chat-client.ts
|
|
54
|
-
/**
|
|
55
|
-
* Provider-neutral chat contract for every model call made by agent-eval.
|
|
56
|
-
*
|
|
57
|
-
* Callers choose the transport at the package boundary with `createChatClient`.
|
|
58
|
-
* Evaluation code receives canonical requests and results without importing a
|
|
59
|
-
* provider SDK.
|
|
60
|
-
*/
|
|
61
|
-
/**
|
|
62
|
-
* Build a ChatClient bound to a specific transport. The returned client
|
|
63
|
-
* is safe to share across analysts in a single registry run.
|
|
64
|
-
*/
|
|
65
|
-
function createChatClient(opts) {
|
|
66
|
-
switch (opts.transport) {
|
|
67
|
-
case "router": return wrapLlmClient(opts.transport, opts.defaultModel, new LlmClient({
|
|
68
|
-
baseUrl: opts.baseUrl ?? "https://router.tangle.tools/v1",
|
|
69
|
-
apiKey: opts.apiKey,
|
|
70
|
-
maximumAttempts: opts.maximumAttempts
|
|
71
|
-
}));
|
|
72
|
-
case "cli-bridge": return wrapLlmClient(opts.transport, opts.defaultModel, new LlmClient({
|
|
73
|
-
baseUrl: opts.baseUrl ?? "http://127.0.0.1:3344/v1",
|
|
74
|
-
apiKey: opts.bearer ?? "",
|
|
75
|
-
maximumAttempts: opts.maximumAttempts
|
|
76
|
-
}));
|
|
77
|
-
case "direct-provider": return wrapLlmClient(opts.transport, opts.defaultModel, new LlmClient({
|
|
78
|
-
baseUrl: opts.baseUrl,
|
|
79
|
-
apiKey: opts.apiKey,
|
|
80
|
-
maximumAttempts: opts.maximumAttempts
|
|
81
|
-
}));
|
|
82
|
-
case "sandbox-sdk": return {
|
|
83
|
-
transport: "sandbox-sdk",
|
|
84
|
-
defaultModel: opts.defaultModel,
|
|
85
|
-
maximumAttempts: opts.maximumAttempts,
|
|
86
|
-
chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts)
|
|
87
|
-
};
|
|
88
|
-
case "custom": return {
|
|
89
|
-
transport: "custom",
|
|
90
|
-
defaultModel: opts.defaultModel,
|
|
91
|
-
maximumAttempts: opts.maximumAttempts,
|
|
92
|
-
chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts)
|
|
93
|
-
};
|
|
94
|
-
case "mock": return {
|
|
95
|
-
transport: "mock",
|
|
96
|
-
defaultModel: opts.defaultModel,
|
|
97
|
-
maximumAttempts: 1,
|
|
98
|
-
chat: async (req, callOpts) => opts.handler(resolveModel(req, opts.defaultModel), callOpts)
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
function wrapLlmClient(transport, defaultModel, inner) {
|
|
103
|
-
return {
|
|
104
|
-
transport,
|
|
105
|
-
defaultModel,
|
|
106
|
-
maximumAttempts: inner.maximumAttempts,
|
|
107
|
-
chat: (req, callOpts) => {
|
|
108
|
-
const request = {
|
|
109
|
-
model: resolveModel(req, defaultModel).model,
|
|
110
|
-
messages: req.messages,
|
|
111
|
-
jsonMode: req.jsonMode,
|
|
112
|
-
jsonSchema: req.jsonSchema,
|
|
113
|
-
temperature: req.temperature,
|
|
114
|
-
maxTokens: req.maxTokens,
|
|
115
|
-
thinking: req.thinking,
|
|
116
|
-
timeoutMs: req.timeoutMs
|
|
117
|
-
};
|
|
118
|
-
return inner.call(request, {
|
|
119
|
-
signal: callOpts?.signal,
|
|
120
|
-
idempotencyKey: callOpts?.idempotencyKey
|
|
121
|
-
});
|
|
122
|
-
}
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
function resolveModel(req, defaultModel) {
|
|
126
|
-
if (req.model) return req;
|
|
127
|
-
if (!defaultModel) throw new Error("ChatClient.chat: no model on request and no defaultModel on the client. Either pass req.model or bind defaultModel at createChatClient().");
|
|
128
|
-
return {
|
|
129
|
-
...req,
|
|
130
|
-
model: defaultModel
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
//#endregion
|
|
134
|
-
//#region src/trace-analyst/behavioral-metrics.ts
|
|
135
|
-
/**
|
|
136
|
-
* Deterministic behavioral metrics over OTLP spans — pure arithmetic, no LLM.
|
|
137
|
-
*
|
|
138
|
-
* It computes token growth, output decay, tool monoculture, and missing
|
|
139
|
-
* self-verification once in TypeScript with no model judgment.
|
|
140
|
-
*
|
|
141
|
-
* General, not trace-specific: the detectors key off token trajectories and
|
|
142
|
-
* tool usage present in any agentic OTLP trace, not any one benchmark.
|
|
143
|
-
*/
|
|
144
|
-
/** ≥ this input-token growth ratio across a run, with no compression, fires. */
|
|
145
|
-
const INPUT_GROWTH_FACTOR = 3;
|
|
146
|
-
/** Tool-usage signals need at least this many calls to be meaningful. */
|
|
147
|
-
const MIN_TOOL_CALLS = 3;
|
|
148
|
-
/** Tool names that read or check state count as self-verification, not mutation.
|
|
149
|
-
* Covers the inspect verbs plus the read/search tools real harnesses use to
|
|
150
|
-
* verify (Claude Code Read/Grep/Glob, codex read_file/ls/cat, git status/diff,
|
|
151
|
-
* test/lint). A pure shell tool (Bash/exec_command) is intentionally NOT matched
|
|
152
|
-
* — its name can't tell a `pytest` from an `rm`. */
|
|
153
|
-
const VERIFY_RE = /verif|eval|inspect|check|assert|validat|review|confirm|read|grep|glob|search|view|\blist\b|\bls\b|\bcat\b|\bfind\b|diff|status|\btest|lint|typecheck/i;
|
|
154
|
-
function num(v) {
|
|
155
|
-
return typeof v === "number" && Number.isFinite(v) ? v : null;
|
|
156
|
-
}
|
|
157
|
-
function numAttr(attrs, keys) {
|
|
158
|
-
for (const key of keys) {
|
|
159
|
-
const value = num(attrs[key]);
|
|
160
|
-
if (value !== null) return value;
|
|
161
|
-
}
|
|
162
|
-
return null;
|
|
163
|
-
}
|
|
164
|
-
function inputTokensOf(s) {
|
|
165
|
-
const exactContext = num(s.attributes[LLM_CONTEXT_TOKENS]);
|
|
166
|
-
if (exactContext !== null) return exactContext;
|
|
167
|
-
return numAttr(s.attributes, LLM_INPUT_TOKEN_ATTR_KEYS) ?? num(s.attributes["llm.usage.input_tokens"]);
|
|
168
|
-
}
|
|
169
|
-
function outputTokensOf(s) {
|
|
170
|
-
return numAttr(s.attributes, LLM_OUTPUT_TOKEN_ATTR_KEYS) ?? num(s.attributes["llm.usage.output_tokens"]);
|
|
171
|
-
}
|
|
172
|
-
function stepOf(s) {
|
|
173
|
-
return num(s.attributes.step);
|
|
174
|
-
}
|
|
175
|
-
function toolNameOf(s) {
|
|
176
|
-
if (s.tool_name) return s.tool_name;
|
|
177
|
-
for (const key of TOOL_NAME_ATTR_KEYS) {
|
|
178
|
-
const t = s.attributes[key];
|
|
179
|
-
if (typeof t === "string" && t.length > 0) return t;
|
|
180
|
-
}
|
|
181
|
-
return null;
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Reduce a span list to behavioral metrics + fired suboptimality signals.
|
|
185
|
-
* Pure + deterministic: same spans → same output, on any machine, no model.
|
|
186
|
-
*/
|
|
187
|
-
function computeTraceMetrics(spans) {
|
|
188
|
-
const traceIds = new Set(spans.map((span) => span.trace_id));
|
|
189
|
-
if (traceIds.size > 1) throw new Error(`computeTraceMetrics: expected spans from one trace, received ${traceIds.size} traces`);
|
|
190
|
-
const traceId = traceIds.values().next().value ?? null;
|
|
191
|
-
const samples = spans.map((span) => ({
|
|
192
|
-
span,
|
|
193
|
-
input: inputTokensOf(span),
|
|
194
|
-
output: outputTokensOf(span),
|
|
195
|
-
step: stepOf(span)
|
|
196
|
-
}));
|
|
197
|
-
const llmSamples = samples.filter((sample) => sample.span.kind === "LLM");
|
|
198
|
-
const tokenSamples = llmSamples.length > 0 ? llmSamples : samples.filter((sample) => sample.input !== null || sample.output !== null);
|
|
199
|
-
const tokenSequences = buildTokenSequences(tokenSamples, spans);
|
|
200
|
-
const primarySequence = tokenSequences[0];
|
|
201
|
-
const inputTokenTrajectory = primarySequence?.inputTokenTrajectory.filter((value) => value !== null) ?? [];
|
|
202
|
-
const outputTokenTrajectory = primarySequence?.outputTokenTrajectory.filter((value) => value !== null) ?? [];
|
|
203
|
-
const toolHistogram = {};
|
|
204
|
-
let hasSelfVerification = false;
|
|
205
|
-
for (const s of spans) {
|
|
206
|
-
const tool = toolNameOf(s);
|
|
207
|
-
if (tool) {
|
|
208
|
-
toolHistogram[tool] = (toolHistogram[tool] ?? 0) + 1;
|
|
209
|
-
if (VERIFY_RE.test(tool)) hasSelfVerification = true;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
const totalToolCalls = Object.values(toolHistogram).reduce((a, b) => a + b, 0);
|
|
213
|
-
const distinctTools = Object.keys(toolHistogram).length;
|
|
214
|
-
const toolDiversityRatio = totalToolCalls === 0 ? 1 : distinctTools / totalToolCalls;
|
|
215
|
-
const signals = [];
|
|
216
|
-
const seenTokenSignals = /* @__PURE__ */ new Set();
|
|
217
|
-
for (const sequence of tokenSequences) for (const signal of tokenSignals(sequence)) {
|
|
218
|
-
if (seenTokenSignals.has(signal.code)) continue;
|
|
219
|
-
seenTokenSignals.add(signal.code);
|
|
220
|
-
signals.push(signal);
|
|
221
|
-
}
|
|
222
|
-
if (totalToolCalls >= MIN_TOOL_CALLS && distinctTools === 1) {
|
|
223
|
-
const only = Object.keys(toolHistogram)[0];
|
|
224
|
-
signals.push({
|
|
225
|
-
code: "single-tool-dependency",
|
|
226
|
-
severity: "medium",
|
|
227
|
-
detail: `All ${totalToolCalls} observed tool calls are \`${only}\`; no alternate tool call was observed.`,
|
|
228
|
-
evidence: {
|
|
229
|
-
tool: only,
|
|
230
|
-
calls: totalToolCalls,
|
|
231
|
-
distinct_tools: 1
|
|
232
|
-
}
|
|
233
|
-
});
|
|
234
|
-
}
|
|
235
|
-
if (totalToolCalls >= MIN_TOOL_CALLS && !hasSelfVerification) signals.push({
|
|
236
|
-
code: "no-self-verification",
|
|
237
|
-
severity: "medium",
|
|
238
|
-
detail: `${totalToolCalls} tool calls were observed without a verification-named tool call.`,
|
|
239
|
-
evidence: {
|
|
240
|
-
tool_calls: totalToolCalls,
|
|
241
|
-
verification_calls: 0
|
|
242
|
-
}
|
|
243
|
-
});
|
|
244
|
-
return {
|
|
245
|
-
traceId,
|
|
246
|
-
llmCallCount: tokenSamples.length,
|
|
247
|
-
tokenSequences,
|
|
248
|
-
inputTokenTrajectory,
|
|
249
|
-
outputTokenTrajectory,
|
|
250
|
-
toolHistogram,
|
|
251
|
-
totalToolCalls,
|
|
252
|
-
distinctTools,
|
|
253
|
-
toolDiversityRatio,
|
|
254
|
-
hasSelfVerification,
|
|
255
|
-
signals
|
|
256
|
-
};
|
|
257
|
-
}
|
|
258
|
-
function buildTokenSequences(samples, spans) {
|
|
259
|
-
const executionScopeFor = createTokenExecutionScopeResolver(new Map(spans.map((span) => [span.span_id, span])));
|
|
260
|
-
const scopedSamples = samples.map((sample) => ({
|
|
261
|
-
sample,
|
|
262
|
-
...executionScopeFor(sample.span)
|
|
263
|
-
}));
|
|
264
|
-
const trackByLane = executionTrackByLane(scopedSamples);
|
|
265
|
-
const byTrack = /* @__PURE__ */ new Map();
|
|
266
|
-
for (const scoped of scopedSamples) {
|
|
267
|
-
const trackId = trackByLane.get(scoped.key);
|
|
268
|
-
const track = byTrack.get(trackId) ?? {
|
|
269
|
-
scopeId: scoped.scopeId,
|
|
270
|
-
samples: []
|
|
271
|
-
};
|
|
272
|
-
track.samples.push(scoped.sample);
|
|
273
|
-
byTrack.set(trackId, track);
|
|
274
|
-
}
|
|
275
|
-
const sequences = [];
|
|
276
|
-
for (const { scopeId, samples: tracked } of byTrack.values()) {
|
|
277
|
-
const runs = serialTokenRuns([...tracked].sort(compareTokenSamples));
|
|
278
|
-
runs.forEach((run, index) => {
|
|
279
|
-
sequences.push({
|
|
280
|
-
scopeId: runs.length === 1 ? scopeId : `${scopeId}#${index + 1}`,
|
|
281
|
-
spanIds: run.map((sample) => sample.span.span_id),
|
|
282
|
-
inputTokenTrajectory: run.map((sample) => sample.input),
|
|
283
|
-
outputTokenTrajectory: run.map((sample) => sample.output)
|
|
284
|
-
});
|
|
285
|
-
});
|
|
286
|
-
}
|
|
287
|
-
return sequences.sort((a, b) => b.spanIds.length - a.spanIds.length || a.scopeId.localeCompare(b.scopeId) || a.spanIds[0].localeCompare(b.spanIds[0]));
|
|
288
|
-
}
|
|
289
|
-
function createTokenExecutionScopeResolver(spansById) {
|
|
290
|
-
const cache = /* @__PURE__ */ new Map();
|
|
291
|
-
return (span) => {
|
|
292
|
-
const ancestry = resolveAncestorScope(span.parent_span_id, spansById, cache);
|
|
293
|
-
const rootId = ancestry.rootId;
|
|
294
|
-
const scopeId = ancestry.agentId ? `span:${ancestry.agentId}` : ancestry.missingParentId ? `parent:${ancestry.missingParentId}` : rootId ? `root:${rootId}` : span.agent_name ? `agent:${span.agent_name}` : `trace:${span.trace_id}`;
|
|
295
|
-
const scopeSpanId = ancestry.agentId ?? ancestry.missingParentId ?? rootId;
|
|
296
|
-
const laneSpan = ancestry.laneSpanId ? spansById.get(ancestry.laneSpanId) : void 0;
|
|
297
|
-
const direct = scopeSpanId === null || ancestry.laneSpanId === scopeSpanId;
|
|
298
|
-
const timedSpan = direct ? span : laneSpan;
|
|
299
|
-
return {
|
|
300
|
-
key: JSON.stringify([scopeId, direct ? span.span_id : ancestry.laneSpanId]),
|
|
301
|
-
scopeKey: scopeId,
|
|
302
|
-
scopeId,
|
|
303
|
-
start: timedSpan ? spanEpochMillis(timedSpan.start_time) : null,
|
|
304
|
-
end: timedSpan ? spanEpochMillis(timedSpan.end_time) : null
|
|
305
|
-
};
|
|
306
|
-
};
|
|
307
|
-
}
|
|
308
|
-
function resolveAncestorScope(startId, spansById, cache) {
|
|
309
|
-
const empty = {
|
|
310
|
-
agentId: null,
|
|
311
|
-
rootId: null,
|
|
312
|
-
missingParentId: null,
|
|
313
|
-
laneSpanId: null
|
|
314
|
-
};
|
|
315
|
-
if (!startId) return empty;
|
|
316
|
-
const path = [];
|
|
317
|
-
const pathIndex = /* @__PURE__ */ new Map();
|
|
318
|
-
let currentId = startId;
|
|
319
|
-
let resolved = empty;
|
|
320
|
-
while (currentId) {
|
|
321
|
-
const cached = cache.get(currentId);
|
|
322
|
-
if (cached) {
|
|
323
|
-
resolved = cached;
|
|
324
|
-
break;
|
|
325
|
-
}
|
|
326
|
-
const cycleStart = pathIndex.get(currentId);
|
|
327
|
-
if (cycleStart !== void 0) {
|
|
328
|
-
resolved = {
|
|
329
|
-
agentId: null,
|
|
330
|
-
rootId: [...path.slice(cycleStart)].sort()[0],
|
|
331
|
-
missingParentId: null,
|
|
332
|
-
laneSpanId: [...path.slice(cycleStart)].sort()[0]
|
|
333
|
-
};
|
|
334
|
-
break;
|
|
335
|
-
}
|
|
336
|
-
const current = spansById.get(currentId);
|
|
337
|
-
if (!current) {
|
|
338
|
-
resolved = {
|
|
339
|
-
agentId: null,
|
|
340
|
-
rootId: null,
|
|
341
|
-
missingParentId: currentId,
|
|
342
|
-
laneSpanId: currentId
|
|
343
|
-
};
|
|
344
|
-
break;
|
|
345
|
-
}
|
|
346
|
-
if (current.kind === "AGENT") {
|
|
347
|
-
resolved = {
|
|
348
|
-
agentId: current.span_id,
|
|
349
|
-
rootId: null,
|
|
350
|
-
missingParentId: null,
|
|
351
|
-
laneSpanId: current.span_id
|
|
352
|
-
};
|
|
353
|
-
break;
|
|
354
|
-
}
|
|
355
|
-
pathIndex.set(currentId, path.length);
|
|
356
|
-
path.push(currentId);
|
|
357
|
-
currentId = current.parent_span_id;
|
|
358
|
-
}
|
|
359
|
-
for (let index = path.length - 1; index >= 0; index -= 1) {
|
|
360
|
-
if (resolved.agentId === null && resolved.rootId === null) resolved = {
|
|
361
|
-
...resolved,
|
|
362
|
-
rootId: path[index],
|
|
363
|
-
laneSpanId: path[index]
|
|
364
|
-
};
|
|
365
|
-
else if (resolved.laneSpanId === (resolved.agentId ?? resolved.missingParentId ?? resolved.rootId)) resolved = {
|
|
366
|
-
...resolved,
|
|
367
|
-
laneSpanId: path[index]
|
|
368
|
-
};
|
|
369
|
-
cache.set(path[index], resolved);
|
|
370
|
-
}
|
|
371
|
-
return resolved;
|
|
372
|
-
}
|
|
373
|
-
function compareTokenSamples(a, b) {
|
|
374
|
-
const aStart = spanEpochMillis(a.span.start_time);
|
|
375
|
-
const bStart = spanEpochMillis(b.span.start_time);
|
|
376
|
-
if (aStart === null && bStart !== null) return 1;
|
|
377
|
-
if (aStart !== null && bStart === null) return -1;
|
|
378
|
-
if (aStart !== null && bStart !== null && aStart !== bStart) return aStart - bStart;
|
|
379
|
-
if (a.step !== null && b.step !== null && a.step !== b.step) return a.step - b.step;
|
|
380
|
-
return a.span.span_id.localeCompare(b.span.span_id);
|
|
381
|
-
}
|
|
382
|
-
function serialTokenRuns(ordered) {
|
|
383
|
-
const runs = [];
|
|
384
|
-
let serial = [];
|
|
385
|
-
let overlap = [];
|
|
386
|
-
let overlapEnd = Number.NEGATIVE_INFINITY;
|
|
387
|
-
const flushSerial = () => {
|
|
388
|
-
if (serial.length > 0) runs.push(serial);
|
|
389
|
-
serial = [];
|
|
390
|
-
};
|
|
391
|
-
const flushOverlap = () => {
|
|
392
|
-
if (overlap.length === 1) serial.push(overlap[0]);
|
|
393
|
-
else if (overlap.length > 1) {
|
|
394
|
-
flushSerial();
|
|
395
|
-
for (const sample of overlap) runs.push([sample]);
|
|
396
|
-
}
|
|
397
|
-
overlap = [];
|
|
398
|
-
overlapEnd = Number.NEGATIVE_INFINITY;
|
|
399
|
-
};
|
|
400
|
-
for (const sample of ordered) {
|
|
401
|
-
const start = spanEpochMillis(sample.span.start_time);
|
|
402
|
-
const end = spanEpochMillis(sample.span.end_time);
|
|
403
|
-
if (start === null || end === null || sample.span.duration_ms <= 0 || end < start) {
|
|
404
|
-
flushOverlap();
|
|
405
|
-
flushSerial();
|
|
406
|
-
runs.push([sample]);
|
|
407
|
-
continue;
|
|
408
|
-
}
|
|
409
|
-
if (overlap.length > 0 && start >= overlapEnd) flushOverlap();
|
|
410
|
-
overlap.push(sample);
|
|
411
|
-
overlapEnd = Math.max(overlapEnd, end);
|
|
412
|
-
}
|
|
413
|
-
flushOverlap();
|
|
414
|
-
flushSerial();
|
|
415
|
-
return runs;
|
|
416
|
-
}
|
|
417
|
-
function tokenSignals(sequence) {
|
|
418
|
-
const signals = [];
|
|
419
|
-
const inputs = sequence.inputTokenTrajectory;
|
|
420
|
-
const outputs = sequence.outputTokenTrajectory;
|
|
421
|
-
if (inputs.length >= 3 && inputs.every((value) => value !== null)) {
|
|
422
|
-
const first = inputs[0];
|
|
423
|
-
const last = inputs[inputs.length - 1];
|
|
424
|
-
const isMonotonic = everyAdjacent(inputs, (previous, current) => current >= previous);
|
|
425
|
-
const growthFromZero = first === 0 && last > 0;
|
|
426
|
-
const growth = growthFromZero ? Infinity : first > 0 ? last / first : 0;
|
|
427
|
-
if (isMonotonic && last > first && growth >= INPUT_GROWTH_FACTOR) {
|
|
428
|
-
const growthLabel = growthFromZero ? "0→nonzero (unbounded)" : `${growth.toFixed(1)}x`;
|
|
429
|
-
signals.push({
|
|
430
|
-
code: "monotonic-input-growth",
|
|
431
|
-
severity: "high",
|
|
432
|
-
detail: `LLM input tokens grew ${growthLabel} (${first}→${last}) across ${inputs.length} serial calls without an intervening decrease.`,
|
|
433
|
-
evidence: {
|
|
434
|
-
first,
|
|
435
|
-
last,
|
|
436
|
-
growth_x: growthFromZero ? "unbounded" : Number(growth.toFixed(2)),
|
|
437
|
-
calls: inputs.length,
|
|
438
|
-
scope: sequence.scopeId,
|
|
439
|
-
first_span_id: sequence.spanIds[0],
|
|
440
|
-
last_span_id: sequence.spanIds[sequence.spanIds.length - 1]
|
|
441
|
-
}
|
|
442
|
-
});
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
if (inputs.length >= 3 && inputs.length === outputs.length && inputs.every((value) => value !== null) && outputs.every((value) => value !== null)) {
|
|
446
|
-
const first = outputs[0];
|
|
447
|
-
const last = outputs[outputs.length - 1];
|
|
448
|
-
const inputIsMonotonic = everyAdjacent(inputs, (previous, current) => current >= previous);
|
|
449
|
-
const outputIsMonotonic = everyAdjacent(outputs, (previous, current) => current <= previous);
|
|
450
|
-
const inputGrew = inputs[inputs.length - 1] > inputs[0];
|
|
451
|
-
if (inputIsMonotonic && inputGrew && outputIsMonotonic && last < first) signals.push({
|
|
452
|
-
code: "output-length-decay",
|
|
453
|
-
severity: "medium",
|
|
454
|
-
detail: `LLM output tokens shrank ${first}→${last} over ${outputs.length} serial calls while input tokens increased monotonically.`,
|
|
455
|
-
evidence: {
|
|
456
|
-
first,
|
|
457
|
-
last,
|
|
458
|
-
calls: outputs.length,
|
|
459
|
-
scope: sequence.scopeId,
|
|
460
|
-
first_span_id: sequence.spanIds[0],
|
|
461
|
-
last_span_id: sequence.spanIds[sequence.spanIds.length - 1]
|
|
462
|
-
}
|
|
463
|
-
});
|
|
464
|
-
}
|
|
465
|
-
return signals;
|
|
466
|
-
}
|
|
467
|
-
function everyAdjacent(values, predicate) {
|
|
468
|
-
return values.slice(1).every((current, index) => predicate(values[index], current));
|
|
469
|
-
}
|
|
470
|
-
//#endregion
|
|
471
|
-
//#region src/analyst/behavioral-analyst.ts
|
|
472
|
-
/**
|
|
473
|
-
* Deterministic behavioral analysis over arithmetic in trace spans.
|
|
474
|
-
* This pass is cheap and repeatable; semantic analysis remains the job of
|
|
475
|
-
* model-backed analysts. Relative quality requires a labeled comparison.
|
|
476
|
-
*/
|
|
477
|
-
const RECOMMENDED_ACTION = {
|
|
478
|
-
"monotonic-input-growth": "Inspect context assembly; if prior history is repeatedly included, summarize completed work before the next model call.",
|
|
479
|
-
"output-length-decay": "Check late-step completeness; if shorter responses omit required work, add explicit completion criteria to the agent instructions.",
|
|
480
|
-
"single-tool-dependency": "Test whether an inspect or verification tool improves outcomes after the repeated call fails or returns no progress.",
|
|
481
|
-
"no-self-verification": "After state-changing actions, require an observable check before the agent proceeds."
|
|
482
|
-
};
|
|
483
|
-
const ANALYST_ID$1 = "efficiency-behavioral";
|
|
484
|
-
const DEFAULT_MAX_TRACES = 1e3;
|
|
485
|
-
const DEFAULT_MAX_EVIDENCE_REFS = 20;
|
|
486
|
-
const TRACE_PAGE_SIZE = 200;
|
|
487
|
-
const AGGREGATE_CLAIM = {
|
|
488
|
-
"monotonic-input-growth": (observed, analyzed) => `${observed}/${analyzed} analyzed traces showed input tokens grow from zero to nonzero or to at least 3x their initial value across at least 3 serial model calls without a decrease.`,
|
|
489
|
-
"output-length-decay": (observed, analyzed) => `${observed}/${analyzed} analyzed traces showed output tokens decrease while input tokens increased monotonically across at least 3 serial model calls.`,
|
|
490
|
-
"single-tool-dependency": (observed, analyzed) => `${observed}/${analyzed} analyzed traces used only one named tool across at least 3 tool calls.`,
|
|
491
|
-
"no-self-verification": (observed, analyzed) => `${observed}/${analyzed} analyzed traces had at least 3 tool calls without a verification-named tool call.`
|
|
492
|
-
};
|
|
493
|
-
async function listTraceIds(store, maxTraces, signal) {
|
|
494
|
-
const traceIds = /* @__PURE__ */ new Set();
|
|
495
|
-
let offset = 0;
|
|
496
|
-
let expectedTotal;
|
|
497
|
-
while (true) {
|
|
498
|
-
signal?.throwIfAborted();
|
|
499
|
-
const page = await store.queryTraces({
|
|
500
|
-
limit: TRACE_PAGE_SIZE,
|
|
501
|
-
offset
|
|
502
|
-
});
|
|
503
|
-
if (expectedTotal === void 0) expectedTotal = page.total;
|
|
504
|
-
if (page.total !== expectedTotal) throw new Error(`behavioralAnalyst: trace count changed during pagination (${expectedTotal} to ${page.total})`);
|
|
505
|
-
if (page.total > maxTraces) throw new RangeError(`behavioralAnalyst: ${page.total} traces exceed maxTraces=${maxTraces}; filter the store or raise the explicit limit`);
|
|
506
|
-
for (const trace of page.traces) traceIds.add(trace.trace_id);
|
|
507
|
-
if (traceIds.size > maxTraces) throw new RangeError(`behavioralAnalyst: more than maxTraces=${maxTraces} unique traces were returned`);
|
|
508
|
-
if (!page.has_more) break;
|
|
509
|
-
if (page.traces.length === 0) throw new Error("behavioralAnalyst: trace store returned an empty page with has_more=true");
|
|
510
|
-
offset += page.traces.length;
|
|
511
|
-
}
|
|
512
|
-
if (traceIds.size !== expectedTotal) throw new Error(`behavioralAnalyst: pagination returned ${traceIds.size}/${expectedTotal ?? 0} unique traces`);
|
|
513
|
-
return [...traceIds].sort();
|
|
514
|
-
}
|
|
515
|
-
/**
|
|
516
|
-
* Map computed signals → structured AnalystFindings. Pure: no LLM, no clock
|
|
517
|
-
* dependence beyond `produced_at` (overridable for deterministic tests).
|
|
518
|
-
*/
|
|
519
|
-
function deriveEfficiencyFindings(metrics, opts = {}) {
|
|
520
|
-
const analystId = opts.analystId ?? ANALYST_ID$1;
|
|
521
|
-
const traceId = metrics.traceId;
|
|
522
|
-
return metrics.signals.map((sig) => makeFinding({
|
|
523
|
-
analyst_id: analystId,
|
|
524
|
-
area: "efficiency",
|
|
525
|
-
subject: sig.code,
|
|
526
|
-
claim: sig.detail,
|
|
527
|
-
severity: sig.severity,
|
|
528
|
-
confidence: 1,
|
|
529
|
-
evidence_refs: [{
|
|
530
|
-
kind: "metric",
|
|
531
|
-
uri: traceId ? `metric://trace/${encodeURIComponent(traceId)}/efficiency/${sig.code}` : `metric://efficiency/${sig.code}`,
|
|
532
|
-
excerpt: JSON.stringify(sig.evidence)
|
|
533
|
-
}],
|
|
534
|
-
recommended_action: RECOMMENDED_ACTION[sig.code],
|
|
535
|
-
metadata: {
|
|
536
|
-
deterministic: true,
|
|
537
|
-
evidence: sig.evidence,
|
|
538
|
-
...traceId ? { trace_id: traceId } : {}
|
|
539
|
-
},
|
|
540
|
-
id_basis: sig.code,
|
|
541
|
-
...opts.producedAt ? { produced_at: opts.producedAt } : {}
|
|
542
|
-
}));
|
|
543
|
-
}
|
|
544
|
-
/** The deterministic behavioral/efficiency analyst (no LLM, any-model). */
|
|
545
|
-
function behavioralAnalyst(options = {}) {
|
|
546
|
-
const maxTraces = positiveInteger(options.maxTraces ?? DEFAULT_MAX_TRACES, "maxTraces");
|
|
547
|
-
const maxEvidenceRefsPerFinding = positiveInteger(options.maxEvidenceRefsPerFinding ?? DEFAULT_MAX_EVIDENCE_REFS, "maxEvidenceRefsPerFinding");
|
|
548
|
-
return {
|
|
549
|
-
id: ANALYST_ID$1,
|
|
550
|
-
description: "Deterministic behavioral/efficiency findings over OTLP spans — token-growth, output-decay, tool-monoculture, missing self-verification. Zero LLM; model-agnostic by construction.",
|
|
551
|
-
inputKind: "trace-store",
|
|
552
|
-
cost: { kind: "deterministic" },
|
|
553
|
-
version: "2.0.0",
|
|
554
|
-
async analyze(store, context) {
|
|
555
|
-
const analyzedTraceIds = await listTraceIds(store, maxTraces, context.signal);
|
|
556
|
-
const findingsById = /* @__PURE__ */ new Map();
|
|
557
|
-
for (const traceId of analyzedTraceIds) {
|
|
558
|
-
context.signal?.throwIfAborted();
|
|
559
|
-
const viewed = await store.viewTrace({ trace_id: traceId });
|
|
560
|
-
if (viewed.trace_id !== traceId) throw new Error(`behavioralAnalyst: requested trace '${traceId}', received '${viewed.trace_id}'`);
|
|
561
|
-
if (!viewed.spans) throw new Error(`behavioralAnalyst: trace '${traceId}' is oversized; complete spans are required`);
|
|
562
|
-
const metrics = computeTraceMetrics(viewed.spans);
|
|
563
|
-
if (metrics.traceId !== null && metrics.traceId !== traceId) throw new Error(`behavioralAnalyst: requested trace '${traceId}', received '${metrics.traceId}'`);
|
|
564
|
-
for (const finding of deriveEfficiencyFindings(metrics)) {
|
|
565
|
-
const current = findingsById.get(finding.finding_id);
|
|
566
|
-
if (!current) {
|
|
567
|
-
findingsById.set(finding.finding_id, {
|
|
568
|
-
finding,
|
|
569
|
-
observedTraceCount: 1,
|
|
570
|
-
evidenceTraceIds: [traceId],
|
|
571
|
-
evidence: [...finding.evidence_refs]
|
|
572
|
-
});
|
|
573
|
-
continue;
|
|
574
|
-
}
|
|
575
|
-
current.observedTraceCount += 1;
|
|
576
|
-
if (current.evidence.length < maxEvidenceRefsPerFinding) {
|
|
577
|
-
current.evidenceTraceIds.push(traceId);
|
|
578
|
-
current.evidence.push(...finding.evidence_refs);
|
|
579
|
-
}
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
return [...findingsById.values()].map(({ finding, observedTraceCount, evidenceTraceIds, evidence }) => ({
|
|
583
|
-
...finding,
|
|
584
|
-
claim: AGGREGATE_CLAIM[finding.subject](observedTraceCount, analyzedTraceIds.length),
|
|
585
|
-
rationale: `${observedTraceCount}/${analyzedTraceIds.length} analyzed traces exhibited this pattern.`,
|
|
586
|
-
evidence_refs: evidence,
|
|
587
|
-
metadata: {
|
|
588
|
-
deterministic: true,
|
|
589
|
-
evidence_trace_ids: evidenceTraceIds,
|
|
590
|
-
omitted_evidence_trace_count: observedTraceCount - evidenceTraceIds.length,
|
|
591
|
-
observed_trace_count: observedTraceCount,
|
|
592
|
-
analyzed_trace_count: analyzedTraceIds.length
|
|
593
|
-
}
|
|
594
|
-
}));
|
|
595
|
-
}
|
|
596
|
-
};
|
|
597
|
-
}
|
|
598
|
-
function positiveInteger(value, name) {
|
|
599
|
-
if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`behavioralAnalyst: ${name} must be a positive safe integer`);
|
|
600
|
-
return value;
|
|
601
|
-
}
|
|
602
|
-
//#endregion
|
|
603
|
-
//#region src/analyst/ax-cost-service.ts
|
|
604
|
-
/**
|
|
605
|
-
* Meter every chat call an Ax program makes through the shared paid-call ledger.
|
|
606
|
-
* The wrapper disables provider streaming because a stream has no complete usage
|
|
607
|
-
* receipt until it is consumed, while Ax's analyst output is not streamed to users.
|
|
608
|
-
*/
|
|
609
|
-
function meterAxChatService(ai, options) {
|
|
610
|
-
assertPositiveInteger(options.maxOutputTokens, "maxOutputTokens");
|
|
611
|
-
const source = ai;
|
|
612
|
-
if (typeof source.chat !== "function") throw new TypeError("meterAxChatService: Ax service must implement chat()");
|
|
613
|
-
const providerChat = source.chat.bind(ai);
|
|
614
|
-
const chat = async (request, callOptions = {}) => {
|
|
615
|
-
const boundedRequest = boundOutputTokens(request, options.maxOutputTokens);
|
|
616
|
-
const model = modelName(boundedRequest.model) || options.defaultModel || "";
|
|
617
|
-
const canTurnOffThinking = canDisableThinking(ai, model);
|
|
618
|
-
const combined = combineSignals(options.signal, callOptions.abortSignal);
|
|
619
|
-
try {
|
|
620
|
-
const paid = await options.ledger.runPaidCall({
|
|
621
|
-
channel: "analyst",
|
|
622
|
-
phase: options.phase ?? "analyst.ax.chat",
|
|
623
|
-
actor: options.actor,
|
|
624
|
-
model,
|
|
625
|
-
tags: options.tags,
|
|
626
|
-
signal: combined.signal,
|
|
627
|
-
maximumCharge: maximumChargeForAxChatRequest(boundedRequest, model),
|
|
628
|
-
execute: async (executionSignal) => {
|
|
629
|
-
const providerOptions = {
|
|
630
|
-
...callOptions,
|
|
631
|
-
abortSignal: executionSignal,
|
|
632
|
-
retry: {
|
|
633
|
-
...callOptions.retry,
|
|
634
|
-
maxRetries: 0
|
|
635
|
-
},
|
|
636
|
-
stream: false,
|
|
637
|
-
showThoughts: false
|
|
638
|
-
};
|
|
639
|
-
if (canTurnOffThinking) providerOptions.thinkingTokenBudget = "none";
|
|
640
|
-
else Reflect.deleteProperty(providerOptions, "thinkingTokenBudget");
|
|
641
|
-
const response = await providerChat(boundedRequest, providerOptions);
|
|
642
|
-
if (response instanceof ReadableStream) throw new Error("meterAxChatService: provider returned a stream after stream:false");
|
|
643
|
-
return response;
|
|
644
|
-
},
|
|
645
|
-
receipt: (response) => costReceiptFromAxResponse(response, model)
|
|
646
|
-
});
|
|
647
|
-
if (!paid.succeeded) throw paid.error;
|
|
648
|
-
return paid.value;
|
|
649
|
-
} finally {
|
|
650
|
-
combined.dispose();
|
|
651
|
-
}
|
|
652
|
-
};
|
|
653
|
-
return new Proxy(ai, { get(target, property) {
|
|
654
|
-
if (property === "chat") return chat;
|
|
655
|
-
const value = Reflect.get(target, property, target);
|
|
656
|
-
return typeof value === "function" ? value.bind(target) : value;
|
|
657
|
-
} });
|
|
658
|
-
}
|
|
659
|
-
/** Conservative priced bound for one Ax text chat request. */
|
|
660
|
-
function maximumChargeForAxChatRequest(request, defaultModel) {
|
|
661
|
-
const model = modelName(request.model) || defaultModel || "";
|
|
662
|
-
const maxTokens = request.modelConfig?.maxTokens;
|
|
663
|
-
const completions = request.modelConfig?.n;
|
|
664
|
-
if (!model || maxTokens === void 0 || completions === void 0) return void 0;
|
|
665
|
-
assertPositiveInteger(maxTokens, "request.modelConfig.maxTokens");
|
|
666
|
-
assertPositiveInteger(completions, "request.modelConfig.n");
|
|
667
|
-
const maximumOutputTokens = maxTokens * completions;
|
|
668
|
-
assertPositiveInteger(maximumOutputTokens, "maximum output tokens");
|
|
669
|
-
if (containsUnboundedOrCacheableContent(request)) return void 0;
|
|
670
|
-
let inputTokens;
|
|
671
|
-
try {
|
|
672
|
-
const pricedRequest = request.model === void 0 ? {
|
|
673
|
-
...request,
|
|
674
|
-
model
|
|
675
|
-
} : request;
|
|
676
|
-
inputTokens = new TextEncoder().encode(JSON.stringify(pricedRequest)).byteLength * completions;
|
|
677
|
-
} catch {
|
|
678
|
-
return;
|
|
679
|
-
}
|
|
680
|
-
assertPositiveInteger(inputTokens, "maximum input tokens");
|
|
681
|
-
return {
|
|
682
|
-
model,
|
|
683
|
-
inputTokens,
|
|
684
|
-
outputTokens: maximumOutputTokens
|
|
685
|
-
};
|
|
686
|
-
}
|
|
687
|
-
function boundOutputTokens(request, limit) {
|
|
688
|
-
const requested = request.modelConfig?.maxTokens;
|
|
689
|
-
if (requested !== void 0) assertPositiveInteger(requested, "request.modelConfig.maxTokens");
|
|
690
|
-
const completions = request.modelConfig?.n ?? 1;
|
|
691
|
-
assertPositiveInteger(completions, "request.modelConfig.n");
|
|
692
|
-
const maxTokens = requested === void 0 ? limit : Math.min(requested, limit);
|
|
693
|
-
return {
|
|
694
|
-
...request,
|
|
695
|
-
modelConfig: {
|
|
696
|
-
...request.modelConfig,
|
|
697
|
-
maxTokens,
|
|
698
|
-
n: completions
|
|
699
|
-
}
|
|
700
|
-
};
|
|
701
|
-
}
|
|
702
|
-
function costReceiptFromAxResponse(response, fallbackModel) {
|
|
703
|
-
const usage = response.modelUsage;
|
|
704
|
-
const tokens = usage?.tokens;
|
|
705
|
-
const model = usage?.model || fallbackModel;
|
|
706
|
-
if (!tokens || !validUsage(tokens.promptTokens) || !validUsage(tokens.completionTokens) || !validUsage(tokens.totalTokens) || tokens.totalTokens < tokens.promptTokens + tokens.completionTokens || !validOptionalUsage(tokens.cacheReadTokens) || !validOptionalUsage(tokens.cacheCreationTokens) || !validOptionalUsage(tokens.reasoningTokens) || !validOptionalUsage(tokens.thoughtsTokens)) return {
|
|
707
|
-
model,
|
|
708
|
-
inputTokens: 0,
|
|
709
|
-
outputTokens: 0,
|
|
710
|
-
usageUnknown: true
|
|
711
|
-
};
|
|
712
|
-
const cacheReadTokens = validUsage(tokens.cacheReadTokens) ? tokens.cacheReadTokens : 0;
|
|
713
|
-
const cacheCreationTokens = validUsage(tokens.cacheCreationTokens) ? tokens.cacheCreationTokens : 0;
|
|
714
|
-
const totalCacheTokens = cacheReadTokens + cacheCreationTokens;
|
|
715
|
-
const thoughtsTokens = validUsage(tokens.thoughtsTokens) ? tokens.thoughtsTokens : 0;
|
|
716
|
-
const reasoningTokens = Math.max(validUsage(tokens.reasoningTokens) ? tokens.reasoningTokens : 0, thoughtsTokens);
|
|
717
|
-
const separateReasoningTokens = reasoningTokens > tokens.completionTokens ? reasoningTokens : 0;
|
|
718
|
-
const additionalOutputTokens = Math.max(thoughtsTokens, separateReasoningTokens);
|
|
719
|
-
const outputTokens = tokens.completionTokens + additionalOutputTokens;
|
|
720
|
-
const directTotal = tokens.promptTokens + tokens.completionTokens;
|
|
721
|
-
if (!(/* @__PURE__ */ new Set([
|
|
722
|
-
directTotal,
|
|
723
|
-
directTotal + totalCacheTokens,
|
|
724
|
-
directTotal + additionalOutputTokens,
|
|
725
|
-
directTotal + totalCacheTokens + additionalOutputTokens
|
|
726
|
-
])).has(tokens.totalTokens)) return {
|
|
727
|
-
model,
|
|
728
|
-
inputTokens: 0,
|
|
729
|
-
outputTokens: 0,
|
|
730
|
-
usageUnknown: true
|
|
731
|
-
};
|
|
732
|
-
return {
|
|
733
|
-
model,
|
|
734
|
-
inputTokens: tokens.promptTokens,
|
|
735
|
-
outputTokens,
|
|
736
|
-
...reasoningTokens > 0 ? { reasoningTokens } : {},
|
|
737
|
-
...cacheReadTokens > 0 ? { cachedTokens: cacheReadTokens } : {},
|
|
738
|
-
...cacheCreationTokens > 0 ? { cacheWriteTokens: cacheCreationTokens } : {}
|
|
739
|
-
};
|
|
740
|
-
}
|
|
741
|
-
function combineSignals(first, second) {
|
|
742
|
-
if (!first) return {
|
|
743
|
-
signal: second,
|
|
744
|
-
dispose: () => {}
|
|
745
|
-
};
|
|
746
|
-
if (!second || first === second) return {
|
|
747
|
-
signal: first,
|
|
748
|
-
dispose: () => {}
|
|
749
|
-
};
|
|
750
|
-
if (typeof AbortSignal.any === "function") return {
|
|
751
|
-
signal: AbortSignal.any([first, second]),
|
|
752
|
-
dispose: () => {}
|
|
753
|
-
};
|
|
754
|
-
const controller = new AbortController();
|
|
755
|
-
const dispose = () => {
|
|
756
|
-
first.removeEventListener("abort", abortFromFirst);
|
|
757
|
-
second.removeEventListener("abort", abortFromSecond);
|
|
758
|
-
};
|
|
759
|
-
const abortFrom = (source) => {
|
|
760
|
-
if (!controller.signal.aborted) controller.abort(source.reason);
|
|
761
|
-
dispose();
|
|
762
|
-
};
|
|
763
|
-
const abortFromFirst = () => abortFrom(first);
|
|
764
|
-
const abortFromSecond = () => abortFrom(second);
|
|
765
|
-
if (first.aborted) abortFrom(first);
|
|
766
|
-
else if (second.aborted) abortFrom(second);
|
|
767
|
-
else {
|
|
768
|
-
first.addEventListener("abort", abortFromFirst, { once: true });
|
|
769
|
-
second.addEventListener("abort", abortFromSecond, { once: true });
|
|
770
|
-
}
|
|
771
|
-
return {
|
|
772
|
-
signal: controller.signal,
|
|
773
|
-
dispose
|
|
774
|
-
};
|
|
775
|
-
}
|
|
776
|
-
function containsUnboundedOrCacheableContent(request) {
|
|
777
|
-
if (request.functions?.some((fn) => fn.cache === true)) return true;
|
|
778
|
-
return request.chatPrompt.some((message) => {
|
|
779
|
-
if (message.cache === true) return true;
|
|
780
|
-
if (!("content" in message) || !Array.isArray(message.content)) return false;
|
|
781
|
-
return message.content.some((part) => part.cache === true || part.type !== "text");
|
|
782
|
-
});
|
|
783
|
-
}
|
|
784
|
-
function modelName(value) {
|
|
785
|
-
return typeof value === "string" ? value : "";
|
|
786
|
-
}
|
|
787
|
-
function canDisableThinking(ai, model) {
|
|
788
|
-
const namedAi = ai;
|
|
789
|
-
const serviceName = typeof namedAi.getName === "function" ? namedAi.getName() : "";
|
|
790
|
-
const modelId = model.slice(model.lastIndexOf("/") + 1);
|
|
791
|
-
return serviceName !== "GoogleGeminiAI" || !/^gemini-3(?:[.-]|$)/i.test(modelId);
|
|
792
|
-
}
|
|
793
|
-
function validUsage(value) {
|
|
794
|
-
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
795
|
-
}
|
|
796
|
-
function validOptionalUsage(value) {
|
|
797
|
-
return value === void 0 || validUsage(value);
|
|
798
|
-
}
|
|
799
|
-
function assertPositiveInteger(value, field) {
|
|
800
|
-
if (!Number.isSafeInteger(value) || value <= 0) throw new RangeError(`meterAxChatService: ${field} must be a positive integer`);
|
|
801
|
-
}
|
|
802
|
-
//#endregion
|
|
803
|
-
//#region src/analyst/finding-subject.ts
|
|
804
|
-
/**
|
|
805
|
-
* Typed `FindingSubject` — the canonical grammar every analyst kind emits.
|
|
806
|
-
*
|
|
807
|
-
* Background: kind actor prompts have always documented a subject grammar
|
|
808
|
-
* (e.g. `system-prompt:<section>`, `agent-knowledge:wiki:<slug>`) but the
|
|
809
|
-
* LLM was unconstrained — it could emit `subject: "fix the prompt"`
|
|
810
|
-
* (prose) and downstream adapters routed on `startsWith(...)` would
|
|
811
|
-
* silently skip it. Every per-vertical `ImprovementAdapter` had a
|
|
812
|
-
* routing table that mostly caught nothing.
|
|
813
|
-
*
|
|
814
|
-
* This module fixes that:
|
|
815
|
-
* - `parseFindingSubject(raw)` — returns the typed `FindingSubject`
|
|
816
|
-
* when `raw` matches the grammar, else `null`. Used at the
|
|
817
|
-
* `RawAnalystFindingSchema` boundary so malformed subjects are
|
|
818
|
-
* rejected loudly instead of silently lifted into the registry.
|
|
819
|
-
* - `FindingSubjectKind` — the union of valid locus categories. Each
|
|
820
|
-
* variant carries the typed components downstream adapters resolve
|
|
821
|
-
* against the agent's surface manifest (no string parsing in the
|
|
822
|
-
* adapter).
|
|
823
|
-
* - `FINDING_SUBJECT_GRAMMAR_PROMPT` — single source of truth for the
|
|
824
|
-
* grammar string embedded in kind actor prompts. Drift between
|
|
825
|
-
* prompt and parser is impossible if every kind imports this.
|
|
826
|
-
*
|
|
827
|
-
* The grammar is intentionally NARROW — only loci the substrate's
|
|
828
|
-
* default `ImprovementAdapter` / `KnowledgeAdapter` can act on. A
|
|
829
|
-
* finding with a subject outside this set fails the parser; the kind
|
|
830
|
-
* author either extends the grammar here (and adds adapter routing)
|
|
831
|
-
* or rephrases the prompt to map onto an existing variant.
|
|
832
|
-
*
|
|
833
|
-
* `failure-mode` is the one exception — its subjects are free-form
|
|
834
|
-
* cluster labels, not loci. The schema preserves them as
|
|
835
|
-
* `{ kind: 'cluster', label }` and the adapters skip them (cluster
|
|
836
|
-
* findings are evidence, not actionable mutations).
|
|
837
|
-
*/
|
|
838
|
-
const FINDING_SUBJECT_KINDS = [
|
|
839
|
-
"knowledge.wiki",
|
|
840
|
-
"knowledge.claim",
|
|
841
|
-
"knowledge.raw",
|
|
842
|
-
"knowledge.stale",
|
|
843
|
-
"system-prompt",
|
|
844
|
-
"skill",
|
|
845
|
-
"tool-doc",
|
|
846
|
-
"new-tool",
|
|
847
|
-
"mcp",
|
|
848
|
-
"hook",
|
|
849
|
-
"subagent",
|
|
850
|
-
"workflow",
|
|
851
|
-
"rollout-policy",
|
|
852
|
-
"agent-profile",
|
|
853
|
-
"code",
|
|
854
|
-
"rag",
|
|
855
|
-
"memory",
|
|
856
|
-
"scaffolding",
|
|
857
|
-
"output-schema",
|
|
858
|
-
"websearch.outdated",
|
|
859
|
-
"prior-run-summary",
|
|
860
|
-
"cluster"
|
|
861
|
-
];
|
|
862
|
-
/**
|
|
863
|
-
* Parse a raw subject string emitted by an analyst kind's actor.
|
|
864
|
-
*
|
|
865
|
-
* Returns the typed `FindingSubject` when `raw` matches the grammar,
|
|
866
|
-
* else `null`. Callers use the `null` return as a signal to either
|
|
867
|
-
* (a) reject the finding at parse time (kinds that emit typed loci —
|
|
868
|
-
* knowledge-gap, improvement, knowledge-poisoning) or (b) lift it as
|
|
869
|
-
* a cluster label (failure-mode).
|
|
870
|
-
*
|
|
871
|
-
* Slugs are constrained to `[a-z0-9-]+` (lowercase kebab) to keep file
|
|
872
|
-
* paths sane downstream. Topics / keys / sections allow any non-empty
|
|
873
|
-
* string (free-form for the LLM's voice) but get trimmed.
|
|
874
|
-
*
|
|
875
|
-
* Empty / whitespace-only inputs return `null`. `undefined` returns
|
|
876
|
-
* `null`. Both are surfaced by the caller as a rejected subject.
|
|
877
|
-
*/
|
|
878
|
-
function parseFindingSubject(raw) {
|
|
879
|
-
if (raw === null || raw === void 0) return null;
|
|
880
|
-
const trimmed = raw.trim();
|
|
881
|
-
if (trimmed.length === 0) return null;
|
|
882
|
-
const wiki = trimmed.match(/^agent-knowledge:wiki:([a-z0-9][a-z0-9-]*)(?:#([a-z0-9][a-z0-9-]*))?$/);
|
|
883
|
-
if (wiki) return {
|
|
884
|
-
kind: "knowledge.wiki",
|
|
885
|
-
slug: wiki[1],
|
|
886
|
-
...wiki[2] ? { heading: wiki[2] } : {}
|
|
887
|
-
};
|
|
888
|
-
const claim = trimmed.match(/^agent-knowledge:claim:(.+)$/);
|
|
889
|
-
if (claim && claim[1].trim().length > 0) return {
|
|
890
|
-
kind: "knowledge.claim",
|
|
891
|
-
topic: claim[1].trim()
|
|
892
|
-
};
|
|
893
|
-
const raw_ = trimmed.match(/^agent-knowledge:raw:(.+)$/);
|
|
894
|
-
if (raw_ && raw_[1].trim().length > 0) return {
|
|
895
|
-
kind: "knowledge.raw",
|
|
896
|
-
sourceId: raw_[1].trim()
|
|
897
|
-
};
|
|
898
|
-
const stale = trimmed.match(/^agent-knowledge:stale:([a-z0-9][a-z0-9-]*)$/);
|
|
899
|
-
if (stale) return {
|
|
900
|
-
kind: "knowledge.stale",
|
|
901
|
-
slug: stale[1]
|
|
902
|
-
};
|
|
903
|
-
const sp = trimmed.match(/^system-prompt:(.+)$/);
|
|
904
|
-
if (sp && sp[1].trim().length > 0) return {
|
|
905
|
-
kind: "system-prompt",
|
|
906
|
-
section: sp[1].trim()
|
|
907
|
-
};
|
|
908
|
-
const skill = trimmed.match(/^skill:([a-z0-9][a-z0-9_.-]*)$/);
|
|
909
|
-
if (skill) return {
|
|
910
|
-
kind: "skill",
|
|
911
|
-
name: skill[1]
|
|
912
|
-
};
|
|
913
|
-
const tdAspect = trimmed.match(/^tool-doc:([a-z0-9][a-z0-9_-]*):(.+)$/);
|
|
914
|
-
if (tdAspect && tdAspect[2].trim().length > 0) return {
|
|
915
|
-
kind: "tool-doc",
|
|
916
|
-
tool: tdAspect[1],
|
|
917
|
-
aspect: tdAspect[2].trim()
|
|
918
|
-
};
|
|
919
|
-
const td = trimmed.match(/^tool-doc:([a-z0-9][a-z0-9_-]*)$/);
|
|
920
|
-
if (td) return {
|
|
921
|
-
kind: "tool-doc",
|
|
922
|
-
tool: td[1]
|
|
923
|
-
};
|
|
924
|
-
const nt = trimmed.match(/^new-tool:([a-z0-9][a-z0-9_-]*)$/);
|
|
925
|
-
if (nt) return {
|
|
926
|
-
kind: "new-tool",
|
|
927
|
-
name: nt[1]
|
|
928
|
-
};
|
|
929
|
-
const mcp = trimmed.match(/^mcp:([a-z0-9][a-z0-9_.-]*)(?::([a-z0-9][a-z0-9_.-]*))?$/);
|
|
930
|
-
if (mcp) return {
|
|
931
|
-
kind: "mcp",
|
|
932
|
-
server: mcp[1],
|
|
933
|
-
...mcp[2] ? { tool: mcp[2] } : {}
|
|
934
|
-
};
|
|
935
|
-
const hook = trimmed.match(/^hook:([a-z0-9][a-z0-9_.-]*)$/);
|
|
936
|
-
if (hook) return {
|
|
937
|
-
kind: "hook",
|
|
938
|
-
name: hook[1]
|
|
939
|
-
};
|
|
940
|
-
const subagent = trimmed.match(/^subagent:([a-z0-9][a-z0-9_.-]*)$/);
|
|
941
|
-
if (subagent) return {
|
|
942
|
-
kind: "subagent",
|
|
943
|
-
name: subagent[1]
|
|
944
|
-
};
|
|
945
|
-
const workflow = trimmed.match(/^workflow:([a-z0-9][a-z0-9_.-]*)$/);
|
|
946
|
-
if (workflow) return {
|
|
947
|
-
kind: "workflow",
|
|
948
|
-
name: workflow[1]
|
|
949
|
-
};
|
|
950
|
-
const rolloutPolicy = trimmed.match(/^rollout-policy:(.+)$/);
|
|
951
|
-
if (rolloutPolicy && rolloutPolicy[1].trim().length > 0) return {
|
|
952
|
-
kind: "rollout-policy",
|
|
953
|
-
field: rolloutPolicy[1].trim()
|
|
954
|
-
};
|
|
955
|
-
const agentProfile = trimmed.match(/^agent-profile:(.+)$/);
|
|
956
|
-
if (agentProfile && agentProfile[1].trim().length > 0) return {
|
|
957
|
-
kind: "agent-profile",
|
|
958
|
-
field: agentProfile[1].trim()
|
|
959
|
-
};
|
|
960
|
-
const code = trimmed.match(/^code:(.+)$/);
|
|
961
|
-
if (code && code[1].trim().length > 0) return {
|
|
962
|
-
kind: "code",
|
|
963
|
-
path: code[1].trim()
|
|
964
|
-
};
|
|
965
|
-
const rag = trimmed.match(/^rag:([a-z0-9][a-z0-9_-]*):(.+)$/);
|
|
966
|
-
if (rag && rag[2].trim().length > 0) return {
|
|
967
|
-
kind: "rag",
|
|
968
|
-
corpus: rag[1],
|
|
969
|
-
docId: rag[2].trim()
|
|
970
|
-
};
|
|
971
|
-
const mem = trimmed.match(/^memory:(.+)$/);
|
|
972
|
-
if (mem && mem[1].trim().length > 0) return {
|
|
973
|
-
kind: "memory",
|
|
974
|
-
key: mem[1].trim()
|
|
975
|
-
};
|
|
976
|
-
const sc = trimmed.match(/^scaffolding:(.+)$/);
|
|
977
|
-
if (sc && sc[1].trim().length > 0) return {
|
|
978
|
-
kind: "scaffolding",
|
|
979
|
-
concern: sc[1].trim()
|
|
980
|
-
};
|
|
981
|
-
const os = trimmed.match(/^output-schema:(.+)$/);
|
|
982
|
-
if (os && os[1].trim().length > 0) return {
|
|
983
|
-
kind: "output-schema",
|
|
984
|
-
field: os[1].trim()
|
|
985
|
-
};
|
|
986
|
-
const ws = trimmed.match(/^websearch:outdated:(.+)$/);
|
|
987
|
-
if (ws && ws[1].trim().length > 0) return {
|
|
988
|
-
kind: "websearch.outdated",
|
|
989
|
-
topic: ws[1].trim()
|
|
990
|
-
};
|
|
991
|
-
const prs = trimmed.match(/^prior-run-summary:(.+)$/);
|
|
992
|
-
if (prs && prs[1].trim().length > 0) return {
|
|
993
|
-
kind: "prior-run-summary",
|
|
994
|
-
topic: prs[1].trim()
|
|
995
|
-
};
|
|
996
|
-
if (/^[a-z0-9][a-z0-9._-]*$/.test(trimmed) && trimmed.length <= 80) return {
|
|
997
|
-
kind: "cluster",
|
|
998
|
-
label: trimmed
|
|
999
|
-
};
|
|
1000
|
-
return null;
|
|
1001
|
-
}
|
|
1002
|
-
/**
|
|
1003
|
-
* Render the parsed subject back to its canonical string form. Inverse
|
|
1004
|
-
* of `parseFindingSubject`; useful when the substrate constructs new
|
|
1005
|
-
* findings programmatically (e.g. for tests, replays, or
|
|
1006
|
-
* `id_basis` carry-forward).
|
|
1007
|
-
*/
|
|
1008
|
-
function renderFindingSubject(s) {
|
|
1009
|
-
switch (s.kind) {
|
|
1010
|
-
case "knowledge.wiki": return s.heading ? `agent-knowledge:wiki:${s.slug}#${s.heading}` : `agent-knowledge:wiki:${s.slug}`;
|
|
1011
|
-
case "knowledge.claim": return `agent-knowledge:claim:${s.topic}`;
|
|
1012
|
-
case "knowledge.raw": return `agent-knowledge:raw:${s.sourceId}`;
|
|
1013
|
-
case "knowledge.stale": return `agent-knowledge:stale:${s.slug}`;
|
|
1014
|
-
case "system-prompt": return `system-prompt:${s.section}`;
|
|
1015
|
-
case "skill": return `skill:${s.name}`;
|
|
1016
|
-
case "tool-doc": return s.aspect ? `tool-doc:${s.tool}:${s.aspect}` : `tool-doc:${s.tool}`;
|
|
1017
|
-
case "new-tool": return `new-tool:${s.name}`;
|
|
1018
|
-
case "mcp": return s.tool ? `mcp:${s.server}:${s.tool}` : `mcp:${s.server}`;
|
|
1019
|
-
case "hook": return `hook:${s.name}`;
|
|
1020
|
-
case "subagent": return `subagent:${s.name}`;
|
|
1021
|
-
case "workflow": return `workflow:${s.name}`;
|
|
1022
|
-
case "rollout-policy": return `rollout-policy:${s.field}`;
|
|
1023
|
-
case "agent-profile": return `agent-profile:${s.field}`;
|
|
1024
|
-
case "code": return `code:${s.path}`;
|
|
1025
|
-
case "rag": return `rag:${s.corpus}:${s.docId}`;
|
|
1026
|
-
case "memory": return `memory:${s.key}`;
|
|
1027
|
-
case "scaffolding": return `scaffolding:${s.concern}`;
|
|
1028
|
-
case "output-schema": return `output-schema:${s.field}`;
|
|
1029
|
-
case "websearch.outdated": return `websearch:outdated:${s.topic}`;
|
|
1030
|
-
case "prior-run-summary": return `prior-run-summary:${s.topic}`;
|
|
1031
|
-
case "cluster": return s.label;
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
/**
|
|
1035
|
-
* The grammar text embedded into kind actor prompts. Kinds opt into
|
|
1036
|
-
* the subset of variants they emit (e.g. `improvement` excludes the
|
|
1037
|
-
* cluster variant; `failure-mode` includes ONLY the cluster variant).
|
|
1038
|
-
*
|
|
1039
|
-
* Drift between prompt and parser is impossible: every kind imports
|
|
1040
|
-
* this constant + the matching `expects` set, and the unit tests below
|
|
1041
|
-
* lock the table to the parser.
|
|
1042
|
-
*/
|
|
1043
|
-
const FINDING_SUBJECT_SYNTAX = {
|
|
1044
|
-
"knowledge.wiki": "agent-knowledge:wiki:<slug>[#<heading>]",
|
|
1045
|
-
"knowledge.claim": "agent-knowledge:claim:<topic>",
|
|
1046
|
-
"knowledge.raw": "agent-knowledge:raw:<source-id>",
|
|
1047
|
-
"knowledge.stale": "agent-knowledge:stale:<slug>",
|
|
1048
|
-
"system-prompt": "system-prompt:<section>",
|
|
1049
|
-
skill: "skill:<name>",
|
|
1050
|
-
"tool-doc": "tool-doc:<tool>[:<aspect>]",
|
|
1051
|
-
"new-tool": "new-tool:<name>",
|
|
1052
|
-
mcp: "mcp:<server>[:<tool>]",
|
|
1053
|
-
hook: "hook:<name>",
|
|
1054
|
-
subagent: "subagent:<name>",
|
|
1055
|
-
workflow: "workflow:<name>",
|
|
1056
|
-
"rollout-policy": "rollout-policy:<field>",
|
|
1057
|
-
"agent-profile": "agent-profile:<field>",
|
|
1058
|
-
code: "code:<path>",
|
|
1059
|
-
rag: "rag:<corpus>:<doc-id>",
|
|
1060
|
-
memory: "memory:<key>",
|
|
1061
|
-
scaffolding: "scaffolding:<concern>",
|
|
1062
|
-
"output-schema": "output-schema:<field>",
|
|
1063
|
-
"websearch.outdated": "websearch:outdated:<topic>",
|
|
1064
|
-
"prior-run-summary": "prior-run-summary:<topic>",
|
|
1065
|
-
cluster: "<lowercase-cluster-label>"
|
|
1066
|
-
};
|
|
1067
|
-
const FINDING_SUBJECT_PURPOSE = {
|
|
1068
|
-
"knowledge.wiki": "create or update a wiki page",
|
|
1069
|
-
"knowledge.claim": "draft a claim or relation",
|
|
1070
|
-
"knowledge.raw": "curate a raw source",
|
|
1071
|
-
"knowledge.stale": "mark a stale page",
|
|
1072
|
-
"system-prompt": "revise a system-prompt section",
|
|
1073
|
-
skill: "create or revise a skill",
|
|
1074
|
-
"tool-doc": "revise a tool contract",
|
|
1075
|
-
"new-tool": "propose a new tool",
|
|
1076
|
-
mcp: "revise an MCP server or tool",
|
|
1077
|
-
hook: "revise a lifecycle hook",
|
|
1078
|
-
subagent: "revise a delegated agent",
|
|
1079
|
-
workflow: "revise an orchestration workflow",
|
|
1080
|
-
"rollout-policy": "revise budget, sampling, or stop policy",
|
|
1081
|
-
"agent-profile": "revise another AgentProfile field",
|
|
1082
|
-
code: "revise an implementation path",
|
|
1083
|
-
rag: "ingest or correct a RAG document",
|
|
1084
|
-
memory: "invalidate or set memory",
|
|
1085
|
-
scaffolding: "revise preconditions, retries, or verification",
|
|
1086
|
-
"output-schema": "constrain the output shape",
|
|
1087
|
-
"websearch.outdated": "identify a stale web result",
|
|
1088
|
-
"prior-run-summary": "identify a stale prior-run summary",
|
|
1089
|
-
cluster: "name one failure cluster"
|
|
1090
|
-
};
|
|
1091
|
-
function renderFindingSubjectGrammar(kinds) {
|
|
1092
|
-
return [
|
|
1093
|
-
"Subjects MUST match one of these forms — anything else is rejected at parse time:",
|
|
1094
|
-
...kinds.map((kind) => ` ${FINDING_SUBJECT_SYNTAX[kind]} — ${FINDING_SUBJECT_PURPOSE[kind]}`),
|
|
1095
|
-
"Runtime ids are lowercase [a-z0-9_.-]+. Topics, keys, paths, and sections are free-form and trimmed."
|
|
1096
|
-
].join("\n");
|
|
1097
|
-
}
|
|
1098
|
-
const FINDING_SUBJECT_GRAMMAR_PROMPT = renderFindingSubjectGrammar(FINDING_SUBJECT_KINDS);
|
|
1099
|
-
/**
|
|
1100
|
-
* The variants each kind is allowed to emit. Used at the kind factory
|
|
1101
|
-
* boundary so a knowledge-gap finding can't sneak in a `system-prompt:*`
|
|
1102
|
-
* subject (the improvement-analyst's job) and vice versa.
|
|
1103
|
-
*
|
|
1104
|
-
* `failure-mode` is restricted to `cluster` — the only kind that emits
|
|
1105
|
-
* a non-locus subject.
|
|
1106
|
-
*/
|
|
1107
|
-
const KIND_EXPECTED_SUBJECTS = {
|
|
1108
|
-
"failure-mode": ["cluster"],
|
|
1109
|
-
"knowledge-gap": [
|
|
1110
|
-
"knowledge.wiki",
|
|
1111
|
-
"knowledge.claim",
|
|
1112
|
-
"knowledge.raw",
|
|
1113
|
-
"knowledge.stale",
|
|
1114
|
-
"tool-doc",
|
|
1115
|
-
"system-prompt",
|
|
1116
|
-
"skill",
|
|
1117
|
-
"mcp",
|
|
1118
|
-
"subagent",
|
|
1119
|
-
"workflow",
|
|
1120
|
-
"memory",
|
|
1121
|
-
"websearch.outdated",
|
|
1122
|
-
"prior-run-summary"
|
|
1123
|
-
],
|
|
1124
|
-
"knowledge-poisoning": [
|
|
1125
|
-
"knowledge.wiki",
|
|
1126
|
-
"knowledge.claim",
|
|
1127
|
-
"knowledge.raw",
|
|
1128
|
-
"tool-doc",
|
|
1129
|
-
"system-prompt",
|
|
1130
|
-
"skill",
|
|
1131
|
-
"mcp",
|
|
1132
|
-
"hook",
|
|
1133
|
-
"memory",
|
|
1134
|
-
"websearch.outdated",
|
|
1135
|
-
"prior-run-summary"
|
|
1136
|
-
],
|
|
1137
|
-
improvement: [
|
|
1138
|
-
"system-prompt",
|
|
1139
|
-
"skill",
|
|
1140
|
-
"tool-doc",
|
|
1141
|
-
"new-tool",
|
|
1142
|
-
"mcp",
|
|
1143
|
-
"hook",
|
|
1144
|
-
"subagent",
|
|
1145
|
-
"workflow",
|
|
1146
|
-
"rollout-policy",
|
|
1147
|
-
"agent-profile",
|
|
1148
|
-
"code",
|
|
1149
|
-
"rag",
|
|
1150
|
-
"memory",
|
|
1151
|
-
"scaffolding",
|
|
1152
|
-
"output-schema",
|
|
1153
|
-
"knowledge.wiki",
|
|
1154
|
-
"knowledge.claim"
|
|
1155
|
-
]
|
|
1156
|
-
};
|
|
1157
|
-
/** Render only the subject forms one analyst kind is permitted to emit. */
|
|
1158
|
-
function findingSubjectGrammarPromptFor(kindId) {
|
|
1159
|
-
const kinds = KIND_EXPECTED_SUBJECTS[kindId];
|
|
1160
|
-
if (!kinds) throw new Error(`unknown analyst kind: ${kindId}`);
|
|
1161
|
-
return renderFindingSubjectGrammar(kinds);
|
|
1162
|
-
}
|
|
1163
|
-
/**
|
|
1164
|
-
* Zod schema that validates a raw subject string and returns the parsed
|
|
1165
|
-
* `FindingSubject`. Embedded in `RawAnalystFindingSchema` via
|
|
1166
|
-
* `transform`, so `subject` arrives at the kind factory either as a
|
|
1167
|
-
* typed locus or as a parse error attached to a single Zod issue.
|
|
1168
|
-
*
|
|
1169
|
-
* Optionality is preserved: subjects ARE optional on the wire (some
|
|
1170
|
-
* findings are descriptive, not actionable). When present, they MUST
|
|
1171
|
-
* parse — emitting a malformed subject is a contract violation, not a
|
|
1172
|
-
* soft signal.
|
|
1173
|
-
*/
|
|
1174
|
-
const FindingSubjectStringSchema = z.string().refine((s) => parseFindingSubject(s) !== null, { message: "subject does not match the finding-subject grammar" });
|
|
1175
|
-
//#endregion
|
|
1176
|
-
//#region src/analyst/parse-tolerant.ts
|
|
1177
|
-
/**
|
|
1178
|
-
* Forgiving pre-parse for analyst findings. Weak models routinely emit
|
|
1179
|
-
* schema-correct content in an unusable wrapper — fenced ```json blocks, a
|
|
1180
|
-
* single object where an array is expected, trailing commas. Measured: GPT-4o
|
|
1181
|
-
* drops to 0% usable output purely from markdown-fence wrapping
|
|
1182
|
-
* (arXiv:2605.02363). A five-line de-fence recovers most of it. This module is
|
|
1183
|
-
* the de-fence/coerce step that runs BEFORE Zod, so a recoverable finding is
|
|
1184
|
-
* repaired, not dropped.
|
|
1185
|
-
*
|
|
1186
|
-
* Pure + deterministic. No model, no network.
|
|
1187
|
-
*/
|
|
1188
|
-
/** Strip a ```lang ... ``` (or bare ``` ... ```) code fence, if the string is one. */
|
|
1189
|
-
function stripCodeFences(text) {
|
|
1190
|
-
const t = text.trim();
|
|
1191
|
-
const m = t.match(/^```[a-zA-Z0-9]*\s*\n?([\s\S]*?)\n?```$/);
|
|
1192
|
-
return m ? m[1].trim() : t;
|
|
1193
|
-
}
|
|
1194
|
-
/** Remove trailing commas before } or ] — the most common near-JSON defect. */
|
|
1195
|
-
function dropTrailingCommas(s) {
|
|
1196
|
-
return s.replace(/,(\s*[}\]])/g, "$1");
|
|
1197
|
-
}
|
|
1198
|
-
/**
|
|
1199
|
-
* Best-effort parse of a string into JSON. De-fences, drops trailing commas,
|
|
1200
|
-
* then `JSON.parse`. Returns `undefined` (never throws) when unrecoverable.
|
|
1201
|
-
*/
|
|
1202
|
-
function coerceJson(text) {
|
|
1203
|
-
const candidate = dropTrailingCommas(stripCodeFences(text));
|
|
1204
|
-
try {
|
|
1205
|
-
return JSON.parse(candidate);
|
|
1206
|
-
} catch {
|
|
1207
|
-
return;
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1210
|
-
/**
|
|
1211
|
-
* Coerce arbitrary actor/structurer output into an array of candidate finding
|
|
1212
|
-
* rows: a JSON string → parse; a single object → 1-element array; an array →
|
|
1213
|
-
* as-is; anything else → []. Callers still run each row through Zod
|
|
1214
|
-
* (`parseRawFinding`) — this only fixes the shape and never invents fields.
|
|
1215
|
-
*/
|
|
1216
|
-
function coerceToFindingRows(raw) {
|
|
1217
|
-
let value = raw;
|
|
1218
|
-
if (typeof value === "string") {
|
|
1219
|
-
const parsed = coerceJson(value);
|
|
1220
|
-
if (parsed === void 0) return [];
|
|
1221
|
-
value = parsed;
|
|
1222
|
-
}
|
|
1223
|
-
if (Array.isArray(value)) return value;
|
|
1224
|
-
if (value && typeof value === "object") {
|
|
1225
|
-
const inner = value.findings;
|
|
1226
|
-
if (Array.isArray(inner)) return inner;
|
|
1227
|
-
return [value];
|
|
1228
|
-
}
|
|
1229
|
-
return [];
|
|
1230
|
-
}
|
|
1231
|
-
//#endregion
|
|
1232
|
-
//#region src/analyst/finding-signature.ts
|
|
1233
|
-
/**
|
|
1234
|
-
* Typed Ax output for analyst findings.
|
|
1235
|
-
*
|
|
1236
|
-
* Ax binds the field as `findings:json[]` so the provider emits native
|
|
1237
|
-
* structured output. At the kind-factory boundary every row is validated
|
|
1238
|
-
* before it becomes an `AnalystFinding`.
|
|
1239
|
-
*
|
|
1240
|
-
* Why not `f.object().array()` directly in the signature? The Ax
|
|
1241
|
-
* signature string `question:string -> findings:json[]` already lets
|
|
1242
|
-
* the provider emit JSON arrays. A Zod boundary is required either
|
|
1243
|
-
* way (the provider can return any JSON), and Zod gives us a single
|
|
1244
|
-
* validation surface independent of which Ax version is installed.
|
|
1245
|
-
*/
|
|
1246
|
-
const ANALYST_SEVERITIES = [
|
|
1247
|
-
"critical",
|
|
1248
|
-
"high",
|
|
1249
|
-
"medium",
|
|
1250
|
-
"low",
|
|
1251
|
-
"info"
|
|
1252
|
-
];
|
|
1253
|
-
const RawAnalystEvidenceSchema = z.object({
|
|
1254
|
-
uri: z.string().trim().min(1).max(2e3),
|
|
1255
|
-
excerpt: z.string().max(2e3).optional()
|
|
1256
|
-
}).strict();
|
|
1257
|
-
const RawAnalystFindingBaseShape = {
|
|
1258
|
-
severity: z.enum(ANALYST_SEVERITIES),
|
|
1259
|
-
claim: z.string().min(1).max(2e3),
|
|
1260
|
-
subject: z.string().max(400).refine((subject) => parseFindingSubject(subject) !== null, { message: "subject does not match the finding-subject grammar" }).optional(),
|
|
1261
|
-
confidence: z.number().min(0).max(1),
|
|
1262
|
-
rationale: z.string().max(4e3).optional(),
|
|
1263
|
-
recommended_action: z.string().max(2e3).optional()
|
|
1264
|
-
};
|
|
1265
|
-
const RawAnalystFindingSchema = z.object({
|
|
1266
|
-
...RawAnalystFindingBaseShape,
|
|
1267
|
-
evidence: z.array(RawAnalystEvidenceSchema).min(1)
|
|
1268
|
-
}).strict();
|
|
1269
|
-
/**
|
|
1270
|
-
* Description embedded into the actor prompt so the LLM knows what
|
|
1271
|
-
* shape to emit. Kept here so kinds share one source of truth rather
|
|
1272
|
-
* than restating the schema in every prompt.
|
|
1273
|
-
*/
|
|
1274
|
-
const RAW_FINDING_SCHEMA_PROMPT = `Each finding MUST be a strict JSON object with:
|
|
1275
|
-
- severity: "critical" | "high" | "medium" | "low" | "info"
|
|
1276
|
-
- claim: one-sentence statement (max 2000 chars)
|
|
1277
|
-
- subject?: one exact subject form listed by this kind; omit rather than guess
|
|
1278
|
-
- evidence: REQUIRED non-empty array of {"uri": string, "excerpt"?: string}. Use real identifiers with span://, event://, artifact://, metric://, or finding://. Include a short exact quote in excerpt when available. If nothing is citable, do not emit the finding.
|
|
1279
|
-
- confidence: number 0..1 (0.9+ exact evidence; 0.6-0.8 inferred pattern; <0.5 speculative)
|
|
1280
|
-
- rationale?: one or two reasoning sentences
|
|
1281
|
-
- recommended_action?: concrete imperative change; omit for descriptive findings
|
|
1282
|
-
|
|
1283
|
-
Unknown fields are rejected. Do not emit area; the factory assigns it. Emit [] when there are no findings. Never fabricate evidence.`;
|
|
1284
|
-
/** Convert raw citations into the public finding evidence envelope. */
|
|
1285
|
-
function evidenceRefsFromRawFinding(finding) {
|
|
1286
|
-
return finding.evidence.map(({ uri, excerpt }) => ({
|
|
1287
|
-
kind: evidenceKindFromUri(uri),
|
|
1288
|
-
uri,
|
|
1289
|
-
excerpt
|
|
1290
|
-
}));
|
|
1291
|
-
}
|
|
1292
|
-
function parseRawFinding(row, log) {
|
|
1293
|
-
return parseFindingWithSchema(RawAnalystFindingSchema, row, log);
|
|
1294
|
-
}
|
|
1295
|
-
function parseFindingWithSchema(schema, row, log) {
|
|
1296
|
-
const result = schema.safeParse(row);
|
|
1297
|
-
if (result.success) return result.data;
|
|
1298
|
-
if (typeof row === "string") {
|
|
1299
|
-
const coerced = coerceJson(row);
|
|
1300
|
-
if (coerced !== void 0) {
|
|
1301
|
-
const retry = schema.safeParse(coerced);
|
|
1302
|
-
if (retry.success) return retry.data;
|
|
1303
|
-
}
|
|
1304
|
-
}
|
|
1305
|
-
log?.("finding rejected: schema failure", { issues: result.error.issues.map((i) => ({
|
|
1306
|
-
path: i.path.join("."),
|
|
1307
|
-
code: i.code,
|
|
1308
|
-
message: i.message
|
|
1309
|
-
})) });
|
|
1310
|
-
return null;
|
|
1311
|
-
}
|
|
1312
|
-
function evidenceKindFromUri(uri) {
|
|
1313
|
-
if (uri.startsWith("span://")) return "span";
|
|
1314
|
-
if (uri.startsWith("event://")) return "event";
|
|
1315
|
-
if (uri.startsWith("finding://")) return "finding";
|
|
1316
|
-
if (uri.startsWith("metric://")) return "metric";
|
|
1317
|
-
return "artifact";
|
|
1318
|
-
}
|
|
1319
|
-
//#endregion
|
|
1320
|
-
//#region src/analyst/structure-findings.ts
|
|
1321
|
-
/**
|
|
1322
|
-
* `structureFindings` — the deferred structuring pass (DSPy TwoStepAdapter /
|
|
1323
|
-
* HALO `synthesize_traces` analog). The agentic actor reasons FREE-FORM and
|
|
1324
|
-
* emits a prose `report` (which any model does reliably); this separate, cheap
|
|
1325
|
-
* call's ONLY job is to turn that report into `AnalystFinding[]`. Decoupling
|
|
1326
|
-
* reasoning from structuring is what makes the SEMANTIC findings model-agnostic
|
|
1327
|
-
* — the reasoning model never has to satisfy a strict typed-array contract
|
|
1328
|
-
* while it diagnoses.
|
|
1329
|
-
*
|
|
1330
|
-
* Forgiving: the response runs through `coerceToFindingRows` (de-fence, lift
|
|
1331
|
-
* single→array) before Zod, and on a zero-finding extraction from a substantive
|
|
1332
|
-
* report it reasks ONCE with the schema restated. Returns a typed outcome so a
|
|
1333
|
-
* legitimate "nothing to report" is distinguishable from a failed extraction
|
|
1334
|
-
* (no silent empty).
|
|
1335
|
-
*/
|
|
1336
|
-
const SYSTEM = [
|
|
1337
|
-
"You convert a free-form trace-analysis report into a STRICT JSON array of findings.",
|
|
1338
|
-
"Output ONLY the JSON array — no prose, no code fences.",
|
|
1339
|
-
RAW_FINDING_SCHEMA_PROMPT,
|
|
1340
|
-
"Omit subject when the report does not contain an exact valid locus.",
|
|
1341
|
-
"If the report asserts NO problems, output exactly []."
|
|
1342
|
-
].join(" ");
|
|
1343
|
-
function buildRows(raw, opts) {
|
|
1344
|
-
const rows = coerceToFindingRows(raw);
|
|
1345
|
-
const out = [];
|
|
1346
|
-
for (const row of rows) {
|
|
1347
|
-
const parsed = parseRawFinding(row);
|
|
1348
|
-
if (!parsed) continue;
|
|
1349
|
-
const callbackResult = opts.processRow ? opts.processRow(parsed) : parsed;
|
|
1350
|
-
if (!callbackResult) continue;
|
|
1351
|
-
const processed = parseRawFinding(callbackResult);
|
|
1352
|
-
if (!processed) continue;
|
|
1353
|
-
out.push(makeFinding({
|
|
1354
|
-
analyst_id: opts.analystId,
|
|
1355
|
-
area: opts.area,
|
|
1356
|
-
subject: processed.subject,
|
|
1357
|
-
claim: processed.claim,
|
|
1358
|
-
rationale: processed.rationale,
|
|
1359
|
-
severity: processed.severity,
|
|
1360
|
-
confidence: processed.confidence,
|
|
1361
|
-
evidence_refs: evidenceRefsFromRawFinding(processed),
|
|
1362
|
-
recommended_action: processed.recommended_action,
|
|
1363
|
-
...opts.findingMetadata ? { metadata: { ...opts.findingMetadata } } : {}
|
|
1364
|
-
}));
|
|
1365
|
-
}
|
|
1366
|
-
return out;
|
|
1367
|
-
}
|
|
1368
|
-
async function structureFindings(opts) {
|
|
1369
|
-
const maxReasks = opts.maxReasks ?? 1;
|
|
1370
|
-
if (!Number.isSafeInteger(maxReasks) || maxReasks < 0) throw new RangeError("structureFindings: maxReasks must be a non-negative safe integer");
|
|
1371
|
-
const llm = {
|
|
1372
|
-
baseUrl: opts.baseUrl,
|
|
1373
|
-
apiKey: opts.apiKey,
|
|
1374
|
-
fetch: opts.fetchImpl
|
|
1375
|
-
};
|
|
1376
|
-
const costLedger = opts.costLedger ?? new CostLedger();
|
|
1377
|
-
let user = `TRACE-ANALYSIS REPORT:\n${opts.report}\n\nReturn the findings JSON array.`;
|
|
1378
|
-
for (let attempt = 0; attempt <= maxReasks; attempt++) {
|
|
1379
|
-
const request = {
|
|
1380
|
-
model: opts.model,
|
|
1381
|
-
messages: [{
|
|
1382
|
-
role: "system",
|
|
1383
|
-
content: SYSTEM
|
|
1384
|
-
}, {
|
|
1385
|
-
role: "user",
|
|
1386
|
-
content: user
|
|
1387
|
-
}],
|
|
1388
|
-
maxTokens: opts.maxTokens ?? 2e3
|
|
1389
|
-
};
|
|
1390
|
-
const paid = await costLedger.runPaidCall({
|
|
1391
|
-
channel: "analyst",
|
|
1392
|
-
phase: opts.costPhase ?? "analyst.structure-findings",
|
|
1393
|
-
actor: "structure-findings",
|
|
1394
|
-
model: opts.model,
|
|
1395
|
-
signal: opts.signal,
|
|
1396
|
-
maximumCharge: maximumChargeForLlmRequest(request, llm),
|
|
1397
|
-
tags: {
|
|
1398
|
-
...opts.costTags,
|
|
1399
|
-
analystId: opts.analystId,
|
|
1400
|
-
attempt: String(attempt)
|
|
1401
|
-
},
|
|
1402
|
-
execute: (signal, callId) => callLlm(request, {
|
|
1403
|
-
...llm,
|
|
1404
|
-
signal,
|
|
1405
|
-
idempotencyKey: callId
|
|
1406
|
-
}),
|
|
1407
|
-
receipt: costReceiptFromLlm,
|
|
1408
|
-
receiptFromError: costReceiptFromLlmError
|
|
1409
|
-
});
|
|
1410
|
-
if (!paid.succeeded) throw paid.error;
|
|
1411
|
-
const findings = buildRows(paid.value.content.trim(), opts);
|
|
1412
|
-
if (findings.length > 0) return {
|
|
1413
|
-
findings,
|
|
1414
|
-
outcome: "ok"
|
|
1415
|
-
};
|
|
1416
|
-
if (opts.report.trim().length < 200) return {
|
|
1417
|
-
findings: [],
|
|
1418
|
-
outcome: "ok"
|
|
1419
|
-
};
|
|
1420
|
-
user = `${user}\n\nThat produced no valid findings. The report DOES describe issues — re-extract them as the strict JSON array described in the system prompt. Output ONLY the array.`;
|
|
1421
|
-
}
|
|
1422
|
-
return {
|
|
1423
|
-
findings: [],
|
|
1424
|
-
outcome: "extraction_failed"
|
|
1425
|
-
};
|
|
1426
|
-
}
|
|
1427
|
-
/** Convert one ledger channel's complete call set into one analyst receipt. */
|
|
1428
|
-
function usageReceiptFromCostLedger(ledger, filter = "analyst") {
|
|
1429
|
-
const resolvedFilter = typeof filter === "string" ? { channel: filter } : filter;
|
|
1430
|
-
const summary = ledger.summary(resolvedFilter);
|
|
1431
|
-
const receipts = ledger.list(resolvedFilter);
|
|
1432
|
-
const hasReasoningUsage = receipts.some((receipt) => receipt.reasoningTokens !== void 0);
|
|
1433
|
-
const hasCacheWriteUsage = receipts.some((receipt) => receipt.cacheWriteTokens !== void 0);
|
|
1434
|
-
const cost = summary.costProvenance;
|
|
1435
|
-
return {
|
|
1436
|
-
calls: summary.totalCalls + summary.pendingCalls,
|
|
1437
|
-
tokens: summary.usageComplete ? {
|
|
1438
|
-
input: summary.inputTokens,
|
|
1439
|
-
output: summary.outputTokens,
|
|
1440
|
-
...hasReasoningUsage ? { reasoning: summary.reasoningTokens ?? 0 } : {},
|
|
1441
|
-
...summary.cachedTokens > 0 ? { cached: summary.cachedTokens } : {},
|
|
1442
|
-
...hasCacheWriteUsage ? { cacheWrite: summary.cacheWriteTokens ?? 0 } : {}
|
|
1443
|
-
} : null,
|
|
1444
|
-
cost,
|
|
1445
|
-
...cost.kind === "uncaptured" ? { knownCostUsd: summary.totalCostUsd } : {}
|
|
1446
|
-
};
|
|
1447
|
-
}
|
|
1448
|
-
/** Wait a bounded time for late provider receipts, then take one immutable snapshot. */
|
|
1449
|
-
async function settleUsageReceiptFromCostLedger(ledger, options = {}) {
|
|
1450
|
-
const { timeoutMs: requestedTimeoutMs, ...requestedFilter } = options;
|
|
1451
|
-
const filter = {
|
|
1452
|
-
channel: requestedFilter.channel ?? "analyst",
|
|
1453
|
-
...requestedFilter.phase === void 0 ? {} : { phase: requestedFilter.phase },
|
|
1454
|
-
...requestedFilter.tags === void 0 ? {} : { tags: requestedFilter.tags }
|
|
1455
|
-
};
|
|
1456
|
-
const timeoutMs = validateUsageSettlementTimeout(requestedTimeoutMs);
|
|
1457
|
-
const waitResult = ledger.summary(filter).pendingCalls === 0 ? true : ledger.waitForIdle ? await ledger.waitForIdle({ timeoutMs }) : false;
|
|
1458
|
-
const pendingCalls = ledger.summary(filter).pendingCalls;
|
|
1459
|
-
return {
|
|
1460
|
-
settled: waitResult && pendingCalls === 0,
|
|
1461
|
-
pendingCalls,
|
|
1462
|
-
receipt: usageReceiptFromCostLedger(ledger, filter)
|
|
1463
|
-
};
|
|
1464
|
-
}
|
|
1465
|
-
function validateUsageSettlementTimeout(timeoutMs) {
|
|
1466
|
-
const resolved = timeoutMs ?? 5e3;
|
|
1467
|
-
if (!Number.isSafeInteger(resolved) || resolved < 0 || resolved > 2147483647) throw new TypeError("settlementTimeoutMs must be a non-negative safe integer no greater than 2147483647");
|
|
1468
|
-
return resolved;
|
|
1469
|
-
}
|
|
1470
|
-
//#endregion
|
|
1471
|
-
//#region src/analyst/kind-factory.ts
|
|
1472
|
-
/**
|
|
1473
|
-
* Build an `Analyst<TraceAnalysisStore>` from a kind spec.
|
|
1474
|
-
*
|
|
1475
|
-
* Lifts the Ax pipeline once at registration time so the registry
|
|
1476
|
-
* gets a stateless analyst. The Ax agent is freshly constructed per
|
|
1477
|
-
* `analyze()` call (the agent carries chat-log + usage state we don't
|
|
1478
|
-
* want shared across analyst runs).
|
|
1479
|
-
*/
|
|
1480
|
-
function createTraceAnalystKind(spec, opts) {
|
|
1481
|
-
rejectRemovedKindOptions(spec);
|
|
1482
|
-
const version = opts.versionSuffix ? `${spec.version}+${opts.versionSuffix}` : spec.version;
|
|
1483
|
-
const model = resolveAnalystModel(opts.ai, opts.model);
|
|
1484
|
-
const minimumEvidenceCitations = spec.minimumEvidenceCitations ?? 1;
|
|
1485
|
-
if (!Number.isInteger(minimumEvidenceCitations) || minimumEvidenceCitations < 1) throw new TypeError("minimumEvidenceCitations must be a positive integer");
|
|
1486
|
-
const settlementTimeoutMs = validateUsageSettlementTimeout(opts.settlementTimeoutMs);
|
|
1487
|
-
return {
|
|
1488
|
-
id: spec.id,
|
|
1489
|
-
description: spec.description,
|
|
1490
|
-
inputKind: "trace-store",
|
|
1491
|
-
cost: {
|
|
1492
|
-
...spec.cost,
|
|
1493
|
-
settlement_timeout_ms: settlementTimeoutMs
|
|
1494
|
-
},
|
|
1495
|
-
version,
|
|
1496
|
-
async analyze(store, ctx) {
|
|
1497
|
-
const maxOutputTokens = spec.maxOutputTokens ?? 4096;
|
|
1498
|
-
const costLedger = ctx.costLedger ?? new CostLedger(ctx.budgetUsd);
|
|
1499
|
-
const costTags = {
|
|
1500
|
-
...ctx.tags ?? {},
|
|
1501
|
-
analystId: spec.id,
|
|
1502
|
-
...ctx.correlationId ? { analystRunId: ctx.correlationId } : {}
|
|
1503
|
-
};
|
|
1504
|
-
const meteredAi = meterAxChatService(opts.ai, {
|
|
1505
|
-
ledger: costLedger,
|
|
1506
|
-
actor: spec.id,
|
|
1507
|
-
maxOutputTokens,
|
|
1508
|
-
defaultModel: model,
|
|
1509
|
-
phase: ctx.costPhase,
|
|
1510
|
-
signal: ctx.signal,
|
|
1511
|
-
tags: costTags
|
|
1512
|
-
});
|
|
1513
|
-
try {
|
|
1514
|
-
const tools = spec.buildTools(store);
|
|
1515
|
-
const maxSubqueries = spec.subqueries?.maxCalls ?? 0;
|
|
1516
|
-
const maxParallel = spec.subqueries?.maxParallel ?? 2;
|
|
1517
|
-
const priorContext = renderPriorFindings(ctx.priorFindings);
|
|
1518
|
-
const upstreamContext = renderUpstreamFindings(ctx.upstreamFindings);
|
|
1519
|
-
const actorDescription = spec.actorDescription.trim() + priorContext + upstreamContext + "\n\n" + RAW_FINDING_SCHEMA_PROMPT + (minimumEvidenceCitations > 1 ? `\n\nThis kind requires at least ${minimumEvidenceCitations} evidence citations per finding; rows with fewer are rejected.` : "") + "\n\nFirst write `report`: a concise free-form prose diagnosis of what the traces show — what succeeded, what was suboptimal or failed — with concrete trace ids and numbers. THEN return the structured `findings` array (it MAY be empty when there is nothing to report).";
|
|
1520
|
-
ctx.log?.(`analyst.kind ${spec.id} forward`, {
|
|
1521
|
-
max_subqueries: maxSubqueries,
|
|
1522
|
-
tool_count: tools.length,
|
|
1523
|
-
tags: ctx.tags
|
|
1524
|
-
});
|
|
1525
|
-
const { report, findings: submittedFindings } = await runTraceAnalysisLoop({
|
|
1526
|
-
id: spec.id,
|
|
1527
|
-
description: spec.description,
|
|
1528
|
-
prompt: actorDescription,
|
|
1529
|
-
question: deriveQuestion(ctx, spec),
|
|
1530
|
-
ai: meteredAi,
|
|
1531
|
-
model,
|
|
1532
|
-
tools,
|
|
1533
|
-
findingType: "object",
|
|
1534
|
-
maxSubqueries,
|
|
1535
|
-
maxParallelSubqueries: maxParallel,
|
|
1536
|
-
maxTurns: spec.maxTurns ?? 12,
|
|
1537
|
-
maxRuntimeChars: spec.maxRuntimeChars ?? 6e3,
|
|
1538
|
-
...ctx.signal ? { signal: ctx.signal } : {}
|
|
1539
|
-
});
|
|
1540
|
-
const expectedSubjects = KIND_EXPECTED_SUBJECTS[spec.id];
|
|
1541
|
-
const out = [];
|
|
1542
|
-
const rawRows = submittedFindings;
|
|
1543
|
-
let rejectedWrongKind = 0;
|
|
1544
|
-
let rejectedInsufficientEvidence = 0;
|
|
1545
|
-
const processRow = (parsed) => {
|
|
1546
|
-
const callbackResult = spec.postProcess ? spec.postProcess(parsed, ctx) : parsed;
|
|
1547
|
-
if (!callbackResult) return null;
|
|
1548
|
-
const postProcessed = parseRawFinding(callbackResult, ctx.log);
|
|
1549
|
-
if (!postProcessed) return null;
|
|
1550
|
-
if (expectedSubjects && postProcessed.subject !== void 0) {
|
|
1551
|
-
const parsedSubject = parseFindingSubject(postProcessed.subject);
|
|
1552
|
-
if (parsedSubject === null) {
|
|
1553
|
-
ctx.log?.("finding rejected: subject failed to parse", {
|
|
1554
|
-
kind: spec.id,
|
|
1555
|
-
subject: postProcessed.subject
|
|
1556
|
-
});
|
|
1557
|
-
rejectedWrongKind += 1;
|
|
1558
|
-
return null;
|
|
1559
|
-
}
|
|
1560
|
-
if (!expectedSubjects.includes(parsedSubject.kind)) {
|
|
1561
|
-
ctx.log?.("finding rejected: subject variant not allowed for this kind", {
|
|
1562
|
-
kind: spec.id,
|
|
1563
|
-
subject_kind: parsedSubject.kind,
|
|
1564
|
-
subject: postProcessed.subject,
|
|
1565
|
-
allowed: expectedSubjects
|
|
1566
|
-
});
|
|
1567
|
-
rejectedWrongKind += 1;
|
|
1568
|
-
return null;
|
|
1569
|
-
}
|
|
1570
|
-
}
|
|
1571
|
-
const distinctEvidenceCitations = new Set(postProcessed.evidence.map((citation) => citation.uri.trim())).size;
|
|
1572
|
-
if (distinctEvidenceCitations < minimumEvidenceCitations) {
|
|
1573
|
-
ctx.log?.("finding rejected: insufficient evidence citations", {
|
|
1574
|
-
kind: spec.id,
|
|
1575
|
-
required: minimumEvidenceCitations,
|
|
1576
|
-
received: postProcessed.evidence.length,
|
|
1577
|
-
distinct: distinctEvidenceCitations
|
|
1578
|
-
});
|
|
1579
|
-
rejectedInsufficientEvidence += 1;
|
|
1580
|
-
return null;
|
|
1581
|
-
}
|
|
1582
|
-
return postProcessed;
|
|
1583
|
-
};
|
|
1584
|
-
for (const row of rawRows) {
|
|
1585
|
-
const parsed = parseRawFinding(row, ctx.log);
|
|
1586
|
-
if (!parsed) continue;
|
|
1587
|
-
const postProcessed = processRow(parsed);
|
|
1588
|
-
if (!postProcessed) continue;
|
|
1589
|
-
out.push(toAnalystFinding(spec, version, postProcessed));
|
|
1590
|
-
}
|
|
1591
|
-
ctx.log?.(`analyst.kind ${spec.id} done`, {
|
|
1592
|
-
emitted: rawRows.length,
|
|
1593
|
-
accepted: out.length,
|
|
1594
|
-
rejected_wrong_subject: rejectedWrongKind,
|
|
1595
|
-
rejected_insufficient_evidence: rejectedInsufficientEvidence
|
|
1596
|
-
});
|
|
1597
|
-
if (out.length === 0 && report.trim().length >= 200) {
|
|
1598
|
-
if (opts.recovery) {
|
|
1599
|
-
const wrongKindBefore = rejectedWrongKind;
|
|
1600
|
-
const insufficientEvidenceBefore = rejectedInsufficientEvidence;
|
|
1601
|
-
const recovered = await structureFindings({
|
|
1602
|
-
report,
|
|
1603
|
-
analystId: spec.id,
|
|
1604
|
-
area: spec.area,
|
|
1605
|
-
model: opts.recovery.model ?? model,
|
|
1606
|
-
baseUrl: opts.recovery.baseUrl,
|
|
1607
|
-
apiKey: opts.recovery.apiKey,
|
|
1608
|
-
fetchImpl: opts.recovery.fetchImpl,
|
|
1609
|
-
costLedger,
|
|
1610
|
-
costPhase: ctx.costPhase,
|
|
1611
|
-
costTags,
|
|
1612
|
-
signal: ctx.signal,
|
|
1613
|
-
maxTokens: Math.min(maxOutputTokens, 2e3),
|
|
1614
|
-
processRow,
|
|
1615
|
-
findingMetadata: { kind_version: version }
|
|
1616
|
-
});
|
|
1617
|
-
out.push(...recovered.findings);
|
|
1618
|
-
ctx.log?.(`analyst.kind ${spec.id} recovery`, {
|
|
1619
|
-
outcome: recovered.outcome,
|
|
1620
|
-
recovered: recovered.findings.length,
|
|
1621
|
-
rejected_wrong_subject: rejectedWrongKind - wrongKindBefore,
|
|
1622
|
-
rejected_insufficient_evidence: rejectedInsufficientEvidence - insufficientEvidenceBefore
|
|
1623
|
-
});
|
|
1624
|
-
}
|
|
1625
|
-
if (out.length === 0) {
|
|
1626
|
-
const fallback = processRow({
|
|
1627
|
-
claim: "Analyst produced a diagnosis but no structured findings — see report.",
|
|
1628
|
-
rationale: report.slice(0, 1500),
|
|
1629
|
-
severity: "info",
|
|
1630
|
-
confidence: .3,
|
|
1631
|
-
evidence: [{
|
|
1632
|
-
uri: "report://summary",
|
|
1633
|
-
excerpt: report.slice(0, 2e3)
|
|
1634
|
-
}]
|
|
1635
|
-
});
|
|
1636
|
-
if (fallback) out.push(toAnalystFinding(spec, version, fallback, { outcome: "extraction_failed" }));
|
|
1637
|
-
else throw new Error(`Trace analyst '${spec.id}' produced a substantive report, but no finding satisfied its acceptance rules`);
|
|
1638
|
-
}
|
|
1639
|
-
}
|
|
1640
|
-
return out;
|
|
1641
|
-
} finally {
|
|
1642
|
-
const usage = await settleUsageReceiptFromCostLedger(costLedger, {
|
|
1643
|
-
tags: {
|
|
1644
|
-
analystId: spec.id,
|
|
1645
|
-
...ctx.correlationId ? { analystRunId: ctx.correlationId } : {}
|
|
1646
|
-
},
|
|
1647
|
-
timeoutMs: settlementTimeoutMs
|
|
1648
|
-
});
|
|
1649
|
-
if (!usage.settled) ctx.log?.(`analyst.kind ${spec.id} provider settlement timed out`, {
|
|
1650
|
-
pending_calls: usage.pendingCalls,
|
|
1651
|
-
timeout_ms: settlementTimeoutMs
|
|
1652
|
-
});
|
|
1653
|
-
ctx.recordUsage?.(usage.receipt);
|
|
1654
|
-
}
|
|
1655
|
-
}
|
|
1656
|
-
};
|
|
1657
|
-
}
|
|
1658
|
-
function rejectRemovedKindOptions(spec) {
|
|
1659
|
-
const supplied = spec;
|
|
1660
|
-
for (const [removed, replacement] of [
|
|
1661
|
-
["recursion", "subqueries"],
|
|
1662
|
-
["responderDescription", "actorDescription"],
|
|
1663
|
-
["maxDepth", "subqueries"],
|
|
1664
|
-
["maxParallelSubagents", "subqueries.maxParallel"],
|
|
1665
|
-
["subagentDescription", "actorDescription"]
|
|
1666
|
-
]) if (removed in supplied) throw new TypeError(`createTraceAnalystKind: '${removed}' is unsupported; use '${replacement}'`);
|
|
1667
|
-
}
|
|
1668
|
-
function deriveQuestion(ctx, spec) {
|
|
1669
|
-
const focus = ctx.tags?.focus?.trim();
|
|
1670
|
-
const task = `Analyze this trace dataset with the available tools and report ${spec.area} findings. ${spec.description}`;
|
|
1671
|
-
return focus ? `${task} Focus: ${focus}.` : task;
|
|
1672
|
-
}
|
|
1673
|
-
function toAnalystFinding(spec, version, raw, metadata = {}) {
|
|
1674
|
-
return makeFinding({
|
|
1675
|
-
analyst_id: spec.id,
|
|
1676
|
-
area: spec.area,
|
|
1677
|
-
subject: raw.subject,
|
|
1678
|
-
claim: raw.claim,
|
|
1679
|
-
rationale: raw.rationale,
|
|
1680
|
-
severity: raw.severity,
|
|
1681
|
-
confidence: raw.confidence,
|
|
1682
|
-
evidence_refs: evidenceRefsFromRawFinding(raw),
|
|
1683
|
-
recommended_action: raw.recommended_action,
|
|
1684
|
-
metadata: {
|
|
1685
|
-
kind_version: version,
|
|
1686
|
-
...metadata
|
|
1687
|
-
}
|
|
1688
|
-
});
|
|
1689
|
-
}
|
|
1690
|
-
/**
|
|
1691
|
-
* Render a compact prior-findings block the actor reads alongside its
|
|
1692
|
-
* brief. Each row is one line so the actor can scan dozens cheaply.
|
|
1693
|
-
* The kind's prompt instructs the actor to (a) check whether a new
|
|
1694
|
-
* cluster matches a prior `finding_id` (carry the id forward via
|
|
1695
|
-
* `id_basis` to keep diffs stable) and (b) raise severity / confidence
|
|
1696
|
-
* when a prior finding has reappeared without remediation.
|
|
1697
|
-
*
|
|
1698
|
-
* Returns the empty string when there are no prior findings — most
|
|
1699
|
-
* runs are "first-of-its-kind" and the prompt stays unchanged.
|
|
1700
|
-
*
|
|
1701
|
-
* Exported for tests + for consumers that build their own actor
|
|
1702
|
-
* prompts (e.g. specialized analysts living outside the default kinds).
|
|
1703
|
-
*/
|
|
1704
|
-
function renderPriorFindings(prior) {
|
|
1705
|
-
if (!prior || prior.length === 0) return "";
|
|
1706
|
-
const MAX_ROWS = 40;
|
|
1707
|
-
const rows = prior.slice(0, MAX_ROWS).map((f) => {
|
|
1708
|
-
const subject = f.subject ? ` [${f.subject}]` : "";
|
|
1709
|
-
return ` - id=${f.finding_id} ${f.severity}${subject} ${truncateForContext(f.claim, 160)}`;
|
|
1710
|
-
});
|
|
1711
|
-
const overflow = prior.length > MAX_ROWS ? `\n ... +${prior.length - MAX_ROWS} more prior findings (older history truncated)` : "";
|
|
1712
|
-
return [
|
|
1713
|
-
"",
|
|
1714
|
-
"",
|
|
1715
|
-
"PRIOR FINDINGS (from a previous run on related data):",
|
|
1716
|
-
"When the work you do now matches a row below, REUSE the `finding_id` (pass it as `id_basis`) so the cross-run diff stays stable.",
|
|
1717
|
-
"A finding that reappears with no remediation evidence SHOULD raise its `confidence` and may justify a higher `severity`.",
|
|
1718
|
-
...rows,
|
|
1719
|
-
overflow
|
|
1720
|
-
].filter(Boolean).join("\n");
|
|
1721
|
-
}
|
|
1722
|
-
/** Render findings produced earlier in this same registry run. */
|
|
1723
|
-
function renderUpstreamFindings(upstream) {
|
|
1724
|
-
if (!upstream || upstream.length === 0) return "";
|
|
1725
|
-
const MAX_ROWS = 40;
|
|
1726
|
-
const rows = upstream.slice(0, MAX_ROWS).map((finding) => {
|
|
1727
|
-
const subject = finding.subject ? ` [${finding.subject}]` : "";
|
|
1728
|
-
const action = finding.recommended_action ? ` action=${truncateForContext(finding.recommended_action, 120)}` : "";
|
|
1729
|
-
const evidence = finding.evidence_refs[0] ? ` evidence=${truncateForContext(finding.evidence_refs[0].uri, 120)}` : "";
|
|
1730
|
-
return ` - id=${finding.finding_id} source=${finding.analyst_id} ${finding.severity}${subject} claim=${truncateForContext(finding.claim, 160)}${action}${evidence}`;
|
|
1731
|
-
});
|
|
1732
|
-
const overflow = upstream.length > MAX_ROWS ? `\n ... +${upstream.length - MAX_ROWS} more upstream findings (truncated)` : "";
|
|
1733
|
-
return [
|
|
1734
|
-
"",
|
|
1735
|
-
"",
|
|
1736
|
-
"UPSTREAM FINDINGS (produced earlier in this same registry run):",
|
|
1737
|
-
"Use these as intermediate evidence. Build on them instead of repeating the same diagnosis, and cite a dependency with `finding://<id>`.",
|
|
1738
|
-
...rows,
|
|
1739
|
-
overflow
|
|
1740
|
-
].filter(Boolean).join("\n");
|
|
1741
|
-
}
|
|
1742
|
-
function truncateForContext(s, max) {
|
|
1743
|
-
if (s.length <= max) return s;
|
|
1744
|
-
return `${s.slice(0, max - 1).trimEnd()}…`;
|
|
1745
|
-
}
|
|
1746
|
-
//#endregion
|
|
1747
|
-
//#region src/analyst/kinds/control-integrity.ts
|
|
1748
|
-
const ANALYST_ID = "control-integrity";
|
|
1749
|
-
function shown(value) {
|
|
1750
|
-
if (value === void 0) return "<absent>";
|
|
1751
|
-
const encoded = JSON.stringify(value);
|
|
1752
|
-
return encoded === void 0 ? String(value) : encoded;
|
|
1753
|
-
}
|
|
1754
|
-
function evidenceRef(namespace, value) {
|
|
1755
|
-
return {
|
|
1756
|
-
kind: "metric",
|
|
1757
|
-
uri: `supervisor-run://${encodeURIComponent(namespace)}/${value.path}`,
|
|
1758
|
-
excerpt: shown(value.value)
|
|
1759
|
-
};
|
|
1760
|
-
}
|
|
1761
|
-
/** Translate typed supervisor-run integrity issues into the shared analyst envelope. */
|
|
1762
|
-
function emitControlIntegrityFindings(input, producedAt) {
|
|
1763
|
-
const report = analyzeSupervisorRunIntegrity(input, { capturedAt: producedAt });
|
|
1764
|
-
return report.issues.map((issue) => makeFinding({
|
|
1765
|
-
analyst_id: ANALYST_ID,
|
|
1766
|
-
produced_at: producedAt,
|
|
1767
|
-
area: issue.area,
|
|
1768
|
-
severity: issue.severity,
|
|
1769
|
-
subject: `${report.runRef}/${issue.subject}`,
|
|
1770
|
-
claim: issue.claim,
|
|
1771
|
-
rationale: issue.detail,
|
|
1772
|
-
evidence_refs: issue.evidence.map((value) => evidenceRef(report.runRef, value)),
|
|
1773
|
-
recommended_action: issue.recommendedAction,
|
|
1774
|
-
validation_plan: "Re-run this deterministic analyst on the retained SupervisorRunSources or SupervisorRunTree after correcting the producer.",
|
|
1775
|
-
confidence: 1,
|
|
1776
|
-
metadata: {
|
|
1777
|
-
integrity_code: issue.code,
|
|
1778
|
-
integrity_input: report.input,
|
|
1779
|
-
integrity_run_ref: report.runRef,
|
|
1780
|
-
integrity_subject: issue.subject,
|
|
1781
|
-
...issue.metadata
|
|
1782
|
-
}
|
|
1783
|
-
}));
|
|
1784
|
-
}
|
|
1785
|
-
/** Deterministic Analyst adapter for `SupervisorRunSources | SupervisorRunTree`. */
|
|
1786
|
-
var ControlIntegrityAnalyst = class {
|
|
1787
|
-
id = ANALYST_ID;
|
|
1788
|
-
description = "Deterministic supervisor-run integrity checks with explicit unavailable evidence.";
|
|
1789
|
-
inputKind = "custom";
|
|
1790
|
-
cost = {
|
|
1791
|
-
kind: "deterministic",
|
|
1792
|
-
est_usd_per_run: 0
|
|
1793
|
-
};
|
|
1794
|
-
version = "2.0.0";
|
|
1795
|
-
async analyze(input, ctx) {
|
|
1796
|
-
const findings = emitControlIntegrityFindings(input, ctx.tags?.producedAt ?? (/* @__PURE__ */ new Date()).toISOString());
|
|
1797
|
-
ctx.log?.(`control-integrity: ${findings.length} finding(s)`, { input: "nodes" in input ? "SupervisorRunTree" : "SupervisorRunSources" });
|
|
1798
|
-
return findings;
|
|
1799
|
-
}
|
|
1800
|
-
};
|
|
1801
|
-
const CONTROL_INTEGRITY_ANALYST = new ControlIntegrityAnalyst();
|
|
1802
|
-
//#endregion
|
|
1803
|
-
//#region src/analyst/tool-groups.ts
|
|
1804
|
-
const TOOL_NAMES_BY_GROUP = {
|
|
1805
|
-
all: /* @__PURE__ */ new Set(),
|
|
1806
|
-
discovery: /* @__PURE__ */ new Set([
|
|
1807
|
-
"getDatasetOverview",
|
|
1808
|
-
"queryTraces",
|
|
1809
|
-
"countTraces"
|
|
1810
|
-
]),
|
|
1811
|
-
discoveryAndRead: /* @__PURE__ */ new Set([
|
|
1812
|
-
"getDatasetOverview",
|
|
1813
|
-
"queryTraces",
|
|
1814
|
-
"countTraces",
|
|
1815
|
-
"viewTrace",
|
|
1816
|
-
"viewSpans"
|
|
1817
|
-
]),
|
|
1818
|
-
discoveryAndSearch: /* @__PURE__ */ new Set([
|
|
1819
|
-
"getDatasetOverview",
|
|
1820
|
-
"queryTraces",
|
|
1821
|
-
"countTraces",
|
|
1822
|
-
"searchTrace",
|
|
1823
|
-
"searchSpan"
|
|
1824
|
-
]),
|
|
1825
|
-
targeted: /* @__PURE__ */ new Set([
|
|
1826
|
-
"getDatasetOverview",
|
|
1827
|
-
"queryTraces",
|
|
1828
|
-
"viewSpans",
|
|
1829
|
-
"searchSpan"
|
|
1830
|
-
])
|
|
1831
|
-
};
|
|
1832
|
-
/**
|
|
1833
|
-
* Build the tool set for a named group bound to a specific trace store.
|
|
1834
|
-
*
|
|
1835
|
-
* `all` returns every tool. Other groups filter `buildTraceAnalystTools`
|
|
1836
|
-
* by name to the documented subset. An unrecognised group name throws —
|
|
1837
|
-
* silently returning all tools would defeat the cost-control point.
|
|
1838
|
-
*/
|
|
1839
|
-
function buildTraceToolsForGroup(group, store) {
|
|
1840
|
-
const all = buildTraceAnalystTools({ store });
|
|
1841
|
-
if (group === "all") return all;
|
|
1842
|
-
const allow = TOOL_NAMES_BY_GROUP[group];
|
|
1843
|
-
if (!allow) throw new Error(`unknown trace tool group: ${group}`);
|
|
1844
|
-
return all.filter((tool) => allow.has(tool.name));
|
|
1845
|
-
}
|
|
1846
|
-
const FAILURE_MODE_KIND_SPEC = {
|
|
1847
|
-
id: "failure-mode",
|
|
1848
|
-
description: "Clusters trace-dataset failures into distinct failure modes with cited evidence and a short recommended action.",
|
|
1849
|
-
area: "failure-mode",
|
|
1850
|
-
version: "1.2.0",
|
|
1851
|
-
actorDescription: `You are a failure-mode classifier for an OTLP trace dataset. Your job is to identify the **distinct ways agents failed** in this dataset, not to grade individual runs.
|
|
1852
|
-
|
|
1853
|
-
${findingSubjectGrammarPromptFor("failure-mode")}
|
|
1854
|
-
|
|
1855
|
-
DISCOVERY → CLUSTER → CITE protocol:
|
|
1856
|
-
|
|
1857
|
-
1. Call \`traces.getDatasetOverview({})\` first. Use \`has_errors\`, \`models\`, \`agent_names\`, \`tools\`, and \`sample_trace_ids\` to size the failure surface.
|
|
1858
|
-
2. Use \`traces.queryTraces({ filters: { has_errors: true }, limit })\` to pull error-bearing traces. Combine with \`traces.countTraces\` to see what fraction of the dataset failed.
|
|
1859
|
-
3. For each candidate failure cluster, use \`traces.searchTrace\` with regex like \`STATUS_CODE_ERROR\`, \`MaxTurnsExceeded\`, \`assertion\`, \`unauthorized\`, \`timeout\`, \`429\`, \`5\\d\\d\`, the agent's specific error strings, or the names of its tools. Pull one or two representative traces per cluster, **not all** of them.
|
|
1860
|
-
4. **Cluster, do not enumerate.** Two failures with the same root cause should be ONE finding citing both traces, not two findings. The point of this analyst is to compress N runs into K modes.
|
|
1861
|
-
5. For each defensible cluster, emit ONE finding. Use a lowercase cluster label matching the subject grammar ("tool-call-loop", "auth-revoked-mid-run", ...). Rate it critical when it blocks the run, high when the run finishes degraded, and medium when it slows convergence. Cite representative spans and include exact error, payload, or contradictory-output quotes. Use confidence 0.85+ when multiple traces show the same shape, 0.6-0.8 for a single-trace inference, and <0.5 for speculation. Keep the imperative fix idea short; the improvement analyst expands it.
|
|
1862
|
-
|
|
1863
|
-
If the dataset has no failures, return an empty findings array — do NOT pad with low-confidence speculation.
|
|
1864
|
-
|
|
1865
|
-
**Use subqueries over loaded evidence.** After the first scan, load representative span excerpts for each candidate cluster. Then send one bounded \`llmQuery\` per cluster in one batch, including the exact excerpts and asking it to classify the root cause. Subqueries cannot call trace tools. Merge or split clusters yourself from their classifications and the cited source evidence.
|
|
1866
|
-
|
|
1867
|
-
OBSERVABILITY rules:
|
|
1868
|
-
- Each non-final turn must emit at least one \`console.log\` for evidence.
|
|
1869
|
-
- Reuse runtime variables across turns; don't recompute.`,
|
|
1870
|
-
buildTools: (store) => buildTraceToolsForGroup("all", store),
|
|
1871
|
-
subqueries: {
|
|
1872
|
-
maxCalls: 8,
|
|
1873
|
-
maxParallel: 4
|
|
1874
|
-
},
|
|
1875
|
-
maxTurns: 24,
|
|
1876
|
-
cost: { kind: "llm" }
|
|
1877
|
-
};
|
|
1878
|
-
const IMPROVEMENT_KIND_SPEC = {
|
|
1879
|
-
id: "improvement",
|
|
1880
|
-
description: "Converts upstream failure / gap / poisoning findings into concrete locus-named edits (prompt, tool-doc, RAG, scaffolding) with leverage grades.",
|
|
1881
|
-
area: "improvement",
|
|
1882
|
-
version: "1.2.0",
|
|
1883
|
-
actorDescription: `You are a self-improvement analyst. Your job is to propose **concrete, locus-named edits** the agent's runtime should adopt to fix the failure modes, knowledge gaps, and poisonings present in this dataset.
|
|
1884
|
-
|
|
1885
|
-
Upstream analysts have already classified the problems. Your job is to convert each problem into a *change to make* and grade its expected leverage. Each finding is one proposed edit.
|
|
1886
|
-
|
|
1887
|
-
${findingSubjectGrammarPromptFor("improvement")}
|
|
1888
|
-
|
|
1889
|
-
DISCOVERY → CANDIDATE-FIXES → COMPETE → CITE protocol:
|
|
1890
|
-
|
|
1891
|
-
1. \`traces.getDatasetOverview({})\` first. Note the agents, tools, and any system-prompt fingerprints (look for the prompt text echoed in early spans).
|
|
1892
|
-
2. For each high-severity failure pattern, generate 2-3 candidate fixes. Real candidate axes:
|
|
1893
|
-
- **System-prompt edit** — add an instruction, remove a misleading one, restructure precedence
|
|
1894
|
-
- **Tool description edit** — rewrite a tool's description so the agent picks it correctly / passes valid args
|
|
1895
|
-
- **New tool** — add a tool the agent kept emulating in code
|
|
1896
|
-
- **RAG ingestion** — add a document or correct a stale one
|
|
1897
|
-
- **Memory invalidation** — clear cached prior-run decisions that no longer apply
|
|
1898
|
-
- **Scaffolding** — add a precondition check, a retry policy, a turn budget, a verification step
|
|
1899
|
-
- **Output schema** — narrow the agent's output to forbid the failure shape
|
|
1900
|
-
- **Skill / MCP / hook / subagent** — change the reusable profile component responsible for the behavior
|
|
1901
|
-
- **Workflow / rollout policy** — change orchestration, budget, sampling, or stopping behavior
|
|
1902
|
-
- **Code** — change an implementation path when profile edits cannot repair the behavior
|
|
1903
|
-
3. **Compare candidate fixes with bounded subqueries.** Load the representative failure excerpts, then send one \`llmQuery\` per candidate-fix axis the same evidence. Ask for likely effect, side effects, and implementation scope. Subqueries cannot call trace tools; trace ids alone are insufficient context.
|
|
1904
|
-
4. After the comparisons return, **pick the winning candidate per cluster** based on expected effect and risk, then emit ONE finding. Keep the alternatives and rejection reasons in the rationale so the recommendation is auditable.
|
|
1905
|
-
5. **Cross-reference upstream findings.** Cite prior failure-mode or knowledge-gap findings as \`finding://<prior-finding-id>\`. This builds the dependency graph that lets the dashboard show "fix #X resolves failure modes A, B, C."
|
|
1906
|
-
|
|
1907
|
-
For each winning recommendation, emit ONE finding. Use one exact locus from the subject grammar and state the edit in one sentence. Match leverage to the source failure's severity; use medium for quality-of-life changes and info for cleanup with no behavioral effect. Cite the targeted \`finding://<id>\` when available and the most representative span when useful. Quote the problem being fixed. Use confidence 0.85+ for a mechanical fix to a well-evidenced failure, 0.6-0.8 when judgment is required, and <0.5 for speculation. Explain in at most two sentences why this candidate beat its alternatives. The recommended action must be the literal diff, quoted replacement, tool description, or setting change.
|
|
1908
|
-
|
|
1909
|
-
If no upstream failure findings exist in this run, derive your own from the trace dataset using the failure-mode protocol inline (\`searchTrace\` for STATUS_CODE_ERROR / MaxTurnsExceeded / etc.). But prefer to consume upstream findings when present — the kinds are designed to chain.
|
|
1910
|
-
|
|
1911
|
-
Do NOT propose a fix you cannot defend with evidence. "Tighten the prompt" is not a finding; "Add 'When the user asks for X, always Y' to the system prompt section "request-classification"" is.
|
|
1912
|
-
|
|
1913
|
-
OBSERVABILITY rules:
|
|
1914
|
-
- Each non-final turn must emit at least one \`console.log\` for evidence.`,
|
|
1915
|
-
buildTools: (store) => buildTraceToolsForGroup("all", store),
|
|
1916
|
-
subqueries: {
|
|
1917
|
-
maxCalls: 8,
|
|
1918
|
-
maxParallel: 4
|
|
1919
|
-
},
|
|
1920
|
-
maxTurns: 30,
|
|
1921
|
-
maxRuntimeChars: 12e3,
|
|
1922
|
-
cost: { kind: "llm" }
|
|
1923
|
-
};
|
|
1924
|
-
const KNOWLEDGE_GAP_KIND_SPEC = {
|
|
1925
|
-
id: "knowledge-gap",
|
|
1926
|
-
description: "Identifies missing or stale pieces of knowledge — primarily against the agent-knowledge wiki — and attributes each to the runtime layer (wiki page, claim, raw source, websearch, tool-doc, system-prompt, memory) that should have held it.",
|
|
1927
|
-
area: "knowledge-gap",
|
|
1928
|
-
version: "1.2.0",
|
|
1929
|
-
actorDescription: `You are a knowledge-gap analyst for an OTLP trace dataset. Your job is to identify the **specific pieces of information the agent lacked, or that were stale**, that caused poor decisions.
|
|
1930
|
-
|
|
1931
|
-
The agent under analysis maintains a curated knowledge base via \`@tangle-network/agent-knowledge\` — a wiki of \`KnowledgePage\`s with raw source anchors, claims, and relations. The primary expected store of agent-knowable facts IS that wiki. A "knowledge gap" is anything the agent had to discover or guess at run-time that the wiki should have held — or an outdated/contradictory fact the agent picked up from a non-wiki source.
|
|
1932
|
-
|
|
1933
|
-
${findingSubjectGrammarPromptFor("knowledge-gap")}
|
|
1934
|
-
|
|
1935
|
-
DISCOVERY → ATTRIBUTE-TO-LAYER → CITE protocol:
|
|
1936
|
-
|
|
1937
|
-
1. \`traces.getDatasetOverview({})\` first. Note which agents, tools, and models appear.
|
|
1938
|
-
2. Pull traces where the agent shows gap signals. The strongest signals are:
|
|
1939
|
-
- Self-correction turns ("I assumed X but…", "let me re-check", "actually,")
|
|
1940
|
-
- Clarifying-question turns where the agent asked the user something the runtime should have surfaced
|
|
1941
|
-
- Repeated retrieval / lookup calls for the same artifact with slightly varied queries
|
|
1942
|
-
- Tool errors that name a missing argument or unknown resource
|
|
1943
|
-
- Web-search calls returning pages dated before a known cutoff for content that changes (versioned APIs, schemas, policies)
|
|
1944
|
-
- Agent quoting a tool's docs / system prompt incorrectly because the actual text was insufficient
|
|
1945
|
-
- Fabricated identifiers that don't appear in dataset \`sample_trace_ids\`
|
|
1946
|
-
Use \`traces.searchTrace\` with patterns like \`I (don.?t|do not) know\`, \`assumed\`, \`unclear\`, \`could you (clarify|tell me|provide)\`, \`not found\`, \`undefined\`, \`unknown\`, \`null\`, dates older than the analysis window, or the agent's specific clarification phrases.
|
|
1947
|
-
3. For each gap, identify the **layer of the runtime that should have prevented it** and use its exact locus from the subject grammar above.
|
|
1948
|
-
4. For each defensible gap, emit ONE finding. Use an exact locus from the subject grammar and name the missing or stale knowledge (for example, "wiki has no page on invoice line-item shape; agent re-derived it from raw spans"). Rate it high when it caused failure or a clarifying question, medium for unnecessary turns, and low for minor inefficiency. Cite the span where the question, correction, retrieval miss, or stale result surfaced and quote it exactly. Use confidence 0.85+ when the agent articulated the gap and 0.6-0.8 when inferred. Recommend a concrete wiki edit for an agent-knowledge locus or a prompt/tool-description edit otherwise.
|
|
1949
|
-
|
|
1950
|
-
**Compare layers over loaded evidence.** After the first scan, load the exact excerpts behind candidates across \`agent-knowledge:*\`, \`websearch:outdated\`, \`tool-doc:*\`, \`system-prompt:*\`, and \`memory:*\`. Use one bounded \`llmQuery\` per layer to classify those excerpts. Subqueries cannot call trace tools. Merge their classifications into the final finding set only when the source excerpts support them.
|
|
1951
|
-
|
|
1952
|
-
Do NOT report a gap that the agent later recovered from cleanly within the same turn — that's resilience, not a gap. Cite the *non-recovery* version when both exist.
|
|
1953
|
-
|
|
1954
|
-
OBSERVABILITY rules:
|
|
1955
|
-
- Each non-final turn must emit at least one \`console.log\` for evidence.`,
|
|
1956
|
-
buildTools: (store) => buildTraceToolsForGroup("discoveryAndSearch", store),
|
|
1957
|
-
subqueries: {
|
|
1958
|
-
maxCalls: 5,
|
|
1959
|
-
maxParallel: 4
|
|
1960
|
-
},
|
|
1961
|
-
maxTurns: 18,
|
|
1962
|
-
cost: { kind: "llm" }
|
|
1963
|
-
};
|
|
1964
|
-
const KNOWLEDGE_POISONING_KIND_SPEC = {
|
|
1965
|
-
id: "knowledge-poisoning",
|
|
1966
|
-
description: "Identifies confident-but-wrong actions caused by stale memory, contradicting RAG, deprecated tool docs, or outdated system-prompt instructions.",
|
|
1967
|
-
area: "knowledge-poisoning",
|
|
1968
|
-
version: "1.2.0",
|
|
1969
|
-
actorDescription: `You are a knowledge-poisoning analyst for an OTLP trace dataset. Your job is to identify cases where the agent **confidently used wrong information** — not where it lacked information (that's the knowledge-gap analyst).
|
|
1970
|
-
|
|
1971
|
-
${findingSubjectGrammarPromptFor("knowledge-poisoning")}
|
|
1972
|
-
|
|
1973
|
-
DISCOVERY → DUAL-VERIFY → CITE protocol:
|
|
1974
|
-
|
|
1975
|
-
1. \`traces.getDatasetOverview({})\` first. Identify the agents, models, and tools.
|
|
1976
|
-
2. Pull traces where the agent's confident action was later contradicted. Strongest signals:
|
|
1977
|
-
- Agent stated a fact in one span; a later span surfaced contradictory evidence; the agent then proceeded anyway or fabricated reconciliation.
|
|
1978
|
-
- Tool call with stale arguments (an id that no longer exists, an API shape that changed).
|
|
1979
|
-
- Agent cited an \`agent-knowledge\` wiki page or claim whose content contradicts the trace's own evidence — the wiki itself drifted.
|
|
1980
|
-
- Web-search result the agent cited that returned an outdated page; agent treated it as canonical.
|
|
1981
|
-
- System-prompt instruction the agent followed that ground-truth evidence in the trace contradicts (e.g. prompt says "use endpoint A"; tool reply says "endpoint A deprecated, use B").
|
|
1982
|
-
- Repeated wrong-shape parsing despite the tool's actual output proving the shape.
|
|
1983
|
-
3. Use \`traces.searchTrace\` with regex on phrases like \`actually\`, \`turns out\`, \`previously assumed\`, \`old version\`, \`deprecated\`, \`updated to\`, \`now uses\`, or specific entity names you suspect have changed.
|
|
1984
|
-
4. For each candidate poisoning, **DUAL-VERIFY**:
|
|
1985
|
-
- Confirm the agent actually acted on the false belief (cite the span where it did)
|
|
1986
|
-
- Confirm the belief is actually false in this trace's own evidence (cite the span that contradicts it)
|
|
1987
|
-
Only emit a finding when both halves are nailed down. If you can only nail one, drop it — single-evidence poisoning findings are too speculative to be useful.
|
|
1988
|
-
|
|
1989
|
-
**Independently assess both halves.** Load the action excerpt and contradicting excerpt yourself, then send bounded \`llmQuery\` calls the exact evidence for "did the agent act?" and "does the trace contradict the belief?" Subqueries cannot call trace tools. Accept a poisoning only when both assessments and the source excerpts support it.
|
|
1990
|
-
|
|
1991
|
-
For each confirmed poisoning, emit ONE finding. Use the source of the false belief as the exact subject. State "agent believed X (from source S); trace evidence shows X is false." Rate it critical for a wrong user-visible action, high when caught internally after significant waste, and medium for inefficiency. Cite BOTH the action span and the contradicting span with exact quotes. Use confidence 0.85+ when both halves have exact quotes and 0.6-0.8 when one half is inferred. Recommend the literal source correction: update the wiki claim, invalidate and re-curate the raw source, or replace the stale prompt/tool instruction.
|
|
1992
|
-
|
|
1993
|
-
Do NOT report a finding if the agent caught and corrected the false belief in the same turn — that's the system working. Reserve poisoning for cases where the false belief shaped downstream action.
|
|
1994
|
-
|
|
1995
|
-
OBSERVABILITY rules:
|
|
1996
|
-
- Each non-final turn must emit at least one \`console.log\` for evidence.`,
|
|
1997
|
-
buildTools: (store) => buildTraceToolsForGroup("all", store),
|
|
1998
|
-
subqueries: {
|
|
1999
|
-
maxCalls: 8,
|
|
2000
|
-
maxParallel: 4
|
|
2001
|
-
},
|
|
2002
|
-
maxTurns: 20,
|
|
2003
|
-
minimumEvidenceCitations: 2,
|
|
2004
|
-
cost: { kind: "llm" }
|
|
2005
|
-
};
|
|
2006
|
-
//#endregion
|
|
2007
|
-
//#region src/analyst/kinds/index.ts
|
|
2008
|
-
/**
|
|
2009
|
-
* The default kind suite. Order is the run order operators should
|
|
2010
|
-
* use: failure-mode first (no upstream deps), gap + poisoning next
|
|
2011
|
-
* (both depend on failures), improvement last (chains all three).
|
|
2012
|
-
*/
|
|
2013
|
-
const DEFAULT_TRACE_ANALYST_KINDS = [
|
|
2014
|
-
FAILURE_MODE_KIND_SPEC,
|
|
2015
|
-
KNOWLEDGE_GAP_KIND_SPEC,
|
|
2016
|
-
KNOWLEDGE_POISONING_KIND_SPEC,
|
|
2017
|
-
IMPROVEMENT_KIND_SPEC
|
|
2018
|
-
];
|
|
2019
|
-
//#endregion
|
|
2020
|
-
//#region src/analyst/registry.ts
|
|
2021
|
-
/**
|
|
2022
|
-
* AnalystRegistry — orchestrate N analysts against one run.
|
|
2023
|
-
*
|
|
2024
|
-
* Owns three responsibilities and only three:
|
|
2025
|
-
* 1. Registration — ids must be unique; bad registrations fail loudly
|
|
2026
|
-
* at register-time, not run-time.
|
|
2027
|
-
* 2. Routing — each analyst declares its `inputKind`; the registry
|
|
2028
|
-
* picks the matching field from AnalystRunInputs and skips the
|
|
2029
|
-
* analyst with a logged reason if it's missing.
|
|
2030
|
-
* 3. Isolation — one analyst's exception MUST NOT stop other analysts.
|
|
2031
|
-
* Failed analysts produce zero findings + a 'failed' summary row.
|
|
2032
|
-
*
|
|
2033
|
-
* Cross-cutting concerns (telemetry, error → finding conversion, cost
|
|
2034
|
-
* ingestion, storage rotation) live in `AnalystHooks`. Budget shaping
|
|
2035
|
-
* (equal split vs weighted vs custom) lives in `BudgetPolicy`. Both
|
|
2036
|
-
* have sensible defaults; consumers override only what they need.
|
|
2037
|
-
*/
|
|
2038
|
-
var AnalystRegistry = class {
|
|
2039
|
-
analysts = /* @__PURE__ */ new Map();
|
|
2040
|
-
options;
|
|
2041
|
-
constructor(options = {}) {
|
|
2042
|
-
this.options = options;
|
|
2043
|
-
}
|
|
2044
|
-
register(analyst) {
|
|
2045
|
-
if (!analyst.id) throw new Error("AnalystRegistry.register: analyst.id is required");
|
|
2046
|
-
if (this.analysts.has(analyst.id)) throw new Error(`AnalystRegistry.register: duplicate analyst id "${analyst.id}"`);
|
|
2047
|
-
if (!analyst.version) throw new Error(`AnalystRegistry.register: analyst "${analyst.id}" must declare a version`);
|
|
2048
|
-
if (analyst.cost.kind === "deterministic" && analyst.cost.settlement_timeout_ms !== void 0) throw new TypeError(`AnalystRegistry.register: deterministic analyst "${analyst.id}" cannot declare settlement_timeout_ms`);
|
|
2049
|
-
if (analyst.cost.settlement_timeout_ms !== void 0) validateUsageSettlementTimeout(analyst.cost.settlement_timeout_ms);
|
|
2050
|
-
this.analysts.set(analyst.id, analyst);
|
|
2051
|
-
}
|
|
2052
|
-
list() {
|
|
2053
|
-
return Array.from(this.analysts.values()).map((a) => ({
|
|
2054
|
-
id: a.id,
|
|
2055
|
-
description: a.description,
|
|
2056
|
-
version: a.version,
|
|
2057
|
-
cost: a.cost
|
|
2058
|
-
}));
|
|
2059
|
-
}
|
|
2060
|
-
async run(runId, inputs, runOpts = {}) {
|
|
2061
|
-
for await (const ev of this.runStream(runId, inputs, runOpts)) if (ev.type === "run-completed") return ev.result;
|
|
2062
|
-
throw new Error("AnalystRegistry.run: stream completed without run-completed event");
|
|
2063
|
-
}
|
|
2064
|
-
/**
|
|
2065
|
-
* Streaming counterpart to `run()`. Emits `AnalystRunEvent` values
|
|
2066
|
-
* in real time — `run-started`, then per-analyst `skipped` /
|
|
2067
|
-
* `started` / `completed`, then a terminal `run-completed` whose
|
|
2068
|
-
* payload is the full `AnalystRunResult`. UIs use this to render
|
|
2069
|
-
* progress; persistence consumers use `run()` and read the result.
|
|
2070
|
-
*
|
|
2071
|
-
* Hooks (`onBeforeAnalyze` / `onAfterAnalyze` / `onError` /
|
|
2072
|
-
* `onComplete`) fire as before — streaming is additive, not a hook
|
|
2073
|
-
* replacement.
|
|
2074
|
-
*/
|
|
2075
|
-
async *runStream(runId, inputs, runOpts = {}) {
|
|
2076
|
-
const correlationId = `ar_${randomUUID().slice(0, 12)}`;
|
|
2077
|
-
const log = this.options.log ?? (() => {});
|
|
2078
|
-
const hooks = this.options.hooks ?? {};
|
|
2079
|
-
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2080
|
-
const started = Date.now();
|
|
2081
|
-
const timeoutMs = validateTimeout(runOpts.timeoutMs);
|
|
2082
|
-
const deadlineMs = timeoutMs === void 0 ? void 0 : started + timeoutMs;
|
|
2083
|
-
const timeoutSignal = timeoutMs === void 0 ? void 0 : AbortSignal.timeout(timeoutMs);
|
|
2084
|
-
const runSignal = combineAbortSignals(runOpts.signal, timeoutSignal);
|
|
2085
|
-
const selected = this.selectAnalysts(runOpts);
|
|
2086
|
-
const budget = runOpts.budget ?? this.options.defaultBudget;
|
|
2087
|
-
validateBudgetPolicy(budget);
|
|
2088
|
-
yield {
|
|
2089
|
-
type: "run-started",
|
|
2090
|
-
run_id: runId,
|
|
2091
|
-
correlation_id: correlationId,
|
|
2092
|
-
started_at: startedAt,
|
|
2093
|
-
analyst_ids: selected.map((a) => a.id)
|
|
2094
|
-
};
|
|
2095
|
-
const summaries = [];
|
|
2096
|
-
const allFindings = [];
|
|
2097
|
-
let totalCost = 0;
|
|
2098
|
-
let remainingUsd = budget?.totalUsd;
|
|
2099
|
-
const runnableAnalysts = selected.filter((a) => this.routeInput(a, inputs).kind !== "missing");
|
|
2100
|
-
const runnableCount = runnableAnalysts.length;
|
|
2101
|
-
const weights = budget?.weights;
|
|
2102
|
-
const totalWeight = weights && budget?.totalUsd != null && !budget.allocate && runnableCount > 0 ? runnableAnalysts.reduce((sum, analyst) => sum + analystWeight(weights, analyst.id), 0) : void 0;
|
|
2103
|
-
if (totalWeight === 0) throw new Error("BudgetPolicy.weights must allocate positive weight to a runnable analyst");
|
|
2104
|
-
for (const analyst of selected) {
|
|
2105
|
-
const t0 = Date.now();
|
|
2106
|
-
if (runSignal?.aborted) {
|
|
2107
|
-
const summary = abortedBeforeStartSummary(analyst, runSignal);
|
|
2108
|
-
summaries.push(summary);
|
|
2109
|
-
log(`[analyst] skip ${analyst.id} — run aborted`, {
|
|
2110
|
-
runId,
|
|
2111
|
-
reason: summary.reason
|
|
2112
|
-
});
|
|
2113
|
-
yield {
|
|
2114
|
-
type: "analyst-skipped",
|
|
2115
|
-
summary
|
|
2116
|
-
};
|
|
2117
|
-
continue;
|
|
2118
|
-
}
|
|
2119
|
-
const input = this.routeInput(analyst, inputs);
|
|
2120
|
-
if (input.kind === "missing") {
|
|
2121
|
-
const summary = {
|
|
2122
|
-
analyst_id: analyst.id,
|
|
2123
|
-
status: "skipped",
|
|
2124
|
-
reason: `missing input of kind '${analyst.inputKind}'`,
|
|
2125
|
-
findings_count: 0,
|
|
2126
|
-
latency_ms: 0,
|
|
2127
|
-
usage: zeroUsage()
|
|
2128
|
-
};
|
|
2129
|
-
summaries.push(summary);
|
|
2130
|
-
log(`[analyst] skip ${analyst.id} — missing input`, {
|
|
2131
|
-
runId,
|
|
2132
|
-
kind: analyst.inputKind
|
|
2133
|
-
});
|
|
2134
|
-
await waitForHook(hooks.onAfterAnalyze ? () => hooks.onAfterAnalyze?.({
|
|
2135
|
-
analyst,
|
|
2136
|
-
summary,
|
|
2137
|
-
findings: [],
|
|
2138
|
-
runId
|
|
2139
|
-
}) : void 0, runSignal);
|
|
2140
|
-
yield {
|
|
2141
|
-
type: "analyst-skipped",
|
|
2142
|
-
summary
|
|
2143
|
-
};
|
|
2144
|
-
continue;
|
|
2145
|
-
}
|
|
2146
|
-
const perBudget = allocateBudget(budget, {
|
|
2147
|
-
analyst,
|
|
2148
|
-
remainingUsd,
|
|
2149
|
-
runningCount: runnableCount,
|
|
2150
|
-
totalWeight
|
|
2151
|
-
});
|
|
2152
|
-
const usageReceipts = [];
|
|
2153
|
-
const ctx = {
|
|
2154
|
-
runId,
|
|
2155
|
-
correlationId,
|
|
2156
|
-
deadlineMs,
|
|
2157
|
-
budgetUsd: perBudget,
|
|
2158
|
-
costLedger: runOpts.costLedger,
|
|
2159
|
-
costPhase: runOpts.costPhase,
|
|
2160
|
-
chat: this.options.chat,
|
|
2161
|
-
tags: runOpts.tags,
|
|
2162
|
-
log: (msg, fields) => log(`[${analyst.id}] ${msg}`, {
|
|
2163
|
-
runId,
|
|
2164
|
-
correlationId,
|
|
2165
|
-
...fields
|
|
2166
|
-
}),
|
|
2167
|
-
signal: runSignal,
|
|
2168
|
-
priorFindings: selectPriorFindings(runOpts.priorFindings, analyst.id),
|
|
2169
|
-
upstreamFindings: runOpts.chainFindings && allFindings.length > 0 ? [...allFindings] : void 0,
|
|
2170
|
-
recordUsage: (receipt) => {
|
|
2171
|
-
assertValidUsageReceipt(receipt);
|
|
2172
|
-
usageReceipts.push(receipt);
|
|
2173
|
-
}
|
|
2174
|
-
};
|
|
2175
|
-
await waitForHook(hooks.onBeforeAnalyze ? () => hooks.onBeforeAnalyze?.({
|
|
2176
|
-
analyst,
|
|
2177
|
-
ctx,
|
|
2178
|
-
runId
|
|
2179
|
-
}) : void 0, runSignal);
|
|
2180
|
-
if (runSignal?.aborted) {
|
|
2181
|
-
const summary = abortedBeforeStartSummary(analyst, runSignal, Date.now() - t0);
|
|
2182
|
-
summaries.push(summary);
|
|
2183
|
-
log(`[analyst] skip ${analyst.id} — run aborted`, {
|
|
2184
|
-
runId,
|
|
2185
|
-
reason: summary.reason
|
|
2186
|
-
});
|
|
2187
|
-
yield {
|
|
2188
|
-
type: "analyst-skipped",
|
|
2189
|
-
summary
|
|
2190
|
-
};
|
|
2191
|
-
continue;
|
|
2192
|
-
}
|
|
2193
|
-
const effectiveBudget = validateEffectiveBudget(ctx.budgetUsd, remainingUsd, analyst.id);
|
|
2194
|
-
yield {
|
|
2195
|
-
type: "analyst-started",
|
|
2196
|
-
analyst_id: analyst.id,
|
|
2197
|
-
started_at: new Date(t0).toISOString()
|
|
2198
|
-
};
|
|
2199
|
-
let findings;
|
|
2200
|
-
let summary;
|
|
2201
|
-
try {
|
|
2202
|
-
if (runSignal?.aborted) throw abortReason(runSignal);
|
|
2203
|
-
findings = await waitForOperation(analyst.analyze(input.value, ctx), runSignal, analystAbortGraceMs(analyst));
|
|
2204
|
-
const latency = Date.now() - t0;
|
|
2205
|
-
const usage = resolveUsage(analyst, usageReceipts);
|
|
2206
|
-
const cost = knownCostUsd(usage);
|
|
2207
|
-
totalCost += cost;
|
|
2208
|
-
if (typeof remainingUsd === "number") remainingUsd = Math.max(0, remainingUsd - budgetDebit(usage, effectiveBudget));
|
|
2209
|
-
allFindings.push(...findings);
|
|
2210
|
-
summary = {
|
|
2211
|
-
analyst_id: analyst.id,
|
|
2212
|
-
status: "ok",
|
|
2213
|
-
findings_count: findings.length,
|
|
2214
|
-
latency_ms: latency,
|
|
2215
|
-
usage
|
|
2216
|
-
};
|
|
2217
|
-
summaries.push(summary);
|
|
2218
|
-
log(`[analyst] ok ${analyst.id}`, {
|
|
2219
|
-
runId,
|
|
2220
|
-
findings: findings.length,
|
|
2221
|
-
latency_ms: latency,
|
|
2222
|
-
cost_usd: cost,
|
|
2223
|
-
cost_kind: usage.cost.kind,
|
|
2224
|
-
input_tokens: usage.tokens?.input ?? null,
|
|
2225
|
-
output_tokens: usage.tokens?.output ?? null
|
|
2226
|
-
});
|
|
2227
|
-
if (effectiveBudget !== void 0 && usage.cost.kind === "uncaptured") log(`[analyst] WARN ${analyst.id} — USD cost uncaptured; budget not reconciled`, {
|
|
2228
|
-
runId,
|
|
2229
|
-
budget_usd: effectiveBudget,
|
|
2230
|
-
cost_captured: false
|
|
2231
|
-
});
|
|
2232
|
-
} catch (err) {
|
|
2233
|
-
const latency = Date.now() - t0;
|
|
2234
|
-
const e = err instanceof Error ? err : new Error(String(err));
|
|
2235
|
-
const hookFindings = runSignal?.aborted ? [] : await hooks.onError?.({
|
|
2236
|
-
analyst,
|
|
2237
|
-
error: e,
|
|
2238
|
-
runId
|
|
2239
|
-
}) ?? [];
|
|
2240
|
-
if (hookFindings.length) allFindings.push(...hookFindings);
|
|
2241
|
-
const usage = resolveUsage(analyst, usageReceipts);
|
|
2242
|
-
const cost = knownCostUsd(usage);
|
|
2243
|
-
totalCost += cost;
|
|
2244
|
-
if (typeof remainingUsd === "number") remainingUsd = Math.max(0, remainingUsd - budgetDebit(usage, effectiveBudget));
|
|
2245
|
-
const summary = {
|
|
2246
|
-
analyst_id: analyst.id,
|
|
2247
|
-
status: "failed",
|
|
2248
|
-
findings_count: hookFindings.length,
|
|
2249
|
-
latency_ms: latency,
|
|
2250
|
-
usage,
|
|
2251
|
-
error: {
|
|
2252
|
-
class: e.constructor.name,
|
|
2253
|
-
message: e.message
|
|
2254
|
-
}
|
|
2255
|
-
};
|
|
2256
|
-
summaries.push(summary);
|
|
2257
|
-
log(`[analyst] FAIL ${analyst.id}`, {
|
|
2258
|
-
runId,
|
|
2259
|
-
error_class: e.constructor.name,
|
|
2260
|
-
error: e.message,
|
|
2261
|
-
cost_usd: cost,
|
|
2262
|
-
cost_kind: usage.cost.kind
|
|
2263
|
-
});
|
|
2264
|
-
if (effectiveBudget !== void 0 && usage.cost.kind === "uncaptured") log(`[analyst] WARN ${analyst.id} — USD cost uncaptured; budget not reconciled`, {
|
|
2265
|
-
runId,
|
|
2266
|
-
budget_usd: effectiveBudget,
|
|
2267
|
-
cost_captured: false
|
|
2268
|
-
});
|
|
2269
|
-
await waitForHook(hooks.onAfterAnalyze ? () => hooks.onAfterAnalyze?.({
|
|
2270
|
-
analyst,
|
|
2271
|
-
summary,
|
|
2272
|
-
findings: hookFindings,
|
|
2273
|
-
runId
|
|
2274
|
-
}) : void 0, runSignal);
|
|
2275
|
-
yield {
|
|
2276
|
-
type: "analyst-completed",
|
|
2277
|
-
summary,
|
|
2278
|
-
findings: hookFindings
|
|
2279
|
-
};
|
|
2280
|
-
continue;
|
|
2281
|
-
}
|
|
2282
|
-
await waitForHook(hooks.onAfterAnalyze ? () => hooks.onAfterAnalyze?.({
|
|
2283
|
-
analyst,
|
|
2284
|
-
summary,
|
|
2285
|
-
findings,
|
|
2286
|
-
runId
|
|
2287
|
-
}) : void 0, runSignal);
|
|
2288
|
-
yield {
|
|
2289
|
-
type: "analyst-completed",
|
|
2290
|
-
summary,
|
|
2291
|
-
findings
|
|
2292
|
-
};
|
|
2293
|
-
}
|
|
2294
|
-
const result = {
|
|
2295
|
-
run_id: runId,
|
|
2296
|
-
correlation_id: correlationId,
|
|
2297
|
-
started_at: startedAt,
|
|
2298
|
-
ended_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2299
|
-
findings: allFindings,
|
|
2300
|
-
per_analyst: summaries,
|
|
2301
|
-
total_cost_usd: totalCost,
|
|
2302
|
-
total_cost_provenance: aggregateCostProvenance(summaries.map((summary) => summary.usage?.cost ?? {
|
|
2303
|
-
kind: "uncaptured",
|
|
2304
|
-
usd: null
|
|
2305
|
-
}))
|
|
2306
|
-
};
|
|
2307
|
-
await waitForHook(hooks.onComplete ? () => hooks.onComplete?.({ result }) : void 0, runSignal);
|
|
2308
|
-
yield {
|
|
2309
|
-
type: "run-completed",
|
|
2310
|
-
result
|
|
2311
|
-
};
|
|
2312
|
-
}
|
|
2313
|
-
selectAnalysts(opts) {
|
|
2314
|
-
let candidates = Array.from(this.analysts.values());
|
|
2315
|
-
if (opts.only?.length) {
|
|
2316
|
-
const only = new Set(opts.only);
|
|
2317
|
-
candidates = candidates.filter((a) => only.has(a.id));
|
|
2318
|
-
}
|
|
2319
|
-
if (opts.skip?.length) {
|
|
2320
|
-
const skip = new Set(opts.skip);
|
|
2321
|
-
candidates = candidates.filter((a) => !skip.has(a.id));
|
|
2322
|
-
}
|
|
2323
|
-
return candidates;
|
|
2324
|
-
}
|
|
2325
|
-
routeInput(analyst, inputs) {
|
|
2326
|
-
switch (analyst.inputKind) {
|
|
2327
|
-
case "trace-store": return inputs.traceStore ? {
|
|
2328
|
-
kind: "present",
|
|
2329
|
-
value: inputs.traceStore
|
|
2330
|
-
} : { kind: "missing" };
|
|
2331
|
-
case "artifact-dir": return inputs.artifactDir ? {
|
|
2332
|
-
kind: "present",
|
|
2333
|
-
value: inputs.artifactDir
|
|
2334
|
-
} : { kind: "missing" };
|
|
2335
|
-
case "run-record": return inputs.runRecord ? {
|
|
2336
|
-
kind: "present",
|
|
2337
|
-
value: inputs.runRecord
|
|
2338
|
-
} : { kind: "missing" };
|
|
2339
|
-
case "judge-input": return inputs.judgeInput ? {
|
|
2340
|
-
kind: "present",
|
|
2341
|
-
value: inputs.judgeInput
|
|
2342
|
-
} : { kind: "missing" };
|
|
2343
|
-
case "custom": {
|
|
2344
|
-
const v = inputs.custom?.[analyst.id];
|
|
2345
|
-
return v !== void 0 ? {
|
|
2346
|
-
kind: "present",
|
|
2347
|
-
value: v
|
|
2348
|
-
} : { kind: "missing" };
|
|
2349
|
-
}
|
|
2350
|
-
}
|
|
2351
|
-
}
|
|
2352
|
-
};
|
|
2353
|
-
function validateTimeout(timeoutMs) {
|
|
2354
|
-
if (timeoutMs === void 0) return void 0;
|
|
2355
|
-
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new TypeError("RegistryRunOpts.timeoutMs must be a positive safe integer no greater than 2147483647");
|
|
2356
|
-
return timeoutMs;
|
|
2357
|
-
}
|
|
2358
|
-
async function waitForOperation(operation, signal, abortGraceMs) {
|
|
2359
|
-
if (!signal) return operation;
|
|
2360
|
-
if (signal.aborted) {
|
|
2361
|
-
operation.catch(() => {});
|
|
2362
|
-
throw abortReason(signal);
|
|
2363
|
-
}
|
|
2364
|
-
return new Promise((resolve, reject) => {
|
|
2365
|
-
let settlementTimer;
|
|
2366
|
-
const cleanup = () => {
|
|
2367
|
-
signal.removeEventListener("abort", onAbort);
|
|
2368
|
-
if (settlementTimer) clearTimeout(settlementTimer);
|
|
2369
|
-
};
|
|
2370
|
-
const onAbort = () => {
|
|
2371
|
-
if (abortGraceMs === 0) {
|
|
2372
|
-
cleanup();
|
|
2373
|
-
reject(abortReason(signal));
|
|
2374
|
-
return;
|
|
2375
|
-
}
|
|
2376
|
-
settlementTimer = setTimeout(() => {
|
|
2377
|
-
cleanup();
|
|
2378
|
-
reject(abortReason(signal));
|
|
2379
|
-
}, abortGraceMs);
|
|
2380
|
-
};
|
|
2381
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
2382
|
-
operation.then((value) => {
|
|
2383
|
-
cleanup();
|
|
2384
|
-
if (signal.aborted) reject(abortReason(signal));
|
|
2385
|
-
else resolve(value);
|
|
2386
|
-
}, (error) => {
|
|
2387
|
-
cleanup();
|
|
2388
|
-
reject(signal.aborted ? abortReason(signal) : error);
|
|
2389
|
-
});
|
|
2390
|
-
});
|
|
2391
|
-
}
|
|
2392
|
-
async function waitForHook(operation, signal) {
|
|
2393
|
-
if (operation === void 0 || signal?.aborted) return void 0;
|
|
2394
|
-
try {
|
|
2395
|
-
return await waitForOperation(Promise.resolve().then(() => {
|
|
2396
|
-
if (signal?.aborted) throw abortReason(signal);
|
|
2397
|
-
return operation();
|
|
2398
|
-
}), signal, 0);
|
|
2399
|
-
} catch (error) {
|
|
2400
|
-
if (signal?.aborted) return void 0;
|
|
2401
|
-
throw error;
|
|
2402
|
-
}
|
|
2403
|
-
}
|
|
2404
|
-
function analystAbortGraceMs(analyst) {
|
|
2405
|
-
if (analyst.cost.kind === "deterministic") return 0;
|
|
2406
|
-
const settlementMs = validateUsageSettlementTimeout(analyst.cost.settlement_timeout_ms);
|
|
2407
|
-
if (settlementMs === 0) return 0;
|
|
2408
|
-
return Math.min(settlementMs + 100, 2147483647);
|
|
2409
|
-
}
|
|
2410
|
-
function abortedBeforeStartSummary(analyst, signal, latencyMs = 0) {
|
|
2411
|
-
const reason = abortReason(signal);
|
|
2412
|
-
return {
|
|
2413
|
-
analyst_id: analyst.id,
|
|
2414
|
-
status: "skipped",
|
|
2415
|
-
reason: `${reason.name}: ${reason.message}`,
|
|
2416
|
-
findings_count: 0,
|
|
2417
|
-
latency_ms: latencyMs,
|
|
2418
|
-
usage: zeroUsage()
|
|
2419
|
-
};
|
|
2420
|
-
}
|
|
2421
|
-
function abortReason(signal) {
|
|
2422
|
-
return signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");
|
|
2423
|
-
}
|
|
2424
|
-
/**
|
|
2425
|
-
* Default budget allocator: prefer the custom `allocate` callback if
|
|
2426
|
-
* provided; else weighted split when weights are set; else equal split
|
|
2427
|
-
* across `runningCount`. Returns undefined when no totalUsd is known.
|
|
2428
|
-
*/
|
|
2429
|
-
function allocateBudget(policy, args) {
|
|
2430
|
-
if (!policy) return void 0;
|
|
2431
|
-
if (policy.allocate) {
|
|
2432
|
-
const allocated = policy.allocate({
|
|
2433
|
-
analyst: args.analyst,
|
|
2434
|
-
totalUsd: policy.totalUsd,
|
|
2435
|
-
remainingUsd: args.remainingUsd,
|
|
2436
|
-
runningCount: args.runningCount
|
|
2437
|
-
});
|
|
2438
|
-
if (allocated === void 0) {
|
|
2439
|
-
if (policy.totalUsd !== void 0) throw new Error(`BudgetPolicy.allocate('${args.analyst.id}') cannot return undefined when totalUsd is set`);
|
|
2440
|
-
return;
|
|
2441
|
-
}
|
|
2442
|
-
assertBudgetAmount(allocated, `BudgetPolicy.allocate('${args.analyst.id}')`);
|
|
2443
|
-
return args.remainingUsd === void 0 ? allocated : Math.min(allocated, args.remainingUsd);
|
|
2444
|
-
}
|
|
2445
|
-
if (policy.totalUsd == null) return void 0;
|
|
2446
|
-
const allocated = policy.weights ? policy.totalUsd * analystWeight(policy.weights, args.analyst.id) / args.totalWeight : policy.totalUsd / Math.max(1, args.runningCount);
|
|
2447
|
-
return args.remainingUsd === void 0 ? allocated : Math.min(allocated, args.remainingUsd);
|
|
2448
|
-
}
|
|
2449
|
-
function validateBudgetPolicy(policy) {
|
|
2450
|
-
if (!policy) return;
|
|
2451
|
-
if (policy.totalUsd !== void 0) assertBudgetAmount(policy.totalUsd, "BudgetPolicy.totalUsd");
|
|
2452
|
-
for (const [analystId, weight] of Object.entries(policy.weights ?? {})) assertBudgetAmount(weight, `BudgetPolicy.weights['${analystId}']`);
|
|
2453
|
-
}
|
|
2454
|
-
function assertBudgetAmount(value, field) {
|
|
2455
|
-
if (!Number.isFinite(value) || value < 0) throw new Error(`${field} must be a non-negative finite number`);
|
|
2456
|
-
}
|
|
2457
|
-
function validateEffectiveBudget(budgetUsd, remainingUsd, analystId) {
|
|
2458
|
-
if (budgetUsd !== void 0) assertBudgetAmount(budgetUsd, `AnalystContext.budgetUsd for '${analystId}'`);
|
|
2459
|
-
if (remainingUsd === void 0) return budgetUsd;
|
|
2460
|
-
if (budgetUsd === void 0) throw new Error(`AnalystContext.budgetUsd for '${analystId}' cannot be removed while an overall budget remains`);
|
|
2461
|
-
if (budgetUsd > remainingUsd) throw new Error(`AnalystContext.budgetUsd for '${analystId}' (${budgetUsd}) exceeds the remaining overall budget (${remainingUsd})`);
|
|
2462
|
-
return budgetUsd;
|
|
2463
|
-
}
|
|
2464
|
-
function analystWeight(weights, analystId) {
|
|
2465
|
-
const weight = weights[analystId] ?? 1;
|
|
2466
|
-
assertBudgetAmount(weight, `BudgetPolicy.weights['${analystId}']`);
|
|
2467
|
-
return weight;
|
|
2468
|
-
}
|
|
2469
|
-
function zeroUsage() {
|
|
2470
|
-
return {
|
|
2471
|
-
calls: 0,
|
|
2472
|
-
tokens: {
|
|
2473
|
-
input: 0,
|
|
2474
|
-
output: 0
|
|
2475
|
-
},
|
|
2476
|
-
cost: {
|
|
2477
|
-
kind: "observed",
|
|
2478
|
-
usd: 0
|
|
2479
|
-
}
|
|
2480
|
-
};
|
|
2481
|
-
}
|
|
2482
|
-
function resolveUsage(analyst, receipts) {
|
|
2483
|
-
if (receipts.length > 0) return mergeUsageReceipts(receipts);
|
|
2484
|
-
if (analyst.cost.kind === "deterministic") return zeroUsage();
|
|
2485
|
-
return {
|
|
2486
|
-
calls: null,
|
|
2487
|
-
tokens: null,
|
|
2488
|
-
cost: {
|
|
2489
|
-
kind: "uncaptured",
|
|
2490
|
-
usd: null
|
|
2491
|
-
}
|
|
2492
|
-
};
|
|
2493
|
-
}
|
|
2494
|
-
function mergeUsageReceipts(receipts) {
|
|
2495
|
-
const calls = receipts.every((receipt) => receipt.calls !== null) ? receipts.reduce((sum, receipt) => sum + (receipt.calls ?? 0), 0) : null;
|
|
2496
|
-
const tokens = receipts.every((receipt) => receipt.tokens !== null) ? receipts.reduce((sum, receipt) => ({
|
|
2497
|
-
input: sum.input + (receipt.tokens?.input ?? 0),
|
|
2498
|
-
output: sum.output + (receipt.tokens?.output ?? 0),
|
|
2499
|
-
...sum.reasoning !== void 0 || receipt.tokens?.reasoning !== void 0 ? { reasoning: (sum.reasoning ?? 0) + (receipt.tokens?.reasoning ?? 0) } : {},
|
|
2500
|
-
...sum.cached !== void 0 || receipt.tokens?.cached !== void 0 ? { cached: (sum.cached ?? 0) + (receipt.tokens?.cached ?? 0) } : {},
|
|
2501
|
-
...sum.cacheWrite !== void 0 || receipt.tokens?.cacheWrite !== void 0 ? { cacheWrite: (sum.cacheWrite ?? 0) + (receipt.tokens?.cacheWrite ?? 0) } : {}
|
|
2502
|
-
}), {
|
|
2503
|
-
input: 0,
|
|
2504
|
-
output: 0
|
|
2505
|
-
}) : null;
|
|
2506
|
-
const cost = aggregateCostProvenance(receipts.map((receipt) => receipt.cost));
|
|
2507
|
-
return {
|
|
2508
|
-
calls,
|
|
2509
|
-
tokens,
|
|
2510
|
-
cost,
|
|
2511
|
-
...cost.kind === "uncaptured" ? { knownCostUsd: receipts.reduce((sum, receipt) => sum + knownCostUsd(receipt), 0) } : {}
|
|
2512
|
-
};
|
|
2513
|
-
}
|
|
2514
|
-
function knownCostUsd(receipt) {
|
|
2515
|
-
return receipt.cost.kind === "uncaptured" ? receipt.knownCostUsd ?? 0 : receipt.cost.usd;
|
|
2516
|
-
}
|
|
2517
|
-
function budgetDebit(receipt, allocatedUsd) {
|
|
2518
|
-
const known = knownCostUsd(receipt);
|
|
2519
|
-
return receipt.cost.kind === "uncaptured" && allocatedUsd !== void 0 ? Math.max(known, allocatedUsd) : known;
|
|
2520
|
-
}
|
|
2521
|
-
function aggregateCostProvenance(costs) {
|
|
2522
|
-
if (costs.some((cost) => cost.kind === "uncaptured")) return {
|
|
2523
|
-
kind: "uncaptured",
|
|
2524
|
-
usd: null
|
|
2525
|
-
};
|
|
2526
|
-
const usd = costs.reduce((sum, cost) => sum + (cost.usd ?? 0), 0);
|
|
2527
|
-
return costs.some((cost) => cost.kind === "estimated") ? {
|
|
2528
|
-
kind: "estimated",
|
|
2529
|
-
usd
|
|
2530
|
-
} : {
|
|
2531
|
-
kind: "observed",
|
|
2532
|
-
usd
|
|
2533
|
-
};
|
|
2534
|
-
}
|
|
2535
|
-
function assertValidUsageReceipt(receipt) {
|
|
2536
|
-
if (receipt.calls !== null && (!Number.isInteger(receipt.calls) || receipt.calls < 0)) throw new Error("AnalystContext.recordUsage: calls must be a non-negative integer or null");
|
|
2537
|
-
if (receipt.tokens) {
|
|
2538
|
-
assertNonNegativeFinite(receipt.tokens.input, "tokens.input");
|
|
2539
|
-
assertNonNegativeFinite(receipt.tokens.output, "tokens.output");
|
|
2540
|
-
if (receipt.tokens.reasoning !== void 0) {
|
|
2541
|
-
assertNonNegativeFinite(receipt.tokens.reasoning, "tokens.reasoning");
|
|
2542
|
-
if (receipt.tokens.reasoning > receipt.tokens.output) throw new Error("AnalystContext.recordUsage: tokens.reasoning must not exceed tokens.output");
|
|
2543
|
-
}
|
|
2544
|
-
if (receipt.tokens.cached !== void 0) assertNonNegativeFinite(receipt.tokens.cached, "tokens.cached");
|
|
2545
|
-
if (receipt.tokens.cacheWrite !== void 0) assertNonNegativeFinite(receipt.tokens.cacheWrite, "tokens.cacheWrite");
|
|
2546
|
-
}
|
|
2547
|
-
if (receipt.cost.kind !== "uncaptured") assertNonNegativeFinite(receipt.cost.usd, "cost.usd");
|
|
2548
|
-
else if (receipt.cost.usd !== null) throw new Error("AnalystContext.recordUsage: uncaptured cost.usd must be null");
|
|
2549
|
-
if (receipt.knownCostUsd !== void 0) assertNonNegativeFinite(receipt.knownCostUsd, "knownCostUsd");
|
|
2550
|
-
}
|
|
2551
|
-
function assertNonNegativeFinite(value, field) {
|
|
2552
|
-
if (!Number.isFinite(value) || value < 0) throw new Error(`AnalystContext.recordUsage: ${field} must be a non-negative finite number`);
|
|
2553
|
-
}
|
|
2554
|
-
/**
|
|
2555
|
-
* Resolve the `priorFindings` slice an analyst sees.
|
|
2556
|
-
*
|
|
2557
|
-
* - Array form → the analyst sees only findings whose `analyst_id`
|
|
2558
|
-
* matches its own id, so a kind never reads
|
|
2559
|
-
* another kind's history by accident.
|
|
2560
|
-
* - Record form → the analyst gets the entry keyed by its id, with
|
|
2561
|
-
* the `'*'` wildcard appended (in that order). Use
|
|
2562
|
-
* the wildcard when several kinds should see the same
|
|
2563
|
-
* historical findings.
|
|
2564
|
-
*/
|
|
2565
|
-
function selectPriorFindings(source, analystId) {
|
|
2566
|
-
if (!source) return void 0;
|
|
2567
|
-
if (Array.isArray(source)) {
|
|
2568
|
-
const own = source.filter((f) => f.analyst_id === analystId);
|
|
2569
|
-
return own.length > 0 ? own : void 0;
|
|
2570
|
-
}
|
|
2571
|
-
const record = source;
|
|
2572
|
-
const own = record[analystId] ?? [];
|
|
2573
|
-
const wildcard = record["*"] ?? [];
|
|
2574
|
-
const merged = [...own, ...wildcard];
|
|
2575
|
-
return merged.length > 0 ? merged : void 0;
|
|
2576
|
-
}
|
|
2577
|
-
//#endregion
|
|
2578
|
-
//#region src/analyst/default-registry.ts
|
|
2579
|
-
function buildDefaultAnalystRegistry(opts = {}) {
|
|
2580
|
-
const registry = new AnalystRegistry(opts.registry);
|
|
2581
|
-
if (opts.includeBehavioral !== false) registry.register(behavioralAnalyst(opts.behavioral));
|
|
2582
|
-
if (opts.ai) {
|
|
2583
|
-
const kinds = opts.kinds ?? DEFAULT_TRACE_ANALYST_KINDS;
|
|
2584
|
-
for (const spec of kinds) registry.register(createTraceAnalystKind(spec, {
|
|
2585
|
-
ai: opts.ai,
|
|
2586
|
-
model: opts.model
|
|
2587
|
-
}));
|
|
2588
|
-
}
|
|
2589
|
-
return registry;
|
|
2590
|
-
}
|
|
2591
|
-
//#endregion
|
|
2592
|
-
export { FindingSubjectStringSchema as A, parseRawFinding as C, FINDING_SUBJECT_GRAMMAR_PROMPT as D, stripCodeFences as E, behavioralAnalyst as F, deriveEfficiencyFindings as I, computeTraceMetrics as L, findingSubjectGrammarPromptFor as M, parseFindingSubject as N, FINDING_SUBJECT_KINDS as O, renderFindingSubject as P, createChatClient as R, evidenceRefsFromRawFinding as S, coerceToFindingRows as T, structureFindings as _, KNOWLEDGE_GAP_KIND_SPEC as a, RawAnalystEvidenceSchema as b, buildTraceToolsForGroup as c, emitControlIntegrityFindings as d, createTraceAnalystKind as f, validateUsageSettlementTimeout as g, settleUsageReceiptFromCostLedger as h, KNOWLEDGE_POISONING_KIND_SPEC as i, KIND_EXPECTED_SUBJECTS as j, FINDING_SUBJECT_SYNTAX as k, CONTROL_INTEGRITY_ANALYST as l, renderUpstreamFindings as m, AnalystRegistry as n, IMPROVEMENT_KIND_SPEC as o, renderPriorFindings as p, DEFAULT_TRACE_ANALYST_KINDS as r, FAILURE_MODE_KIND_SPEC as s, buildDefaultAnalystRegistry as t, ControlIntegrityAnalyst as u, ANALYST_SEVERITIES as v, coerceJson as w, RawAnalystFindingSchema as x, RAW_FINDING_SCHEMA_PROMPT as y, createAnalystAi as z };
|
|
2593
|
-
|
|
2594
|
-
//# sourceMappingURL=default-registry-CLXbRt0f.js.map
|