@tangle-network/agent-eval 0.189.0 → 0.190.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 +79 -0
- package/README.md +3 -2
- package/dist/adapters/http.d.ts +10 -1
- package/dist/adapters/http.d.ts.map +1 -1
- package/dist/adapters/http.js +75 -7
- package/dist/adapters/http.js.map +1 -1
- package/dist/analyst/index.d.ts +66 -3
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +212 -7
- package/dist/analyst/index.js.map +1 -1
- package/dist/{benchmark-command-BhhAYstU.js → benchmark-command-TZlsuAh9.js} +10 -10
- package/dist/{benchmark-command-BhhAYstU.js.map → benchmark-command-TZlsuAh9.js.map} +1 -1
- package/dist/benchmarks/index.d.ts +1 -1
- package/dist/benchmarks/index.js +3 -3
- package/dist/campaign/index.d.ts +4 -4
- package/dist/campaign/index.js +7 -7
- package/dist/{campaign-BWoSQPSU.js → campaign-_29Qpc9Z.js} +255 -10
- package/dist/campaign-_29Qpc9Z.js.map +1 -0
- package/dist/{campaign-evidence-CBlGJ3kC.js → campaign-evidence-CWF8pEIk.js} +5 -4
- package/dist/campaign-evidence-CWF8pEIk.js.map +1 -0
- package/dist/{chat-client-C4dg7Ng_.js → chat-client-DbH06Ek6.js} +2 -2
- package/dist/{chat-client-C4dg7Ng_.js.map → chat-client-DbH06Ek6.js.map} +1 -1
- package/dist/{chat-json-call-JVGbfx95.js → chat-json-call-B0xTEY0I.js} +2 -2
- package/dist/{chat-json-call-JVGbfx95.js.map → chat-json-call-B0xTEY0I.js.map} +1 -1
- package/dist/claim-BGOUqoMq.d.ts +38 -0
- package/dist/claim-BGOUqoMq.d.ts.map +1 -0
- package/dist/cli.js +3 -3
- package/dist/contract/index.d.ts +4 -4
- package/dist/contract/index.js +7 -7
- package/dist/{default-registry-m2jhbG6Q.js → default-registry-16I-Bxlf.js} +2 -2
- package/dist/{default-registry-m2jhbG6Q.js.map → default-registry-16I-Bxlf.js.map} +1 -1
- package/dist/{define-agent-eval-q6890HU4.d.ts → define-agent-eval-BWeyIpny.d.ts} +4 -3
- package/dist/define-agent-eval-BWeyIpny.d.ts.map +1 -0
- package/dist/{define-agent-eval-98sgUaC1.js → define-agent-eval-DrGfrCTZ.js} +4 -4
- package/dist/{define-agent-eval-98sgUaC1.js.map → define-agent-eval-DrGfrCTZ.js.map} +1 -1
- package/dist/diagnosis/index.d.ts +1 -1
- package/dist/diagnosis/index.d.ts.map +1 -1
- package/dist/diagnosis/index.js +3 -3
- package/dist/diagnosis/index.js.map +1 -1
- package/dist/{dspy-rlm-engine-DLYttKBm.js → dspy-rlm-engine-CTIGomgr.js} +3 -3
- package/dist/{dspy-rlm-engine-DLYttKBm.js.map → dspy-rlm-engine-CTIGomgr.js.map} +1 -1
- package/dist/{eval-campaign-C0Q1Eeo_.js → eval-campaign-CMKRjWl0.js} +2 -2
- package/dist/{eval-campaign-C0Q1Eeo_.js.map → eval-campaign-CMKRjWl0.js.map} +1 -1
- package/dist/experiment/index.d.ts +2 -1
- package/dist/experiment/index.d.ts.map +1 -1
- package/dist/experiment/index.js +1 -1
- package/dist/exporters-XMCYJlqT.d.ts +161 -0
- package/dist/exporters-XMCYJlqT.d.ts.map +1 -0
- package/dist/{external-optimizer-process-C3quNeKV.js → external-optimizer-process-Mc83UoWl.js} +2 -2
- package/dist/{external-optimizer-process-C3quNeKV.js.map → external-optimizer-process-Mc83UoWl.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-BDwgKLO1.js → external-optimizer-subprocess-C0dHXH8e.js} +2 -2
- package/dist/{external-optimizer-subprocess-BDwgKLO1.js.map → external-optimizer-subprocess-C0dHXH8e.js.map} +1 -1
- package/dist/{feedback-trajectory-B3ZSkfAq.d.ts → feedback-trajectory-BYjh7NEM.d.ts} +2 -2
- package/dist/{feedback-trajectory-B3ZSkfAq.d.ts.map → feedback-trajectory-BYjh7NEM.d.ts.map} +1 -1
- package/dist/{index-Dk1dOUfm.d.ts → index-BR_R1eBE.d.ts} +4 -4
- package/dist/{index-Dk1dOUfm.d.ts.map → index-BR_R1eBE.d.ts.map} +1 -1
- package/dist/{index-CnJOPR_E.d.ts → index-Ci0-EYzc.d.ts} +673 -244
- package/dist/index-Ci0-EYzc.d.ts.map +1 -0
- package/dist/{index-Bcc9PkOz.d.ts → index-D4pC7Tvd.d.ts} +3 -2
- package/dist/index-D4pC7Tvd.d.ts.map +1 -0
- package/dist/index.d.ts +66 -17
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +375 -31
- package/dist/index.js.map +1 -1
- package/dist/{kind-factory-BGwN0nE6.js → kind-factory-ByZeXDqF.js} +2 -2
- package/dist/{kind-factory-BGwN0nE6.js.map → kind-factory-ByZeXDqF.js.map} +1 -1
- package/dist/{llm-client-DF9bPNYA.js → llm-client-BqmRnibA.js} +2 -2
- package/dist/{llm-client-DF9bPNYA.js.map → llm-client-BqmRnibA.js.map} +1 -1
- package/dist/{llm-judge-M_l_WXw2.js → llm-judge-bwbgDMP0.js} +1891 -1377
- package/dist/llm-judge-bwbgDMP0.js.map +1 -0
- package/dist/mint-C9Lojt1V.d.ts +147 -0
- package/dist/mint-C9Lojt1V.d.ts.map +1 -0
- package/dist/openapi.json +1 -1
- package/dist/pipelines/index.d.ts +1 -1
- package/dist/{produced-state-BOY98IJO.js → produced-state-zSaGDC_Q.js} +4 -4
- package/dist/{produced-state-BOY98IJO.js.map → produced-state-zSaGDC_Q.js.map} +1 -1
- package/dist/{raw-provider-sink-C96CcqeG.js → raw-provider-sink-DIRCZjP_.js} +2 -2
- package/dist/{raw-provider-sink-C96CcqeG.js.map → raw-provider-sink-DIRCZjP_.js.map} +1 -1
- package/dist/{redact-DxwlUAvh.js → redact-8fX8-uKr.js} +16 -7
- package/dist/redact-8fX8-uKr.js.map +1 -0
- package/dist/{redact-DPoH1-OW.d.ts → redact-Du3WKUOP.d.ts} +7 -5
- package/dist/redact-Du3WKUOP.d.ts.map +1 -0
- package/dist/rl.d.ts +3 -2
- package/dist/rl.d.ts.map +1 -1
- package/dist/rl.js +1 -1
- package/dist/rollout/index.d.ts +3 -2
- package/dist/search-ledger-types-C9anU2DX.d.ts +489 -0
- package/dist/search-ledger-types-C9anU2DX.d.ts.map +1 -0
- package/dist/{semantic-concept-judge-Cm2K2wAo.js → semantic-concept-judge-BY0me-Jq.js} +5 -5
- package/dist/{semantic-concept-judge-Cm2K2wAo.js.map → semantic-concept-judge-BY0me-Jq.js.map} +1 -1
- package/dist/{server-C8XvqCg8.js → server-DnJCDLf8.js} +2 -2
- package/dist/{server-C8XvqCg8.js.map → server-DnJCDLf8.js.map} +1 -1
- package/dist/{skillopt-optimization-method-BVSB676o.js → skillopt-optimization-method-CfnQEjgT.js} +363 -18
- package/dist/skillopt-optimization-method-CfnQEjgT.js.map +1 -0
- package/dist/{spans-W0o8pbEg.d.ts → spans-D1RftP_w.d.ts} +2 -2
- package/dist/{spans-W0o8pbEg.d.ts.map → spans-D1RftP_w.d.ts.map} +1 -1
- package/dist/{statistical-heldout-plAHG82H.d.ts → statistical-heldout-CLpjYffJ.d.ts} +2 -36
- package/dist/statistical-heldout-CLpjYffJ.d.ts.map +1 -0
- package/dist/{store-otlp-D0AV4cvB.js → store-otlp-84DH0OEH.js} +2 -2
- package/dist/{store-otlp-D0AV4cvB.js.map → store-otlp-84DH0OEH.js.map} +1 -1
- package/dist/{store-tool-spans-8PAyhRqb.d.ts → store-tool-spans-BBXs8hDP.d.ts} +2 -2
- package/dist/{store-tool-spans-8PAyhRqb.d.ts.map → store-tool-spans-BBXs8hDP.d.ts.map} +1 -1
- package/dist/{store-tool-spans-B_0mXvYl.js → store-tool-spans-DSbYpl7f.js} +5 -5
- package/dist/{store-tool-spans-B_0mXvYl.js.map → store-tool-spans-DSbYpl7f.js.map} +1 -1
- package/dist/traces.d.ts +3 -63
- package/dist/traces.d.ts.map +1 -1
- package/dist/traces.js +6 -195
- package/dist/traces.js.map +1 -1
- package/dist/wire/index.d.ts +1 -1
- package/dist/wire/index.js +1 -1
- package/docs/adapters-observability.md +31 -27
- package/docs/charter.md +1 -1
- package/docs/design/mlbenchmarks-book-review.md +1 -1
- package/docs/distributed-driver.md +1 -5
- package/docs/experiment.md +15 -0
- package/docs/public-api.md +174 -68
- package/docs/redaction.md +7 -1
- package/docs/search-ledger.md +174 -0
- package/docs/trace-contracts.md +48 -3
- package/package.json +1 -1
- package/dist/campaign-BWoSQPSU.js.map +0 -1
- package/dist/campaign-evidence-CBlGJ3kC.js.map +0 -1
- package/dist/define-agent-eval-q6890HU4.d.ts.map +0 -1
- package/dist/index-Bcc9PkOz.d.ts.map +0 -1
- package/dist/index-CnJOPR_E.d.ts.map +0 -1
- package/dist/llm-judge-M_l_WXw2.js.map +0 -1
- package/dist/mint-DsS38v5c.d.ts +0 -305
- package/dist/mint-DsS38v5c.d.ts.map +0 -1
- package/dist/redact-DPoH1-OW.d.ts.map +0 -1
- package/dist/redact-DxwlUAvh.js.map +0 -1
- package/dist/search-ledger-types-D7KDVg-o.d.ts +0 -302
- package/dist/search-ledger-types-D7KDVg-o.d.ts.map +0 -1
- package/dist/skillopt-optimization-method-BVSB676o.js.map +0 -1
- package/dist/statistical-heldout-plAHG82H.d.ts.map +0 -1
- package/docs/search-history-receipts.md +0 -233
package/dist/analyst/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { i as CostLedger } from "../cost-ledger-_IbkejCF.js";
|
|
2
2
|
import { n as assertProposalFindings, r as isProposalFinding } from "../abort-signal-CtzAM_sJ.js";
|
|
3
|
-
import { B as
|
|
3
|
+
import { B as FINDING_SUBJECT_SYNTAX, F as parseRawFinding, G as DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS, H as findingSubjectGrammarPromptFor, I as parseTraceSpanEvidenceUri, K as resolveTraceAnalystLimits, L as coerceJson, M as RAW_FINDING_SCHEMA_PROMPT, N as RawAnalystFindingSchema, P as evidenceRefsFromRawFinding, R as stripCodeFences, U as parseFindingSubject, V as KIND_EXPECTED_SUBJECTS, W as renderFindingSubject, i as buildTraceToolsForGroup, n as renderPriorFindings, r as runTraceAnalyst, t as createTraceAnalyst, z as FINDING_SUBJECT_KINDS } from "../kind-factory-ByZeXDqF.js";
|
|
4
4
|
import { i as validateUsageSettlementTimeout, n as settleUsageReceiptFromCostLedger } from "../usage-receipt-Cx3xNeyB.js";
|
|
5
|
-
import { a as KNOWLEDGE_POISONING_KIND_SPEC, c as FAILURE_MODE_KIND_SPEC, d as emitControlIntegrityFindings, f as behavioralAnalyst, i as DEFAULT_TRACE_ANALYST_KINDS, l as CONTROL_INTEGRITY_ANALYST, n as AnalystRegistry, o as KNOWLEDGE_GAP_KIND_SPEC, p as deriveEfficiencyFindings, r as ExactAnalystRunExecutionError, s as IMPROVEMENT_KIND_SPEC, t as buildDefaultAnalystRegistry, u as ControlIntegrityAnalyst } from "../default-registry-
|
|
5
|
+
import { a as KNOWLEDGE_POISONING_KIND_SPEC, c as FAILURE_MODE_KIND_SPEC, d as emitControlIntegrityFindings, f as behavioralAnalyst, i as DEFAULT_TRACE_ANALYST_KINDS, l as CONTROL_INTEGRITY_ANALYST, n as AnalystRegistry, o as KNOWLEDGE_GAP_KIND_SPEC, p as deriveEfficiencyFindings, r as ExactAnalystRunExecutionError, s as IMPROVEMENT_KIND_SPEC, t as buildDefaultAnalystRegistry, u as ControlIntegrityAnalyst } from "../default-registry-16I-Bxlf.js";
|
|
6
6
|
import { i as makeProposalFinding, n as computeFindingId, r as makeFinding } from "../types-CW5b90JH.js";
|
|
7
|
-
import { t as createDspyRlmTraceEngine } from "../dspy-rlm-engine-
|
|
8
|
-
import { a as diffFindings, i as defaultIsMaterial, n as runSemanticConceptJudge, o as createChatTraceEngine, r as FindingsStore, t as SEMANTIC_CONCEPT_JUDGE_VERSION } from "../semantic-concept-judge-
|
|
9
|
-
import { t as createChatClient } from "../chat-client-
|
|
7
|
+
import { t as createDspyRlmTraceEngine } from "../dspy-rlm-engine-CTIGomgr.js";
|
|
8
|
+
import { a as diffFindings, i as defaultIsMaterial, n as runSemanticConceptJudge, o as createChatTraceEngine, r as FindingsStore, t as SEMANTIC_CONCEPT_JUDGE_VERSION } from "../semantic-concept-judge-BY0me-Jq.js";
|
|
9
|
+
import { t as createChatClient } from "../chat-client-DbH06Ek6.js";
|
|
10
10
|
import { a as scoreAnalystFindings, i as summarizeAnalystBenchmarkRunner, n as runAnalystBenchmark, r as traceStoreEvidenceResolver, t as registryBenchmarkRunner } from "../benchmark-BeQJyrRC.js";
|
|
11
|
-
import { $ as ANALYST_BENCHMARK_MANIFEST_FILE, A as readAnalystInstructionsOverride, B as parseVerificationOutcome, C as emptyPublicBenchmarkRunner, D as summarizeCodeTraceCalibration, E as renderCodeTraceCalibrationMarkdown, F as publicBenchmarkRlmInstructions, G as ANALYST_BENCHMARK_EVIDENCE_IMPLEMENTATION_SHA256, H as ANALYST_BENCHMARK_DEPENDENCY_LOCK_FILES, I as publicBenchmarkSystemPrompt, J as ANALYST_BENCHMARK_IMPLEMENTATION_SHA256, K as ANALYST_BENCHMARK_IMPLEMENTATION_DIGEST_ALGORITHM, L as DEFAULT_MAX_VERIFICATION_ARTIFACT_BYTES, M as MAX_INCORRECT_BLOCKS, N as MAX_INCORRECT_BLOCK_STEPS, O as analystInstructionsOverrideFromText, P as publicBenchmarkProtocolSha256, Q as ANALYST_BENCHMARK_LOCAL_RECEIPT_FILE, R as appendVerificationArtifactsToOtlp, S as adaptPublicBenchmarkFindings, T as readAnalystBenchmarkArtifact, U as ANALYST_BENCHMARK_DEPENDENCY_LOCK_SHA256, V as ANALYST_BENCHMARK_DEPENDENCY_LOCK_DIGEST_ALGORITHM, W as ANALYST_BENCHMARK_EVIDENCE_DEPENDENCY_LOCK_SHA256, X as analystBenchmarkImplementationDigest, Y as analystBenchmarkDependencyLockDigest, Z as ANALYST_BENCHMARK_COST_LEDGER_FILE, _ as publicDirectAnalystDefinition, a as primeCodeTraceAnalystDefinition, at as codeTraceBenchCase, b as analystDefinitionAsymmetries, c as preparePublicAnalystBenchmark, ct as agentRxPredictionsToFindings, d as selectPublicBenchmarkRows, dt as normalizeBenchmarkLabel, et as ANALYST_BENCHMARK_OBSERVATIONS_FILE, f as createPublicBenchmarkRlmRunner, g as createPublicBenchmarkDirectRunner, h as runReplVariableAnalystDefinition, i as primeAnalystProtocolSha256, it as summarizeAgentRxCalibration, j as CODE_TRACE_BENCH_ANALYST_PROMPT, k as effectiveAnalystProtocolSha256, l as publicBenchmarkDistributions, lt as normalizeAgentRxCategory, m as rlmEngineLimits, n as renderAnalystBenchmarkMarkdown, nt as AGENT_RX_UPSTREAM_REVISION, o as runInlineAnalystDefinition, ot as codeTracerPredictionsToFindings, p as publicRlmAnalystDefinition, q as ANALYST_BENCHMARK_IMPLEMENTATION_FILES, r as createPrimeBenchmarkRunner, rt as renderAgentRxCalibrationMarkdown, s as loadPublicBenchmarkRows, st as agentRxBenchmarkCase, t as runAnalystBenchmarkCommand, tt as compareAnalystRunners, u as publicBenchmarkSelectionReport, ut as roundAgentRxStep, v as runChunkedAnalystDefinition, w as expandCodeTraceFailureBlocks, x as analystDefinitionProtocolSha256, y as AnalystExpressivenessError, z as loadCodeTraceVerificationArtifacts } from "../benchmark-command-
|
|
11
|
+
import { $ as ANALYST_BENCHMARK_MANIFEST_FILE, A as readAnalystInstructionsOverride, B as parseVerificationOutcome, C as emptyPublicBenchmarkRunner, D as summarizeCodeTraceCalibration, E as renderCodeTraceCalibrationMarkdown, F as publicBenchmarkRlmInstructions, G as ANALYST_BENCHMARK_EVIDENCE_IMPLEMENTATION_SHA256, H as ANALYST_BENCHMARK_DEPENDENCY_LOCK_FILES, I as publicBenchmarkSystemPrompt, J as ANALYST_BENCHMARK_IMPLEMENTATION_SHA256, K as ANALYST_BENCHMARK_IMPLEMENTATION_DIGEST_ALGORITHM, L as DEFAULT_MAX_VERIFICATION_ARTIFACT_BYTES, M as MAX_INCORRECT_BLOCKS, N as MAX_INCORRECT_BLOCK_STEPS, O as analystInstructionsOverrideFromText, P as publicBenchmarkProtocolSha256, Q as ANALYST_BENCHMARK_LOCAL_RECEIPT_FILE, R as appendVerificationArtifactsToOtlp, S as adaptPublicBenchmarkFindings, T as readAnalystBenchmarkArtifact, U as ANALYST_BENCHMARK_DEPENDENCY_LOCK_SHA256, V as ANALYST_BENCHMARK_DEPENDENCY_LOCK_DIGEST_ALGORITHM, W as ANALYST_BENCHMARK_EVIDENCE_DEPENDENCY_LOCK_SHA256, X as analystBenchmarkImplementationDigest, Y as analystBenchmarkDependencyLockDigest, Z as ANALYST_BENCHMARK_COST_LEDGER_FILE, _ as publicDirectAnalystDefinition, a as primeCodeTraceAnalystDefinition, at as codeTraceBenchCase, b as analystDefinitionAsymmetries, c as preparePublicAnalystBenchmark, ct as agentRxPredictionsToFindings, d as selectPublicBenchmarkRows, dt as normalizeBenchmarkLabel, et as ANALYST_BENCHMARK_OBSERVATIONS_FILE, f as createPublicBenchmarkRlmRunner, g as createPublicBenchmarkDirectRunner, h as runReplVariableAnalystDefinition, i as primeAnalystProtocolSha256, it as summarizeAgentRxCalibration, j as CODE_TRACE_BENCH_ANALYST_PROMPT, k as effectiveAnalystProtocolSha256, l as publicBenchmarkDistributions, lt as normalizeAgentRxCategory, m as rlmEngineLimits, n as renderAnalystBenchmarkMarkdown, nt as AGENT_RX_UPSTREAM_REVISION, o as runInlineAnalystDefinition, ot as codeTracerPredictionsToFindings, p as publicRlmAnalystDefinition, q as ANALYST_BENCHMARK_IMPLEMENTATION_FILES, r as createPrimeBenchmarkRunner, rt as renderAgentRxCalibrationMarkdown, s as loadPublicBenchmarkRows, st as agentRxBenchmarkCase, t as runAnalystBenchmarkCommand, tt as compareAnalystRunners, u as publicBenchmarkSelectionReport, ut as roundAgentRxStep, v as runChunkedAnalystDefinition, w as expandCodeTraceFailureBlocks, x as analystDefinitionProtocolSha256, y as AnalystExpressivenessError, z as loadCodeTraceVerificationArtifacts } from "../benchmark-command-TZlsuAh9.js";
|
|
12
12
|
import { a as extractPrimeJsonObject, c as primeProtocolSha256, d as runPrimeExchange, f as decodeReplyRows, i as emptyPrimeRawUsage, l as primeReplyDefect, n as buildPrimePrompt, o as mergePrimeRawUsage, r as buildPrimeRepairPrompt, s as normalizePrimeUsage, t as analystUsageReceiptFromPrimeUsage, u as projectPrimeTrajectory } from "../prime-protocol-DcAK9pC8.js";
|
|
13
13
|
import { t as nodeHttpPrimeBridgeTransport } from "../prime-bridge-transport-Z3cpKGoV.js";
|
|
14
14
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
@@ -377,6 +377,211 @@ var SkillUsageAnalyst = class {
|
|
|
377
377
|
};
|
|
378
378
|
const SKILL_USAGE_ANALYST = new SkillUsageAnalyst();
|
|
379
379
|
//#endregion
|
|
380
|
-
|
|
380
|
+
//#region src/analyst/trace-questions.ts
|
|
381
|
+
const QUESTION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
|
|
382
|
+
const DEFINITION_VERSION = "1.0.0";
|
|
383
|
+
const QUESTION_RULES = [
|
|
384
|
+
"Answer QUESTION only from trace tool results retrieved in this run.",
|
|
385
|
+
"Cite each fact as trace://<trace_id>/span/<span_id>, and quote the span in the excerpt.",
|
|
386
|
+
"If the trace does not record a fact, say \"not in trace\". Never infer a trace fact from the question."
|
|
387
|
+
].join("\n");
|
|
388
|
+
const VERIFIER_RULES = [
|
|
389
|
+
"You check one CLAIM against the spans it cites, and nothing else.",
|
|
390
|
+
"Read each cited span with viewSpans. No other trace is readable.",
|
|
391
|
+
"First line: SUPPORTED if the spans themselves establish the claim, otherwise NOT SUPPORTED.",
|
|
392
|
+
"Second line: one sentence naming the span that decides it.",
|
|
393
|
+
"Return no findings."
|
|
394
|
+
].join("\n");
|
|
395
|
+
/**
|
|
396
|
+
* Ask every question, then verify every admitted finding. Never throws for a failed question or
|
|
397
|
+
* verifier: each failure is recorded on its outcome. Throws before any model call for a malformed
|
|
398
|
+
* question list or options.
|
|
399
|
+
*/
|
|
400
|
+
async function askTraceQuestions(opts) {
|
|
401
|
+
const concurrency = opts.concurrency ?? 4;
|
|
402
|
+
if (!Number.isSafeInteger(concurrency) || concurrency < 1) throw new RangeError("askTraceQuestions: concurrency must be an integer >= 1");
|
|
403
|
+
const minimum = opts.minimumEvidenceCitations ?? 2;
|
|
404
|
+
if (!Number.isSafeInteger(minimum) || minimum < 1) throw new RangeError("askTraceQuestions: minimumEvidenceCitations must be an integer >= 1");
|
|
405
|
+
const seen = /* @__PURE__ */ new Set();
|
|
406
|
+
for (const question of opts.questions) {
|
|
407
|
+
if (!QUESTION_ID.test(question.id)) throw new TypeError(`askTraceQuestions: question id ${JSON.stringify(question.id)} is malformed`);
|
|
408
|
+
if (seen.has(question.id)) throw new TypeError(`askTraceQuestions: duplicate question id ${JSON.stringify(question.id)}`);
|
|
409
|
+
seen.add(question.id);
|
|
410
|
+
if (question.question.trim() === "") throw new TypeError(`askTraceQuestions: question ${question.id} is empty`);
|
|
411
|
+
}
|
|
412
|
+
const askOne = async (question) => {
|
|
413
|
+
if (opts.signal?.aborted) return failed(question, "the run was aborted before the question started");
|
|
414
|
+
let completed;
|
|
415
|
+
try {
|
|
416
|
+
completed = await runTraceAnalyst({
|
|
417
|
+
definition: defineTraceAnalyst({
|
|
418
|
+
id: `question.${question.id}`,
|
|
419
|
+
description: `trace question ${question.id}`,
|
|
420
|
+
area: "question",
|
|
421
|
+
version: DEFINITION_VERSION,
|
|
422
|
+
question: question.question.trim(),
|
|
423
|
+
instructions: [QUESTION_RULES, question.instructions?.trim() ?? ""].filter(Boolean).join("\n\n"),
|
|
424
|
+
toolGroup: "all",
|
|
425
|
+
minimumEvidenceCitations: minimum,
|
|
426
|
+
...opts.context ? { prepareContext: () => opts.context } : {},
|
|
427
|
+
...opts.limits ? { limits: opts.limits } : {}
|
|
428
|
+
}),
|
|
429
|
+
engine: opts.engine,
|
|
430
|
+
store: opts.store,
|
|
431
|
+
context: {
|
|
432
|
+
runId: opts.runId,
|
|
433
|
+
correlationId: `${opts.runId}:${question.id}`,
|
|
434
|
+
costLedger: opts.costLedger,
|
|
435
|
+
costPhase: "trace-question",
|
|
436
|
+
...opts.signal ? { signal: opts.signal } : {},
|
|
437
|
+
...opts.log ? { log: opts.log } : {}
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
} catch (error) {
|
|
441
|
+
return failed(question, errorText(error));
|
|
442
|
+
}
|
|
443
|
+
const findings = [];
|
|
444
|
+
for (const [index, finding] of completed.findings.entries()) {
|
|
445
|
+
const citations = finding.evidence.map((citation) => citation.uri.trim()).filter((uri) => parseTraceSpanEvidenceUri(uri) !== null);
|
|
446
|
+
findings.push(opts.verify === false ? {
|
|
447
|
+
finding,
|
|
448
|
+
citations,
|
|
449
|
+
verified: null
|
|
450
|
+
} : await verifyFinding(opts, `${question.id}.v${index + 1}`, finding, citations));
|
|
451
|
+
}
|
|
452
|
+
const answer = completed.answer.trim() === "" ? null : completed.answer;
|
|
453
|
+
return {
|
|
454
|
+
id: question.id,
|
|
455
|
+
question: question.question,
|
|
456
|
+
status: "answered",
|
|
457
|
+
answer,
|
|
458
|
+
findings,
|
|
459
|
+
modelCalls: completed.modelCalls,
|
|
460
|
+
toolCalls: completed.toolCalls
|
|
461
|
+
};
|
|
462
|
+
};
|
|
463
|
+
const outcomes = new Array(opts.questions.length);
|
|
464
|
+
let next = 0;
|
|
465
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, opts.questions.length) }, async () => {
|
|
466
|
+
while (next < opts.questions.length) {
|
|
467
|
+
const index = next;
|
|
468
|
+
next += 1;
|
|
469
|
+
const question = opts.questions[index];
|
|
470
|
+
outcomes[index] = await askOne(question);
|
|
471
|
+
}
|
|
472
|
+
}));
|
|
473
|
+
return outcomes;
|
|
474
|
+
}
|
|
475
|
+
/** The verifier reads only the spans the finding cites, through a store that holds nothing else. */
|
|
476
|
+
async function verifyFinding(opts, id, finding, citations) {
|
|
477
|
+
const allowed = /* @__PURE__ */ new Map();
|
|
478
|
+
for (const uri of citations) {
|
|
479
|
+
const location = parseTraceSpanEvidenceUri(uri);
|
|
480
|
+
if (location === null) continue;
|
|
481
|
+
const spans = allowed.get(location.traceId) ?? /* @__PURE__ */ new Set();
|
|
482
|
+
spans.add(location.spanId);
|
|
483
|
+
allowed.set(location.traceId, spans);
|
|
484
|
+
}
|
|
485
|
+
if (allowed.size === 0) return {
|
|
486
|
+
finding,
|
|
487
|
+
citations,
|
|
488
|
+
verified: false
|
|
489
|
+
};
|
|
490
|
+
try {
|
|
491
|
+
const verdict = await runTraceAnalyst({
|
|
492
|
+
definition: defineTraceAnalyst({
|
|
493
|
+
id: `verify.${id}`,
|
|
494
|
+
description: `independent check of finding ${id}`,
|
|
495
|
+
area: "question",
|
|
496
|
+
version: DEFINITION_VERSION,
|
|
497
|
+
question: `CLAIM: ${finding.claim}\nCITED SPANS: ${citations.join(", ")}`,
|
|
498
|
+
instructions: VERIFIER_RULES,
|
|
499
|
+
toolGroup: "targeted",
|
|
500
|
+
...opts.limits ? { limits: opts.limits } : {}
|
|
501
|
+
}),
|
|
502
|
+
engine: opts.engine,
|
|
503
|
+
store: citedSpansOnly(opts.store, allowed),
|
|
504
|
+
context: {
|
|
505
|
+
runId: opts.runId,
|
|
506
|
+
correlationId: `${opts.runId}:verify:${id}`,
|
|
507
|
+
costLedger: opts.costLedger,
|
|
508
|
+
costPhase: "trace-question-verifier",
|
|
509
|
+
...opts.signal ? { signal: opts.signal } : {},
|
|
510
|
+
...opts.log ? { log: opts.log } : {}
|
|
511
|
+
}
|
|
512
|
+
});
|
|
513
|
+
return {
|
|
514
|
+
finding,
|
|
515
|
+
citations,
|
|
516
|
+
verified: (verdict.answer.trim().split("\n")[0]?.trim().toUpperCase() ?? "").startsWith("SUPPORTED"),
|
|
517
|
+
verifierAnswer: verdict.answer.trim()
|
|
518
|
+
};
|
|
519
|
+
} catch (error) {
|
|
520
|
+
opts.log?.("verifier failed", {
|
|
521
|
+
finding: id,
|
|
522
|
+
error: errorText(error)
|
|
523
|
+
});
|
|
524
|
+
return {
|
|
525
|
+
finding,
|
|
526
|
+
citations,
|
|
527
|
+
verified: null
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* A store that exposes exactly the cited spans. Discovery and whole-trace reads refuse, so the
|
|
533
|
+
* verifier cannot go looking for other support; the underlying store's bounds still apply.
|
|
534
|
+
*/
|
|
535
|
+
function citedSpansOnly(store, allowed) {
|
|
536
|
+
const refuse = (what) => async () => {
|
|
537
|
+
throw new Error(`${what} is not available to a verifier: read the cited spans with viewSpans`);
|
|
538
|
+
};
|
|
539
|
+
return {
|
|
540
|
+
hasTrace: async (traceId) => allowed.has(traceId),
|
|
541
|
+
hasSpans: async (input, context) => {
|
|
542
|
+
const spans = allowed.get(input.trace_id);
|
|
543
|
+
if (spans === void 0) return [];
|
|
544
|
+
return store.hasSpans({
|
|
545
|
+
trace_id: input.trace_id,
|
|
546
|
+
span_ids: input.span_ids.filter((span) => spans.has(span))
|
|
547
|
+
}, context);
|
|
548
|
+
},
|
|
549
|
+
getOverview: refuse("getOverview"),
|
|
550
|
+
queryTraces: refuse("queryTraces"),
|
|
551
|
+
countTraces: refuse("countTraces"),
|
|
552
|
+
viewTrace: refuse("viewTrace"),
|
|
553
|
+
viewSpans: async (input, context) => {
|
|
554
|
+
const spans = allowed.get(input.trace_id);
|
|
555
|
+
const wanted = input.span_ids.filter((span) => spans?.has(span) === true);
|
|
556
|
+
if (wanted.length === 0) throw new Error("viewSpans: only the cited spans are readable");
|
|
557
|
+
return store.viewSpans({
|
|
558
|
+
...input,
|
|
559
|
+
span_ids: wanted
|
|
560
|
+
}, context);
|
|
561
|
+
},
|
|
562
|
+
searchTrace: refuse("searchTrace"),
|
|
563
|
+
searchSpan: async (input, context) => {
|
|
564
|
+
if (allowed.get(input.trace_id)?.has(input.span_id) !== true) throw new Error("searchSpan: only the cited spans are readable");
|
|
565
|
+
return store.searchSpan(input, context);
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
function failed(question, failure) {
|
|
570
|
+
return {
|
|
571
|
+
id: question.id,
|
|
572
|
+
question: question.question,
|
|
573
|
+
status: "failed",
|
|
574
|
+
failure,
|
|
575
|
+
answer: null,
|
|
576
|
+
findings: [],
|
|
577
|
+
modelCalls: null,
|
|
578
|
+
toolCalls: null
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
function errorText(error) {
|
|
582
|
+
return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
583
|
+
}
|
|
584
|
+
//#endregion
|
|
585
|
+
export { AGENT_RX_UPSTREAM_REVISION, ANALYST_BENCHMARK_COST_LEDGER_FILE, ANALYST_BENCHMARK_DEPENDENCY_LOCK_DIGEST_ALGORITHM, ANALYST_BENCHMARK_DEPENDENCY_LOCK_FILES, ANALYST_BENCHMARK_DEPENDENCY_LOCK_SHA256, ANALYST_BENCHMARK_EVIDENCE_DEPENDENCY_LOCK_SHA256, ANALYST_BENCHMARK_EVIDENCE_IMPLEMENTATION_SHA256, ANALYST_BENCHMARK_IMPLEMENTATION_DIGEST_ALGORITHM, ANALYST_BENCHMARK_IMPLEMENTATION_FILES, ANALYST_BENCHMARK_IMPLEMENTATION_SHA256, ANALYST_BENCHMARK_LOCAL_RECEIPT_FILE, ANALYST_BENCHMARK_MANIFEST_FILE, ANALYST_BENCHMARK_OBSERVATIONS_FILE, AnalystExpressivenessError, AnalystRegistry, CODE_TRACE_BENCH_ANALYST_PROMPT, CONTROL_INTEGRITY_ANALYST, ControlIntegrityAnalyst, DEFAULT_MAX_VERIFICATION_ARTIFACT_BYTES, DEFAULT_TRACE_ANALYST_KINDS, DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS, ExactAnalystRunExecutionError, FAILURE_MODE_KIND_SPEC, FINDING_SUBJECT_KINDS, FINDING_SUBJECT_SYNTAX, FindingsStore, IMPROVEMENT_KIND_SPEC, KIND_EXPECTED_SUBJECTS, KNOWLEDGE_GAP_KIND_SPEC, KNOWLEDGE_POISONING_KIND_SPEC, MAX_INCORRECT_BLOCKS, MAX_INCORRECT_BLOCK_STEPS, RAW_FINDING_SCHEMA_PROMPT, RawAnalystFindingSchema, SKILL_USAGE_ANALYST, adaptPublicBenchmarkFindings, agentRxBenchmarkCase, agentRxPredictionsToFindings, analystBenchmarkDependencyLockDigest, analystBenchmarkImplementationDigest, analystDefinitionAsymmetries, analystDefinitionProtocolSha256, analystInstructionsOverrideFromText, analystUsageReceiptFromPrimeUsage, appendVerificationArtifactsToOtlp, askTraceQuestions, assertProposalFindings, behavioralAnalyst, bindAnalyst, buildDefaultAnalystRegistry, buildPrimePrompt, buildPrimeRepairPrompt, buildSkillUsageReport, buildTraceToolsForGroup, citedSpansOnly, codeTraceBenchCase, codeTracerPredictionsToFindings, coerceJson, compareAnalystRunners, computeFindingId, createChatClient, createChatTraceEngine, createDspyRlmTraceEngine, createPrimeBenchmarkRunner, createPublicBenchmarkDirectRunner, createPublicBenchmarkRlmRunner, createSemanticConceptJudgeAdapter, createTraceAnalyst, decodeReplyRows, defaultIsMaterial, defineCustomAnalyst, defineTraceAnalyst, deriveEfficiencyFindings, diffFindings, effectiveAnalystProtocolSha256, emitControlIntegrityFindings, emitSkillUsageFindings, emptyPrimeRawUsage, emptyPublicBenchmarkRunner, evidenceRefsFromRawFinding, expandCodeTraceFailureBlocks, extractPrimeJsonObject, findingSubjectGrammarPromptFor, isProposalFinding, loadCodeTraceVerificationArtifacts, loadPublicBenchmarkRows, makeFinding, makeProposalFinding, mergePrimeRawUsage, nodeHttpPrimeBridgeTransport, normalizeAgentRxCategory, normalizeBenchmarkLabel, normalizePrimeUsage, parseFindingSubject, parseRawFinding, parseVerificationOutcome, preparePublicAnalystBenchmark, primeAnalystProtocolSha256, primeCodeTraceAnalystDefinition, primeProtocolSha256, primeReplyDefect, projectPrimeTrajectory, publicBenchmarkDistributions, publicBenchmarkProtocolSha256, publicBenchmarkRlmInstructions, publicBenchmarkSelectionReport, publicBenchmarkSystemPrompt, publicDirectAnalystDefinition, publicRlmAnalystDefinition, readAnalystBenchmarkArtifact, readAnalystInstructionsOverride, registryBenchmarkRunner, renderAgentRxCalibrationMarkdown, renderAnalystBenchmarkMarkdown, renderCodeTraceCalibrationMarkdown, renderFindingSubject, renderPriorFindings, resolveTraceAnalystLimits, rlmEngineLimits, roundAgentRxStep, runAnalystBenchmark, runAnalystBenchmarkCommand, runPrimeExchange, runTraceAnalyst, scoreAnalystFindings, selectPublicBenchmarkRows, stripCodeFences, summarizeAgentRxCalibration, summarizeAnalystBenchmarkRunner, summarizeCodeTraceCalibration, traceStoreEvidenceResolver };
|
|
381
586
|
|
|
382
587
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/analyst/adapters.ts","../../src/analyst/bind.ts","../../src/analyst/define.ts","../../src/analyst/kinds/skill-usage.ts"],"sourcesContent":["/**\n * Adapter factory — lifts the semantic-concept judge into the Analyst\n * contract without re-implementing it.\n *\n * It builds an Analyst with a stable id (caller chooses; a default is given),\n * a version derived from the judge's version plus an adapter revision, and an\n * `analyze()` that calls the judge and lifts its output to `AnalystFinding[]`\n * through `makeFinding()`. The judge's `Severity` ('critical' | 'major' |\n * 'minor' | 'info') projects onto `AnalystSeverity`: 'major' becomes 'high'\n * and 'minor' becomes 'medium'.\n *\n * The adapter owns no state. Calling the factory twice is safe.\n */\n\nimport { CostLedger } from '../cost-ledger'\nimport type { Severity as LayerSeverity } from '../multi-layer-verifier'\nimport {\n runSemanticConceptJudge,\n SEMANTIC_CONCEPT_JUDGE_VERSION,\n type SemanticConceptJudgeInput,\n type SemanticConceptJudgeOptions,\n type SemanticConceptJudgeResult,\n} from '../semantic-concept-judge'\nimport type { Analyst, AnalystFinding, AnalystSeverity } from './types'\nimport { makeFinding } from './types'\nimport { settleUsageReceiptFromCostLedger, validateUsageSettlementTimeout } from './usage-receipt'\n\nconst ADAPTER_REV = '1'\n\n// ── Severity bridges ───────────────────────────────────────────────\n\nfunction liftSeverity(s: LayerSeverity): AnalystSeverity {\n switch (s) {\n case 'critical':\n return 'critical'\n case 'major':\n return 'high'\n case 'minor':\n return 'medium'\n case 'info':\n return 'info'\n }\n}\n\n// ── SemanticConceptJudge → Analyst ─────────────────────────────────\n\nexport interface SemanticConceptJudgeAdapterOpts {\n id?: string\n area?: string\n /** Registry context owns cancellation and the per-analyst cost ledger. */\n options: Omit<SemanticConceptJudgeOptions, 'costLedger' | 'signal'>\n /** Maximum post-cancellation wait for a provider receipt. Default 5 seconds. */\n settlementTimeoutMs?: number\n}\n\nexport function createSemanticConceptJudgeAdapter(\n opts: SemanticConceptJudgeAdapterOpts,\n): Analyst<SemanticConceptJudgeInput> {\n const id = opts.id ?? 'semantic-concept-judge'\n const area = opts.area ?? 'concept-coverage'\n const settlementTimeoutMs = validateUsageSettlementTimeout(opts.settlementTimeoutMs)\n return {\n id,\n description:\n 'Runs the semantic-concept judge and surfaces missing / weak concepts as findings.',\n inputKind: 'custom',\n cost: {\n kind: 'llm',\n models: opts.options.model ? [opts.options.model] : undefined,\n settlement_timeout_ms: settlementTimeoutMs,\n },\n version: `${SEMANTIC_CONCEPT_JUDGE_VERSION}-adapter-${ADAPTER_REV}`,\n async analyze(input, ctx) {\n const costLedger = new CostLedger(ctx.budgetUsd)\n let result: SemanticConceptJudgeResult\n try {\n result = await runSemanticConceptJudge(input, {\n ...opts.options,\n costLedger,\n signal: ctx.signal,\n })\n } finally {\n const usage = await settleUsageReceiptFromCostLedger(costLedger, {\n channel: 'judge',\n timeoutMs: settlementTimeoutMs,\n })\n if (!usage.settled) {\n ctx.log?.('semantic-concept judge provider settlement timed out', {\n pending_calls: usage.pendingCalls,\n timeout_ms: settlementTimeoutMs,\n })\n }\n ctx.recordUsage?.(usage.receipt)\n }\n if (!result.available) {\n return [\n makeFinding({\n analyst_id: id,\n area,\n claim: 'semantic-concept judge unavailable',\n rationale: result.error,\n severity: 'info',\n confidence: 1,\n evidence_refs: [],\n metadata: { reason: result.error },\n }),\n ]\n }\n const out: AnalystFinding[] = []\n for (const f of result.findings) {\n // Only surface gaps: missing concepts or low scores. Concepts at\n // 7+/10 with present=true are not findings — they're successes.\n if (f.present && f.score >= 7) continue\n out.push(\n makeFinding({\n analyst_id: id,\n area,\n subject: f.concept,\n claim: f.present\n ? `concept \"${f.concept}\" is weak (${f.score}/10)`\n : `concept \"${f.concept}\" is missing`,\n rationale: f.evidence,\n severity: liftSeverity(f.severity),\n confidence: 0.85,\n evidence_refs: [{ kind: 'artifact', uri: 'inline:evidence', excerpt: f.evidence }],\n metadata: {\n concept: f.concept,\n present: f.present,\n score_10: f.score,\n },\n }),\n )\n }\n return out\n },\n }\n}\n","/**\n * bindAnalyst — compile an `AnalystDefinition` into a runnable arm.\n *\n * The definition declares protocol (question, task text, reply grammar,\n * evidence projection, budget, repair turns); the transport binding supplies\n * execution (a bridge endpoint, or the caller-owned model path). Each\n * projection mode dispatches to the same strategy its arm's entry point runs,\n * so a compiled definition and the historical creator send byte-identical\n * requests — the definition parity suite asserts this per arm.\n *\n * A projection × transport pair with no strategy fails loud with\n * `AnalystExpressivenessError` naming the pair: an arm shape this layer cannot\n * express must be reported, never approximated.\n */\n\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport type { AnalystBenchmarkRunner } from './benchmark'\nimport { runChunkedAnalystDefinition } from './benchmark-public-model'\nimport { runReplVariableAnalystDefinition } from './benchmark-public-rlm'\nimport type { PublicAnalystBenchmarkModelConfig } from './benchmark-public-types'\nimport { runInlineAnalystDefinition } from './benchmark-runner-prime'\nimport { type AnalystDefinition, AnalystExpressivenessError } from './definition'\nimport type { PrimeBridgeTransport } from './prime-bridge-transport'\nimport type { AnalystRunInputs } from './types'\n\n/** Execution half of a binding: who actually reaches the model. */\nexport type AnalystTransportBinding =\n | {\n /** An OpenAI-compatible cli-bridge endpoint (inline projections). */\n readonly kind: 'prime-bridge'\n readonly baseUrl: string\n readonly model: string\n readonly transport?: PrimeBridgeTransport\n readonly pricing?: CustomTokenPricing\n }\n | {\n /** The caller-owned model path (chunked and repl-variable projections). */\n readonly kind: 'model-owner'\n readonly config: PublicAnalystBenchmarkModelConfig\n }\n\n/**\n * Compile a definition plus a transport binding into a runnable arm. Dispatch\n * is total over the expressible pairs; everything else is a loud refusal.\n */\nexport function bindAnalyst<TRow, TAssignment, TBlock>(\n definition: AnalystDefinition<TRow, TAssignment, TBlock>,\n transports: AnalystTransportBinding,\n): AnalystBenchmarkRunner<AnalystRunInputs> {\n const mode = definition.projection.mode\n if (mode === 'inline' && transports.kind === 'prime-bridge') {\n return runInlineAnalystDefinition(definition, {\n baseUrl: transports.baseUrl,\n model: transports.model,\n ...(transports.transport ? { transport: transports.transport } : {}),\n ...(transports.pricing ? { pricing: transports.pricing } : {}),\n })\n }\n if (mode === 'chunked' && transports.kind === 'model-owner') {\n return runChunkedAnalystDefinition(definition, transports.config)\n }\n if (mode === 'repl-variable' && transports.kind === 'model-owner') {\n return runReplVariableAnalystDefinition(\n // The repl-variable strategy is written against the engine's raw-finding\n // row type; the definition's own row declaration carries it.\n definition as Parameters<typeof runReplVariableAnalystDefinition>[0],\n transports.config,\n )\n }\n throw new AnalystExpressivenessError(\n `no strategy compiles a '${mode}' projection over a '${transports.kind}' transport; ` +\n `definition '${definition.id}' cannot be expressed by this layer yet`,\n )\n}\n","import type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { ExactCapableAnalyst } from './exact-types'\nimport type { TraceAnalystDefinition } from './kind-factory'\nimport type { Analyst, AnalystCost } from './types'\n\n/**\n * Define a reusable trace-research question.\n *\n * The returned value contains no model, credentials, or execution state. Bind\n * it to any TraceAnalysisEngine with `runTraceAnalyst` or\n * `createTraceAnalyst`.\n */\nexport function defineTraceAnalyst(definition: TraceAnalystDefinition): TraceAnalystDefinition {\n for (const [name, value] of [\n ['id', definition.id],\n ['description', definition.description],\n ['area', definition.area],\n ['version', definition.version],\n ['instructions', definition.instructions],\n ] as const) {\n if (typeof value !== 'string' || !value.trim()) {\n throw new TypeError(`defineTraceAnalyst: ${name} must be a non-empty string`)\n }\n }\n return {\n ...definition,\n limits: definition.limits ? { ...definition.limits } : undefined,\n }\n}\n\nexport interface DefineCustomAnalystOptions {\n id: string\n description: string\n version?: string\n cost: AnalystCost\n analyze: Analyst<TraceAnalysisStore>['analyze']\n}\n\nexport interface DefineExactCustomAnalystOptions extends DefineCustomAnalystOptions {\n /** Canonical JSON for behavior knobs not already bound by `version`. */\n executionConfig: Readonly<Record<string, unknown>>\n}\n\n/** Construct a registrable analyst from a hand-written analyze function. */\nexport function defineCustomAnalyst(\n options: DefineExactCustomAnalystOptions,\n): ExactCapableAnalyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions,\n): Analyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions | DefineExactCustomAnalystOptions,\n): Analyst<TraceAnalysisStore> | ExactCapableAnalyst<TraceAnalysisStore> {\n if (!options.id.trim()) throw new TypeError('defineCustomAnalyst: id must not be empty')\n if (!options.description.trim()) {\n throw new TypeError('defineCustomAnalyst: description must not be empty')\n }\n if (options.cost === undefined) {\n throw new TypeError('defineCustomAnalyst: cost must be declared')\n }\n if (\n 'executionConfig' in options &&\n (!options.executionConfig ||\n typeof options.executionConfig !== 'object' ||\n Array.isArray(options.executionConfig))\n ) {\n throw new TypeError('defineCustomAnalyst: executionConfig must be an object')\n }\n return {\n id: options.id,\n description: options.description,\n version: options.version ?? '1.0.0',\n inputKind: 'trace-store',\n cost: options.cost,\n analyze: options.analyze,\n ...('executionConfig' in options ? { executionConfig: options.executionConfig } : {}),\n }\n}\n","/**\n * Skill-usage analyst — a DETERMINISTIC `Analyst` over a Claude/Codex skill\n * library + its trace corpus. Unlike the trace-store kinds (failure-mode,\n * improvement, ...) this kind calls no LLM: it mines real usage and skill\n * structure and emits findings by rule.\n *\n * It exists because the naive \"Skill-tool invocation count\" lies low — it\n * misses orchestrated sub-dispatch (a leaf skill run BY /pursue or /governor\n * logs under the parent), slash-command entry, local-script bypass, and\n * on-disk artifacts. The 2026-05-30 skill audit found 39/53 skills at zero\n * direct invocations, yet only one was a genuine cut: the rest were\n * measurement-invisible or discovery-limited. This analyst encodes that\n * lesson as a multi-signal usage model so a cheap repeatable pass can keep\n * the library honest, and so the expensive audit workflow's verdicts can\n * GEPA-distill it toward agreement (see `gold/skill-verdicts.gold.jsonl`).\n *\n * Report-building (`buildSkillUsageReport`, an fs scan) is separated from\n * finding emission (`SkillUsageAnalyst.analyze`, pure) so the slow scan runs\n * once at the registry boundary and the rule logic stays unit-testable.\n */\n\nimport { type Dirent, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { ExactCapableAnalyst } from '../exact-types'\nimport type { AnalystContext, AnalystFinding, AnalystSeverity } from '../types'\nimport { computeFindingId } from '../types'\n\n// ── Input model ──────────────────────────────────────────────────────\n\nexport type SkillKind = 'public' | 'private'\n\n/** One skill's multi-signal usage + structure. All counts are deterministic. */\nexport interface SkillUsageRecord {\n name: string\n kind: SkillKind\n /** Absolute path to the skill's SKILL.md. */\n path: string\n lines: number\n /** `\"skill\":\"<name>\"` Skill-tool invocations across the trace corpus. */\n directInvocations: number\n /** `<command-name>/<name>` slash invocations across the trace corpus. */\n slashInvocations: number\n /** Sibling skills whose SKILL.md dispatches to this one (`/<name>`). Proxy\n * for orchestrated sub-dispatch the per-skill counter cannot see. */\n inboundRefs: number\n /** On-disk artifacts attributable to the skill (e.g. `.evolve/<name>/**`). */\n artifactCount: number\n /** Tangle-private reference count in the body (leak signal for public skills). */\n tanglePrivateRefs: number\n hasReferencesDir: boolean\n hasEvalsDir: boolean\n /** Body mentions `skill-runs.jsonl` (visible to /reflect + /governor). */\n logsRuns: boolean\n /** Description carries an explicit `Triggers:` clause / trigger phrases. */\n hasTriggerPhrases: boolean\n}\n\nexport interface SkillUsageReport {\n generatedFromTraces: number\n records: SkillUsageRecord[]\n}\n\nexport interface SkillUsageScanConfig {\n /** Dirs holding `*.jsonl` transcripts (Claude `~/.claude/projects`, Codex sessions). */\n transcriptDirs: string[]\n /** Skill roots to scan; each dir directly under `root` with a `SKILL.md` is a skill. */\n skillRoots: { root: string; kind: SkillKind }[]\n /** Roots scanned for `<root>/.evolve/<skill>` artifact dirs. */\n artifactRoots?: string[]\n /** Token-prefixed mappings: skill name → extra artifact subpaths under an artifactRoot\n * (e.g. reflect → `.evolve/reflections`). Catches non-eponymous artifact dirs. */\n artifactAliases?: Record<string, string[]>\n /** Cap files read per transcript dir (bounds a huge corpus); 0 = unbounded. */\n maxTranscriptsPerDir?: number\n}\n\n// ── Deterministic thresholds ─────────────────────────────────────────\n\n/** Anthropic's authoring guidance keeps SKILL.md short; past this with no\n * `references/` split the body burns context budget every session. */\nconst BLOAT_LINE_THRESHOLD = 300\n\nconst TANGLE_PRIVATE_RE =\n /\\b(cli-bridge|tangletools|ops-board|drew-gtr-pro|@tangle-network\\/|~\\/company|tangle\\.tools|gtm-agent)\\b|\\bkimi\\b|\\btcloud\\b/gi\nconst TRIGGER_RE = /triggers?\\s*[:-]/i\n\n// ── Report builder (fs scan — slow, runs once at the registry boundary) ──\n\nfunction listSkillDirs(root: string): { name: string; path: string }[] {\n if (!existsSync(root)) return []\n const out: { name: string; path: string }[] = []\n for (const entry of readdirSync(root, { withFileTypes: true })) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue\n const skillMd = join(root, entry.name, 'SKILL.md')\n if (existsSync(skillMd)) out.push({ name: entry.name, path: skillMd })\n }\n return out\n}\n\nfunction walkJsonl(dir: string, cap: number): string[] {\n if (!existsSync(dir)) return []\n const files: string[] = []\n const stack = [dir]\n while (stack.length) {\n const cur = stack.pop()!\n let entries: Dirent[]\n try {\n entries = readdirSync(cur, { withFileTypes: true })\n } catch {\n continue\n }\n for (const e of entries) {\n const full = join(cur, e.name)\n if (e.isDirectory()) stack.push(full)\n else if (e.name.endsWith('.jsonl')) {\n files.push(full)\n if (cap > 0 && files.length >= cap) return files\n }\n }\n }\n return files\n}\n\nfunction frontmatterDescription(body: string): string {\n const fm = /^---\\n([\\s\\S]*?)\\n---/.exec(body)\n const block = fm?.[1] ?? ''\n const m = /description:\\s*(.+)/i.exec(block)\n return m?.[1] ?? ''\n}\n\nfunction countArtifacts(roots: string[], name: string, aliases: string[]): number {\n let n = 0\n for (const root of roots) {\n const candidates = [join(root, '.evolve', name), ...aliases.map((a) => join(root, a))]\n for (const dir of candidates) {\n if (!existsSync(dir)) continue\n try {\n if (statSync(dir).isDirectory()) n += readdirSync(dir).length\n else n += 1\n } catch {\n /* unreadable — skip */\n }\n }\n }\n return n\n}\n\n/** Scan the corpus + skill roots into a {@link SkillUsageReport}. Deterministic. */\nexport function buildSkillUsageReport(config: SkillUsageScanConfig): SkillUsageReport {\n const skills = config.skillRoots.flatMap(({ root, kind }) =>\n listSkillDirs(root).map((s) => ({ ...s, kind })),\n )\n const names = skills.map((s) => s.name)\n\n // One pass over the corpus accumulating direct + slash counts per skill.\n const direct = new Map<string, number>(names.map((n) => [n, 0]))\n const slash = new Map<string, number>(names.map((n) => [n, 0]))\n const skillRe = /\"skill\"\\s*:\\s*\"([a-z0-9_:-]+)\"/g\n const cmdRe = /<command-name>\\/?([a-z0-9_:-]+)<\\/command-name>/g\n let transcripts = 0\n for (const dir of config.transcriptDirs) {\n for (const file of walkJsonl(dir, config.maxTranscriptsPerDir ?? 0)) {\n transcripts += 1\n let data: string\n try {\n data = readFileSync(file, 'utf8')\n } catch {\n continue\n }\n for (const m of data.matchAll(skillRe)) {\n const g = m[1]\n if (!g) continue\n const n = g.split(':').pop() ?? g\n const prev = direct.get(n)\n if (prev !== undefined) direct.set(n, prev + 1)\n }\n for (const m of data.matchAll(cmdRe)) {\n const g = m[1]\n if (g === undefined) continue\n const prev = slash.get(g)\n if (prev !== undefined) slash.set(g, prev + 1)\n }\n }\n }\n\n // Read each skill body once; compute structure + inbound refs across siblings.\n const bodies = new Map<string, string>()\n for (const s of skills) {\n try {\n bodies.set(s.name, readFileSync(s.path, 'utf8'))\n } catch {\n bodies.set(s.name, '')\n }\n }\n const inbound = new Map<string, number>(names.map((n) => [n, 0]))\n for (const target of names) {\n const ref = new RegExp(`/${target}\\\\b|\\\\[\\\\[${target}\\\\]\\\\]`)\n for (const s of skills) {\n if (s.name === target) continue\n if (ref.test(bodies.get(s.name) ?? '')) inbound.set(target, inbound.get(target)! + 1)\n }\n }\n\n const records: SkillUsageRecord[] = skills.map((s) => {\n const body = bodies.get(s.name) ?? ''\n const dir = s.path.replace(/\\/SKILL\\.md$/, '')\n return {\n name: s.name,\n kind: s.kind,\n path: s.path,\n lines: body ? body.split('\\n').length : 0,\n directInvocations: direct.get(s.name) ?? 0,\n slashInvocations: slash.get(s.name) ?? 0,\n inboundRefs: inbound.get(s.name) ?? 0,\n artifactCount: countArtifacts(\n config.artifactRoots ?? [],\n s.name,\n config.artifactAliases?.[s.name] ?? [],\n ),\n tanglePrivateRefs: (body.match(TANGLE_PRIVATE_RE) ?? []).length,\n hasReferencesDir: existsSync(join(dir, 'references')),\n hasEvalsDir: existsSync(join(dir, 'evals')),\n logsRuns: body.includes('skill-runs.jsonl'),\n hasTriggerPhrases: TRIGGER_RE.test(frontmatterDescription(body) || body.slice(0, 600)),\n }\n })\n return { generatedFromTraces: transcripts, records }\n}\n\n// ── Finding emission (pure — unit-testable, no LLM, no fs) ────────────\n\nconst ANALYST_ID = 'skill-usage'\n\nfunction finding(\n area: string,\n subject: string,\n claim: string,\n severity: AnalystSeverity,\n confidence: number,\n producedAt: string,\n recommended: string,\n evidenceUri: string,\n rationale?: string,\n): AnalystFinding {\n return {\n schema_version: '1.0.0',\n finding_id: computeFindingId({ analyst_id: ANALYST_ID, area, subject, claim }),\n analyst_id: ANALYST_ID,\n produced_at: producedAt,\n severity,\n area,\n claim,\n rationale,\n evidence_refs: [{ kind: 'artifact', uri: evidenceUri }],\n recommended_action: recommended,\n confidence,\n subject,\n }\n}\n\n/** Pure rule pass over a report → findings. Exported for direct/unit use. */\nexport function emitSkillUsageFindings(\n report: SkillUsageReport,\n producedAt: string,\n): AnalystFinding[] {\n const out: AnalystFinding[] = []\n for (const r of report.records) {\n const directTotal = r.directInvocations + r.slashInvocations\n const trueUsage = directTotal + r.inboundRefs + r.artifactCount\n\n // 1. Dead: no usage signal of ANY kind. The only real deprecation candidate.\n if (trueUsage === 0) {\n out.push(\n finding(\n 'skill-usage',\n r.name,\n `Skill '${r.name}' has zero usage across all signals (direct, slash, inbound-refs, artifacts)`,\n 'high',\n 0.6,\n producedAt,\n 'Confirm the skill covers a real recurring job; if not, deprecate. Zero true usage is the only deterministic deprecation candidate.',\n r.path,\n 'No Skill-tool call, no slash invocation, no sibling dispatches to it, and no on-disk artifacts.',\n ),\n )\n } else if (directTotal === 0 && r.inboundRefs + r.artifactCount > 0) {\n // 2. Measurement-invisible: real use via orchestration/artifacts, never invoked directly.\n out.push(\n finding(\n 'skill-usage',\n r.name,\n `Skill '${r.name}' shows 0 direct invocations but is used via orchestration/artifacts (inbound=${r.inboundRefs}, artifacts=${r.artifactCount})`,\n 'info',\n 0.8,\n producedAt,\n 'Do NOT treat as unused — usage is real but logged under parent skills or on disk. Strengthen direct-invocation discovery only if direct use is desired.',\n r.path,\n 'The Skill-tool counter undercounts orchestrated/chained leaf skills.',\n ),\n )\n }\n\n // 3. Discovery gap: low direct use AND weak trigger surface.\n if (directTotal <= 2 && !r.hasTriggerPhrases) {\n out.push(\n finding(\n 'discoverability',\n r.name,\n `Skill '${r.name}' is rarely invoked directly and its description has no explicit trigger phrases`,\n 'medium',\n 0.7,\n producedAt,\n 'Add a `Triggers:` clause with verbatim user phrases to the frontmatter description so the model auto-invokes it.',\n r.path,\n ),\n )\n }\n\n // 4. Public-repo leak.\n if (r.kind === 'public' && r.tanglePrivateRefs > 0) {\n out.push(\n finding(\n 'safety',\n r.name,\n `Public skill '${r.name}' carries ${r.tanglePrivateRefs} Tangle-private reference(s)`,\n 'high',\n 0.75,\n producedAt,\n 'Sanitize incidental internal refs (cli-bridge/kimi/tcloud/~company/private repos) or relocate to a private repo. Verify @tangle-network/* refs are to PUBLISHED packages before treating as a leak.',\n r.path,\n ),\n )\n }\n\n // 5. Bloat / no progressive disclosure.\n if (r.lines > BLOAT_LINE_THRESHOLD && !r.hasReferencesDir) {\n out.push(\n finding(\n 'maintainability',\n r.name,\n `Skill '${r.name}' is ${r.lines} lines with no references/ split (progressive disclosure)`,\n 'medium',\n 0.8,\n producedAt,\n `Split detail into references/ loaded on demand; keep SKILL.md a short overview. ${r.lines} lines load into every session's context budget.`,\n r.path,\n ),\n )\n }\n\n // 6. No evals (Anthropic's \">=3 evals before docs\" rule).\n if (!r.hasEvalsDir) {\n out.push(\n finding(\n 'data-quality',\n r.name,\n `Skill '${r.name}' ships no evals/`,\n 'low',\n 0.6,\n producedAt,\n 'Add evals/evals.json with >=3 scenarios proving the skill beats baseline; gives regression coverage.',\n r.path,\n ),\n )\n }\n\n // 7. No run logging → invisible to /reflect and /governor.\n if (!r.logsRuns) {\n out.push(\n finding(\n 'observability',\n r.name,\n `Skill '${r.name}' never appends to .evolve/skill-runs.jsonl`,\n 'low',\n 0.55,\n producedAt,\n 'Append one run line to .evolve/skill-runs.jsonl on completion, or declare it a non-logging leaf, so the self-improvement loop can see it ran.',\n r.path,\n ),\n )\n }\n }\n return out\n}\n\n// ── The Analyst ──────────────────────────────────────────────────────\n\nclass SkillUsageAnalyst implements ExactCapableAnalyst<SkillUsageReport> {\n readonly id = ANALYST_ID\n readonly description =\n 'Deterministic multi-signal skill-usage analysis: flags dead skills, measurement-invisible (orchestrated) usage, discovery gaps, public-repo leaks, bloat, missing evals, and missing run-logging.'\n readonly inputKind = 'custom' as const\n readonly cost = { kind: 'deterministic' as const, est_usd_per_run: 0 }\n readonly version = '1.0.0'\n readonly executionConfig = {\n kind: 'skill-usage',\n bloat_line_threshold: BLOAT_LINE_THRESHOLD,\n produced_at_source: 'tags.producedAt-or-system-clock',\n } as const\n\n async analyze(input: SkillUsageReport, ctx: AnalystContext): Promise<AnalystFinding[]> {\n const producedAt = ctx.tags?.producedAt ?? new Date().toISOString()\n ctx.log?.(\n `skill-usage: ${input.records.length} skills over ${input.generatedFromTraces} transcripts`,\n )\n return emitSkillUsageFindings(input, producedAt)\n }\n}\n\nexport const SKILL_USAGE_ANALYST = new SkillUsageAnalyst()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,cAAc;AAIpB,SAAS,aAAa,GAAmC;CACvD,QAAQ,GAAR;EACE,KAAK,YACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,QACH,OAAO;CACX;AACF;AAaA,SAAgB,kCACd,MACoC;CACpC,MAAM,KAAK,KAAK,MAAM;CACtB,MAAM,OAAO,KAAK,QAAQ;CAC1B,MAAM,sBAAsB,+BAA+B,KAAK,mBAAmB;CACnF,OAAO;EACL;EACA,aACE;EACF,WAAW;EACX,MAAM;GACJ,MAAM;GACN,QAAQ,KAAK,QAAQ,QAAQ,CAAC,KAAK,QAAQ,KAAK,IAAI,KAAA;GACpD,uBAAuB;EACzB;EACA,SAAS,GAAG,+BAA+B,WAAW;EACtD,MAAM,QAAQ,OAAO,KAAK;GACxB,MAAM,aAAa,IAAI,WAAW,IAAI,SAAS;GAC/C,IAAI;GACJ,IAAI;IACF,SAAS,MAAM,wBAAwB,OAAO;KAC5C,GAAG,KAAK;KACR;KACA,QAAQ,IAAI;IACd,CAAC;GACH,UAAU;IACR,MAAM,QAAQ,MAAM,iCAAiC,YAAY;KAC/D,SAAS;KACT,WAAW;IACb,CAAC;IACD,IAAI,CAAC,MAAM,SACT,IAAI,MAAM,wDAAwD;KAChE,eAAe,MAAM;KACrB,YAAY;IACd,CAAC;IAEH,IAAI,cAAc,MAAM,OAAO;GACjC;GACA,IAAI,CAAC,OAAO,WACV,OAAO,CACL,YAAY;IACV,YAAY;IACZ;IACA,OAAO;IACP,WAAW,OAAO;IAClB,UA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;EAIF,IAAI,CAAC,EAAE,aACL,IAAI,KACF,QACE,gBACA,EAAE,MACF,UAAU,EAAE,KAAK,oBACjB,OACA,IACA,YACA,wGACA,EAAE,IACJ,CACF;EAIF,IAAI,CAAC,EAAE,UACL,IAAI,KACF,QACE,iBACA,EAAE,MACF,UAAU,EAAE,KAAK,8CACjB,OACA,KACA,YACA,iJACA,EAAE,IACJ,CACF;CAEJ;CACA,OAAO;AACT;AAIA,IAAM,oBAAN,MAAyE;CACvE,KAAc;CACd,cACE;CACF,YAAqB;CACrB,OAAgB;EAAE,MAAM;EAA0B,iBAAiB;CAAE;CACrE,UAAmB;CACnB,kBAA2B;EACzB,MAAM;EACN,sBAAsB;EACtB,oBAAoB;CACtB;CAEA,MAAM,QAAQ,OAAyB,KAAgD;EACrF,MAAM,aAAa,IAAI,MAAM,+BAAc,IAAI,KAAK,EAAA,CAAE,YAAY;EAClE,IAAI,MACF,gBAAgB,MAAM,QAAQ,OAAO,eAAe,MAAM,oBAAoB,aAChF;EACA,OAAO,uBAAuB,OAAO,UAAU;CACjD;AACF;AAEA,MAAa,sBAAsB,IAAI,kBAAkB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/analyst/adapters.ts","../../src/analyst/bind.ts","../../src/analyst/define.ts","../../src/analyst/kinds/skill-usage.ts","../../src/analyst/trace-questions.ts"],"sourcesContent":["/**\n * Adapter factory — lifts the semantic-concept judge into the Analyst\n * contract without re-implementing it.\n *\n * It builds an Analyst with a stable id (caller chooses; a default is given),\n * a version derived from the judge's version plus an adapter revision, and an\n * `analyze()` that calls the judge and lifts its output to `AnalystFinding[]`\n * through `makeFinding()`. The judge's `Severity` ('critical' | 'major' |\n * 'minor' | 'info') projects onto `AnalystSeverity`: 'major' becomes 'high'\n * and 'minor' becomes 'medium'.\n *\n * The adapter owns no state. Calling the factory twice is safe.\n */\n\nimport { CostLedger } from '../cost-ledger'\nimport type { Severity as LayerSeverity } from '../multi-layer-verifier'\nimport {\n runSemanticConceptJudge,\n SEMANTIC_CONCEPT_JUDGE_VERSION,\n type SemanticConceptJudgeInput,\n type SemanticConceptJudgeOptions,\n type SemanticConceptJudgeResult,\n} from '../semantic-concept-judge'\nimport type { Analyst, AnalystFinding, AnalystSeverity } from './types'\nimport { makeFinding } from './types'\nimport { settleUsageReceiptFromCostLedger, validateUsageSettlementTimeout } from './usage-receipt'\n\nconst ADAPTER_REV = '1'\n\n// ── Severity bridges ───────────────────────────────────────────────\n\nfunction liftSeverity(s: LayerSeverity): AnalystSeverity {\n switch (s) {\n case 'critical':\n return 'critical'\n case 'major':\n return 'high'\n case 'minor':\n return 'medium'\n case 'info':\n return 'info'\n }\n}\n\n// ── SemanticConceptJudge → Analyst ─────────────────────────────────\n\nexport interface SemanticConceptJudgeAdapterOpts {\n id?: string\n area?: string\n /** Registry context owns cancellation and the per-analyst cost ledger. */\n options: Omit<SemanticConceptJudgeOptions, 'costLedger' | 'signal'>\n /** Maximum post-cancellation wait for a provider receipt. Default 5 seconds. */\n settlementTimeoutMs?: number\n}\n\nexport function createSemanticConceptJudgeAdapter(\n opts: SemanticConceptJudgeAdapterOpts,\n): Analyst<SemanticConceptJudgeInput> {\n const id = opts.id ?? 'semantic-concept-judge'\n const area = opts.area ?? 'concept-coverage'\n const settlementTimeoutMs = validateUsageSettlementTimeout(opts.settlementTimeoutMs)\n return {\n id,\n description:\n 'Runs the semantic-concept judge and surfaces missing / weak concepts as findings.',\n inputKind: 'custom',\n cost: {\n kind: 'llm',\n models: opts.options.model ? [opts.options.model] : undefined,\n settlement_timeout_ms: settlementTimeoutMs,\n },\n version: `${SEMANTIC_CONCEPT_JUDGE_VERSION}-adapter-${ADAPTER_REV}`,\n async analyze(input, ctx) {\n const costLedger = new CostLedger(ctx.budgetUsd)\n let result: SemanticConceptJudgeResult\n try {\n result = await runSemanticConceptJudge(input, {\n ...opts.options,\n costLedger,\n signal: ctx.signal,\n })\n } finally {\n const usage = await settleUsageReceiptFromCostLedger(costLedger, {\n channel: 'judge',\n timeoutMs: settlementTimeoutMs,\n })\n if (!usage.settled) {\n ctx.log?.('semantic-concept judge provider settlement timed out', {\n pending_calls: usage.pendingCalls,\n timeout_ms: settlementTimeoutMs,\n })\n }\n ctx.recordUsage?.(usage.receipt)\n }\n if (!result.available) {\n return [\n makeFinding({\n analyst_id: id,\n area,\n claim: 'semantic-concept judge unavailable',\n rationale: result.error,\n severity: 'info',\n confidence: 1,\n evidence_refs: [],\n metadata: { reason: result.error },\n }),\n ]\n }\n const out: AnalystFinding[] = []\n for (const f of result.findings) {\n // Only surface gaps: missing concepts or low scores. Concepts at\n // 7+/10 with present=true are not findings — they're successes.\n if (f.present && f.score >= 7) continue\n out.push(\n makeFinding({\n analyst_id: id,\n area,\n subject: f.concept,\n claim: f.present\n ? `concept \"${f.concept}\" is weak (${f.score}/10)`\n : `concept \"${f.concept}\" is missing`,\n rationale: f.evidence,\n severity: liftSeverity(f.severity),\n confidence: 0.85,\n evidence_refs: [{ kind: 'artifact', uri: 'inline:evidence', excerpt: f.evidence }],\n metadata: {\n concept: f.concept,\n present: f.present,\n score_10: f.score,\n },\n }),\n )\n }\n return out\n },\n }\n}\n","/**\n * bindAnalyst — compile an `AnalystDefinition` into a runnable arm.\n *\n * The definition declares protocol (question, task text, reply grammar,\n * evidence projection, budget, repair turns); the transport binding supplies\n * execution (a bridge endpoint, or the caller-owned model path). Each\n * projection mode dispatches to the same strategy its arm's entry point runs,\n * so a compiled definition and the historical creator send byte-identical\n * requests — the definition parity suite asserts this per arm.\n *\n * A projection × transport pair with no strategy fails loud with\n * `AnalystExpressivenessError` naming the pair: an arm shape this layer cannot\n * express must be reported, never approximated.\n */\n\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport type { AnalystBenchmarkRunner } from './benchmark'\nimport { runChunkedAnalystDefinition } from './benchmark-public-model'\nimport { runReplVariableAnalystDefinition } from './benchmark-public-rlm'\nimport type { PublicAnalystBenchmarkModelConfig } from './benchmark-public-types'\nimport { runInlineAnalystDefinition } from './benchmark-runner-prime'\nimport { type AnalystDefinition, AnalystExpressivenessError } from './definition'\nimport type { PrimeBridgeTransport } from './prime-bridge-transport'\nimport type { AnalystRunInputs } from './types'\n\n/** Execution half of a binding: who actually reaches the model. */\nexport type AnalystTransportBinding =\n | {\n /** An OpenAI-compatible cli-bridge endpoint (inline projections). */\n readonly kind: 'prime-bridge'\n readonly baseUrl: string\n readonly model: string\n readonly transport?: PrimeBridgeTransport\n readonly pricing?: CustomTokenPricing\n }\n | {\n /** The caller-owned model path (chunked and repl-variable projections). */\n readonly kind: 'model-owner'\n readonly config: PublicAnalystBenchmarkModelConfig\n }\n\n/**\n * Compile a definition plus a transport binding into a runnable arm. Dispatch\n * is total over the expressible pairs; everything else is a loud refusal.\n */\nexport function bindAnalyst<TRow, TAssignment, TBlock>(\n definition: AnalystDefinition<TRow, TAssignment, TBlock>,\n transports: AnalystTransportBinding,\n): AnalystBenchmarkRunner<AnalystRunInputs> {\n const mode = definition.projection.mode\n if (mode === 'inline' && transports.kind === 'prime-bridge') {\n return runInlineAnalystDefinition(definition, {\n baseUrl: transports.baseUrl,\n model: transports.model,\n ...(transports.transport ? { transport: transports.transport } : {}),\n ...(transports.pricing ? { pricing: transports.pricing } : {}),\n })\n }\n if (mode === 'chunked' && transports.kind === 'model-owner') {\n return runChunkedAnalystDefinition(definition, transports.config)\n }\n if (mode === 'repl-variable' && transports.kind === 'model-owner') {\n return runReplVariableAnalystDefinition(\n // The repl-variable strategy is written against the engine's raw-finding\n // row type; the definition's own row declaration carries it.\n definition as Parameters<typeof runReplVariableAnalystDefinition>[0],\n transports.config,\n )\n }\n throw new AnalystExpressivenessError(\n `no strategy compiles a '${mode}' projection over a '${transports.kind}' transport; ` +\n `definition '${definition.id}' cannot be expressed by this layer yet`,\n )\n}\n","import type { TraceAnalysisStore } from '../trace-analyst/store'\nimport type { ExactCapableAnalyst } from './exact-types'\nimport type { TraceAnalystDefinition } from './kind-factory'\nimport type { Analyst, AnalystCost } from './types'\n\n/**\n * Define a reusable trace-research question.\n *\n * The returned value contains no model, credentials, or execution state. Bind\n * it to any TraceAnalysisEngine with `runTraceAnalyst` or\n * `createTraceAnalyst`.\n */\nexport function defineTraceAnalyst(definition: TraceAnalystDefinition): TraceAnalystDefinition {\n for (const [name, value] of [\n ['id', definition.id],\n ['description', definition.description],\n ['area', definition.area],\n ['version', definition.version],\n ['instructions', definition.instructions],\n ] as const) {\n if (typeof value !== 'string' || !value.trim()) {\n throw new TypeError(`defineTraceAnalyst: ${name} must be a non-empty string`)\n }\n }\n return {\n ...definition,\n limits: definition.limits ? { ...definition.limits } : undefined,\n }\n}\n\nexport interface DefineCustomAnalystOptions {\n id: string\n description: string\n version?: string\n cost: AnalystCost\n analyze: Analyst<TraceAnalysisStore>['analyze']\n}\n\nexport interface DefineExactCustomAnalystOptions extends DefineCustomAnalystOptions {\n /** Canonical JSON for behavior knobs not already bound by `version`. */\n executionConfig: Readonly<Record<string, unknown>>\n}\n\n/** Construct a registrable analyst from a hand-written analyze function. */\nexport function defineCustomAnalyst(\n options: DefineExactCustomAnalystOptions,\n): ExactCapableAnalyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions,\n): Analyst<TraceAnalysisStore>\nexport function defineCustomAnalyst(\n options: DefineCustomAnalystOptions | DefineExactCustomAnalystOptions,\n): Analyst<TraceAnalysisStore> | ExactCapableAnalyst<TraceAnalysisStore> {\n if (!options.id.trim()) throw new TypeError('defineCustomAnalyst: id must not be empty')\n if (!options.description.trim()) {\n throw new TypeError('defineCustomAnalyst: description must not be empty')\n }\n if (options.cost === undefined) {\n throw new TypeError('defineCustomAnalyst: cost must be declared')\n }\n if (\n 'executionConfig' in options &&\n (!options.executionConfig ||\n typeof options.executionConfig !== 'object' ||\n Array.isArray(options.executionConfig))\n ) {\n throw new TypeError('defineCustomAnalyst: executionConfig must be an object')\n }\n return {\n id: options.id,\n description: options.description,\n version: options.version ?? '1.0.0',\n inputKind: 'trace-store',\n cost: options.cost,\n analyze: options.analyze,\n ...('executionConfig' in options ? { executionConfig: options.executionConfig } : {}),\n }\n}\n","/**\n * Skill-usage analyst — a DETERMINISTIC `Analyst` over a Claude/Codex skill\n * library + its trace corpus. Unlike the trace-store kinds (failure-mode,\n * improvement, ...) this kind calls no LLM: it mines real usage and skill\n * structure and emits findings by rule.\n *\n * It exists because the naive \"Skill-tool invocation count\" lies low — it\n * misses orchestrated sub-dispatch (a leaf skill run BY /pursue or /governor\n * logs under the parent), slash-command entry, local-script bypass, and\n * on-disk artifacts. The 2026-05-30 skill audit found 39/53 skills at zero\n * direct invocations, yet only one was a genuine cut: the rest were\n * measurement-invisible or discovery-limited. This analyst encodes that\n * lesson as a multi-signal usage model so a cheap repeatable pass can keep\n * the library honest, and so the expensive audit workflow's verdicts can\n * GEPA-distill it toward agreement (see `gold/skill-verdicts.gold.jsonl`).\n *\n * Report-building (`buildSkillUsageReport`, an fs scan) is separated from\n * finding emission (`SkillUsageAnalyst.analyze`, pure) so the slow scan runs\n * once at the registry boundary and the rule logic stays unit-testable.\n */\n\nimport { type Dirent, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { ExactCapableAnalyst } from '../exact-types'\nimport type { AnalystContext, AnalystFinding, AnalystSeverity } from '../types'\nimport { computeFindingId } from '../types'\n\n// ── Input model ──────────────────────────────────────────────────────\n\nexport type SkillKind = 'public' | 'private'\n\n/** One skill's multi-signal usage + structure. All counts are deterministic. */\nexport interface SkillUsageRecord {\n name: string\n kind: SkillKind\n /** Absolute path to the skill's SKILL.md. */\n path: string\n lines: number\n /** `\"skill\":\"<name>\"` Skill-tool invocations across the trace corpus. */\n directInvocations: number\n /** `<command-name>/<name>` slash invocations across the trace corpus. */\n slashInvocations: number\n /** Sibling skills whose SKILL.md dispatches to this one (`/<name>`). Proxy\n * for orchestrated sub-dispatch the per-skill counter cannot see. */\n inboundRefs: number\n /** On-disk artifacts attributable to the skill (e.g. `.evolve/<name>/**`). */\n artifactCount: number\n /** Tangle-private reference count in the body (leak signal for public skills). */\n tanglePrivateRefs: number\n hasReferencesDir: boolean\n hasEvalsDir: boolean\n /** Body mentions `skill-runs.jsonl` (visible to /reflect + /governor). */\n logsRuns: boolean\n /** Description carries an explicit `Triggers:` clause / trigger phrases. */\n hasTriggerPhrases: boolean\n}\n\nexport interface SkillUsageReport {\n generatedFromTraces: number\n records: SkillUsageRecord[]\n}\n\nexport interface SkillUsageScanConfig {\n /** Dirs holding `*.jsonl` transcripts (Claude `~/.claude/projects`, Codex sessions). */\n transcriptDirs: string[]\n /** Skill roots to scan; each dir directly under `root` with a `SKILL.md` is a skill. */\n skillRoots: { root: string; kind: SkillKind }[]\n /** Roots scanned for `<root>/.evolve/<skill>` artifact dirs. */\n artifactRoots?: string[]\n /** Token-prefixed mappings: skill name → extra artifact subpaths under an artifactRoot\n * (e.g. reflect → `.evolve/reflections`). Catches non-eponymous artifact dirs. */\n artifactAliases?: Record<string, string[]>\n /** Cap files read per transcript dir (bounds a huge corpus); 0 = unbounded. */\n maxTranscriptsPerDir?: number\n}\n\n// ── Deterministic thresholds ─────────────────────────────────────────\n\n/** Anthropic's authoring guidance keeps SKILL.md short; past this with no\n * `references/` split the body burns context budget every session. */\nconst BLOAT_LINE_THRESHOLD = 300\n\nconst TANGLE_PRIVATE_RE =\n /\\b(cli-bridge|tangletools|ops-board|drew-gtr-pro|@tangle-network\\/|~\\/company|tangle\\.tools|gtm-agent)\\b|\\bkimi\\b|\\btcloud\\b/gi\nconst TRIGGER_RE = /triggers?\\s*[:-]/i\n\n// ── Report builder (fs scan — slow, runs once at the registry boundary) ──\n\nfunction listSkillDirs(root: string): { name: string; path: string }[] {\n if (!existsSync(root)) return []\n const out: { name: string; path: string }[] = []\n for (const entry of readdirSync(root, { withFileTypes: true })) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue\n const skillMd = join(root, entry.name, 'SKILL.md')\n if (existsSync(skillMd)) out.push({ name: entry.name, path: skillMd })\n }\n return out\n}\n\nfunction walkJsonl(dir: string, cap: number): string[] {\n if (!existsSync(dir)) return []\n const files: string[] = []\n const stack = [dir]\n while (stack.length) {\n const cur = stack.pop()!\n let entries: Dirent[]\n try {\n entries = readdirSync(cur, { withFileTypes: true })\n } catch {\n continue\n }\n for (const e of entries) {\n const full = join(cur, e.name)\n if (e.isDirectory()) stack.push(full)\n else if (e.name.endsWith('.jsonl')) {\n files.push(full)\n if (cap > 0 && files.length >= cap) return files\n }\n }\n }\n return files\n}\n\nfunction frontmatterDescription(body: string): string {\n const fm = /^---\\n([\\s\\S]*?)\\n---/.exec(body)\n const block = fm?.[1] ?? ''\n const m = /description:\\s*(.+)/i.exec(block)\n return m?.[1] ?? ''\n}\n\nfunction countArtifacts(roots: string[], name: string, aliases: string[]): number {\n let n = 0\n for (const root of roots) {\n const candidates = [join(root, '.evolve', name), ...aliases.map((a) => join(root, a))]\n for (const dir of candidates) {\n if (!existsSync(dir)) continue\n try {\n if (statSync(dir).isDirectory()) n += readdirSync(dir).length\n else n += 1\n } catch {\n /* unreadable — skip */\n }\n }\n }\n return n\n}\n\n/** Scan the corpus + skill roots into a {@link SkillUsageReport}. Deterministic. */\nexport function buildSkillUsageReport(config: SkillUsageScanConfig): SkillUsageReport {\n const skills = config.skillRoots.flatMap(({ root, kind }) =>\n listSkillDirs(root).map((s) => ({ ...s, kind })),\n )\n const names = skills.map((s) => s.name)\n\n // One pass over the corpus accumulating direct + slash counts per skill.\n const direct = new Map<string, number>(names.map((n) => [n, 0]))\n const slash = new Map<string, number>(names.map((n) => [n, 0]))\n const skillRe = /\"skill\"\\s*:\\s*\"([a-z0-9_:-]+)\"/g\n const cmdRe = /<command-name>\\/?([a-z0-9_:-]+)<\\/command-name>/g\n let transcripts = 0\n for (const dir of config.transcriptDirs) {\n for (const file of walkJsonl(dir, config.maxTranscriptsPerDir ?? 0)) {\n transcripts += 1\n let data: string\n try {\n data = readFileSync(file, 'utf8')\n } catch {\n continue\n }\n for (const m of data.matchAll(skillRe)) {\n const g = m[1]\n if (!g) continue\n const n = g.split(':').pop() ?? g\n const prev = direct.get(n)\n if (prev !== undefined) direct.set(n, prev + 1)\n }\n for (const m of data.matchAll(cmdRe)) {\n const g = m[1]\n if (g === undefined) continue\n const prev = slash.get(g)\n if (prev !== undefined) slash.set(g, prev + 1)\n }\n }\n }\n\n // Read each skill body once; compute structure + inbound refs across siblings.\n const bodies = new Map<string, string>()\n for (const s of skills) {\n try {\n bodies.set(s.name, readFileSync(s.path, 'utf8'))\n } catch {\n bodies.set(s.name, '')\n }\n }\n const inbound = new Map<string, number>(names.map((n) => [n, 0]))\n for (const target of names) {\n const ref = new RegExp(`/${target}\\\\b|\\\\[\\\\[${target}\\\\]\\\\]`)\n for (const s of skills) {\n if (s.name === target) continue\n if (ref.test(bodies.get(s.name) ?? '')) inbound.set(target, inbound.get(target)! + 1)\n }\n }\n\n const records: SkillUsageRecord[] = skills.map((s) => {\n const body = bodies.get(s.name) ?? ''\n const dir = s.path.replace(/\\/SKILL\\.md$/, '')\n return {\n name: s.name,\n kind: s.kind,\n path: s.path,\n lines: body ? body.split('\\n').length : 0,\n directInvocations: direct.get(s.name) ?? 0,\n slashInvocations: slash.get(s.name) ?? 0,\n inboundRefs: inbound.get(s.name) ?? 0,\n artifactCount: countArtifacts(\n config.artifactRoots ?? [],\n s.name,\n config.artifactAliases?.[s.name] ?? [],\n ),\n tanglePrivateRefs: (body.match(TANGLE_PRIVATE_RE) ?? []).length,\n hasReferencesDir: existsSync(join(dir, 'references')),\n hasEvalsDir: existsSync(join(dir, 'evals')),\n logsRuns: body.includes('skill-runs.jsonl'),\n hasTriggerPhrases: TRIGGER_RE.test(frontmatterDescription(body) || body.slice(0, 600)),\n }\n })\n return { generatedFromTraces: transcripts, records }\n}\n\n// ── Finding emission (pure — unit-testable, no LLM, no fs) ────────────\n\nconst ANALYST_ID = 'skill-usage'\n\nfunction finding(\n area: string,\n subject: string,\n claim: string,\n severity: AnalystSeverity,\n confidence: number,\n producedAt: string,\n recommended: string,\n evidenceUri: string,\n rationale?: string,\n): AnalystFinding {\n return {\n schema_version: '1.0.0',\n finding_id: computeFindingId({ analyst_id: ANALYST_ID, area, subject, claim }),\n analyst_id: ANALYST_ID,\n produced_at: producedAt,\n severity,\n area,\n claim,\n rationale,\n evidence_refs: [{ kind: 'artifact', uri: evidenceUri }],\n recommended_action: recommended,\n confidence,\n subject,\n }\n}\n\n/** Pure rule pass over a report → findings. Exported for direct/unit use. */\nexport function emitSkillUsageFindings(\n report: SkillUsageReport,\n producedAt: string,\n): AnalystFinding[] {\n const out: AnalystFinding[] = []\n for (const r of report.records) {\n const directTotal = r.directInvocations + r.slashInvocations\n const trueUsage = directTotal + r.inboundRefs + r.artifactCount\n\n // 1. Dead: no usage signal of ANY kind. The only real deprecation candidate.\n if (trueUsage === 0) {\n out.push(\n finding(\n 'skill-usage',\n r.name,\n `Skill '${r.name}' has zero usage across all signals (direct, slash, inbound-refs, artifacts)`,\n 'high',\n 0.6,\n producedAt,\n 'Confirm the skill covers a real recurring job; if not, deprecate. Zero true usage is the only deterministic deprecation candidate.',\n r.path,\n 'No Skill-tool call, no slash invocation, no sibling dispatches to it, and no on-disk artifacts.',\n ),\n )\n } else if (directTotal === 0 && r.inboundRefs + r.artifactCount > 0) {\n // 2. Measurement-invisible: real use via orchestration/artifacts, never invoked directly.\n out.push(\n finding(\n 'skill-usage',\n r.name,\n `Skill '${r.name}' shows 0 direct invocations but is used via orchestration/artifacts (inbound=${r.inboundRefs}, artifacts=${r.artifactCount})`,\n 'info',\n 0.8,\n producedAt,\n 'Do NOT treat as unused — usage is real but logged under parent skills or on disk. Strengthen direct-invocation discovery only if direct use is desired.',\n r.path,\n 'The Skill-tool counter undercounts orchestrated/chained leaf skills.',\n ),\n )\n }\n\n // 3. Discovery gap: low direct use AND weak trigger surface.\n if (directTotal <= 2 && !r.hasTriggerPhrases) {\n out.push(\n finding(\n 'discoverability',\n r.name,\n `Skill '${r.name}' is rarely invoked directly and its description has no explicit trigger phrases`,\n 'medium',\n 0.7,\n producedAt,\n 'Add a `Triggers:` clause with verbatim user phrases to the frontmatter description so the model auto-invokes it.',\n r.path,\n ),\n )\n }\n\n // 4. Public-repo leak.\n if (r.kind === 'public' && r.tanglePrivateRefs > 0) {\n out.push(\n finding(\n 'safety',\n r.name,\n `Public skill '${r.name}' carries ${r.tanglePrivateRefs} Tangle-private reference(s)`,\n 'high',\n 0.75,\n producedAt,\n 'Sanitize incidental internal refs (cli-bridge/kimi/tcloud/~company/private repos) or relocate to a private repo. Verify @tangle-network/* refs are to PUBLISHED packages before treating as a leak.',\n r.path,\n ),\n )\n }\n\n // 5. Bloat / no progressive disclosure.\n if (r.lines > BLOAT_LINE_THRESHOLD && !r.hasReferencesDir) {\n out.push(\n finding(\n 'maintainability',\n r.name,\n `Skill '${r.name}' is ${r.lines} lines with no references/ split (progressive disclosure)`,\n 'medium',\n 0.8,\n producedAt,\n `Split detail into references/ loaded on demand; keep SKILL.md a short overview. ${r.lines} lines load into every session's context budget.`,\n r.path,\n ),\n )\n }\n\n // 6. No evals (Anthropic's \">=3 evals before docs\" rule).\n if (!r.hasEvalsDir) {\n out.push(\n finding(\n 'data-quality',\n r.name,\n `Skill '${r.name}' ships no evals/`,\n 'low',\n 0.6,\n producedAt,\n 'Add evals/evals.json with >=3 scenarios proving the skill beats baseline; gives regression coverage.',\n r.path,\n ),\n )\n }\n\n // 7. No run logging → invisible to /reflect and /governor.\n if (!r.logsRuns) {\n out.push(\n finding(\n 'observability',\n r.name,\n `Skill '${r.name}' never appends to .evolve/skill-runs.jsonl`,\n 'low',\n 0.55,\n producedAt,\n 'Append one run line to .evolve/skill-runs.jsonl on completion, or declare it a non-logging leaf, so the self-improvement loop can see it ran.',\n r.path,\n ),\n )\n }\n }\n return out\n}\n\n// ── The Analyst ──────────────────────────────────────────────────────\n\nclass SkillUsageAnalyst implements ExactCapableAnalyst<SkillUsageReport> {\n readonly id = ANALYST_ID\n readonly description =\n 'Deterministic multi-signal skill-usage analysis: flags dead skills, measurement-invisible (orchestrated) usage, discovery gaps, public-repo leaks, bloat, missing evals, and missing run-logging.'\n readonly inputKind = 'custom' as const\n readonly cost = { kind: 'deterministic' as const, est_usd_per_run: 0 }\n readonly version = '1.0.0'\n readonly executionConfig = {\n kind: 'skill-usage',\n bloat_line_threshold: BLOAT_LINE_THRESHOLD,\n produced_at_source: 'tags.producedAt-or-system-clock',\n } as const\n\n async analyze(input: SkillUsageReport, ctx: AnalystContext): Promise<AnalystFinding[]> {\n const producedAt = ctx.tags?.producedAt ?? new Date().toISOString()\n ctx.log?.(\n `skill-usage: ${input.records.length} skills over ${input.generatedFromTraces} transcripts`,\n )\n return emitSkillUsageFindings(input, producedAt)\n }\n}\n\nexport const SKILL_USAGE_ANALYST = new SkillUsageAnalyst()\n","/**\n * Many questions over one trace store, concurrently, under one cost ledger, with an independent\n * verifier for every finding.\n *\n * `traces ask` answered questions this way for people. A continuation panel (agent-runtime,\n * discovery `docs/38-one-loop-and-continuation.md`, section 5) asks dozens to hundreds of atomic\n * questions of a director's own trace every time the outside check fails, so the runner lives here,\n * beside `runTraceAnalyst`, where both callers reach one implementation.\n *\n * Each question is one `runTraceAnalyst` call, which already refuses a finding with fewer distinct\n * citations than required or with a citation the store cannot resolve. What this module adds:\n *\n * - a worker pool: at most `concurrency` investigations at once, and one failed question never\n * stops the others; its failure is its answer;\n * - one shared `CostLedger`, so a single ceiling bounds every question and every verifier;\n * - an independent verifier per admitted finding, shown only the spans the finding cites. Analysts\n * misattribute often: the best method in Who&When found the failing step 14.2% of the time. A\n * finding a verifier reading only its own evidence does not support never reaches a caller as\n * verified.\n */\n\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport { defineTraceAnalyst } from './define'\nimport type { TraceAnalysisEngine, TraceAnalystLimits } from './engine'\nimport { parseTraceSpanEvidenceUri, type RawAnalystFinding } from './finding-signature'\nimport { runTraceAnalyst } from './kind-factory'\n\n/** One question to ask of the store. */\nexport interface TraceQuestionSpec {\n /** Stable id: letters, digits, dot, underscore, hyphen. */\n readonly id: string\n readonly question: string\n /** Guidance for this question only, after the shared rules. */\n readonly instructions?: string\n}\n\nexport interface AskTraceQuestionsOptions {\n readonly questions: readonly TraceQuestionSpec[]\n readonly store: TraceAnalysisStore\n readonly engine: TraceAnalysisEngine\n /** Every question and verifier charges this ledger; its ceiling bounds the whole call. */\n readonly costLedger: CostLedgerHandle\n /** Stable id for cost attribution and logs. */\n readonly runId: string\n /** Material every question receives before its first model call, such as the check's verdict. */\n readonly context?: string\n /** Investigations running at once. Default 4. */\n readonly concurrency?: number\n /** Distinct citations a finding needs. Default 2. */\n readonly minimumEvidenceCitations?: number\n /** Run the independent verifier on every admitted finding. Default true. */\n readonly verify?: boolean\n readonly limits?: Partial<TraceAnalystLimits>\n readonly signal?: AbortSignal\n readonly log?: (message: string, fields?: Record<string, unknown>) => void\n}\n\n/** A finding and what the verifier, shown only its cited spans, concluded. */\nexport interface VerifiedTraceFinding {\n readonly finding: RawAnalystFinding\n /** The finding's trace citations, as `trace://` URIs. */\n readonly citations: readonly string[]\n /** `true` supported, `false` not supported, `null` when verification was off or failed. */\n readonly verified: boolean | null\n /** The verifier's own words, when it answered. */\n readonly verifierAnswer?: string\n}\n\nexport interface TraceQuestionOutcome {\n readonly id: string\n readonly question: string\n readonly status: 'answered' | 'failed'\n readonly failure?: string\n /** The engine's prose answer, verbatim; `null` when it returned none. */\n readonly answer: string | null\n readonly findings: readonly VerifiedTraceFinding[]\n /** `null` when the engine failed before reporting. */\n readonly modelCalls: number | null\n readonly toolCalls: number | null\n}\n\nconst QUESTION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u\nconst DEFINITION_VERSION = '1.0.0'\n\nconst QUESTION_RULES = [\n 'Answer QUESTION only from trace tool results retrieved in this run.',\n 'Cite each fact as trace://<trace_id>/span/<span_id>, and quote the span in the excerpt.',\n 'If the trace does not record a fact, say \"not in trace\". Never infer a trace fact from the question.',\n].join('\\n')\n\nconst VERIFIER_RULES = [\n 'You check one CLAIM against the spans it cites, and nothing else.',\n 'Read each cited span with viewSpans. No other trace is readable.',\n 'First line: SUPPORTED if the spans themselves establish the claim, otherwise NOT SUPPORTED.',\n 'Second line: one sentence naming the span that decides it.',\n 'Return no findings.',\n].join('\\n')\n\n/**\n * Ask every question, then verify every admitted finding. Never throws for a failed question or\n * verifier: each failure is recorded on its outcome. Throws before any model call for a malformed\n * question list or options.\n */\nexport async function askTraceQuestions(\n opts: AskTraceQuestionsOptions,\n): Promise<TraceQuestionOutcome[]> {\n const concurrency = opts.concurrency ?? 4\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) {\n throw new RangeError('askTraceQuestions: concurrency must be an integer >= 1')\n }\n const minimum = opts.minimumEvidenceCitations ?? 2\n if (!Number.isSafeInteger(minimum) || minimum < 1) {\n throw new RangeError('askTraceQuestions: minimumEvidenceCitations must be an integer >= 1')\n }\n const seen = new Set<string>()\n for (const question of opts.questions) {\n if (!QUESTION_ID.test(question.id)) {\n throw new TypeError(\n `askTraceQuestions: question id ${JSON.stringify(question.id)} is malformed`,\n )\n }\n if (seen.has(question.id)) {\n throw new TypeError(`askTraceQuestions: duplicate question id ${JSON.stringify(question.id)}`)\n }\n seen.add(question.id)\n if (question.question.trim() === '') {\n throw new TypeError(`askTraceQuestions: question ${question.id} is empty`)\n }\n }\n\n const askOne = async (question: TraceQuestionSpec): Promise<TraceQuestionOutcome> => {\n if (opts.signal?.aborted) {\n return failed(question, 'the run was aborted before the question started')\n }\n let completed: Awaited<ReturnType<typeof runTraceAnalyst>>\n try {\n completed = await runTraceAnalyst({\n definition: defineTraceAnalyst({\n id: `question.${question.id}`,\n description: `trace question ${question.id}`,\n area: 'question',\n version: DEFINITION_VERSION,\n question: question.question.trim(),\n instructions: [QUESTION_RULES, question.instructions?.trim() ?? '']\n .filter(Boolean)\n .join('\\n\\n'),\n toolGroup: 'all',\n minimumEvidenceCitations: minimum,\n ...(opts.context ? { prepareContext: () => opts.context } : {}),\n ...(opts.limits ? { limits: opts.limits } : {}),\n }),\n engine: opts.engine,\n store: opts.store,\n context: {\n runId: opts.runId,\n correlationId: `${opts.runId}:${question.id}`,\n costLedger: opts.costLedger,\n costPhase: 'trace-question',\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.log ? { log: opts.log } : {}),\n },\n })\n } catch (error) {\n return failed(question, errorText(error))\n }\n const findings: VerifiedTraceFinding[] = []\n for (const [index, finding] of completed.findings.entries()) {\n const citations = finding.evidence\n .map((citation) => citation.uri.trim())\n .filter((uri) => parseTraceSpanEvidenceUri(uri) !== null)\n findings.push(\n opts.verify === false\n ? { finding, citations, verified: null }\n : await verifyFinding(opts, `${question.id}.v${index + 1}`, finding, citations),\n )\n }\n const answer = completed.answer.trim() === '' ? null : completed.answer\n return {\n id: question.id,\n question: question.question,\n status: 'answered',\n answer,\n findings,\n modelCalls: completed.modelCalls,\n toolCalls: completed.toolCalls,\n }\n }\n\n // A pool, not Promise.all: at most `concurrency` engines exist at once.\n const outcomes = new Array<TraceQuestionOutcome>(opts.questions.length)\n let next = 0\n await Promise.all(\n Array.from({ length: Math.min(concurrency, opts.questions.length) }, async () => {\n while (next < opts.questions.length) {\n const index = next\n next += 1\n const question = opts.questions[index] as TraceQuestionSpec\n outcomes[index] = await askOne(question)\n }\n }),\n )\n return outcomes\n}\n\n/** The verifier reads only the spans the finding cites, through a store that holds nothing else. */\nasync function verifyFinding(\n opts: AskTraceQuestionsOptions,\n id: string,\n finding: RawAnalystFinding,\n citations: readonly string[],\n): Promise<VerifiedTraceFinding> {\n const allowed = new Map<string, Set<string>>()\n for (const uri of citations) {\n const location = parseTraceSpanEvidenceUri(uri)\n if (location === null) continue\n const spans = allowed.get(location.traceId) ?? new Set<string>()\n spans.add(location.spanId)\n allowed.set(location.traceId, spans)\n }\n if (allowed.size === 0) return { finding, citations, verified: false }\n try {\n const verdict = await runTraceAnalyst({\n definition: defineTraceAnalyst({\n id: `verify.${id}`,\n description: `independent check of finding ${id}`,\n area: 'question',\n version: DEFINITION_VERSION,\n question: `CLAIM: ${finding.claim}\\nCITED SPANS: ${citations.join(', ')}`,\n instructions: VERIFIER_RULES,\n toolGroup: 'targeted',\n ...(opts.limits ? { limits: opts.limits } : {}),\n }),\n engine: opts.engine,\n store: citedSpansOnly(opts.store, allowed),\n context: {\n runId: opts.runId,\n correlationId: `${opts.runId}:verify:${id}`,\n costLedger: opts.costLedger,\n costPhase: 'trace-question-verifier',\n ...(opts.signal ? { signal: opts.signal } : {}),\n ...(opts.log ? { log: opts.log } : {}),\n },\n })\n const first = verdict.answer.trim().split('\\n')[0]?.trim().toUpperCase() ?? ''\n return {\n finding,\n citations,\n verified: first.startsWith('SUPPORTED'),\n verifierAnswer: verdict.answer.trim(),\n }\n } catch (error) {\n opts.log?.('verifier failed', { finding: id, error: errorText(error) })\n return { finding, citations, verified: null }\n }\n}\n\n/**\n * A store that exposes exactly the cited spans. Discovery and whole-trace reads refuse, so the\n * verifier cannot go looking for other support; the underlying store's bounds still apply.\n */\nexport function citedSpansOnly(\n store: TraceAnalysisStore,\n allowed: ReadonlyMap<string, ReadonlySet<string>>,\n): TraceAnalysisStore {\n const refuse = (what: string) => async (): Promise<never> => {\n throw new Error(`${what} is not available to a verifier: read the cited spans with viewSpans`)\n }\n return {\n hasTrace: async (traceId) => allowed.has(traceId),\n hasSpans: async (input, context) => {\n const spans = allowed.get(input.trace_id)\n if (spans === undefined) return []\n return store.hasSpans(\n { trace_id: input.trace_id, span_ids: input.span_ids.filter((span) => spans.has(span)) },\n context,\n )\n },\n getOverview: refuse('getOverview'),\n queryTraces: refuse('queryTraces'),\n countTraces: refuse('countTraces'),\n viewTrace: refuse('viewTrace'),\n viewSpans: async (input, context) => {\n const spans = allowed.get(input.trace_id)\n const wanted = input.span_ids.filter((span) => spans?.has(span) === true)\n if (wanted.length === 0) {\n throw new Error('viewSpans: only the cited spans are readable')\n }\n return store.viewSpans({ ...input, span_ids: wanted }, context)\n },\n searchTrace: refuse('searchTrace'),\n searchSpan: async (input, context) => {\n if (allowed.get(input.trace_id)?.has(input.span_id) !== true) {\n throw new Error('searchSpan: only the cited spans are readable')\n }\n return store.searchSpan(input, context)\n },\n }\n}\n\nfunction failed(question: TraceQuestionSpec, failure: string): TraceQuestionOutcome {\n return {\n id: question.id,\n question: question.question,\n status: 'failed',\n failure,\n answer: null,\n findings: [],\n modelCalls: null,\n toolCalls: null,\n }\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? `${error.name}: ${error.message}` : String(error)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,cAAc;AAIpB,SAAS,aAAa,GAAmC;CACvD,QAAQ,GAAR;EACE,KAAK,YACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,QACH,OAAO;CACX;AACF;AAaA,SAAgB,kCACd,MACoC;CACpC,MAAM,KAAK,KAAK,MAAM;CACtB,MAAM,OAAO,KAAK,QAAQ;CAC1B,MAAM,sBAAsB,+BAA+B,KAAK,mBAAmB;CACnF,OAAO;EACL;EACA,aACE;EACF,WAAW;EACX,MAAM;GACJ,MAAM;GACN,QAAQ,KAAK,QAAQ,QAAQ,CAAC,KAAK,QAAQ,KAAK,IAAI,KAAA;GACpD,uBAAuB;EACzB;EACA,SAAS,GAAG,+BAA+B,WAAW;EACtD,MAAM,QAAQ,OAAO,KAAK;GACxB,MAAM,aAAa,IAAI,WAAW,IAAI,SAAS;GAC/C,IAAI;GACJ,IAAI;IACF,SAAS,MAAM,wBAAwB,OAAO;KAC5C,GAAG,KAAK;KACR;KACA,QAAQ,IAAI;IACd,CAAC;GACH,UAAU;IACR,MAAM,QAAQ,MAAM,iCAAiC,YAAY;KAC/D,SAAS;KACT,WAAW;IACb,CAAC;IACD,IAAI,CAAC,MAAM,SACT,IAAI,MAAM,wDAAwD;KAChE,eAAe,MAAM;KACrB,YAAY;IACd,CAAC;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,IAAI,MAAM,QAAQ;GACxC,IAAI,UAAU,KAAA,GAAW,OAAO,CAAC;GACjC,OAAO,MAAM,SACX;IAAE,UAAU,MAAM;IAAU,UAAU,MAAM,SAAS,QAAQ,SAAS,MAAM,IAAI,IAAI,CAAC;GAAE,GACvF,OACF;EACF;EACA,aAAa,OAAO,aAAa;EACjC,aAAa,OAAO,aAAa;EACjC,aAAa,OAAO,aAAa;EACjC,WAAW,OAAO,WAAW;EAC7B,WAAW,OAAO,OAAO,YAAY;GACnC,MAAM,QAAQ,QAAQ,IAAI,MAAM,QAAQ;GACxC,MAAM,SAAS,MAAM,SAAS,QAAQ,SAAS,OAAO,IAAI,IAAI,MAAM,IAAI;GACxE,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,MAAM,8CAA8C;GAEhE,OAAO,MAAM,UAAU;IAAE,GAAG;IAAO,UAAU;GAAO,GAAG,OAAO;EAChE;EACA,aAAa,OAAO,aAAa;EACjC,YAAY,OAAO,OAAO,YAAY;GACpC,IAAI,QAAQ,IAAI,MAAM,QAAQ,CAAC,EAAE,IAAI,MAAM,OAAO,MAAM,MACtD,MAAM,IAAI,MAAM,+CAA+C;GAEjE,OAAO,MAAM,WAAW,OAAO,OAAO;EACxC;CACF;AACF;AAEA,SAAS,OAAO,UAA6B,SAAuC;CAClF,OAAO;EACL,IAAI,SAAS;EACb,UAAU,SAAS;EACnB,QAAQ;EACR;EACA,QAAQ;EACR,UAAU,CAAC;EACX,YAAY;EACZ,WAAW;CACb;AACF;AAEA,SAAS,UAAU,OAAwB;CACzC,OAAO,iBAAiB,QAAQ,GAAG,MAAM,KAAK,IAAI,MAAM,YAAY,OAAO,KAAK;AAClF"}
|
|
@@ -5,16 +5,16 @@ import { a as resolveModelPricing } from "./metrics-DOMpkoeb.js";
|
|
|
5
5
|
import { a as CostLedgerPersistenceError, i as CostLedger, n as CostCallConflictError, o as CostReceiptCaptureError, r as CostCeilingReachedError, s as CostReservationExceededError, t as CostAccountingIncompleteError } from "./cost-ledger-_IbkejCF.js";
|
|
6
6
|
import { c as withLedgerFileLock, l as writeLedgerFileAtomically } from "./journal-CDP0Vhx_.js";
|
|
7
7
|
import "./ledger-core/index.js";
|
|
8
|
-
import { S as fsCampaignStorage, i as startExternalOptimizerModelProxy, r as runWithCleanup, x as createRunCostLedger, y as resolveExternalOptimizerProcessLimits } from "./external-optimizer-subprocess-
|
|
9
|
-
import { f as redactText } from "./redact-
|
|
10
|
-
import { M as RAW_FINDING_SCHEMA_PROMPT, N as RawAnalystFindingSchema, P as evidenceRefsFromRawFinding, g as TRACE_ANALYSIS_LIMITS, r as runTraceAnalyst } from "./kind-factory-
|
|
8
|
+
import { S as fsCampaignStorage, i as startExternalOptimizerModelProxy, r as runWithCleanup, x as createRunCostLedger, y as resolveExternalOptimizerProcessLimits } from "./external-optimizer-subprocess-C0dHXH8e.js";
|
|
9
|
+
import { f as redactText } from "./redact-8fX8-uKr.js";
|
|
10
|
+
import { M as RAW_FINDING_SCHEMA_PROMPT, N as RawAnalystFindingSchema, P as evidenceRefsFromRawFinding, g as TRACE_ANALYSIS_LIMITS, r as runTraceAnalyst } from "./kind-factory-ByZeXDqF.js";
|
|
11
11
|
import { r as usageReceiptFromCostLedger } from "./usage-receipt-Cx3xNeyB.js";
|
|
12
|
-
import { a as callLlmJson, r as LlmResponseError, t as LlmCallError } from "./llm-client-
|
|
12
|
+
import { a as callLlmJson, r as LlmResponseError, t as LlmCallError } from "./llm-client-BqmRnibA.js";
|
|
13
13
|
import { r as makeFinding } from "./types-CW5b90JH.js";
|
|
14
|
-
import { t as createDspyRlmTraceEngine } from "./dspy-rlm-engine-
|
|
15
|
-
import { i as otlpTextToTraceAnalysisStore, r as createOtlpBufferTraceStore, t as DEFAULT_MAX_TRACE_FILE_BYTES } from "./store-otlp-
|
|
14
|
+
import { t as createDspyRlmTraceEngine } from "./dspy-rlm-engine-CTIGomgr.js";
|
|
15
|
+
import { i as otlpTextToTraceAnalysisStore, r as createOtlpBufferTraceStore, t as DEFAULT_MAX_TRACE_FILE_BYTES } from "./store-otlp-84DH0OEH.js";
|
|
16
16
|
import { i as summarizeAnalystBenchmarkRunner, n as runAnalystBenchmark, r as traceStoreEvidenceResolver } from "./benchmark-BeQJyrRC.js";
|
|
17
|
-
import { n as acquireSingleRunLock } from "./external-optimizer-process-
|
|
17
|
+
import { n as acquireSingleRunLock } from "./external-optimizer-process-Mc83UoWl.js";
|
|
18
18
|
import { t as assertEqualDeclarativeTerms } from "./equal-terms-Blx9Zk5I.js";
|
|
19
19
|
import { c as primeProtocolSha256, d as runPrimeExchange, f as decodeReplyRows, n as buildPrimePrompt, t as analystUsageReceiptFromPrimeUsage, u as projectPrimeTrajectory } from "./prime-protocol-DcAK9pC8.js";
|
|
20
20
|
import { t as nodeHttpPrimeBridgeTransport } from "./prime-bridge-transport-Z3cpKGoV.js";
|
|
@@ -1415,7 +1415,7 @@ const ANALYST_BENCHMARK_DEPENDENCY_LOCK_FILES = Object.freeze([
|
|
|
1415
1415
|
"package.json",
|
|
1416
1416
|
"pnpm-lock.yaml"
|
|
1417
1417
|
]);
|
|
1418
|
-
const ANALYST_BENCHMARK_DEPENDENCY_LOCK_SHA256 = "
|
|
1418
|
+
const ANALYST_BENCHMARK_DEPENDENCY_LOCK_SHA256 = "deece9c68c6c8fd8d4271821b2549b44f586d55480b5e4adff0cef24425ad506";
|
|
1419
1419
|
const ANALYST_BENCHMARK_EVIDENCE_DEPENDENCY_LOCK_SHA256 = "1e03f2daed356d60316aabefb407ec1e437ac94d408d61eea4ae096e9c6fbb5b";
|
|
1420
1420
|
const ANALYST_BENCHMARK_EVIDENCE_IMPLEMENTATION_SHA256 = "4dba263b6256a30d56c7fdb2d992d3a953c0035d731f359b704db806f68f75ac";
|
|
1421
1421
|
const ANALYST_BENCHMARK_IMPLEMENTATION_FILES = Object.freeze([
|
|
@@ -1529,7 +1529,7 @@ const ANALYST_BENCHMARK_IMPLEMENTATION_FILES = Object.freeze([
|
|
|
1529
1529
|
"src/trace/redact.ts",
|
|
1530
1530
|
"src/verdict-cache.ts"
|
|
1531
1531
|
]);
|
|
1532
|
-
const ANALYST_BENCHMARK_IMPLEMENTATION_SHA256 = "
|
|
1532
|
+
const ANALYST_BENCHMARK_IMPLEMENTATION_SHA256 = "34d7abf915171873242a05dc08805b3f78edec593f72d4cdb4c8882dec24621f";
|
|
1533
1533
|
function analystBenchmarkImplementationDigest() {
|
|
1534
1534
|
return ANALYST_BENCHMARK_IMPLEMENTATION_SHA256;
|
|
1535
1535
|
}
|
|
@@ -6315,4 +6315,4 @@ function shellQuote(value) {
|
|
|
6315
6315
|
//#endregion
|
|
6316
6316
|
export { ANALYST_BENCHMARK_MANIFEST_FILE as $, readAnalystInstructionsOverride as A, parseVerificationOutcome as B, emptyPublicBenchmarkRunner as C, summarizeCodeTraceCalibration as D, renderCodeTraceCalibrationMarkdown as E, publicBenchmarkRlmInstructions as F, ANALYST_BENCHMARK_EVIDENCE_IMPLEMENTATION_SHA256 as G, ANALYST_BENCHMARK_DEPENDENCY_LOCK_FILES as H, publicBenchmarkSystemPrompt as I, ANALYST_BENCHMARK_IMPLEMENTATION_SHA256 as J, ANALYST_BENCHMARK_IMPLEMENTATION_DIGEST_ALGORITHM as K, DEFAULT_MAX_VERIFICATION_ARTIFACT_BYTES as L, MAX_INCORRECT_BLOCKS as M, MAX_INCORRECT_BLOCK_STEPS as N, analystInstructionsOverrideFromText as O, publicBenchmarkProtocolSha256 as P, ANALYST_BENCHMARK_LOCAL_RECEIPT_FILE as Q, appendVerificationArtifactsToOtlp as R, adaptPublicBenchmarkFindings as S, readAnalystBenchmarkArtifact as T, ANALYST_BENCHMARK_DEPENDENCY_LOCK_SHA256 as U, ANALYST_BENCHMARK_DEPENDENCY_LOCK_DIGEST_ALGORITHM as V, ANALYST_BENCHMARK_EVIDENCE_DEPENDENCY_LOCK_SHA256 as W, analystBenchmarkImplementationDigest as X, analystBenchmarkDependencyLockDigest as Y, ANALYST_BENCHMARK_COST_LEDGER_FILE as Z, publicDirectAnalystDefinition as _, primeCodeTraceAnalystDefinition as a, codeTraceBenchCase as at, analystDefinitionAsymmetries as b, preparePublicAnalystBenchmark as c, agentRxPredictionsToFindings as ct, selectPublicBenchmarkRows as d, normalizeBenchmarkLabel as dt, ANALYST_BENCHMARK_OBSERVATIONS_FILE as et, createPublicBenchmarkRlmRunner as f, createPublicBenchmarkDirectRunner as g, runReplVariableAnalystDefinition as h, primeAnalystProtocolSha256 as i, summarizeAgentRxCalibration as it, CODE_TRACE_BENCH_ANALYST_PROMPT as j, effectiveAnalystProtocolSha256 as k, publicBenchmarkDistributions as l, normalizeAgentRxCategory as lt, rlmEngineLimits as m, renderAnalystBenchmarkMarkdown as n, AGENT_RX_UPSTREAM_REVISION as nt, runInlineAnalystDefinition as o, codeTracerPredictionsToFindings as ot, publicRlmAnalystDefinition as p, ANALYST_BENCHMARK_IMPLEMENTATION_FILES as q, createPrimeBenchmarkRunner as r, renderAgentRxCalibrationMarkdown as rt, loadPublicBenchmarkRows as s, agentRxBenchmarkCase as st, runAnalystBenchmarkCommand as t, compareAnalystRunners as tt, publicBenchmarkSelectionReport as u, roundAgentRxStep as ut, runChunkedAnalystDefinition as v, expandCodeTraceFailureBlocks as w, analystDefinitionProtocolSha256 as x, AnalystExpressivenessError as y, loadCodeTraceVerificationArtifacts as z };
|
|
6317
6317
|
|
|
6318
|
-
//# sourceMappingURL=benchmark-command-
|
|
6318
|
+
//# sourceMappingURL=benchmark-command-TZlsuAh9.js.map
|