@tangle-network/agent-eval 2.0.21 → 2.0.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-CTneqKs4.d.ts → agent-profile-_A7aMA4F.d.ts} +4 -4
  4. package/dist/{agent-profile-CTneqKs4.d.ts.map → agent-profile-_A7aMA4F.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +10 -10
  6. package/dist/analyst/index.js +3 -3
  7. package/dist/{analyze-runs-ByEuSMUT.d.ts → analyze-runs-Izz_ZeWg.d.ts} +2 -2
  8. package/dist/{analyze-runs-ByEuSMUT.d.ts.map → analyze-runs-Izz_ZeWg.d.ts.map} +1 -1
  9. package/dist/app-grade/index.d.ts +3 -3
  10. package/dist/{benchmark-command-pmeFawvb.js → benchmark-command-Cad4mBro.js} +5 -5
  11. package/dist/{benchmark-command-pmeFawvb.js.map → benchmark-command-Cad4mBro.js.map} +1 -1
  12. package/dist/benchmarks/index.d.ts +4 -4
  13. package/dist/benchmarks/index.js +2 -2
  14. package/dist/campaign/index.d.ts +7 -7
  15. package/dist/campaign/index.js +6 -6
  16. package/dist/{campaign-DPB35MjP.js → campaign-VRqINMNu.js} +313 -8
  17. package/dist/campaign-VRqINMNu.js.map +1 -0
  18. package/dist/{campaign-evidence-CSb3y1ob.d.ts → campaign-evidence-Biq06MQ9.d.ts} +3 -3
  19. package/dist/{campaign-evidence-CSb3y1ob.d.ts.map → campaign-evidence-Biq06MQ9.d.ts.map} +1 -1
  20. package/dist/{campaign-evidence-71uzJMVY.js → campaign-evidence-tY94JzUe.js} +45 -2
  21. package/dist/campaign-evidence-tY94JzUe.js.map +1 -0
  22. package/dist/cli.js +2 -2
  23. package/dist/contract/index.d.ts +10 -10
  24. package/dist/contract/index.js +6 -6
  25. package/dist/{default-registry-CKAFLuJg.d.ts → default-registry-BKHpiYiW.d.ts} +6 -6
  26. package/dist/{default-registry-CKAFLuJg.d.ts.map → default-registry-BKHpiYiW.d.ts.map} +1 -1
  27. package/dist/{define-agent-eval-DyVma2pV.d.ts → define-agent-eval-BPg0IRdI.d.ts} +4 -4
  28. package/dist/{define-agent-eval-DyVma2pV.d.ts.map → define-agent-eval-BPg0IRdI.d.ts.map} +1 -1
  29. package/dist/{define-agent-eval-CBhYD7Gq.js → define-agent-eval-Dto1p8Pd.js} +3 -3
  30. package/dist/{define-agent-eval-CBhYD7Gq.js.map → define-agent-eval-Dto1p8Pd.js.map} +1 -1
  31. package/dist/diagnosis/index.d.ts +2 -2
  32. package/dist/{dspy-rlm-engine-DFgGrKzg.js → dspy-rlm-engine-DA4uW64o.js} +2 -2
  33. package/dist/{dspy-rlm-engine-DFgGrKzg.js.map → dspy-rlm-engine-DA4uW64o.js.map} +1 -1
  34. package/dist/{evaluation-BnRaBCKu.d.ts → evaluation-f-UIDwbL.d.ts} +4 -4
  35. package/dist/{evaluation-BnRaBCKu.d.ts.map → evaluation-f-UIDwbL.d.ts.map} +1 -1
  36. package/dist/evaluation.d.ts +1 -1
  37. package/dist/{exact-types-QwxMWchv.d.ts → exact-types-BIHqYBYf.d.ts} +2 -2
  38. package/dist/{exact-types-QwxMWchv.d.ts.map → exact-types-BIHqYBYf.d.ts.map} +1 -1
  39. package/dist/experiment/index.d.ts +1 -1
  40. package/dist/experiment/index.js +1 -1
  41. package/dist/{external-optimizer-process-DkOMkeHW.js → external-optimizer-process-BfRVOfBK.js} +2 -2
  42. package/dist/{external-optimizer-process-DkOMkeHW.js.map → external-optimizer-process-BfRVOfBK.js.map} +1 -1
  43. package/dist/{external-optimizer-subprocess-CFIiwHSE.js → external-optimizer-subprocess-D2_gmU9_.js} +8 -3
  44. package/dist/external-optimizer-subprocess-D2_gmU9_.js.map +1 -0
  45. package/dist/{feedback-trajectory-BkWAgoY0.d.ts → feedback-trajectory-CoQPmSJV.d.ts} +3 -3
  46. package/dist/{feedback-trajectory-BkWAgoY0.d.ts.map → feedback-trajectory-CoQPmSJV.d.ts.map} +1 -1
  47. package/dist/{findings-store-DcBkRLDk.js → findings-store-Daqo7ksI.js} +2 -2
  48. package/dist/{findings-store-DcBkRLDk.js.map → findings-store-Daqo7ksI.js.map} +1 -1
  49. package/dist/{index-D4SWfwQe.d.ts → index-0GNQgbji.d.ts} +18 -18
  50. package/dist/{index-D4SWfwQe.d.ts.map → index-0GNQgbji.d.ts.map} +1 -1
  51. package/dist/{index-DmsDwlPe.d.ts → index-4khf0Q7g.d.ts} +5 -5
  52. package/dist/{index-DmsDwlPe.d.ts.map → index-4khf0Q7g.d.ts.map} +1 -1
  53. package/dist/{index-BrALSxZU.d.ts → index-AUyYKA-x.d.ts} +9 -9
  54. package/dist/{index-BrALSxZU.d.ts.map → index-AUyYKA-x.d.ts.map} +1 -1
  55. package/dist/{index-CUpIEvoN.d.ts → index-DH_Jxu9p.d.ts} +2 -2
  56. package/dist/{index-CUpIEvoN.d.ts.map → index-DH_Jxu9p.d.ts.map} +1 -1
  57. package/dist/index.d.ts +18 -18
  58. package/dist/index.js +7 -7
  59. package/dist/{llm-judge-DRHTRT66.js → llm-judge-DyHMJrDb.js} +2 -2
  60. package/dist/{llm-judge-DRHTRT66.js.map → llm-judge-DyHMJrDb.js.map} +1 -1
  61. package/dist/{matrix-CHbTz1bP.d.ts → matrix-BtyN7jpb.d.ts} +2 -2
  62. package/dist/{matrix-CHbTz1bP.d.ts.map → matrix-BtyN7jpb.d.ts.map} +1 -1
  63. package/dist/multishot/golden/index.d.ts +1 -1
  64. package/dist/multishot/index.d.ts +7 -7
  65. package/dist/multishot/index.js +3 -3
  66. package/dist/openapi.json +1 -1
  67. package/dist/{optimization-method-B-NFaHom.js → optimization-method-4F1Npdy5.js} +2 -2
  68. package/dist/{optimization-method-B-NFaHom.js.map → optimization-method-4F1Npdy5.js.map} +1 -1
  69. package/dist/{prime-protocol-46WvqIIt.d.ts → prime-protocol-BRMk6dGI.d.ts} +2 -2
  70. package/dist/{prime-protocol-46WvqIIt.d.ts.map → prime-protocol-BRMk6dGI.d.ts.map} +1 -1
  71. package/dist/{registry-Bh1M9hrf.d.ts → registry-BeInzotS.d.ts} +3 -3
  72. package/dist/{registry-Bh1M9hrf.d.ts.map → registry-BeInzotS.d.ts.map} +1 -1
  73. package/dist/rl.d.ts +3 -3
  74. package/dist/rollout/index.d.ts +2 -2
  75. package/dist/{run-improvement-loop-E4Uec3my.d.ts → run-improvement-loop-B9m24xsg.d.ts} +62 -9
  76. package/dist/run-improvement-loop-B9m24xsg.d.ts.map +1 -0
  77. package/dist/search/index.d.ts +23 -8
  78. package/dist/search/index.d.ts.map +1 -1
  79. package/dist/search/index.js +73 -31
  80. package/dist/search/index.js.map +1 -1
  81. package/dist/{search-kernel-By0lhdoJ.d.ts → search-kernel-C2XOJHvk.d.ts} +2 -2
  82. package/dist/{search-kernel-By0lhdoJ.d.ts.map → search-kernel-C2XOJHvk.d.ts.map} +1 -1
  83. package/dist/{self-improve-CpmIIb57.d.ts → self-improve-CcL0tRSr.d.ts} +6 -6
  84. package/dist/{self-improve-CpmIIb57.d.ts.map → self-improve-CcL0tRSr.d.ts.map} +1 -1
  85. package/dist/{self-improve-Dm9PvLF2.js → self-improve-e5hx2cCo.js} +3 -3
  86. package/dist/{self-improve-Dm9PvLF2.js.map → self-improve-e5hx2cCo.js.map} +1 -1
  87. package/dist/{skillopt-optimization-method-QZoNbg57.js → skillopt-optimization-method-Qx0HYCHY.js} +984 -907
  88. package/dist/skillopt-optimization-method-Qx0HYCHY.js.map +1 -0
  89. package/dist/{store-tool-spans-B9zc0I1r.d.ts → store-tool-spans-wH8y7InB.d.ts} +3 -3
  90. package/dist/{store-tool-spans-B9zc0I1r.d.ts.map → store-tool-spans-wH8y7InB.d.ts.map} +1 -1
  91. package/dist/{systemone-Co2Lv810.d.ts → systemone-CpW1U2Uy.d.ts} +6 -6
  92. package/dist/{systemone-Co2Lv810.d.ts.map → systemone-CpW1U2Uy.d.ts.map} +1 -1
  93. package/dist/{systemone-review-CRJ-Zdfo.d.ts → systemone-review-DpAXWDkL.d.ts} +3 -3
  94. package/dist/{systemone-review-CRJ-Zdfo.d.ts.map → systemone-review-DpAXWDkL.d.ts.map} +1 -1
  95. package/dist/systemone.d.ts +3 -3
  96. package/dist/{tool-groups-BHX9G_oE.d.ts → tool-groups-SlnoQNyT.d.ts} +2 -2
  97. package/dist/tool-groups-SlnoQNyT.d.ts.map +1 -0
  98. package/dist/{trace-questions-DfaIVysB.d.ts → trace-questions-ybyF0B6N.d.ts} +2 -2
  99. package/dist/{trace-questions-DfaIVysB.d.ts.map → trace-questions-ybyF0B6N.d.ts.map} +1 -1
  100. package/dist/trace-repair/index.d.ts +1 -1
  101. package/dist/traces.d.ts +2 -2
  102. package/dist/{tree-DBvepwFt.js → tree-CK9h-xZF.js} +5 -4
  103. package/dist/tree-CK9h-xZF.js.map +1 -0
  104. package/dist/{types-CjrzKsOK.d.ts → types-B1W3v8dT.d.ts} +8 -8
  105. package/dist/{types-CjrzKsOK.d.ts.map → types-B1W3v8dT.d.ts.map} +1 -1
  106. package/dist/{types-CmHcpGl0.d.ts → types-BpIAnRCe.d.ts} +2 -2
  107. package/dist/{types-CmHcpGl0.d.ts.map → types-BpIAnRCe.d.ts.map} +1 -1
  108. package/dist/{types-Ci2r6el5.d.ts → types-DSU3qb_o.d.ts} +2 -2
  109. package/dist/{types-Ci2r6el5.d.ts.map → types-DSU3qb_o.d.ts.map} +1 -1
  110. package/dist/wire/index.d.ts +1 -1
  111. package/docs/campaign-proposers.md +31 -0
  112. package/docs/public-api.md +5 -4
  113. package/docs/search-ledger.md +4 -3
  114. package/package.json +1 -1
  115. package/dist/campaign-DPB35MjP.js.map +0 -1
  116. package/dist/campaign-evidence-71uzJMVY.js.map +0 -1
  117. package/dist/external-optimizer-subprocess-CFIiwHSE.js.map +0 -1
  118. package/dist/run-improvement-loop-E4Uec3my.d.ts.map +0 -1
  119. package/dist/skillopt-optimization-method-QZoNbg57.js.map +0 -1
  120. package/dist/tool-groups-BHX9G_oE.d.ts.map +0 -1
  121. package/dist/tree-DBvepwFt.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"dspy-rlm-engine-DFgGrKzg.js","names":[],"sources":["../src/trace-contracts/spans.ts","../src/trace-contracts/predicates.ts","../src/trace-contracts/types.ts","../src/trace-contracts/validate.ts","../src/trace-contracts/explain.ts","../src/trace-contracts/rules.ts","../src/trace-contracts/evaluate.ts","../src/trace-contracts/harness-session.ts","../src/analyst/finding-codec.ts","../src/analyst/trace-tool-callback.ts","../src/analyst/dspy-rlm-engine.ts"],"sourcesContent":["import {\n ATTR,\n firstNumberAttr,\n firstStringAttr,\n INPUT_TOKEN_ATTR_KEYS,\n MODEL_ATTR_KEYS,\n OUTPUT_TOKEN_ATTR_KEYS,\n resolveSpanKind,\n SPAN_KINDS,\n type SpanKind,\n TOOL_NAME_ATTR_KEYS,\n} from '@tangle-network/agent-trace-contract'\nimport { LLM_CACHE_WRITE_TOKENS, LLM_CACHED_TOKENS } from '../trace/attribute-vocabulary'\nimport type { ContractSpan } from './types'\n\n// ── Span readers ──────────────────────────────────────────────────────\n\n// Eval kinds whose names are not contract kinds. `tool`, `llm`, and `agent`\n// already resolve by upper-casing; `sandbox` and `custom` stay undeclared and\n// fall through to inference.\nconst EVAL_KIND_TO_CONTRACT_KIND: ReadonlyMap<string, SpanKind> = new Map([\n ['judge', 'EVALUATOR'],\n ['retrieval', 'RETRIEVER'],\n])\n\n/**\n * The span's contract kind: a declared kind when recognised, else inferred.\n * A top-level `kind` counts as a declaration only when it names a contract\n * kind; OTLP words such as `SPAN_KIND_INTERNAL` and the eval kinds `sandbox`\n * and `custom` fall through to the span-kind attribute and name signals.\n */\nexport function contractSpanKind(span: ContractSpan): SpanKind {\n const raw = typeof span.kind === 'string' ? span.kind : undefined\n const mapped =\n raw === undefined ? undefined : (EVAL_KIND_TO_CONTRACT_KIND.get(raw) ?? raw.toUpperCase())\n const declared =\n mapped !== undefined && (SPAN_KINDS as readonly string[]).includes(mapped) ? mapped : undefined\n return resolveSpanKind({\n ...(declared === undefined ? {} : { kind: declared }),\n name: span.name,\n attributes: span.attributes ?? {},\n })\n}\n\n/**\n * Tool name: `span.toolName` (typed ToolSpan) → the tool-name attributes\n * (`gen_ai.tool.name`, `tool.name`, ..., `toolName`) → `span.name` when the\n * span is a TOOL span.\n */\nexport function contractSpanToolName(span: ContractSpan): string | undefined {\n if (typeof span.toolName === 'string') return span.toolName\n const attributes = span.attributes ?? {}\n const fromAttr =\n firstStringAttr(attributes, TOOL_NAME_ATTR_KEYS) ?? firstStringAttr(attributes, ['toolName'])\n if (fromAttr !== undefined) return fromAttr\n if (typeof span.name === 'string' && contractSpanKind(span) === 'TOOL') return span.name\n return undefined\n}\n\nexport function spanModel(span: ContractSpan): string | undefined {\n if (typeof span.model === 'string' && span.model.length > 0) return span.model\n return firstStringAttr(span.attributes ?? {}, MODEL_ATTR_KEYS)\n}\n\n/**\n * Input plus output tokens, or `undefined` when either side is unrecorded.\n * Input follows the OTel GenAI definition — prompt tokens plus any cache\n * read and cache write tokens the span records — because a cached call's\n * `INPUT_TOKEN_ATTR_KEYS` value (`llm.token_count.prompt` and its aliases)\n * carries only the uncached remainder, and a cache-heavy call can spend far\n * more on cache reads and writes than on that remainder. `llm.maxTotalTokens`\n * would otherwise pass runs at a small fraction of what they actually cost.\n */\nexport function spanTotalTokens(span: ContractSpan): number | undefined {\n const attributes = span.attributes ?? {}\n const input = finite(span.inputTokens) ?? firstNumberAttr(attributes, INPUT_TOKEN_ATTR_KEYS)\n const output = finite(span.outputTokens) ?? firstNumberAttr(attributes, OUTPUT_TOKEN_ATTR_KEYS)\n if (input === undefined || output === undefined) return undefined\n const cacheRead = firstNumberAttr(attributes, [LLM_CACHED_TOKENS]) ?? 0\n const cacheWrite = firstNumberAttr(attributes, [LLM_CACHE_WRITE_TOKENS]) ?? 0\n return input + output + cacheRead + cacheWrite\n}\n\nconst ARGUMENT_ATTR_KEYS = ['gen_ai.tool.call.arguments', 'tool.arguments', 'input.value'] as const\n\nexport type ArgumentEvidence = { known: true; value: unknown } | { known: false; reason: string }\n\n/** The call's arguments: the typed `args` field, else the argument attributes.\n * JSON strings are parsed; an unparseable string is kept as a string. */\nexport function spanArguments(span: ContractSpan): ArgumentEvidence {\n if (span.argsCaptured === false || span.attributes?.['tool.args_captured'] === false) {\n return { known: false, reason: 'arguments were not captured' }\n }\n if (span.args !== undefined) return { known: true, value: parseJsonString(span.args) }\n for (const key of ARGUMENT_ATTR_KEYS) {\n const value = span.attributes?.[key]\n if (value !== undefined && value !== null) return { known: true, value: parseJsonString(value) }\n }\n return { known: false, reason: 'the span carries no argument evidence' }\n}\n\ntype OfferedTools =\n | { recorded: false }\n | { recorded: true; names: string[] }\n | { recorded: true; unreadable: string }\n\n/** The tool names a span records as offered to the model. */\nexport function spanOfferedTools(span: ContractSpan): OfferedTools {\n const raw = span.attributes?.[ATTR.toolDefinitions]\n if (raw === undefined || raw === null) return { recorded: false }\n const value = parseJsonString(raw)\n if (!Array.isArray(value)) {\n return { recorded: true, unreadable: `${ATTR.toolDefinitions} is not a list` }\n }\n const names: string[] = []\n for (const entry of value) {\n const name = typeof entry === 'string' ? entry : definitionName(entry)\n if (name === undefined) {\n return {\n recorded: true,\n unreadable: `${ATTR.toolDefinitions} has an entry without a tool name`,\n }\n }\n names.push(name)\n }\n return { recorded: true, names }\n}\n\nfunction definitionName(entry: unknown): string | undefined {\n if (entry === null || typeof entry !== 'object') return undefined\n const record = entry as Record<string, unknown>\n if (typeof record.name === 'string' && record.name.length > 0) return record.name\n const fn = record.function as Record<string, unknown> | undefined\n return fn !== null && typeof fn === 'object' && typeof fn.name === 'string' && fn.name.length > 0\n ? fn.name\n : undefined\n}\n\nfunction parseJsonString(value: unknown): unknown {\n if (typeof value !== 'string') return value\n try {\n return JSON.parse(value)\n } catch {\n return value\n }\n}\n\nexport function finite(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nexport function isSpanError(span: ContractSpan): boolean {\n return typeof span.status === 'string' && /^(?:error|status_code_error)$/i.test(span.status)\n}\n","import { SPAN_KINDS, type SpanKind } from '@tangle-network/agent-trace-contract'\nimport { ValidationError } from '../errors'\nimport { contractSpanKind, contractSpanToolName, spanModel } from './spans'\nimport type {\n ContractSpan,\n OneOfMatcher,\n SerializedRegex,\n SpanPredicate,\n TextMatcher,\n} from './types'\n\n// ── Predicate matching ────────────────────────────────────────────────\n\nfunction isSerializedRegex(v: unknown): v is SerializedRegex {\n return (\n typeof v === 'object' &&\n v !== null &&\n typeof (v as SerializedRegex).$regex === 'string' &&\n typeof (v as SerializedRegex).flags === 'string'\n )\n}\n\nexport function isOneOfMatcher(v: unknown): v is OneOfMatcher {\n return typeof v === 'object' && v !== null && Array.isArray((v as OneOfMatcher).oneOf)\n}\n\nexport function isRegexValue(v: unknown): v is RegExp | SerializedRegex {\n return v instanceof RegExp || isSerializedRegex(v)\n}\n\nfunction matchText(actual: string | undefined, matcher: TextMatcher): boolean {\n if (typeof actual !== 'string') return false\n if (typeof matcher === 'string') return actual === matcher\n if (matcher instanceof RegExp) return matcher.test(actual)\n if (isOneOfMatcher(matcher)) return matcher.oneOf.includes(actual)\n return new RegExp(matcher.$regex, matcher.flags).test(actual)\n}\n\nfunction assertMatcher(m: unknown, where: string): void {\n if (typeof m === 'string' || m instanceof RegExp) return\n if (isSerializedRegex(m)) {\n try {\n new RegExp(m.$regex, m.flags)\n } catch (error) {\n throw new ValidationError(`${where}: invalid regex /${m.$regex}/${m.flags}: ${String(error)}`)\n }\n return\n }\n if (isOneOfMatcher(m)) {\n if (m.oneOf.length === 0 || !m.oneOf.every((x) => typeof x === 'string')) {\n throw new ValidationError(`${where}: \"oneOf\" must be a non-empty array of strings`)\n }\n return\n }\n throw new ValidationError(\n `${where}: matcher must be string | RegExp | SerializedRegex | { oneOf }`,\n )\n}\n\nexport function assertPredicate(value: unknown, where: string): asserts value is SpanPredicate {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new ValidationError(`${where}: predicate must be an object, got ${typeof value}`)\n }\n const p = value as SpanPredicate\n for (const field of ['name', 'tool', 'model'] as const) {\n if (p[field] !== undefined) assertMatcher(p[field], `${where} \"${field}\"`)\n }\n if (p.kind !== undefined && !(SPAN_KINDS as readonly string[]).includes(p.kind)) {\n throw new ValidationError(`${where}: \"kind\" must be one of ${SPAN_KINDS.join(', ')}`)\n }\n if (\n p.attr !== undefined &&\n (p.attr === null || typeof p.attr !== 'object' || Array.isArray(p.attr))\n ) {\n throw new ValidationError(`${where}: \"attr\" must be a plain object`)\n }\n for (const [key, expected] of Object.entries(p.attr ?? {})) {\n // Any non-primitive attr value must be a complete matcher shape (a\n // RegExp, a `{ $regex, flags }` pair, or `{ oneOf }`) — never a partial\n // one silently compared by reference. `expected !== actual` on an object\n // is always true, so an incomplete `$regex` (missing `flags`) or a bare\n // `oneOf` used to compile and then never match, making `never` rules\n // pass vacuously and `always` rules fail vacuously.\n if (expected !== null && typeof expected === 'object') {\n assertMatcher(expected, `${where} attr \"${key}\"`)\n }\n }\n if (p.not !== undefined) assertPredicate(p.not, `${where} \"not\"`)\n if (p.requiresCustom && typeof p.custom !== 'function') {\n throw new ValidationError(\n `${where}: rule was built with a custom predicate function, which does not survive JSON ` +\n 'serialization — re-attach `custom` after deserializing or drop the rule',\n )\n }\n const hasAttr = p.attr !== undefined && Object.keys(p.attr).length > 0\n if (\n p.name === undefined &&\n p.tool === undefined &&\n p.model === undefined &&\n p.kind === undefined &&\n p.not === undefined &&\n !hasAttr &&\n typeof p.custom !== 'function'\n ) {\n throw new ValidationError(\n `${where}: empty predicate would match every span — specify name, tool, model, kind, attr, not, or custom`,\n )\n }\n}\n\nexport function predicateMatches(span: ContractSpan, p: SpanPredicate): boolean {\n if (p.kind !== undefined && contractSpanKind(span) !== p.kind) return false\n if (p.name !== undefined && !matchText(span.name, p.name)) return false\n if (p.tool !== undefined && !matchText(contractSpanToolName(span), p.tool)) return false\n if (p.model !== undefined && !matchText(spanModel(span), p.model)) return false\n if (p.attr !== undefined) {\n for (const [key, expected] of Object.entries(p.attr)) {\n const actual = span.attributes?.[key]\n if (isRegexValue(expected) || isOneOfMatcher(expected)) {\n if (!matchText(typeof actual === 'string' ? actual : undefined, expected as TextMatcher))\n return false\n } else if (actual !== expected) {\n return false\n }\n }\n }\n if (p.not !== undefined && predicateMatches(span, p.not)) return false\n if (p.custom !== undefined && !p.custom(span)) return false\n return true\n}\n\nfunction normalizeMatcher(m: TextMatcher): Exclude<TextMatcher, RegExp> {\n if (m instanceof RegExp) return { $regex: m.source, flags: m.flags }\n if (isOneOfMatcher(m)) return { oneOf: [...m.oneOf] }\n return m\n}\n\nexport function normalizePredicate(p: SpanPredicate, where: string): SpanPredicate {\n const kind = typeof p?.kind === 'string' ? (p.kind.toUpperCase() as SpanKind) : p?.kind\n const withKind = kind === undefined ? p : { ...p, kind }\n assertPredicate(withKind, where)\n const out: SpanPredicate = {}\n if (withKind.kind !== undefined) out.kind = withKind.kind\n if (withKind.name !== undefined) out.name = normalizeMatcher(withKind.name)\n if (withKind.tool !== undefined) out.tool = normalizeMatcher(withKind.tool)\n if (withKind.model !== undefined) out.model = normalizeMatcher(withKind.model)\n if (withKind.attr !== undefined) {\n out.attr = Object.fromEntries(\n Object.entries(withKind.attr).map(([k, v]) => [\n k,\n v instanceof RegExp ? normalizeMatcher(v) : v,\n ]),\n )\n }\n if (withKind.not !== undefined) out.not = normalizePredicate(withKind.not, `${where} \"not\"`)\n if (typeof withKind.custom === 'function') {\n out.custom = withKind.custom\n out.requiresCustom = true\n }\n return out\n}\n","import type { SpanKind } from '@tangle-network/agent-trace-contract'\nimport type { RunStatus } from '../trace/schema'\nimport type { DefaultVerdict } from '../verdict'\n\n// ── Span surface ──────────────────────────────────────────────────────\n\n/**\n * Minimal structural span the checker reads. The eval-side `Span`\n * (trace/schema) and the output of {@link contractSpansFromOtlp} satisfy it.\n */\nexport interface ContractSpan {\n spanId?: string\n parentSpanId?: string | null\n name?: string\n /** Eval kinds (`tool`, `llm`, ...) or contract kinds (`TOOL`, `LLM`, ...). */\n kind?: string\n startedAt?: number\n endedAt?: number\n status?: string\n error?: string\n /** Typed field on eval-side ToolSpans; OTLP flattenings drop it (see\n * {@link contractSpanToolName}). */\n toolName?: string\n /** Typed field on eval-side LlmSpans. */\n model?: string\n inputTokens?: number\n outputTokens?: number\n /** Typed field on eval-side ToolSpans. */\n args?: unknown\n /** False when the source observed the call but did not capture its arguments. */\n argsCaptured?: boolean\n attributes?: Record<string, unknown>\n}\n\n/**\n * The run a `run` rule reads. The eval-side `Run` satisfies it. When no run is\n * passed, the checker derives it from the trace's single root span; a trace\n * with no unique root leaves the run unknown and every `run` rule fails.\n */\nexport interface ContractRun {\n status?: string\n startedAt?: number\n endedAt?: number\n}\n\n/** JSON-safe RegExp form — what the builder normalizes RegExp matchers to. */\nexport interface SerializedRegex {\n $regex: string\n flags: string\n}\n\n/** Matches when the value equals one of the listed strings. */\nexport interface OneOfMatcher {\n oneOf: string[]\n}\n\nexport type TextMatcher = string | RegExp | SerializedRegex | OneOfMatcher\n\n/**\n * Proposition over one span. All specified fields must match (AND); `not`\n * must NOT match. At least one field is required — an empty predicate would\n * match every span and is rejected.\n *\n * `kind` compares against the span's contract kind (`TOOL`, `LLM`, `AGENT`,\n * ...), resolved by agent-trace-contract's classifier, so eval kinds\n * (`tool`, `llm`) and OTLP spans that declare no kind are read the same way.\n *\n * `tool` resolves through {@link contractSpanToolName}; `model` through the\n * typed `model` field and the gen_ai model attributes.\n *\n * `attr` values match by strict equality, or regex-test when the value is a\n * RegExp/SerializedRegex and the attribute is a string. Structured attribute\n * values need `custom`, or an `argument` rule for tool arguments.\n */\nexport interface SpanPredicate {\n name?: TextMatcher\n tool?: TextMatcher\n model?: TextMatcher\n kind?: SpanKind\n attr?: Record<string, unknown>\n not?: SpanPredicate\n custom?: (span: ContractSpan) => boolean\n /** Stamped by the builder when `custom` is present. Survives JSON while\n * the function does not, so evaluation of a deserialized contract throws\n * instead of silently dropping the check. */\n requiresCustom?: true\n}\n\n// ── Contract shape ────────────────────────────────────────────────────\n\nexport const ORDER_MODES = ['start-order', 'finish-before-start', 'all-occurrences'] as const\nexport type OrderMode = (typeof ORDER_MODES)[number]\n\nexport const RUN_STATUSES: readonly RunStatus[] = ['running', 'completed', 'failed', 'aborted']\n\nexport const ARGUMENT_OCCURRENCES = ['first', 'last', 'any', 'all'] as const\nexport type ArgumentOccurrence = (typeof ARGUMENT_OCCURRENCES)[number]\n\nexport const ARGUMENT_TYPES = ['string', 'number', 'boolean', 'object', 'array', 'null'] as const\nexport type ArgumentType = (typeof ARGUMENT_TYPES)[number]\n\nexport type ArgumentCheck =\n | { op: 'exists' }\n | { op: 'equals'; value: unknown }\n | { op: 'oneOf'; values: unknown[] }\n | { op: 'type'; type: ArgumentType }\n\n/** A tool whose calls change state outside the run. */\nexport interface RetryWrite {\n tool: string\n /** RFC 6901 JSON Pointer to the idempotency key in the call's arguments.\n * Without it, a repeated call of this tool always fails. */\n idempotencyKey?: string\n}\n\nexport interface RunChecks {\n /** The run's status is `completed` and its end time is recorded. A failed\n * or aborted run fails this check. */\n requireCompleted?: boolean\n /** The run's status must be one of these. */\n allowedStatuses?: RunStatus[]\n /** End minus start, in milliseconds. An unknown duration fails. */\n maxDurationMs?: number\n}\n\nexport type ContractRule =\n | { kind: 'always' | 'never' | 'eventually'; label: string; p: SpanPredicate }\n | { kind: 'precedes'; label: string; a: SpanPredicate; b: SpanPredicate; order?: OrderMode }\n | {\n kind: 'neverUnless'\n label: string\n p: SpanPredicate\n prior: SpanPredicate\n order?: OrderMode\n }\n | { kind: 'atMost'; label: string; p: SpanPredicate; max: number }\n | { kind: 'tokensAtMost'; label: string; p: SpanPredicate; max: number }\n | ({ kind: 'run'; label: string } & RunChecks)\n | {\n kind: 'argument'\n label: string\n p: SpanPredicate\n /** RFC 6901 JSON Pointer into the call's arguments; `''` is the whole value. */\n pointer: string\n check: ArgumentCheck\n /** Which matching calls must satisfy the check. Default `all`. */\n occurrence?: ArgumentOccurrence\n }\n | {\n /**\n * The tools the harness offered the model (the OTel GenAI\n * `gen_ai.tool.definitions` attribute) are recorded, every tool call is\n * one of them, and, when `declared` is set, every offered tool is\n * declared. A trace that records no offered tools fails: what the\n * harness enforced is unknown.\n */\n kind: 'toolsOffered'\n label: string\n declared?: string[]\n }\n | {\n /**\n * A tool called again with the same arguments repeats its side effect.\n * A repeated `reads` call passes; a repeated `writes` call passes only\n * when every call carries the same idempotency key; a repeated call of\n * any other tool fails, because its side effect is unknown.\n */\n kind: 'retrySafe'\n label: string\n reads?: string[]\n writes?: RetryWrite[]\n }\n\n/** One legitimate alternate path. The contract passes only when the base\n * rules pass and at least one alternative passes completely. */\nexport interface ContractAlternative {\n id: string\n rules: ContractRule[]\n}\n\n/** Serializable plain object — `traceContract(name)....build()` output. */\nexport interface TraceContract {\n name: string\n /** What the contract protects, for reports and `explainTraceContract`. */\n description?: string\n /** Evaluate only the span matching `root` and its descendants. Exactly one\n * span must match; zero or several make every rule an error. */\n scope?: { root: SpanPredicate }\n rules: ContractRule[]\n alternatives?: ContractAlternative[]\n}\n\nexport type ContractStatus = 'pass' | 'fail' | 'error'\n\nexport interface ContractViolation {\n rule: string\n spanId?: string\n detail: string\n}\n\n/** What happened to one rule. `error` means it could not be evaluated. */\nexport interface ContractRuleExecution {\n rule: string\n /** Set for rules inside `alternatives`. */\n alternative?: string\n status: ContractStatus\n violations: number\n error?: string\n}\n\nexport interface ContractVerdict extends DefaultVerdict {\n /** Contract name — keys this verdict in multi-contract reports. */\n contract: string\n status: ContractStatus\n /** `status === 'pass'`. */\n valid: boolean\n /** Fraction of rules that passed, in [0, 1]. An errored rule is not a pass. */\n score: number\n /** 0|1 per evaluated base rule, keyed by label, plus `anyOf` when the\n * contract has alternatives. Errored rules are absent, never 0. */\n scores: Record<string, number>\n violations: ContractViolation[]\n ruleExecutions: ContractRuleExecution[]\n /** Why rules errored, one line per errored rule or scope failure. */\n errors: string[]\n}\n\nexport interface ContractCheckResult {\n verdicts: ContractVerdict[]\n /** `error` if any verdict errored, else `fail` if any failed, else `pass`. */\n status: ContractStatus\n allValid: boolean\n}\n\nexport interface EvaluateTraceContractOptions {\n /** The run `run` rules read. Ignored under `scope`, where the scope root is the run. */\n run?: ContractRun\n}\n","import { ValidationError } from '../errors'\nimport { assertPredicate } from './predicates'\nimport {\n ARGUMENT_OCCURRENCES,\n ARGUMENT_TYPES,\n type ArgumentCheck,\n type ContractRule,\n ORDER_MODES,\n type OrderMode,\n RUN_STATUSES,\n type TraceContract,\n} from './types'\n\n// ── Validation ────────────────────────────────────────────────────────\n\nexport function assertOrder(order: unknown, where: string): OrderMode | undefined {\n if (order === undefined) return undefined\n if (!(ORDER_MODES as readonly unknown[]).includes(order)) {\n throw new ValidationError(`${where}: order must be one of ${ORDER_MODES.join(', ')}`)\n }\n return order as OrderMode\n}\n\nexport function assertCount(max: unknown, where: string): void {\n if (typeof max !== 'number' || !Number.isInteger(max) || max < 0) {\n throw new ValidationError(`${where}: max must be a non-negative integer`)\n }\n}\n\nfunction assertJsonPointer(pointer: unknown, where: string): void {\n if (typeof pointer !== 'string' || (pointer !== '' && !pointer.startsWith('/'))) {\n throw new ValidationError(`${where}: pointer must be an RFC 6901 JSON Pointer ('' or '/a/b')`)\n }\n if (/~(?![01])/.test(pointer)) {\n throw new ValidationError(`${where}: pointer has an invalid escape; use ~0 for ~ and ~1 for /`)\n }\n}\n\n/** A non-empty list of distinct, non-empty tool names. */\nfunction assertNames(names: unknown, where: string): string[] {\n if (!Array.isArray(names) || names.length === 0) {\n throw new ValidationError(`${where} must be a non-empty array of tool names`)\n }\n for (const name of names) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new ValidationError(`${where} must hold non-empty tool names`)\n }\n }\n const dup = names.find((n, i) => names.indexOf(n) !== i)\n if (dup !== undefined) throw new ValidationError(`${where} lists \"${dup}\" twice`)\n return names as string[]\n}\n\nfunction assertArgumentCheck(check: unknown, where: string): void {\n const c = check as ArgumentCheck\n if (c === null || typeof c !== 'object') {\n throw new ValidationError(`${where}: check must be an object`)\n }\n switch (c.op) {\n case 'exists':\n return\n case 'equals':\n if (!('value' in c)) throw new ValidationError(`${where}: equals needs a value`)\n return\n case 'oneOf':\n if (!Array.isArray(c.values) || c.values.length === 0) {\n throw new ValidationError(`${where}: oneOf needs a non-empty values array`)\n }\n return\n case 'type':\n if (!(ARGUMENT_TYPES as readonly string[]).includes(c.type)) {\n throw new ValidationError(`${where}: type must be one of ${ARGUMENT_TYPES.join(', ')}`)\n }\n return\n default:\n throw new ValidationError(`${where}: check.op must be exists, equals, oneOf, or type`)\n }\n}\n\nexport function assertRule(rule: ContractRule, where: string): void {\n switch (rule.kind) {\n case 'always':\n case 'never':\n case 'eventually':\n assertPredicate(rule.p, `${where} (p)`)\n return\n case 'precedes':\n assertPredicate(rule.a, `${where} (a)`)\n assertPredicate(rule.b, `${where} (b)`)\n assertOrder(rule.order, where)\n return\n case 'neverUnless':\n assertPredicate(rule.p, `${where} (p)`)\n assertPredicate(rule.prior, `${where} (prior)`)\n assertOrder(rule.order, where)\n return\n case 'atMost':\n case 'tokensAtMost':\n assertPredicate(rule.p, `${where} (p)`)\n assertCount(rule.max, where)\n return\n case 'run': {\n if (\n !rule.requireCompleted &&\n rule.allowedStatuses === undefined &&\n rule.maxDurationMs === undefined\n ) {\n throw new ValidationError(`${where}: run rule checks nothing`)\n }\n if (rule.requireCompleted !== undefined && typeof rule.requireCompleted !== 'boolean') {\n throw new ValidationError(`${where}: requireCompleted must be a boolean`)\n }\n if (rule.allowedStatuses !== undefined) {\n if (!Array.isArray(rule.allowedStatuses) || rule.allowedStatuses.length === 0) {\n throw new ValidationError(`${where}: allowedStatuses must be a non-empty array`)\n }\n for (const status of rule.allowedStatuses) {\n if (!RUN_STATUSES.includes(status)) {\n throw new ValidationError(\n `${where}: unknown run status \"${String(status)}\" — expected one of ${RUN_STATUSES.join(', ')}`,\n )\n }\n }\n }\n if (\n rule.maxDurationMs !== undefined &&\n (typeof rule.maxDurationMs !== 'number' ||\n !Number.isFinite(rule.maxDurationMs) ||\n rule.maxDurationMs <= 0)\n ) {\n throw new ValidationError(`${where}: maxDurationMs must be a positive number`)\n }\n return\n }\n case 'argument':\n assertPredicate(rule.p, `${where} (p)`)\n assertJsonPointer(rule.pointer, where)\n assertArgumentCheck(rule.check, where)\n if (\n rule.occurrence !== undefined &&\n !(ARGUMENT_OCCURRENCES as readonly string[]).includes(rule.occurrence)\n ) {\n throw new ValidationError(\n `${where}: occurrence must be one of ${ARGUMENT_OCCURRENCES.join(', ')}`,\n )\n }\n return\n case 'toolsOffered':\n if (rule.declared !== undefined) assertNames(rule.declared, `${where}: declared`)\n return\n case 'retrySafe': {\n const reads = rule.reads === undefined ? [] : assertNames(rule.reads, `${where}: reads`)\n if (rule.writes === undefined && rule.reads === undefined) {\n throw new ValidationError(`${where}: retrySafe needs reads or writes`)\n }\n if (rule.writes !== undefined) {\n if (!Array.isArray(rule.writes) || rule.writes.length === 0) {\n throw new ValidationError(`${where}: writes must be a non-empty array`)\n }\n const writes = assertNames(\n rule.writes.map((w) => w?.tool),\n `${where}: writes[].tool`,\n )\n for (const [i, w] of rule.writes.entries()) {\n if (w.idempotencyKey === undefined) continue\n assertJsonPointer(w.idempotencyKey, `${where}: writes[${i}].idempotencyKey`)\n if (w.idempotencyKey === '') {\n throw new ValidationError(\n `${where}: writes[${i}].idempotencyKey must name a member, not the whole arguments`,\n )\n }\n }\n const both = writes.find((t) => reads.includes(t))\n if (both !== undefined) {\n throw new ValidationError(`${where}: \"${both}\" is both a read and a write`)\n }\n }\n return\n }\n default:\n throw new ValidationError(\n `${where}: unknown rule kind \"${String((rule as { kind?: unknown }).kind)}\"`,\n )\n }\n}\n\nfunction assertRules(rules: unknown, where: string, allowEmpty = false): void {\n if (!Array.isArray(rules) || (rules.length === 0 && !allowEmpty)) {\n throw new ValidationError(`${where}: no rules — an empty contract would vacuously pass`)\n }\n const seen = new Set<string>()\n for (const rule of rules as ContractRule[]) {\n const ruleWhere = `${where} rule \"${rule?.label ?? '<unlabeled>'}\"`\n if (typeof rule?.label !== 'string' || rule.label.length === 0) {\n throw new ValidationError(`${ruleWhere}: label must be a non-empty string`)\n }\n if (seen.has(rule.label)) {\n throw new ValidationError(`${ruleWhere}: duplicate label would collapse per-rule scores`)\n }\n seen.add(rule.label)\n assertRule(rule, ruleWhere)\n }\n}\n\nexport function assertContract(contract: TraceContract, where: string): void {\n if (typeof contract?.name !== 'string' || contract.name.length === 0) {\n throw new ValidationError(`${where}: contract.name must be a non-empty string`)\n }\n const at = `${where} \"${contract.name}\"`\n // Base rules may be empty only when alternatives carry the checks: the\n // contract then passes exactly when one alternative passes.\n assertRules(\n contract.rules,\n at,\n Array.isArray(contract.alternatives) && contract.alternatives.length > 0,\n )\n if (contract.scope !== undefined) assertPredicate(contract.scope?.root, `${at} scope.root`)\n if (contract.alternatives !== undefined) {\n if (!Array.isArray(contract.alternatives) || contract.alternatives.length === 0) {\n throw new ValidationError(`${at}: alternatives must be a non-empty array`)\n }\n const ids = new Set<string>()\n for (const alternative of contract.alternatives) {\n if (typeof alternative?.id !== 'string' || alternative.id.length === 0) {\n throw new ValidationError(`${at}: every alternative needs a non-empty id`)\n }\n if (ids.has(alternative.id)) {\n throw new ValidationError(`${at}: duplicate alternative id \"${alternative.id}\"`)\n }\n ids.add(alternative.id)\n assertRules(alternative.rules, `${at} alternative \"${alternative.id}\"`)\n }\n }\n}\n","import { isOneOfMatcher, isRegexValue } from './predicates'\nimport type {\n ArgumentCheck,\n ContractRule,\n SpanPredicate,\n TextMatcher,\n TraceContract,\n} from './types'\nimport { assertContract } from './validate'\n\n// ── Descriptions ──────────────────────────────────────────────────────\n\nfunction describeMatcher(m: TextMatcher): string {\n if (typeof m === 'string') return m\n if (m instanceof RegExp) return `/${m.source}/${m.flags}`\n if (isOneOfMatcher(m)) return `oneOf(${m.oneOf.join('|')})`\n return `/${m.$regex}/${m.flags}`\n}\n\nexport function describePredicate(p: SpanPredicate): string {\n const parts: string[] = []\n if (p.kind !== undefined) parts.push(`kind=${p.kind}`)\n if (p.name !== undefined) parts.push(`name=${describeMatcher(p.name)}`)\n if (p.tool !== undefined) parts.push(`tool=${describeMatcher(p.tool)}`)\n if (p.model !== undefined) parts.push(`model=${describeMatcher(p.model)}`)\n if (p.attr !== undefined) {\n for (const [k, v] of Object.entries(p.attr)) {\n parts.push(`attr.${k}=${isRegexValue(v) ? describeMatcher(v) : JSON.stringify(v)}`)\n }\n }\n if (p.not !== undefined) parts.push(`not(${describePredicate(p.not)})`)\n if (typeof p.custom === 'function') parts.push(`custom=${p.custom.name || 'fn'}`)\n return parts.join(',')\n}\n\nexport function describeCheck(check: ArgumentCheck): string {\n switch (check.op) {\n case 'exists':\n return 'exists'\n case 'equals':\n return `equals ${JSON.stringify(check.value)}`\n case 'oneOf':\n return `oneOf ${JSON.stringify(check.values)}`\n case 'type':\n return `type ${check.type}`\n }\n}\n\n/** One line per rule, stating what it requires. */\nfunction describeRule(rule: ContractRule): string {\n switch (rule.kind) {\n case 'always':\n return `every span matches ${describePredicate(rule.p)}`\n case 'never':\n return `no span matches ${describePredicate(rule.p)}`\n case 'eventually':\n return `some span matches ${describePredicate(rule.p)}`\n case 'precedes':\n return `${describePredicate(rule.a)} and ${describePredicate(rule.b)} both occur, and the first comes before the second (${rule.order ?? 'start-order'})`\n case 'neverUnless':\n return `every ${describePredicate(rule.p)} has an earlier ${describePredicate(rule.prior)} (${rule.order ?? 'start-order'})`\n case 'atMost':\n return `at most ${rule.max} span(s) match ${describePredicate(rule.p)}`\n case 'tokensAtMost':\n return `spans matching ${describePredicate(rule.p)} use at most ${rule.max} tokens in total`\n case 'run': {\n const parts: string[] = []\n if (rule.requireCompleted) parts.push('the run completed and recorded its end')\n if (rule.allowedStatuses)\n parts.push(`its status is one of ${rule.allowedStatuses.join(', ')}`)\n if (rule.maxDurationMs !== undefined) parts.push(`it took at most ${rule.maxDurationMs} ms`)\n return parts.join('; ')\n }\n case 'argument':\n return `${rule.occurrence ?? 'all'} call(s) matching ${describePredicate(rule.p)} have argument ${rule.pointer || '(whole value)'} that ${describeCheck(rule.check)}`\n case 'toolsOffered':\n return `the trace records the tools offered to the model, every tool call is one of them${rule.declared ? `, and every offered tool is one of ${rule.declared.join(', ')}` : ''}`\n case 'retrySafe': {\n const parts = ['no tool is called twice with the same arguments']\n if (rule.reads) parts.push(`except the reads ${rule.reads.join(', ')}`)\n for (const w of rule.writes ?? []) {\n parts.push(\n w.idempotencyKey === undefined\n ? `write ${w.tool} may never repeat`\n : `write ${w.tool} may repeat only with one idempotency key at ${w.idempotencyKey}`,\n )\n }\n return parts.join('; ')\n }\n }\n}\n\n/** Plain-language statement of everything a contract checks, one rule per line. */\nexport function explainTraceContract(contract: TraceContract): string {\n assertContract(contract, 'explainTraceContract')\n const lines = [\n `Contract \"${contract.name}\"${contract.description ? ` — ${contract.description}` : ''}`,\n ]\n if (contract.scope) {\n lines.push(\n `Scope: only the span matching ${describePredicate(contract.scope.root)} and its descendants; exactly one span must match.`,\n )\n }\n lines.push('Every rule must pass:')\n for (const rule of contract.rules) lines.push(` - ${rule.label}: ${describeRule(rule)}`)\n if (contract.alternatives) {\n lines.push('And at least one alternative must pass completely:')\n for (const alternative of contract.alternatives) {\n lines.push(` ${alternative.id}:`)\n for (const rule of alternative.rules) lines.push(` - ${rule.label}: ${describeRule(rule)}`)\n }\n }\n return lines.join('\\n')\n}\n","import { ATTR } from '@tangle-network/agent-trace-contract'\nimport { CaptureIntegrityError } from '../errors'\nimport { canonicalString } from '../ledger-core/canonical'\nimport { describePredicate } from './explain'\nimport { predicateMatches } from './predicates'\nimport {\n type ArgumentEvidence,\n contractSpanKind,\n contractSpanToolName,\n finite,\n isSpanError,\n spanArguments,\n spanOfferedTools,\n spanTotalTokens,\n} from './spans'\nimport type {\n ArgumentCheck,\n ArgumentType,\n ContractRule,\n ContractRun,\n ContractSpan,\n ContractStatus,\n ContractViolation,\n OrderMode,\n SpanPredicate,\n} from './types'\n\n// ── Evaluation ────────────────────────────────────────────────────────\n\nexport interface RuleContext {\n spans: readonly ContractSpan[]\n run: { run: ContractRun } | { unknown: string }\n}\n\nexport interface RuleOutcome {\n status: ContractStatus\n violations: ContractViolation[]\n error?: string\n}\n\nfunction spanRef(span: ContractSpan, index: number): string {\n return span.spanId ?? `#${index}`\n}\n\n/**\n * Whether this trace shows any sign that spans of `kind` are actually\n * captured, independent of whether any span happens to match a given rule's\n * predicate. A `never`, `atMost`, `tokensAtMost` or `retrySafe` rule that\n * targets TOOL or LLM spans and finds zero matches cannot otherwise tell \"no\n * calls happened\" from \"calls were not recorded\": an exporter that silently\n * drops a span kind makes `forbidden`, `allowed`, `maxCalls` and `retries`\n * checks on that kind pass vacuously. Evidence is: a span of that kind\n * anywhere in the trace, or — for TOOL — a recorded offered-tool set\n * (`gen_ai.tool.definitions`), which proves the capture pipeline ran even on\n * a turn that called no tool.\n */\nfunction hasCaptureEvidence(spans: readonly ContractSpan[], kind: 'TOOL' | 'LLM'): boolean {\n if (spans.some((span) => contractSpanKind(span) === kind)) return true\n if (kind === 'TOOL') return spans.some((span) => spanOfferedTools(span).recorded)\n return false\n}\n\n/** Only `TOOL`/`LLM`-scoped predicates have capture evidence to check. */\nfunction capturedKindOf(p: SpanPredicate): 'TOOL' | 'LLM' | undefined {\n return p.kind === 'TOOL' || p.kind === 'LLM' ? p.kind : undefined\n}\n\nfunction requireCaptureEvidence(\n spans: readonly ContractSpan[],\n p: SpanPredicate,\n rule: string,\n situation: string,\n): void {\n const kind = capturedKindOf(p)\n if (kind === undefined) return\n if (hasCaptureEvidence(spans, kind)) return\n throw new CaptureIntegrityError(\n `rule '${rule}': ${situation} and the trace has no ${kind} capture evidence (no ${kind} span` +\n (kind === 'TOOL' ? `, no ${ATTR.toolDefinitions}` : '') +\n `) — cannot tell whether ${describePredicate(p)} never happened or was never recorded`,\n )\n}\n\nfunction indexed(\n spans: readonly ContractSpan[],\n p: SpanPredicate,\n): Array<{ span: ContractSpan; ref: string }> {\n const out: Array<{ span: ContractSpan; ref: string }> = []\n spans.forEach((span, i) => {\n if (predicateMatches(span, p)) out.push({ span, ref: spanRef(span, i) })\n })\n return out\n}\n\ntype Witness = { ok: true } | { ok: false; detail: string }\n\n/**\n * Is guarded span `b` preceded by the guard spans under `order`? A span never\n * witnesses itself. Missing timestamps fail: the checker cannot prove an\n * order it cannot see.\n */\nfunction witnessed(\n b: { span: ContractSpan; ref: string },\n guards: ReadonlyArray<{ span: ContractSpan; ref: string }>,\n order: OrderMode,\n): Witness {\n const bStart = finite(b.span.startedAt)\n if (bStart === undefined) {\n return { ok: false, detail: `span ${b.ref} has no startedAt, so its order cannot be proven` }\n }\n const candidates = guards.filter((a) => a.span !== b.span)\n if (candidates.length === 0) return { ok: false, detail: `span ${b.ref} has no earlier match` }\n const boundary = order === 'start-order' ? 'startedAt' : 'endedAt'\n const untimed = candidates.find((a) => finite(a.span[boundary]) === undefined)\n if (order === 'all-occurrences') {\n if (untimed) {\n return {\n ok: false,\n detail: `span ${untimed.ref} has no endedAt, so its order cannot be proven`,\n }\n }\n const late = candidates.find((a) => a.span.endedAt! > bStart)\n return late\n ? { ok: false, detail: `span ${late.ref} ends after span ${b.ref} starts` }\n : { ok: true }\n }\n const earlier = candidates.some((a) => {\n const t = finite(a.span[boundary])\n return t !== undefined && (order === 'start-order' ? t < bStart : t <= bStart)\n })\n if (earlier) return { ok: true }\n if (untimed) {\n return {\n ok: false,\n detail: `span ${untimed.ref} has no ${boundary}, so its order cannot be proven`,\n }\n }\n return {\n ok: false,\n detail:\n order === 'start-order'\n ? `span ${b.ref} has no match that started before it`\n : `span ${b.ref} has no match that finished before it started`,\n }\n}\n\nfunction orderViolations(\n label: string,\n guards: ReadonlyArray<{ span: ContractSpan; ref: string }>,\n guarded: ReadonlyArray<{ span: ContractSpan; ref: string }>,\n order: OrderMode,\n describe: string,\n): ContractViolation[] {\n const out: ContractViolation[] = []\n for (const b of guarded) {\n const w = witnessed(b, guards, order)\n if (!w.ok) out.push({ rule: label, spanId: b.span.spanId, detail: `${describe}: ${w.detail}` })\n }\n return out\n}\n\n/** RFC 6901 resolution. `found: false` when any reference token is absent. */\nfunction resolveJsonPointer(value: unknown, pointer: string): { found: boolean; value?: unknown } {\n if (pointer === '') return { found: true, value }\n let current: unknown = value\n for (const raw of pointer.slice(1).split('/')) {\n const token = raw.replace(/~1/g, '/').replace(/~0/g, '~')\n if (Array.isArray(current)) {\n if (!/^(?:0|[1-9]\\d*)$/.test(token) || Number(token) >= current.length)\n return { found: false }\n current = current[Number(token)]\n } else if (current !== null && typeof current === 'object' && Object.hasOwn(current, token)) {\n current = (current as Record<string, unknown>)[token]\n } else {\n return { found: false }\n }\n }\n return { found: true, value: current }\n}\n\nfunction jsonType(value: unknown): ArgumentType | 'undefined' {\n if (value === null) return 'null'\n if (Array.isArray(value)) return 'array'\n const t = typeof value\n return t === 'string' || t === 'number' || t === 'boolean' || t === 'object' ? t : 'undefined'\n}\n\nfunction jsonEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true\n const ta = jsonType(a)\n if (ta !== jsonType(b)) return false\n if (ta === 'array') {\n const x = a as unknown[]\n const y = b as unknown[]\n return x.length === y.length && x.every((v, i) => jsonEqual(v, y[i]))\n }\n if (ta === 'object') {\n const x = a as Record<string, unknown>\n const y = b as Record<string, unknown>\n const keys = Object.keys(x)\n return (\n keys.length === Object.keys(y).length &&\n keys.every((k) => Object.hasOwn(y, k) && jsonEqual(x[k], y[k]))\n )\n }\n return false\n}\n\n/** Why `value` fails `check`, or `undefined` when it passes. Never echoes the\n * actual argument value: arguments can carry customer data. */\nfunction argumentFailure(\n evidence: ArgumentEvidence,\n pointer: string,\n check: ArgumentCheck,\n): string | undefined {\n if (!evidence.known) return evidence.reason\n const resolved = resolveJsonPointer(evidence.value, pointer)\n if (!resolved.found) return `argument ${pointer || '(whole value)'} is absent`\n switch (check.op) {\n case 'exists':\n return undefined\n case 'equals':\n return jsonEqual(resolved.value, check.value)\n ? undefined\n : `argument ${pointer || '(whole value)'} (a ${jsonType(resolved.value)}) does not equal the expected value`\n case 'oneOf':\n return check.values.some((v) => jsonEqual(resolved.value, v))\n ? undefined\n : `argument ${pointer || '(whole value)'} (a ${jsonType(resolved.value)}) is not one of the expected values`\n case 'type':\n return jsonType(resolved.value) === check.type\n ? undefined\n : `argument ${pointer || '(whole value)'} is a ${jsonType(resolved.value)}, not a ${check.type}`\n }\n}\n\nfunction checkArgument(\n rule: Extract<ContractRule, { kind: 'argument' }>,\n spans: readonly ContractSpan[],\n): ContractViolation[] {\n const matches = indexed(spans, rule.p)\n if (matches.length === 0) {\n return [\n {\n rule: rule.label,\n detail: `no span matches ${describePredicate(rule.p)}, so there is no argument evidence to check`,\n },\n ]\n }\n const occurrence = rule.occurrence ?? 'all'\n let selected = matches\n if ((occurrence === 'first' || occurrence === 'last') && matches.length > 1) {\n const untimed = matches.find((m) => finite(m.span.startedAt) === undefined)\n if (untimed) {\n return [\n {\n rule: rule.label,\n spanId: untimed.span.spanId,\n detail: `span ${untimed.ref} has no startedAt, so the ${occurrence} call cannot be chosen`,\n },\n ]\n }\n const sorted = [...matches].sort((x, y) => x.span.startedAt! - y.span.startedAt!)\n selected = [occurrence === 'first' ? sorted[0]! : sorted[sorted.length - 1]!]\n }\n const failures = selected.map((m) => ({\n m,\n why: argumentFailure(spanArguments(m.span), rule.pointer, rule.check),\n }))\n const failed = failures.filter((f) => f.why !== undefined)\n if (occurrence === 'any' ? failed.length < failures.length : failed.length === 0) return []\n return failed.map((f) => ({\n rule: rule.label,\n spanId: f.m.span.spanId,\n detail: `span ${f.m.ref}: ${f.why}`,\n }))\n}\n\nfunction checkRun(\n rule: Extract<ContractRule, { kind: 'run' }>,\n context: RuleContext['run'],\n): ContractViolation[] {\n if ('unknown' in context) {\n return [{ rule: rule.label, detail: `run record unavailable: ${context.unknown}` }]\n }\n const run = context.run\n const out: ContractViolation[] = []\n if (rule.requireCompleted && (run.status !== 'completed' || finite(run.endedAt) === undefined)) {\n out.push({\n rule: rule.label,\n detail:\n run.status === 'completed'\n ? 'run status is completed but no end time was recorded'\n : `run status is ${run.status ?? 'unknown'}, not completed`,\n })\n }\n if (\n rule.allowedStatuses &&\n !(rule.allowedStatuses as readonly string[]).includes(run.status ?? '')\n ) {\n out.push({\n rule: rule.label,\n detail: `run status ${run.status ?? 'unknown'} is not one of ${rule.allowedStatuses.join(', ')}`,\n })\n }\n if (rule.maxDurationMs !== undefined) {\n const start = finite(run.startedAt)\n const end = finite(run.endedAt)\n if (start === undefined || end === undefined) {\n out.push({\n rule: rule.label,\n detail: 'run duration is unknown: start or end time is missing',\n })\n } else if (end - start > rule.maxDurationMs) {\n out.push({\n rule: rule.label,\n detail: `run took ${end - start} ms, over ${rule.maxDurationMs} ms`,\n })\n }\n }\n return out\n}\n\nconst listed = (names: readonly string[], max = 6): string =>\n names.length <= max\n ? names.join(', ')\n : `${names.slice(0, max).join(', ')} and ${names.length - max} more`\n\nfunction toolSpans(spans: readonly ContractSpan[]): Array<{ span: ContractSpan; ref: string }> {\n const out: Array<{ span: ContractSpan; ref: string }> = []\n spans.forEach((span, i) => {\n if (contractSpanKind(span) === 'TOOL') out.push({ span, ref: spanRef(span, i) })\n })\n return out\n}\n\n/** Declared, offered and called tools agree. */\nfunction checkToolsOffered(\n rule: Extract<ContractRule, { kind: 'toolsOffered' }>,\n spans: readonly ContractSpan[],\n): ContractViolation[] {\n const out: ContractViolation[] = []\n const offered = new Set<string>()\n let recorded = 0\n const declared = rule.declared ? new Set(rule.declared) : undefined\n spans.forEach((span, i) => {\n const tools = spanOfferedTools(span)\n if (!tools.recorded) return\n recorded += 1\n const ref = spanRef(span, i)\n if ('unreadable' in tools) {\n out.push({\n rule: rule.label,\n spanId: span.spanId,\n detail: `span ${ref}: ${tools.unreadable}`,\n })\n return\n }\n for (const name of tools.names) offered.add(name)\n const undeclared = declared ? [...new Set(tools.names)].filter((n) => !declared.has(n)) : []\n if (undeclared.length > 0) {\n out.push({\n rule: rule.label,\n spanId: span.spanId,\n detail: `span ${ref} offered the model ${undeclared.length} undeclared tool(s): ${listed(undeclared)}`,\n })\n }\n })\n if (recorded === 0) {\n return [\n {\n rule: rule.label,\n detail: `no span records the tools offered to the model (${ATTR.toolDefinitions}), so what the harness enforced is unknown`,\n },\n ]\n }\n for (const { span, ref } of toolSpans(spans)) {\n const name = contractSpanToolName(span)\n if (name === undefined) {\n out.push({\n rule: rule.label,\n spanId: span.spanId,\n detail: `span ${ref} has no tool name, so it cannot be matched to an offered tool`,\n })\n } else if (!offered.has(name)) {\n out.push({\n rule: rule.label,\n spanId: span.spanId,\n detail: `span ${ref} called ${name}, which was never offered: the harness did not enforce its tool set`,\n })\n }\n }\n return out\n}\n\n/** The call's idempotency key, or why it has none. */\nfunction idempotencyKey(\n span: ContractSpan,\n pointer: string,\n): { key: string } | { missing: string } {\n const evidence = spanArguments(span)\n if (!evidence.known) return { missing: evidence.reason }\n const resolved = resolveJsonPointer(evidence.value, pointer)\n const value = resolved.value\n if (resolved.found && typeof value === 'string' && value.length > 0) return { key: value }\n if (resolved.found && typeof value === 'number' && Number.isFinite(value)) {\n return { key: String(value) }\n }\n return { missing: `no idempotency key at ${pointer}` }\n}\n\n/** No call repeats a side effect that is not proven safe to repeat. */\nfunction checkRetrySafe(\n rule: Extract<ContractRule, { kind: 'retrySafe' }>,\n spans: readonly ContractSpan[],\n): ContractViolation[] {\n const reads = new Set(rule.reads ?? [])\n const writes = new Map((rule.writes ?? []).map((w) => [w.tool, w]))\n const out: ContractViolation[] = []\n const groups = new Map<string, Array<{ span: ContractSpan; ref: string }>>()\n const unseen = new Map<string, Array<{ span: ContractSpan; ref: string }>>()\n const calls = toolSpans(spans)\n if (calls.length === 0 && !hasCaptureEvidence(spans, 'TOOL')) {\n throw new CaptureIntegrityError(\n `rule '${rule.label}': retrySafe found 0 TOOL spans and the trace has no TOOL capture ` +\n `evidence (no TOOL span, no ${ATTR.toolDefinitions}) — cannot tell whether no reads or ` +\n 'writes happened or the trace lost its TOOL spans',\n )\n }\n for (const call of calls) {\n const name = contractSpanToolName(call.span)\n if (name === undefined) {\n out.push({\n rule: rule.label,\n spanId: call.span.spanId,\n detail: `span ${call.ref} has no tool name, so whether it repeats a call is unknown`,\n })\n continue\n }\n if (reads.has(name)) continue\n const args = spanArguments(call.span)\n if (!args.known) {\n const list = unseen.get(name) ?? []\n list.push(call)\n unseen.set(name, list)\n continue\n }\n // A write's key differs between tries that mean the same operation, so a\n // declared key is left out of the call's identity and checked below.\n const pointer = writes.get(name)?.idempotencyKey\n const identity = pointer === undefined ? args.value : withoutMember(args.value, pointer)\n const key = `${name}\\u0000${canonicalString(identity)}`\n const list = groups.get(key) ?? []\n list.push(call)\n groups.set(key, list)\n }\n // A call without arguments may repeat any other call of its tool.\n for (const [name, calls] of unseen) {\n const total =\n calls.length +\n [...groups].reduce((n, [k, list]) => (k.startsWith(`${name}\\u0000`) ? n + list.length : n), 0)\n if (total > 1) {\n out.push({\n rule: rule.label,\n spanId: calls[0]!.span.spanId,\n detail: `${name} was called ${total} times and span ${calls[0]!.ref} has no captured arguments, so whether a call repeats another is unknown`,\n })\n }\n }\n for (const [key, calls] of groups) {\n if (calls.length < 2) continue\n const name = key.slice(0, key.indexOf('\\u0000'))\n const refs = listed(calls.map((c) => c.ref))\n const write = writes.get(name)\n if (!write) {\n out.push({\n rule: rule.label,\n spanId: calls[1]!.span.spanId,\n detail: `${name} was called ${calls.length} times with the same arguments (spans ${refs}) and its side effect is not declared, so the repeat is not proven safe`,\n })\n continue\n }\n const pointer = write.idempotencyKey\n if (pointer === undefined) {\n out.push({\n rule: rule.label,\n spanId: calls[1]!.span.spanId,\n detail: `write ${name} was called ${calls.length} times with the same arguments (spans ${refs}) and declares no idempotency key, so it may have applied more than once`,\n })\n continue\n }\n const keyed = calls.map((c) => ({ c, k: idempotencyKey(c.span, pointer) }))\n const missing = keyed.find((x) => 'missing' in x.k)\n const keys = new Set(keyed.flatMap((x) => ('key' in x.k ? [x.k.key] : [])))\n if (missing) {\n out.push({\n rule: rule.label,\n spanId: missing.c.span.spanId,\n detail: `write ${name} was called ${calls.length} times with the same arguments (spans ${refs}); span ${missing.c.ref} has ${(missing.k as { missing: string }).missing}, so it may have applied more than once`,\n })\n } else if (keys.size > 1) {\n out.push({\n rule: rule.label,\n spanId: calls[1]!.span.spanId,\n detail: `write ${name} was called ${calls.length} times with the same arguments (spans ${refs}) under ${keys.size} different idempotency keys, so the target cannot tell they are one operation`,\n })\n }\n }\n // A declared write whose call errored (a timeout included: the target's\n // handling of the write is unknown) and carries no idempotency key is\n // unsafe to retry even when no repeat is detected — a retry that changes\n // the argument encoding, or one this trace never captured, would apply\n // the write twice with nothing to de-duplicate it by.\n const flagged = new Set(out.map((v) => v.spanId))\n for (const call of toolSpans(spans)) {\n const name = contractSpanToolName(call.span)\n if (name === undefined || flagged.has(call.span.spanId)) continue\n const write = writes.get(name)\n if (!write || !isSpanError(call.span)) continue\n const pointer = write.idempotencyKey\n const hasKey = pointer !== undefined && 'key' in idempotencyKey(call.span, pointer)\n if (!hasKey) {\n out.push({\n rule: rule.label,\n spanId: call.span.spanId,\n detail: `write ${name} (span ${call.ref}) errored and ${pointer === undefined ? 'declares no idempotency key' : `has ${(idempotencyKey(call.span, pointer) as { missing: string }).missing}`}; its outcome is unknown, so a retry cannot be proven safe`,\n })\n flagged.add(call.span.spanId)\n }\n }\n return out\n}\n\n/** A copy of `value` without the member `pointer` names (RFC 6901). */\nfunction withoutMember(value: unknown, pointer: string): unknown {\n const tokens = pointer\n .slice(1)\n .split('/')\n .map((t) => t.replace(/~1/g, '/').replace(/~0/g, '~'))\n const strip = (node: unknown, depth: number): unknown => {\n const token = tokens[depth]!\n const last = depth === tokens.length - 1\n if (Array.isArray(node)) {\n const index = /^(?:0|[1-9]\\d*)$/.test(token) ? Number(token) : -1\n if (index < 0 || index >= node.length) return node\n return last\n ? node.filter((_, i) => i !== index)\n : node.map((v, i) => (i === index ? strip(v, depth + 1) : v))\n }\n if (node === null || typeof node !== 'object' || !Object.hasOwn(node, token)) return node\n const copy = { ...(node as Record<string, unknown>) }\n if (last) delete copy[token]\n else copy[token] = strip(copy[token], depth + 1)\n return copy\n }\n return strip(value, 0)\n}\n\nfunction checkRule(rule: ContractRule, ctx: RuleContext): ContractViolation[] {\n const { spans } = ctx\n switch (rule.kind) {\n case 'always':\n return spans.flatMap((span, i) =>\n predicateMatches(span, rule.p)\n ? []\n : [\n {\n rule: rule.label,\n spanId: span.spanId,\n detail: `span ${spanRef(span, i)} (\"${span.name ?? ''}\") fails always(${describePredicate(rule.p)})`,\n },\n ],\n )\n case 'never': {\n const matches = indexed(spans, rule.p)\n if (matches.length === 0) {\n requireCaptureEvidence(\n spans,\n rule.p,\n rule.label,\n `never(${describePredicate(rule.p)}) matched 0 spans`,\n )\n }\n return matches.map(({ span, ref }) => ({\n rule: rule.label,\n spanId: span.spanId,\n detail: `span ${ref} (\"${span.name ?? ''}\") matches never(${describePredicate(rule.p)})`,\n }))\n }\n case 'eventually':\n return spans.some((span) => predicateMatches(span, rule.p))\n ? []\n : [\n {\n rule: rule.label,\n detail: `no span matches eventually(${describePredicate(rule.p)}) over ${spans.length} span(s)`,\n },\n ]\n case 'precedes': {\n const as = indexed(spans, rule.a)\n const bs = indexed(spans, rule.b)\n const out: ContractViolation[] = []\n if (as.length === 0) {\n out.push({\n rule: rule.label,\n detail: `required predecessor ${describePredicate(rule.a)} never occurred`,\n })\n }\n if (bs.length === 0) {\n out.push({\n rule: rule.label,\n detail: `required successor ${describePredicate(rule.b)} never occurred`,\n })\n }\n if (out.length > 0) return out\n return orderViolations(\n rule.label,\n as,\n bs,\n rule.order ?? 'start-order',\n `${describePredicate(rule.b)} is not preceded by ${describePredicate(rule.a)}`,\n )\n }\n case 'neverUnless':\n return orderViolations(\n rule.label,\n indexed(spans, rule.prior),\n indexed(spans, rule.p),\n rule.order ?? 'start-order',\n `${describePredicate(rule.p)} without an earlier ${describePredicate(rule.prior)}`,\n )\n case 'atMost': {\n const matches = indexed(spans, rule.p)\n if (matches.length === 0) {\n requireCaptureEvidence(\n spans,\n rule.p,\n rule.label,\n `atMost(${describePredicate(rule.p)}) matched 0 spans`,\n )\n }\n return matches.length <= rule.max\n ? []\n : [\n {\n rule: rule.label,\n spanId: matches[rule.max]?.span.spanId,\n detail: `${matches.length} span(s) match ${describePredicate(rule.p)}, over the limit of ${rule.max}`,\n },\n ]\n }\n case 'tokensAtMost': {\n const matches = indexed(spans, rule.p)\n if (matches.length === 0) {\n requireCaptureEvidence(\n spans,\n rule.p,\n rule.label,\n `tokensAtMost(${describePredicate(rule.p)}) matched 0 spans`,\n )\n }\n const unknown = matches.find((m) => spanTotalTokens(m.span) === undefined)\n if (unknown) {\n return [\n {\n rule: rule.label,\n spanId: unknown.span.spanId,\n detail: `span ${unknown.ref} has no recorded input and output token counts, so the total is unknown`,\n },\n ]\n }\n const total = matches.reduce((sum, m) => sum + spanTotalTokens(m.span)!, 0)\n return total <= rule.max\n ? []\n : [\n {\n rule: rule.label,\n detail: `${total} tokens across ${matches.length} span(s) matching ${describePredicate(rule.p)}, over the limit of ${rule.max}`,\n },\n ]\n }\n case 'run':\n return checkRun(rule, ctx.run)\n case 'argument':\n return checkArgument(rule, spans)\n case 'toolsOffered':\n return checkToolsOffered(rule, spans)\n case 'retrySafe':\n return checkRetrySafe(rule, spans)\n }\n}\n\nexport function executeRule(rule: ContractRule, ctx: RuleContext): RuleOutcome {\n try {\n const violations = checkRule(rule, ctx)\n return { status: violations.length === 0 ? 'pass' : 'fail', violations }\n } catch (error) {\n return {\n status: 'error',\n violations: [],\n error: error instanceof Error ? error.message : String(error),\n }\n }\n}\n","import { ValidationError } from '../errors'\nimport { packageVersion } from '../package-version'\nimport { certificationEvidenceDigest } from '../verdict'\nimport { describePredicate } from './explain'\nimport { predicateMatches } from './predicates'\nimport { executeRule, type RuleContext, type RuleOutcome } from './rules'\nimport { finite, isSpanError } from './spans'\nimport {\n type ContractCheckResult,\n type ContractRule,\n type ContractRuleExecution,\n type ContractRun,\n type ContractSpan,\n type ContractStatus,\n type ContractVerdict,\n type EvaluateTraceContractOptions,\n RUN_STATUSES,\n type SpanPredicate,\n type TraceContract,\n} from './types'\nimport { assertContract } from './validate'\n\n// ── Evaluation ────────────────────────────────────────────────────────\n\n/**\n * A run derived from one span: the `run.status` attribute a run-anchor span\n * carries (store-to-otlp writes it), else failed on an error status, else\n * unknown. An ended span with an OK status and no declared `run.status` is\n * NOT inferred as completed — a span exporter can end its root span cleanly\n * without ever learning whether the underlying run actually finished (for\n * example, a trace reader that saw no terminal record). `requireCompleted`\n * and `allowedStatuses` must fail closed on that gap rather than pass it.\n */\nfunction runOfSpan(span: ContractSpan): ContractRun {\n const declared = span.attributes?.['run.status']\n return {\n status:\n typeof declared === 'string' && (RUN_STATUSES as readonly string[]).includes(declared)\n ? declared\n : isSpanError(span)\n ? 'failed'\n : undefined,\n ...(finite(span.startedAt) === undefined ? {} : { startedAt: span.startedAt }),\n ...(finite(span.endedAt) === undefined ? {} : { endedAt: span.endedAt }),\n }\n}\n\nfunction rootsOf(spans: readonly ContractSpan[]): ContractSpan[] {\n const ids = new Set(\n spans.map((s) => s.spanId).filter((id): id is string => typeof id === 'string'),\n )\n return spans.filter((s) => !s.parentSpanId || !ids.has(s.parentSpanId))\n}\n\nfunction subtree(spans: readonly ContractSpan[], root: ContractSpan): ContractSpan[] {\n if (typeof root.spanId !== 'string') return [root]\n const children = new Map<string, ContractSpan[]>()\n for (const span of spans) {\n if (typeof span.parentSpanId === 'string') {\n const list = children.get(span.parentSpanId) ?? []\n list.push(span)\n children.set(span.parentSpanId, list)\n }\n }\n const members = new Set<ContractSpan>([root])\n const queue = [root]\n while (queue.length > 0) {\n const current = queue.shift()!\n for (const child of (typeof current.spanId === 'string' && children.get(current.spanId)) ||\n []) {\n if (!members.has(child)) {\n members.add(child)\n queue.push(child)\n }\n }\n }\n return spans.filter((s) => members.has(s))\n}\n\nfunction statusOf(outcomes: readonly RuleOutcome[]): ContractStatus {\n if (outcomes.some((o) => o.status === 'error')) return 'error'\n return outcomes.every((o) => o.status === 'pass') ? 'pass' : 'fail'\n}\n\n/**\n * Evaluate one contract over a span sequence. Pure and synchronous — works on\n * `Span[]` from a TraceStore, `contractSpansFromOtlp` output, or any array\n * satisfying `ContractSpan`. Throws\n * `ValidationError` for a malformed contract; a rule that cannot be evaluated\n * is reported as `error` in the verdict instead.\n */\nexport function evaluateTraceContract(\n contract: TraceContract,\n spans: readonly ContractSpan[],\n options: EvaluateTraceContractOptions = {},\n): ContractVerdict {\n assertContract(contract, 'evaluateTraceContract')\n if (!Array.isArray(spans)) {\n throw new ValidationError(`evaluateTraceContract: spans must be an array, got ${typeof spans}`)\n }\n let subject: readonly ContractSpan[] = spans\n let run: RuleContext['run']\n let scopeError: string | undefined\n if (contract.scope) {\n const roots = spans.filter((s) => predicateMatches(s, contract.scope!.root))\n if (roots.length === 1) {\n subject = subtree(spans, roots[0]!)\n run = { run: runOfSpan(roots[0]!) }\n } else {\n scopeError = `scope root ${describePredicate(contract.scope.root)} matched ${roots.length} spans; exactly one is required`\n run = { unknown: scopeError }\n }\n } else if (options.run) {\n run = { run: options.run }\n } else {\n const roots = rootsOf(spans)\n run =\n roots.length === 1\n ? { run: runOfSpan(roots[0]!) }\n : { unknown: `the trace has ${roots.length} root spans and no run record was passed` }\n }\n const ctx: RuleContext = { spans: subject, run }\n const execute = (rule: ContractRule): RuleOutcome =>\n scopeError === undefined\n ? executeRule(rule, ctx)\n : { status: 'error', violations: [], error: scopeError }\n\n const base = contract.rules.map(execute)\n const branches = (contract.alternatives ?? []).map((alternative) => ({\n alternative,\n outcomes: alternative.rules.map(execute),\n }))\n const passedBranch = branches.find((b) => statusOf(b.outcomes) === 'pass')\n\n const baseStatus = statusOf(base)\n let status: ContractStatus = baseStatus\n if (baseStatus === 'pass' && branches.length > 0 && !passedBranch) {\n status = branches.some((b) => statusOf(b.outcomes) === 'error') ? 'error' : 'fail'\n }\n\n const ruleExecutions: ContractRuleExecution[] = [\n ...contract.rules.map((rule, i) => execution(rule.label, undefined, base[i]!)),\n ...branches.flatMap((b) =>\n b.alternative.rules.map((rule, i) => execution(rule.label, b.alternative.id, b.outcomes[i]!)),\n ),\n ]\n const violations = base.flatMap((o) => o.violations)\n if (branches.length > 0 && !passedBranch) {\n for (const b of branches) {\n for (const o of b.outcomes) {\n violations.push(\n ...o.violations.map((v) => ({ ...v, rule: `${b.alternative.id}/${v.rule}` })),\n )\n }\n }\n }\n const errors = ruleExecutions\n .filter((e) => e.status === 'error')\n .map((e) => `${e.alternative ? `${e.alternative}/` : ''}${e.rule}: ${e.error}`)\n\n const scores: Record<string, number> = {}\n contract.rules.forEach((rule, i) => {\n const s = base[i]!.status\n if (s !== 'error') scores[rule.label] = s === 'pass' ? 1 : 0\n })\n if (branches.length > 0 && (passedBranch || status !== 'error'))\n scores.anyOf = passedBranch ? 1 : 0\n const total = contract.rules.length + (branches.length > 0 ? 1 : 0)\n const passCount = Object.values(scores).filter((s) => s === 1).length\n\n const assumptions: string[] = []\n for (const rule of [...contract.rules, ...branches.flatMap((b) => b.alternative.rules)]) {\n if (rulePredicates(rule).some(usesCustom)) {\n assumptions.push(`rule '${rule.label}' rests on a custom predicate function`)\n }\n }\n return {\n contract: contract.name,\n status,\n valid: status === 'pass',\n score: passCount / total,\n scores,\n violations,\n ruleExecutions,\n errors,\n notes:\n `${passCount}/${total} rules passed` +\n (errors.length > 0 ? `; ${errors.length} could not be evaluated` : ''),\n certification: {\n strategy: 'invariant',\n checker: { name: 'agent-eval:trace-contracts', version: packageVersion() },\n assumptions,\n evidenceDigest: certificationEvidenceDigest({\n contract: contract.name,\n status,\n scores,\n violations,\n ruleExecutions,\n }),\n },\n }\n}\n\nfunction execution(\n rule: string,\n alternative: string | undefined,\n outcome: RuleOutcome,\n): ContractRuleExecution {\n return {\n rule,\n ...(alternative === undefined ? {} : { alternative }),\n status: outcome.status,\n violations: outcome.violations.length,\n ...(outcome.error === undefined ? {} : { error: outcome.error }),\n }\n}\n\nfunction rulePredicates(rule: ContractRule): SpanPredicate[] {\n switch (rule.kind) {\n case 'precedes':\n return [rule.a, rule.b]\n case 'neverUnless':\n return [rule.p, rule.prior]\n case 'run':\n case 'toolsOffered':\n case 'retrySafe':\n return []\n default:\n return [rule.p]\n }\n}\n\nfunction usesCustom(p: SpanPredicate): boolean {\n return typeof p.custom === 'function' || (p.not !== undefined && usesCustom(p.not))\n}\n\n/**\n * Evaluate many contracts over one span sequence. Throws on an empty\n * contract list — `allValid: true` over zero contracts is a silent pass.\n */\nexport function checkTraceContracts(\n spans: readonly ContractSpan[],\n contracts: readonly TraceContract[],\n options: EvaluateTraceContractOptions = {},\n): ContractCheckResult {\n if (contracts.length === 0) {\n throw new ValidationError(\n 'checkTraceContracts: empty contract list would vacuously pass — supply at least one contract',\n )\n }\n const verdicts = contracts.map((c) => evaluateTraceContract(c, spans, options))\n const status: ContractStatus = verdicts.some((v) => v.status === 'error')\n ? 'error'\n : verdicts.every((v) => v.status === 'pass')\n ? 'pass'\n : 'fail'\n return { verdicts, status, allValid: status === 'pass' }\n}\n","/**\n * The spans a trace contract reads from a recorded harness session.\n *\n * A session becomes one root span for the session, one LLM span per assistant\n * message that answered with text, and one TOOL span per tool call, in the\n * session's recorded order. A tool span carries the call's arguments as `args`\n * and its input and result text as `input.value` and `output.value`; an LLM\n * span carries its text as `output.value`. Calls and messages a fork copied\n * from its parent are the parent's work and are left out.\n */\n\nimport type { HarnessSession } from '@tangle-network/harness-sessions'\nimport type { ContractSpan } from './types'\n\nfunction epochMs(at: string | null): number | undefined {\n if (at === null) return undefined\n const value = Date.parse(at)\n return Number.isFinite(value) ? value : undefined\n}\n\nfunction timed(\n start: string | null,\n end: string | null,\n): Pick<ContractSpan, 'startedAt' | 'endedAt'> {\n const startedAt = epochMs(start)\n const endedAt = epochMs(end) ?? startedAt\n return {\n ...(startedAt === undefined ? {} : { startedAt }),\n ...(endedAt === undefined ? {} : { endedAt }),\n }\n}\n\nexport function contractSpansFromHarnessSession(session: HarnessSession): ContractSpan[] {\n const root = `session:${session.nativeSessionId}`\n const spans: ContractSpan[] = [\n {\n spanId: root,\n parentSpanId: null,\n name: 'session',\n kind: 'AGENT',\n ...timed(session.startedAt, session.endedAt),\n attributes: { 'session.harness': session.harness },\n },\n ]\n const calls = new Map(session.toolCalls.map((call) => [call.id, call]))\n const placed = new Set<string>()\n const toolSpan = (id: string): void => {\n const call = calls.get(id)\n if (call === undefined || placed.has(id) || call.inherited === true) return\n placed.add(id)\n const input = call.inputText ?? JSON.stringify(call.input ?? null)\n spans.push({\n spanId: `tool:${call.id}`,\n parentSpanId: root,\n name: call.name,\n kind: 'TOOL',\n toolName: call.name,\n ...timed(call.startedAt, call.endedAt ?? call.result?.at ?? null),\n ...(call.status === 'error' || call.result?.isError === true\n ? { status: 'error' }\n : call.status === 'completed'\n ? { status: 'ok' }\n : {}),\n args: call.input,\n attributes: {\n 'input.value': input,\n ...(call.result?.text ? { 'output.value': call.result.text } : {}),\n },\n })\n }\n for (const message of session.messages) {\n if (message.inherited === true || message.role !== 'assistant') continue\n const text = message.parts\n .flatMap((part) => (part.type === 'text' ? [part.text] : []))\n .join('\\n')\n .trim()\n if (text !== '') {\n spans.push({\n spanId: `llm:${message.id}`,\n parentSpanId: root,\n name: 'llm.call',\n kind: 'LLM',\n ...timed(message.at, message.at),\n attributes: { 'output.value': text },\n })\n }\n for (const part of message.parts) if (part.type === 'tool-call') toolSpan(part.toolCallId)\n }\n for (const call of session.toolCalls) toolSpan(call.id)\n return spans\n}\n","/**\n * The raw-finding wire contract — one decoder for both sides of the process\n * boundary.\n *\n * A finding array crosses a process boundary twice: an optimizer bridge writes\n * it in Python, TypeScript reads it back. Two decoders written independently\n * accept different shapes, so Python could report a completed investigation\n * whose rows TypeScript then dropped — the paid work disappearing between two\n * \"successes\". This module is the TypeScript half; `finding_contract.json`\n * carries the same rules to the Python half, generated from the schema here.\n *\n * Decoding never invents an empty result. A value that is not an array of rows\n * fails with the exact type it was, and a malformed row is reported with its\n * index and path while its valid siblings survive.\n */\n\nimport { type RawAnalystFinding, RawAnalystFindingSchema } from './finding-signature'\nimport { parseFindingSubject } from './finding-subject'\nimport { coerceJson } from './parse-tolerant'\n\n/**\n * Version of the wire contract both languages implement. Bump when the\n * accepted row shape changes; the Python package pins the same value, and the\n * emitted contract carries it so a mismatched pair is visible.\n */\nexport const FINDING_WIRE_CONTRACT_VERSION = 1\n\n/** Why one row was refused. Stable across languages: Python reports the same codes. */\ntype FindingRejectionCode = 'not-an-object' | 'schema' | 'invalid-subject' | 'row-limit'\n\n/** A refused row, named precisely enough to repair or report. */\ninterface RejectedFindingRow {\n /** Position in the submitted array. */\n readonly index: number\n /** Dotted path to the offending field, `''` for the row itself. */\n readonly path: string\n readonly code: FindingRejectionCode\n readonly message: string\n}\n\ninterface DecodedFindingArray {\n readonly accepted: RawAnalystFinding[]\n readonly rejected: RejectedFindingRow[]\n /**\n * Set when the value was not a finding array at all — the array itself is\n * the failure, so `accepted` and `rejected` are both empty and a caller must\n * not read the result as \"no findings\".\n */\n readonly topLevelError?: string\n}\n\n/**\n * Rows past this count are refused rather than validated. A model that emits\n * thousands of rows has lost the plot, and the diagnostics for them would\n * dwarf the answer they came with.\n */\nexport const MAX_FINDING_ROWS = 500\n\n/**\n * Decode a submitted findings value into accepted rows plus per-row\n * diagnostics.\n *\n * Accepts an array of rows, or a string carrying one (a JSON array, possibly\n * fenced). Anything else — an object, a number, null, undefined — sets\n * `topLevelError` naming the type received: a caller that asked for findings\n * and got a number has a defect to report, not an empty result to record.\n */\nexport function decodeRawFindingArray(value: unknown): DecodedFindingArray {\n const rows = findingRows(value)\n if (typeof rows === 'string') return { accepted: [], rejected: [], topLevelError: rows }\n\n const accepted: RawAnalystFinding[] = []\n const rejected: RejectedFindingRow[] = []\n for (const [index, row] of rows.entries()) {\n if (index >= MAX_FINDING_ROWS) {\n rejected.push({\n index,\n path: '',\n code: 'row-limit',\n message: `findings array exceeds ${MAX_FINDING_ROWS} rows`,\n })\n continue\n }\n const decoded = decodeRow(row, index)\n if ('finding' in decoded) accepted.push(decoded.finding)\n else rejected.push(decoded.rejection)\n }\n return { accepted, rejected }\n}\n\nfunction decodeRow(\n row: unknown,\n index: number,\n): { finding: RawAnalystFinding } | { rejection: RejectedFindingRow } {\n if (row === null || typeof row !== 'object' || Array.isArray(row)) {\n return {\n rejection: {\n index,\n path: '',\n code: 'not-an-object',\n message: `finding row must be an object, received ${describe(row)}`,\n },\n }\n }\n const parsed = RawAnalystFindingSchema.safeParse(row)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n const path = (issue?.path ?? []).join('.')\n // The schema refines `subject` against the grammar; name that refusal\n // separately so a repair turn can be told which rule the row broke.\n const code: FindingRejectionCode =\n path === 'subject' && parseFindingSubject((row as { subject?: string }).subject) === null\n ? 'invalid-subject'\n : 'schema'\n return {\n rejection: { index, path, code, message: issue?.message ?? 'row does not match the schema' },\n }\n }\n return { finding: parsed.data }\n}\n\n/**\n * Narrow a submitted value to candidate rows, or return the message naming why\n * it is not a findings array at all.\n */\nfunction findingRows(value: unknown): unknown[] | string {\n if (Array.isArray(value)) return value\n if (typeof value === 'string') {\n const parsed = coerceJson(value)\n if (parsed === undefined) {\n return 'findings must be a JSON array; the string received is not JSON'\n }\n if (Array.isArray(parsed)) return parsed\n const unwrapped = findingsProperty(parsed)\n if (unwrapped !== undefined) return unwrapped\n return `findings must be a JSON array, received ${describe(parsed)}`\n }\n const unwrapped = findingsProperty(value)\n if (unwrapped !== undefined) return unwrapped\n return `findings must be an array, received ${describe(value)}`\n}\n\n/** `{ findings: [...] }` is the one wrapper models emit often enough to unwrap. */\nfunction findingsProperty(value: unknown): unknown[] | undefined {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined\n const inner = (value as Record<string, unknown>).findings\n return Array.isArray(inner) ? inner : undefined\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (Array.isArray(value)) return 'an array'\n return `a ${typeof value}`\n}\n","import { randomBytes } from 'node:crypto'\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport {\n type ExternalOptimizerCallbackLimits,\n resolveExternalOptimizerCallbackLimits,\n} from '../campaign/external-optimizer-contracts'\nimport {\n closeServer,\n listenLocal,\n sendJsonIfOpen,\n waitForActiveHandlers,\n} from '../campaign/external-optimizer-http'\nimport { isRecord } from '../llm-client/json'\nimport type { TraceAnalysisToolDescriptor } from '../trace-analyst/tools'\n\ninterface TraceToolCallback {\n url: string\n token: string\n calls: () => number\n close: () => Promise<void>\n}\n\nexport type TraceToolCallbackLimits = ExternalOptimizerCallbackLimits\n\n/** Expose one bounded trace-tool set only on an authenticated loopback socket. */\nexport async function startTraceToolCallback(args: {\n tools: readonly TraceAnalysisToolDescriptor[]\n maxCalls: number\n /** Trace-tool request/response byte limits. Omitted fields use finite defaults. */\n limits?: Partial<TraceToolCallbackLimits>\n signal?: AbortSignal\n}): Promise<TraceToolCallback> {\n if (!Number.isSafeInteger(args.maxCalls) || args.maxCalls <= 0) {\n throw new TypeError('trace tool callback maxCalls must be a positive safe integer')\n }\n const limits = resolveExternalOptimizerCallbackLimits(args.limits, 'trace tool callback limits')\n args.signal?.throwIfAborted()\n const byName = new Map(args.tools.map((tool) => [tool.name, tool]))\n if (byName.size !== args.tools.length) {\n throw new Error('trace tool callback received duplicate tool names')\n }\n\n const token = randomBytes(32).toString('hex')\n let calls = 0\n let accepting = true\n let closePromise: Promise<void> | undefined\n const activeControllers = new Set<AbortController>()\n const activeHandlers = new Set<Promise<void>>()\n const server = createServer((request, response) => {\n if (!accepting) {\n sendJsonIfOpen(response, 503, { error: 'trace tool callback is closing' })\n return\n }\n const controller = new AbortController()\n const abortRequest = (): void => {\n request.destroy()\n response.destroy()\n }\n activeControllers.add(controller)\n controller.signal.addEventListener('abort', abortRequest, { once: true })\n\n let handler!: Promise<void>\n handler = handleRequest(request, response, controller.signal).finally(() => {\n controller.signal.removeEventListener('abort', abortRequest)\n activeControllers.delete(controller)\n activeHandlers.delete(handler)\n })\n activeHandlers.add(handler)\n void handler.catch(() => undefined)\n })\n const port = await listenLocal(server)\n const close = (): Promise<void> => {\n closePromise ??= closeCallback()\n return closePromise\n }\n const onAbort = (): void => {\n void close().catch(() => undefined)\n }\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n\n return {\n url: `http://127.0.0.1:${port}/call`,\n token,\n calls: () => calls,\n close,\n }\n\n async function handleRequest(\n request: IncomingMessage,\n response: ServerResponse,\n signal: AbortSignal,\n ): Promise<void> {\n try {\n if (request.method !== 'POST' || request.url !== '/call') {\n sendJsonIfOpen(response, 404, { error: 'not found' })\n return\n }\n if (request.headers.authorization !== `Bearer ${token}`) {\n sendJsonIfOpen(response, 401, { error: 'unauthorized' })\n return\n }\n if (calls >= args.maxCalls) {\n sendJsonIfOpen(response, 429, { error: 'trace tool call limit reached' })\n return\n }\n const body = await readJson(request, limits.maxRequestBytes)\n if (!isRecord(body) || typeof body.name !== 'string' || !('args' in body)) {\n sendJsonIfOpen(response, 400, { error: 'name and args are required' })\n return\n }\n const tool = byName.get(body.name)\n if (!tool) {\n sendJsonIfOpen(response, 404, { error: `unknown trace tool '${body.name}'` })\n return\n }\n calls += 1\n const result = await tool.handler(body.args, { signal })\n const encoded = JSON.stringify({ result })\n if (Buffer.byteLength(encoded) > limits.maxResponseBytes) {\n sendJsonIfOpen(response, 413, { error: 'trace tool response too large' })\n return\n }\n response.writeHead(200, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': String(Buffer.byteLength(encoded)),\n })\n response.end(encoded)\n } catch (error) {\n sendJsonIfOpen(response, signal.aborted ? 499 : 400, {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n async function closeCallback(): Promise<void> {\n args.signal?.removeEventListener('abort', onAbort)\n accepting = false\n const closingServer = closeServer(server)\n server.closeIdleConnections?.()\n for (const controller of activeControllers) controller.abort()\n const [serverResult] = await Promise.allSettled([\n closingServer,\n waitForActiveHandlers(activeHandlers),\n ])\n if (activeControllers.size !== 0 || activeHandlers.size !== 0) {\n throw new Error('trace tool callback closed with active requests')\n }\n if (serverResult?.status === 'rejected') throw serverResult.reason\n }\n}\n\nfunction readJson(request: IncomingMessage, maxRequestBytes: number): Promise<unknown> {\n return new Promise((resolve, reject) => {\n let size = 0\n const chunks: Buffer[] = []\n request.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > maxRequestBytes) {\n reject(new Error('trace tool request too large'))\n request.destroy()\n return\n }\n chunks.push(chunk)\n })\n request.on('error', reject)\n request.on('end', () => {\n try {\n resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))\n } catch (error) {\n reject(error)\n }\n })\n })\n}\n","import {\n assertExternalOptimizerModelBudget,\n type ExternalOptimizerModelCall,\n type ExternalOptimizerModelExecutionObservation,\n type ExternalOptimizerModelProxy,\n type ExternalOptimizerRunnerCommand,\n removeCredentialEnvironment,\n resolveExternalOptimizerCallbackLimits,\n resolveExternalOptimizerProcessLimits,\n} from '../campaign/external-optimizer-contracts'\nimport { startExternalOptimizerModelProxy } from '../campaign/external-optimizer-model-proxy'\nimport { runWithCleanup } from '../campaign/external-optimizer-resources'\nimport { runExternalOptimizerProcess } from '../campaign/external-optimizer-subprocess'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport { isRecord } from '../llm-client/json'\nimport { resolveModelPricing } from '../metrics'\nimport {\n DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS,\n type TraceAnalysisEngine,\n type TraceAnalysisEngineResult,\n} from './engine'\nimport { decodeRawFindingArray } from './finding-codec'\nimport { startTraceToolCallback, type TraceToolCallbackLimits } from './trace-tool-callback'\n\nconst DEFAULT_TIMEOUT_MS = 10 * 60_000\nconst DEFAULT_MAX_COST_USD = 1\nconst DEFAULT_MAX_MODEL_REQUEST_BYTES = 16 * 1024 * 1024\nconst DEFAULT_MAX_MODEL_RESPONSE_BYTES = 4 * 1024 * 1024\nconst DEFAULT_TRACE_TOOL_TIMEOUT_MS = 60_000\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\nconst BRIDGE_MODULE = 'agent_eval_rpc.dspy_rlm_bridge'\n/** Bumped whenever this engine's execution behavior changes. */\nconst DSPY_RLM_ENGINE_VERSION = '2.0.2'\n\nexport interface DspyRlmTraceEngineOptions {\n /** Caller-owned execution path. Agent Eval never receives provider credentials. */\n call: ExternalOptimizerModelCall\n /** Stable public identity for the caller-owned path, such as an AgentProfile digest. */\n callRef: string\n /** Persist the finite execution record returned for every admitted call. */\n recordExecution: (observation: ExternalOptimizerModelExecutionObservation) => void\n model: string\n /** Exact provider rates. Required when the model is absent from the pricing table. */\n pricing?: CustomTokenPricing\n /** Maximum provider spend for one investigation. Default: 1 USD. */\n maxCostUsd?: number\n /** Controller response cap. Default: {@link DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS}. */\n maxOutputTokens?: number\n /**\n * Thinking tokens one controller turn may bill on top of its completion.\n * A reasoning model bills these beyond `maxOutputTokens`, so the cost\n * reservation must cover them. Default: four times the completion cap.\n */\n maxReasoningTokens?: number\n /** Maximum caller-owned model invocations. Default derives from the analysis limits. */\n maxModelRequests?: number\n /** Maximum model request bytes. Default: 16 MiB. */\n maxModelRequestBytes?: number\n /** Maximum model response bytes. Default: 4 MiB. */\n maxModelResponseBytes?: number\n /** Deadline for one caller-owned model invocation. Default: the whole analysis deadline. */\n modelRequestTimeoutMs?: number\n /** Trace-tool loopback request/response byte limits. */\n traceToolLimits?: Partial<TraceToolCallbackLimits>\n /** Deadline for one Python-to-Node trace-tool call. Default: 60 seconds. */\n traceToolTimeoutMs?: number\n /**\n * How the controller's reasoning and code fields are obtained.\n *\n * `tolerant` parses marker output strictly first, then recovers the fields\n * deterministically from prose plus a fenced code block — the shape coding\n * models naturally emit — at no extra model cost. `two-step` extracts with a\n * second call per turn. `chat` accepts marker output only. Default:\n * `tolerant`.\n */\n controlAdapter?: 'chat' | 'two-step' | 'tolerant'\n /** Python command used to load agent-eval-rpc[dspy]. Default: python. */\n runner?: ExternalOptimizerRunnerCommand\n /** Whole investigation deadline. Default: 10 minutes. */\n timeoutMs?: number\n}\n\n/** Use the official DSPy RLM as a bounded recursive trace-analysis engine. */\nexport function createDspyRlmTraceEngine(options: DspyRlmTraceEngineOptions): TraceAnalysisEngine {\n assertOptions(options)\n const maxOutputTokens = options.maxOutputTokens ?? DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS\n if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) {\n throw new TypeError('DSPy RLM maxOutputTokens must be a positive safe integer')\n }\n const controlAdapter = options.controlAdapter ?? 'tolerant'\n const maxReasoningTokens = options.maxReasoningTokens ?? maxOutputTokens * 4\n if (!Number.isSafeInteger(maxReasoningTokens) || maxReasoningTokens < 0) {\n throw new TypeError('DSPy RLM maxReasoningTokens must be a non-negative safe integer')\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n assertTimerDelay(timeoutMs, 'timeoutMs')\n const maxCostUsd = options.maxCostUsd ?? DEFAULT_MAX_COST_USD\n if (!Number.isFinite(maxCostUsd) || maxCostUsd <= 0) {\n throw new TypeError('DSPy RLM maxCostUsd must be positive and finite')\n }\n const pricing = options.pricing ?? pricingForModel(options.model)\n const maxModelRequestBytes = options.maxModelRequestBytes ?? DEFAULT_MAX_MODEL_REQUEST_BYTES\n const maxModelResponseBytes = options.maxModelResponseBytes ?? DEFAULT_MAX_MODEL_RESPONSE_BYTES\n const modelRequestTimeoutMs = options.modelRequestTimeoutMs ?? timeoutMs\n const traceToolTimeoutMs = options.traceToolTimeoutMs ?? DEFAULT_TRACE_TOOL_TIMEOUT_MS\n assertExternalOptimizerModelBudget(\n {\n maxCostUsd,\n maxRequests: options.maxModelRequests ?? 1,\n maxRequestBytes: maxModelRequestBytes,\n maxResponseBytes: maxModelResponseBytes,\n maxOutputTokensPerRequest: maxOutputTokens,\n maxReasoningTokensPerRequest: maxReasoningTokens,\n pricing,\n requestTimeoutMs: modelRequestTimeoutMs,\n },\n 'DSPy RLM model limits',\n )\n resolveExternalOptimizerCallbackLimits(options.traceToolLimits, 'DSPy RLM trace tool limits')\n assertTimerDelay(traceToolTimeoutMs, 'traceToolTimeoutMs')\n\n const runner = sanitizedRunner(options.runner)\n const processLimits = resolveExternalOptimizerProcessLimits(runner?.limits)\n return {\n id: 'dspy-rlm',\n description: 'Official DSPy RLM with bounded trace tools and metered model calls.',\n model: options.model,\n version: DSPY_RLM_ENGINE_VERSION,\n executionConfig: {\n bridge_module: BRIDGE_MODULE,\n call_ref: options.callRef,\n model: options.model,\n pricing: { ...pricing },\n max_cost_usd: maxCostUsd,\n max_output_tokens: maxOutputTokens,\n max_reasoning_tokens: maxReasoningTokens,\n control_adapter: controlAdapter,\n timeout_ms: timeoutMs,\n max_model_requests: options.maxModelRequests ?? null,\n max_request_bytes: maxModelRequestBytes,\n max_response_bytes: maxModelResponseBytes,\n model_request_timeout_ms: modelRequestTimeoutMs,\n trace_tool_limits: options.traceToolLimits ?? null,\n trace_tool_timeout_ms: traceToolTimeoutMs,\n process_limits: processLimits,\n runner: runner ? 'caller-supplied' : 'default',\n runner_command: runner?.command ?? null,\n },\n async analyze(request) {\n const callback = await startTraceToolCallback({\n tools: request.tools,\n maxCalls: request.limits.maxToolCalls,\n ...(options.traceToolLimits ? { limits: options.traceToolLimits } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n let modelProxy: ExternalOptimizerModelProxy | undefined\n const modelExecutions: ExternalOptimizerModelExecutionObservation[] = []\n const result = await runWithCleanup({\n label: 'DSPy RLM trace-analysis resources',\n run: async () => {\n modelProxy = await startExternalOptimizerModelProxy({\n call: options.call,\n callRef: options.callRef,\n recordExecution: (observation) => {\n modelExecutions.push(structuredClone(observation))\n options.recordExecution(observation)\n },\n model: options.model,\n budget: {\n maxCostUsd,\n maxRequests: resolveMaxModelRequests(options.maxModelRequests, request.limits),\n maxRequestBytes: maxModelRequestBytes,\n maxResponseBytes: maxModelResponseBytes,\n maxOutputTokensPerRequest: maxOutputTokens,\n maxReasoningTokensPerRequest: maxReasoningTokens,\n requestTimeoutMs: modelRequestTimeoutMs,\n pricing,\n },\n costLedger: request.costLedger,\n channel: 'analyst',\n phase: request.costPhase,\n actor: request.analystId,\n ...(request.costTags ? { tags: request.costTags } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n request.log?.('trace analyst engine started', {\n engine: 'dspy-rlm',\n model: options.model,\n tools: request.tools.map((tool) => tool.name),\n limits: request.limits,\n })\n const raw = await runExternalOptimizerProcess<unknown>({\n label: 'DSPy RLM trace analysis',\n tempPrefix: 'agent-eval-dspy-rlm-',\n module: BRIDGE_MODULE,\n input: {\n operation: 'analyze',\n question: request.question,\n instructions: request.instructions,\n modelProxy: {\n baseUrl: modelProxy.baseUrl,\n apiKey: modelProxy.apiKey,\n model: options.model,\n maxOutputTokens,\n },\n toolCallback: {\n url: callback.url,\n token: callback.token,\n timeoutMs: traceToolTimeoutMs,\n },\n toolSpecs: request.tools.map(({ name, description, parameters }) => ({\n name,\n description,\n parameters,\n })),\n controlAdapter,\n limits: {\n maxIterations: request.limits.maxIterations,\n maxLlmCalls: request.limits.maxLlmCalls,\n maxOutputChars: request.limits.maxOutputChars,\n },\n // Omitted entirely when the caller supplied none, so a request\n // without structured inputs sends the payload it always sent.\n ...(request.taskInputs ? { taskInputs: request.taskInputs } : {}),\n },\n ...(runner ? { runner } : {}),\n additionalArgs: ['--max-input-bytes', String(processLimits.maxInputBytes)],\n timeoutMs,\n ...(request.signal ? { signal: request.signal } : {}),\n })\n const parsed = parseBridgeOutput(raw, (index, reason) => {\n request.log?.('finding rejected: bridge row failed schema validation', {\n engine: 'dspy-rlm',\n index,\n reason,\n })\n })\n const successfulCompletions = modelProxy.successfulCompletions()\n const requestAttempts = modelProxy.requestAttempts()\n if (parsed.modelCalls !== successfulCompletions) {\n throw new Error(\n `DSPy RLM reported ${parsed.modelCalls} model calls, but the provider proxy recorded ${successfulCompletions}`,\n )\n }\n modelProxy.assertExecutionComplete()\n return {\n ...parsed,\n toolCalls: callback.calls(),\n runtime: {\n ...parsed.runtime,\n modelRequestAttempts: requestAttempts,\n modelSuccessfulCompletions: successfulCompletions,\n modelExecutions,\n },\n } satisfies TraceAnalysisEngineResult\n },\n cleanup: async () => {\n const results = await Promise.allSettled([\n ...(modelProxy ? [modelProxy.close()] : []),\n callback.close(),\n ])\n const errors = results.flatMap((entry) =>\n entry.status === 'rejected' ? [entry.reason] : [],\n )\n if (errors.length > 0) {\n throw new AggregateError(errors, 'DSPy RLM resource cleanup failed')\n }\n if (modelProxy) {\n request.recordActivity?.({\n modelCalls: modelProxy.successfulCompletions(),\n toolCalls: callback.calls(),\n })\n }\n },\n })\n request.log?.('trace analyst engine completed', {\n engine: 'dspy-rlm',\n model_calls: result.modelCalls,\n model_request_attempts: result.runtime.modelRequestAttempts,\n tool_calls: result.toolCalls,\n findings: result.findings.length,\n })\n return result\n },\n }\n}\n\nfunction parseBridgeOutput(\n value: unknown,\n onRejectedFinding: (index: number, reason: string) => void,\n): Omit<TraceAnalysisEngineResult, 'toolCalls'> {\n if (!isRecord(value)) throw new Error('DSPy RLM bridge output must be an object')\n if (typeof value.answer !== 'string' || !value.answer.trim()) {\n throw new Error('DSPy RLM bridge returned no answer')\n }\n // Findings are model output: one malformed row is model noise, not a bridge\n // fault, and the rest of the paid investigation must survive it. The codec\n // is the same decoder the Python side runs, so a row this bridge accepts is\n // a row the optimizer could report, and vice versa.\n const decoded = decodeRawFindingArray(value.findings)\n if (decoded.topLevelError !== undefined) {\n throw new Error(`DSPy RLM bridge findings must be an array: ${decoded.topLevelError}`)\n }\n const findings = decoded.accepted\n const rejectedFindings = decoded.rejected.length\n for (const rejection of decoded.rejected) {\n onRejectedFinding(\n rejection.index,\n `${rejection.code}${rejection.path ? ` at ${rejection.path}` : ''}: ${rejection.message}`,\n )\n }\n if (!Array.isArray(value.trajectory)) {\n throw new Error('DSPy RLM bridge trajectory must be an array')\n }\n if (!Number.isSafeInteger(value.modelCalls) || (value.modelCalls as number) <= 0) {\n throw new Error('DSPy RLM bridge modelCalls must be a positive safe integer')\n }\n if (!isRecord(value.runtime)) {\n throw new Error('DSPy RLM bridge runtime must be an object')\n }\n return {\n answer: value.answer,\n findings,\n trajectory: value.trajectory,\n modelCalls: value.modelCalls as number,\n runtime: { ...value.runtime, rejectedFindings },\n }\n}\n\nfunction assertOptions(options: DspyRlmTraceEngineOptions): void {\n for (const [name, value] of [\n ['callRef', options.callRef],\n ['model', options.model],\n ] as const) {\n if (typeof value !== 'string' || !value.trim() || value !== value.trim()) {\n throw new TypeError(`DSPy RLM ${name} must be a trimmed non-empty string`)\n }\n }\n if (typeof options.call !== 'function') {\n throw new TypeError('DSPy RLM call must be a function')\n }\n if (typeof options.recordExecution !== 'function') {\n throw new TypeError('DSPy RLM recordExecution must be a function')\n }\n if (\n options.maxModelRequests !== undefined &&\n (!Number.isSafeInteger(options.maxModelRequests) || options.maxModelRequests <= 0)\n ) {\n throw new TypeError('DSPy RLM maxModelRequests must be a positive safe integer')\n }\n}\n\nfunction resolveMaxModelRequests(\n configured: number | undefined,\n limits: { maxIterations: number; maxLlmCalls: number },\n): number {\n if (configured !== undefined) return configured\n const derived = limits.maxIterations + limits.maxLlmCalls + 1\n if (!Number.isSafeInteger(derived) || derived <= 0) {\n throw new Error('DSPy RLM analysis limits produce an invalid model request limit')\n }\n return derived\n}\n\nfunction assertTimerDelay(value: number, field: string): void {\n if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) {\n throw new TypeError(`DSPy RLM ${field} must be between 1 and ${MAX_TIMER_DELAY_MS}`)\n }\n}\n\nfunction pricingForModel(model: string): CustomTokenPricing {\n const pricing = resolveModelPricing(model)\n if (!pricing) {\n throw new Error(\n `no pricing is configured for '${model}'; provide DspyRlmTraceEngineOptions.pricing`,\n )\n }\n return {\n inputUsdPerMillion: pricing.input * 1_000,\n outputUsdPerMillion: pricing.output * 1_000,\n }\n}\n\nfunction sanitizedRunner(\n runner: ExternalOptimizerRunnerCommand | undefined,\n): ExternalOptimizerRunnerCommand | undefined {\n if (!runner) return undefined\n return {\n ...(runner.command ? { command: runner.command } : {}),\n ...(runner.args ? { args: runner.args } : {}),\n ...(runner.env ? { env: removeCredentialEnvironment(runner.env) } : {}),\n ...(runner.limits ? { limits: { ...runner.limits } } : {}),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAM,6CAA4D,IAAI,IAAI,CACxE,CAAC,SAAS,WAAW,GACrB,CAAC,aAAa,WAAW,CAC3B,CAAC;;;;;;;AAQD,SAAgB,iBAAiB,MAA8B;CAC7D,MAAM,MAAM,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO,KAAA;CACxD,MAAM,SACJ,QAAQ,KAAA,IAAY,KAAA,IAAa,2BAA2B,IAAI,GAAG,KAAK,IAAI,YAAY;CAC1F,MAAM,WACJ,WAAW,KAAA,KAAc,WAAiC,SAAS,MAAM,IAAI,SAAS,KAAA;CACxF,OAAO,gBAAgB;EACrB,GAAI,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,SAAS;EACnD,MAAM,KAAK;EACX,YAAY,KAAK,cAAc,CAAC;CAClC,CAAC;AACH;;;;;;AAOA,SAAgB,qBAAqB,MAAwC;CAC3E,IAAI,OAAO,KAAK,aAAa,UAAU,OAAO,KAAK;CACnD,MAAM,aAAa,KAAK,cAAc,CAAC;CACvC,MAAM,WACJ,gBAAgB,YAAY,mBAAmB,KAAK,gBAAgB,YAAY,CAAC,UAAU,CAAC;CAC9F,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,IAAI,OAAO,KAAK,SAAS,YAAY,iBAAiB,IAAI,MAAM,QAAQ,OAAO,KAAK;AAEtF;AAEA,SAAgB,UAAU,MAAwC;CAChE,IAAI,OAAO,KAAK,UAAU,YAAY,KAAK,MAAM,SAAS,GAAG,OAAO,KAAK;CACzE,OAAO,gBAA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BAAgB,KAAK,QAAQ,oBAAoB,IAEhF,MAAM,IAAI,UAAU,2DAA2D;AAEnF;AAEA,SAAS,wBACP,YACA,QACQ;CACR,IAAI,eAAe,KAAA,GAAW,OAAO;CACrC,MAAM,UAAU,OAAO,gBAAgB,OAAO,cAAc;CAC5D,IAAI,CAAC,OAAO,cAAc,OAAO,KAAK,WAAW,GAC/C,MAAM,IAAI,MAAM,iEAAiE;CAEnF,OAAO;AACT;AAEA,SAAS,iBAAiB,OAAe,OAAqB;CAC5D,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,SAAS,KAAK,QAAQ,oBACxD,MAAM,IAAI,UAAU,YAAY,MAAM,yBAAyB,oBAAoB;AAEvF;AAEA,SAAS,gBAAgB,OAAmC;CAC1D,MAAM,UAAU,oBAAoB,KAAK;CACzC,IAAI,CAAC,SACH,MAAM,IAAI,MACR,iCAAiC,MAAM,6CACzC;CAEF,OAAO;EACL,oBAAoB,QAAQ,QAAQ;EACpC,qBAAqB,QAAQ,SAAS;CACxC;AACF;AAEA,SAAS,gBACP,QAC4C;CAC5C,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,OAAO;EACL,GAAI,OAAO,UAAU,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;EACpD,GAAI,OAAO,OAAO,EAAE,MAAM,OAAO,KAAK,IAAI,CAAC;EAC3C,GAAI,OAAO,MAAM,EAAE,KAAK,4BAA4B,OAAO,GAAG,EAAE,IAAI,CAAC;EACrE,GAAI,OAAO,SAAS,EAAE,QAAQ,EAAE,GAAG,OAAO,OAAO,EAAE,IAAI,CAAC;CAC1D;AACF"}
1
+ {"version":3,"file":"dspy-rlm-engine-DA4uW64o.js","names":[],"sources":["../src/trace-contracts/spans.ts","../src/trace-contracts/predicates.ts","../src/trace-contracts/types.ts","../src/trace-contracts/validate.ts","../src/trace-contracts/explain.ts","../src/trace-contracts/rules.ts","../src/trace-contracts/evaluate.ts","../src/trace-contracts/harness-session.ts","../src/analyst/finding-codec.ts","../src/analyst/trace-tool-callback.ts","../src/analyst/dspy-rlm-engine.ts"],"sourcesContent":["import {\n ATTR,\n firstNumberAttr,\n firstStringAttr,\n INPUT_TOKEN_ATTR_KEYS,\n MODEL_ATTR_KEYS,\n OUTPUT_TOKEN_ATTR_KEYS,\n resolveSpanKind,\n SPAN_KINDS,\n type SpanKind,\n TOOL_NAME_ATTR_KEYS,\n} from '@tangle-network/agent-trace-contract'\nimport { LLM_CACHE_WRITE_TOKENS, LLM_CACHED_TOKENS } from '../trace/attribute-vocabulary'\nimport type { ContractSpan } from './types'\n\n// ── Span readers ──────────────────────────────────────────────────────\n\n// Eval kinds whose names are not contract kinds. `tool`, `llm`, and `agent`\n// already resolve by upper-casing; `sandbox` and `custom` stay undeclared and\n// fall through to inference.\nconst EVAL_KIND_TO_CONTRACT_KIND: ReadonlyMap<string, SpanKind> = new Map([\n ['judge', 'EVALUATOR'],\n ['retrieval', 'RETRIEVER'],\n])\n\n/**\n * The span's contract kind: a declared kind when recognised, else inferred.\n * A top-level `kind` counts as a declaration only when it names a contract\n * kind; OTLP words such as `SPAN_KIND_INTERNAL` and the eval kinds `sandbox`\n * and `custom` fall through to the span-kind attribute and name signals.\n */\nexport function contractSpanKind(span: ContractSpan): SpanKind {\n const raw = typeof span.kind === 'string' ? span.kind : undefined\n const mapped =\n raw === undefined ? undefined : (EVAL_KIND_TO_CONTRACT_KIND.get(raw) ?? raw.toUpperCase())\n const declared =\n mapped !== undefined && (SPAN_KINDS as readonly string[]).includes(mapped) ? mapped : undefined\n return resolveSpanKind({\n ...(declared === undefined ? {} : { kind: declared }),\n name: span.name,\n attributes: span.attributes ?? {},\n })\n}\n\n/**\n * Tool name: `span.toolName` (typed ToolSpan) → the tool-name attributes\n * (`gen_ai.tool.name`, `tool.name`, ..., `toolName`) → `span.name` when the\n * span is a TOOL span.\n */\nexport function contractSpanToolName(span: ContractSpan): string | undefined {\n if (typeof span.toolName === 'string') return span.toolName\n const attributes = span.attributes ?? {}\n const fromAttr =\n firstStringAttr(attributes, TOOL_NAME_ATTR_KEYS) ?? firstStringAttr(attributes, ['toolName'])\n if (fromAttr !== undefined) return fromAttr\n if (typeof span.name === 'string' && contractSpanKind(span) === 'TOOL') return span.name\n return undefined\n}\n\nexport function spanModel(span: ContractSpan): string | undefined {\n if (typeof span.model === 'string' && span.model.length > 0) return span.model\n return firstStringAttr(span.attributes ?? {}, MODEL_ATTR_KEYS)\n}\n\n/**\n * Input plus output tokens, or `undefined` when either side is unrecorded.\n * Input follows the OTel GenAI definition — prompt tokens plus any cache\n * read and cache write tokens the span records — because a cached call's\n * `INPUT_TOKEN_ATTR_KEYS` value (`llm.token_count.prompt` and its aliases)\n * carries only the uncached remainder, and a cache-heavy call can spend far\n * more on cache reads and writes than on that remainder. `llm.maxTotalTokens`\n * would otherwise pass runs at a small fraction of what they actually cost.\n */\nexport function spanTotalTokens(span: ContractSpan): number | undefined {\n const attributes = span.attributes ?? {}\n const input = finite(span.inputTokens) ?? firstNumberAttr(attributes, INPUT_TOKEN_ATTR_KEYS)\n const output = finite(span.outputTokens) ?? firstNumberAttr(attributes, OUTPUT_TOKEN_ATTR_KEYS)\n if (input === undefined || output === undefined) return undefined\n const cacheRead = firstNumberAttr(attributes, [LLM_CACHED_TOKENS]) ?? 0\n const cacheWrite = firstNumberAttr(attributes, [LLM_CACHE_WRITE_TOKENS]) ?? 0\n return input + output + cacheRead + cacheWrite\n}\n\nconst ARGUMENT_ATTR_KEYS = ['gen_ai.tool.call.arguments', 'tool.arguments', 'input.value'] as const\n\nexport type ArgumentEvidence = { known: true; value: unknown } | { known: false; reason: string }\n\n/** The call's arguments: the typed `args` field, else the argument attributes.\n * JSON strings are parsed; an unparseable string is kept as a string. */\nexport function spanArguments(span: ContractSpan): ArgumentEvidence {\n if (span.argsCaptured === false || span.attributes?.['tool.args_captured'] === false) {\n return { known: false, reason: 'arguments were not captured' }\n }\n if (span.args !== undefined) return { known: true, value: parseJsonString(span.args) }\n for (const key of ARGUMENT_ATTR_KEYS) {\n const value = span.attributes?.[key]\n if (value !== undefined && value !== null) return { known: true, value: parseJsonString(value) }\n }\n return { known: false, reason: 'the span carries no argument evidence' }\n}\n\ntype OfferedTools =\n | { recorded: false }\n | { recorded: true; names: string[] }\n | { recorded: true; unreadable: string }\n\n/** The tool names a span records as offered to the model. */\nexport function spanOfferedTools(span: ContractSpan): OfferedTools {\n const raw = span.attributes?.[ATTR.toolDefinitions]\n if (raw === undefined || raw === null) return { recorded: false }\n const value = parseJsonString(raw)\n if (!Array.isArray(value)) {\n return { recorded: true, unreadable: `${ATTR.toolDefinitions} is not a list` }\n }\n const names: string[] = []\n for (const entry of value) {\n const name = typeof entry === 'string' ? entry : definitionName(entry)\n if (name === undefined) {\n return {\n recorded: true,\n unreadable: `${ATTR.toolDefinitions} has an entry without a tool name`,\n }\n }\n names.push(name)\n }\n return { recorded: true, names }\n}\n\nfunction definitionName(entry: unknown): string | undefined {\n if (entry === null || typeof entry !== 'object') return undefined\n const record = entry as Record<string, unknown>\n if (typeof record.name === 'string' && record.name.length > 0) return record.name\n const fn = record.function as Record<string, unknown> | undefined\n return fn !== null && typeof fn === 'object' && typeof fn.name === 'string' && fn.name.length > 0\n ? fn.name\n : undefined\n}\n\nfunction parseJsonString(value: unknown): unknown {\n if (typeof value !== 'string') return value\n try {\n return JSON.parse(value)\n } catch {\n return value\n }\n}\n\nexport function finite(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nexport function isSpanError(span: ContractSpan): boolean {\n return typeof span.status === 'string' && /^(?:error|status_code_error)$/i.test(span.status)\n}\n","import { SPAN_KINDS, type SpanKind } from '@tangle-network/agent-trace-contract'\nimport { ValidationError } from '../errors'\nimport { contractSpanKind, contractSpanToolName, spanModel } from './spans'\nimport type {\n ContractSpan,\n OneOfMatcher,\n SerializedRegex,\n SpanPredicate,\n TextMatcher,\n} from './types'\n\n// ── Predicate matching ────────────────────────────────────────────────\n\nfunction isSerializedRegex(v: unknown): v is SerializedRegex {\n return (\n typeof v === 'object' &&\n v !== null &&\n typeof (v as SerializedRegex).$regex === 'string' &&\n typeof (v as SerializedRegex).flags === 'string'\n )\n}\n\nexport function isOneOfMatcher(v: unknown): v is OneOfMatcher {\n return typeof v === 'object' && v !== null && Array.isArray((v as OneOfMatcher).oneOf)\n}\n\nexport function isRegexValue(v: unknown): v is RegExp | SerializedRegex {\n return v instanceof RegExp || isSerializedRegex(v)\n}\n\nfunction matchText(actual: string | undefined, matcher: TextMatcher): boolean {\n if (typeof actual !== 'string') return false\n if (typeof matcher === 'string') return actual === matcher\n if (matcher instanceof RegExp) return matcher.test(actual)\n if (isOneOfMatcher(matcher)) return matcher.oneOf.includes(actual)\n return new RegExp(matcher.$regex, matcher.flags).test(actual)\n}\n\nfunction assertMatcher(m: unknown, where: string): void {\n if (typeof m === 'string' || m instanceof RegExp) return\n if (isSerializedRegex(m)) {\n try {\n new RegExp(m.$regex, m.flags)\n } catch (error) {\n throw new ValidationError(`${where}: invalid regex /${m.$regex}/${m.flags}: ${String(error)}`)\n }\n return\n }\n if (isOneOfMatcher(m)) {\n if (m.oneOf.length === 0 || !m.oneOf.every((x) => typeof x === 'string')) {\n throw new ValidationError(`${where}: \"oneOf\" must be a non-empty array of strings`)\n }\n return\n }\n throw new ValidationError(\n `${where}: matcher must be string | RegExp | SerializedRegex | { oneOf }`,\n )\n}\n\nexport function assertPredicate(value: unknown, where: string): asserts value is SpanPredicate {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new ValidationError(`${where}: predicate must be an object, got ${typeof value}`)\n }\n const p = value as SpanPredicate\n for (const field of ['name', 'tool', 'model'] as const) {\n if (p[field] !== undefined) assertMatcher(p[field], `${where} \"${field}\"`)\n }\n if (p.kind !== undefined && !(SPAN_KINDS as readonly string[]).includes(p.kind)) {\n throw new ValidationError(`${where}: \"kind\" must be one of ${SPAN_KINDS.join(', ')}`)\n }\n if (\n p.attr !== undefined &&\n (p.attr === null || typeof p.attr !== 'object' || Array.isArray(p.attr))\n ) {\n throw new ValidationError(`${where}: \"attr\" must be a plain object`)\n }\n for (const [key, expected] of Object.entries(p.attr ?? {})) {\n // Any non-primitive attr value must be a complete matcher shape (a\n // RegExp, a `{ $regex, flags }` pair, or `{ oneOf }`) — never a partial\n // one silently compared by reference. `expected !== actual` on an object\n // is always true, so an incomplete `$regex` (missing `flags`) or a bare\n // `oneOf` used to compile and then never match, making `never` rules\n // pass vacuously and `always` rules fail vacuously.\n if (expected !== null && typeof expected === 'object') {\n assertMatcher(expected, `${where} attr \"${key}\"`)\n }\n }\n if (p.not !== undefined) assertPredicate(p.not, `${where} \"not\"`)\n if (p.requiresCustom && typeof p.custom !== 'function') {\n throw new ValidationError(\n `${where}: rule was built with a custom predicate function, which does not survive JSON ` +\n 'serialization — re-attach `custom` after deserializing or drop the rule',\n )\n }\n const hasAttr = p.attr !== undefined && Object.keys(p.attr).length > 0\n if (\n p.name === undefined &&\n p.tool === undefined &&\n p.model === undefined &&\n p.kind === undefined &&\n p.not === undefined &&\n !hasAttr &&\n typeof p.custom !== 'function'\n ) {\n throw new ValidationError(\n `${where}: empty predicate would match every span — specify name, tool, model, kind, attr, not, or custom`,\n )\n }\n}\n\nexport function predicateMatches(span: ContractSpan, p: SpanPredicate): boolean {\n if (p.kind !== undefined && contractSpanKind(span) !== p.kind) return false\n if (p.name !== undefined && !matchText(span.name, p.name)) return false\n if (p.tool !== undefined && !matchText(contractSpanToolName(span), p.tool)) return false\n if (p.model !== undefined && !matchText(spanModel(span), p.model)) return false\n if (p.attr !== undefined) {\n for (const [key, expected] of Object.entries(p.attr)) {\n const actual = span.attributes?.[key]\n if (isRegexValue(expected) || isOneOfMatcher(expected)) {\n if (!matchText(typeof actual === 'string' ? actual : undefined, expected as TextMatcher))\n return false\n } else if (actual !== expected) {\n return false\n }\n }\n }\n if (p.not !== undefined && predicateMatches(span, p.not)) return false\n if (p.custom !== undefined && !p.custom(span)) return false\n return true\n}\n\nfunction normalizeMatcher(m: TextMatcher): Exclude<TextMatcher, RegExp> {\n if (m instanceof RegExp) return { $regex: m.source, flags: m.flags }\n if (isOneOfMatcher(m)) return { oneOf: [...m.oneOf] }\n return m\n}\n\nexport function normalizePredicate(p: SpanPredicate, where: string): SpanPredicate {\n const kind = typeof p?.kind === 'string' ? (p.kind.toUpperCase() as SpanKind) : p?.kind\n const withKind = kind === undefined ? p : { ...p, kind }\n assertPredicate(withKind, where)\n const out: SpanPredicate = {}\n if (withKind.kind !== undefined) out.kind = withKind.kind\n if (withKind.name !== undefined) out.name = normalizeMatcher(withKind.name)\n if (withKind.tool !== undefined) out.tool = normalizeMatcher(withKind.tool)\n if (withKind.model !== undefined) out.model = normalizeMatcher(withKind.model)\n if (withKind.attr !== undefined) {\n out.attr = Object.fromEntries(\n Object.entries(withKind.attr).map(([k, v]) => [\n k,\n v instanceof RegExp ? normalizeMatcher(v) : v,\n ]),\n )\n }\n if (withKind.not !== undefined) out.not = normalizePredicate(withKind.not, `${where} \"not\"`)\n if (typeof withKind.custom === 'function') {\n out.custom = withKind.custom\n out.requiresCustom = true\n }\n return out\n}\n","import type { SpanKind } from '@tangle-network/agent-trace-contract'\nimport type { RunStatus } from '../trace/schema'\nimport type { DefaultVerdict } from '../verdict'\n\n// ── Span surface ──────────────────────────────────────────────────────\n\n/**\n * Minimal structural span the checker reads. The eval-side `Span`\n * (trace/schema) and the output of {@link contractSpansFromOtlp} satisfy it.\n */\nexport interface ContractSpan {\n spanId?: string\n parentSpanId?: string | null\n name?: string\n /** Eval kinds (`tool`, `llm`, ...) or contract kinds (`TOOL`, `LLM`, ...). */\n kind?: string\n startedAt?: number\n endedAt?: number\n status?: string\n error?: string\n /** Typed field on eval-side ToolSpans; OTLP flattenings drop it (see\n * {@link contractSpanToolName}). */\n toolName?: string\n /** Typed field on eval-side LlmSpans. */\n model?: string\n inputTokens?: number\n outputTokens?: number\n /** Typed field on eval-side ToolSpans. */\n args?: unknown\n /** False when the source observed the call but did not capture its arguments. */\n argsCaptured?: boolean\n attributes?: Record<string, unknown>\n}\n\n/**\n * The run a `run` rule reads. The eval-side `Run` satisfies it. When no run is\n * passed, the checker derives it from the trace's single root span; a trace\n * with no unique root leaves the run unknown and every `run` rule fails.\n */\nexport interface ContractRun {\n status?: string\n startedAt?: number\n endedAt?: number\n}\n\n/** JSON-safe RegExp form — what the builder normalizes RegExp matchers to. */\nexport interface SerializedRegex {\n $regex: string\n flags: string\n}\n\n/** Matches when the value equals one of the listed strings. */\nexport interface OneOfMatcher {\n oneOf: string[]\n}\n\nexport type TextMatcher = string | RegExp | SerializedRegex | OneOfMatcher\n\n/**\n * Proposition over one span. All specified fields must match (AND); `not`\n * must NOT match. At least one field is required — an empty predicate would\n * match every span and is rejected.\n *\n * `kind` compares against the span's contract kind (`TOOL`, `LLM`, `AGENT`,\n * ...), resolved by agent-trace-contract's classifier, so eval kinds\n * (`tool`, `llm`) and OTLP spans that declare no kind are read the same way.\n *\n * `tool` resolves through {@link contractSpanToolName}; `model` through the\n * typed `model` field and the gen_ai model attributes.\n *\n * `attr` values match by strict equality, or regex-test when the value is a\n * RegExp/SerializedRegex and the attribute is a string. Structured attribute\n * values need `custom`, or an `argument` rule for tool arguments.\n */\nexport interface SpanPredicate {\n name?: TextMatcher\n tool?: TextMatcher\n model?: TextMatcher\n kind?: SpanKind\n attr?: Record<string, unknown>\n not?: SpanPredicate\n custom?: (span: ContractSpan) => boolean\n /** Stamped by the builder when `custom` is present. Survives JSON while\n * the function does not, so evaluation of a deserialized contract throws\n * instead of silently dropping the check. */\n requiresCustom?: true\n}\n\n// ── Contract shape ────────────────────────────────────────────────────\n\nexport const ORDER_MODES = ['start-order', 'finish-before-start', 'all-occurrences'] as const\nexport type OrderMode = (typeof ORDER_MODES)[number]\n\nexport const RUN_STATUSES: readonly RunStatus[] = ['running', 'completed', 'failed', 'aborted']\n\nexport const ARGUMENT_OCCURRENCES = ['first', 'last', 'any', 'all'] as const\nexport type ArgumentOccurrence = (typeof ARGUMENT_OCCURRENCES)[number]\n\nexport const ARGUMENT_TYPES = ['string', 'number', 'boolean', 'object', 'array', 'null'] as const\nexport type ArgumentType = (typeof ARGUMENT_TYPES)[number]\n\nexport type ArgumentCheck =\n | { op: 'exists' }\n | { op: 'equals'; value: unknown }\n | { op: 'oneOf'; values: unknown[] }\n | { op: 'type'; type: ArgumentType }\n\n/** A tool whose calls change state outside the run. */\nexport interface RetryWrite {\n tool: string\n /** RFC 6901 JSON Pointer to the idempotency key in the call's arguments.\n * Without it, a repeated call of this tool always fails. */\n idempotencyKey?: string\n}\n\nexport interface RunChecks {\n /** The run's status is `completed` and its end time is recorded. A failed\n * or aborted run fails this check. */\n requireCompleted?: boolean\n /** The run's status must be one of these. */\n allowedStatuses?: RunStatus[]\n /** End minus start, in milliseconds. An unknown duration fails. */\n maxDurationMs?: number\n}\n\nexport type ContractRule =\n | { kind: 'always' | 'never' | 'eventually'; label: string; p: SpanPredicate }\n | { kind: 'precedes'; label: string; a: SpanPredicate; b: SpanPredicate; order?: OrderMode }\n | {\n kind: 'neverUnless'\n label: string\n p: SpanPredicate\n prior: SpanPredicate\n order?: OrderMode\n }\n | { kind: 'atMost'; label: string; p: SpanPredicate; max: number }\n | { kind: 'tokensAtMost'; label: string; p: SpanPredicate; max: number }\n | ({ kind: 'run'; label: string } & RunChecks)\n | {\n kind: 'argument'\n label: string\n p: SpanPredicate\n /** RFC 6901 JSON Pointer into the call's arguments; `''` is the whole value. */\n pointer: string\n check: ArgumentCheck\n /** Which matching calls must satisfy the check. Default `all`. */\n occurrence?: ArgumentOccurrence\n }\n | {\n /**\n * The tools the harness offered the model (the OTel GenAI\n * `gen_ai.tool.definitions` attribute) are recorded, every tool call is\n * one of them, and, when `declared` is set, every offered tool is\n * declared. A trace that records no offered tools fails: what the\n * harness enforced is unknown.\n */\n kind: 'toolsOffered'\n label: string\n declared?: string[]\n }\n | {\n /**\n * A tool called again with the same arguments repeats its side effect.\n * A repeated `reads` call passes; a repeated `writes` call passes only\n * when every call carries the same idempotency key; a repeated call of\n * any other tool fails, because its side effect is unknown.\n */\n kind: 'retrySafe'\n label: string\n reads?: string[]\n writes?: RetryWrite[]\n }\n\n/** One legitimate alternate path. The contract passes only when the base\n * rules pass and at least one alternative passes completely. */\nexport interface ContractAlternative {\n id: string\n rules: ContractRule[]\n}\n\n/** Serializable plain object — `traceContract(name)....build()` output. */\nexport interface TraceContract {\n name: string\n /** What the contract protects, for reports and `explainTraceContract`. */\n description?: string\n /** Evaluate only the span matching `root` and its descendants. Exactly one\n * span must match; zero or several make every rule an error. */\n scope?: { root: SpanPredicate }\n rules: ContractRule[]\n alternatives?: ContractAlternative[]\n}\n\nexport type ContractStatus = 'pass' | 'fail' | 'error'\n\nexport interface ContractViolation {\n rule: string\n spanId?: string\n detail: string\n}\n\n/** What happened to one rule. `error` means it could not be evaluated. */\nexport interface ContractRuleExecution {\n rule: string\n /** Set for rules inside `alternatives`. */\n alternative?: string\n status: ContractStatus\n violations: number\n error?: string\n}\n\nexport interface ContractVerdict extends DefaultVerdict {\n /** Contract name — keys this verdict in multi-contract reports. */\n contract: string\n status: ContractStatus\n /** `status === 'pass'`. */\n valid: boolean\n /** Fraction of rules that passed, in [0, 1]. An errored rule is not a pass. */\n score: number\n /** 0|1 per evaluated base rule, keyed by label, plus `anyOf` when the\n * contract has alternatives. Errored rules are absent, never 0. */\n scores: Record<string, number>\n violations: ContractViolation[]\n ruleExecutions: ContractRuleExecution[]\n /** Why rules errored, one line per errored rule or scope failure. */\n errors: string[]\n}\n\nexport interface ContractCheckResult {\n verdicts: ContractVerdict[]\n /** `error` if any verdict errored, else `fail` if any failed, else `pass`. */\n status: ContractStatus\n allValid: boolean\n}\n\nexport interface EvaluateTraceContractOptions {\n /** The run `run` rules read. Ignored under `scope`, where the scope root is the run. */\n run?: ContractRun\n}\n","import { ValidationError } from '../errors'\nimport { assertPredicate } from './predicates'\nimport {\n ARGUMENT_OCCURRENCES,\n ARGUMENT_TYPES,\n type ArgumentCheck,\n type ContractRule,\n ORDER_MODES,\n type OrderMode,\n RUN_STATUSES,\n type TraceContract,\n} from './types'\n\n// ── Validation ────────────────────────────────────────────────────────\n\nexport function assertOrder(order: unknown, where: string): OrderMode | undefined {\n if (order === undefined) return undefined\n if (!(ORDER_MODES as readonly unknown[]).includes(order)) {\n throw new ValidationError(`${where}: order must be one of ${ORDER_MODES.join(', ')}`)\n }\n return order as OrderMode\n}\n\nexport function assertCount(max: unknown, where: string): void {\n if (typeof max !== 'number' || !Number.isInteger(max) || max < 0) {\n throw new ValidationError(`${where}: max must be a non-negative integer`)\n }\n}\n\nfunction assertJsonPointer(pointer: unknown, where: string): void {\n if (typeof pointer !== 'string' || (pointer !== '' && !pointer.startsWith('/'))) {\n throw new ValidationError(`${where}: pointer must be an RFC 6901 JSON Pointer ('' or '/a/b')`)\n }\n if (/~(?![01])/.test(pointer)) {\n throw new ValidationError(`${where}: pointer has an invalid escape; use ~0 for ~ and ~1 for /`)\n }\n}\n\n/** A non-empty list of distinct, non-empty tool names. */\nfunction assertNames(names: unknown, where: string): string[] {\n if (!Array.isArray(names) || names.length === 0) {\n throw new ValidationError(`${where} must be a non-empty array of tool names`)\n }\n for (const name of names) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new ValidationError(`${where} must hold non-empty tool names`)\n }\n }\n const dup = names.find((n, i) => names.indexOf(n) !== i)\n if (dup !== undefined) throw new ValidationError(`${where} lists \"${dup}\" twice`)\n return names as string[]\n}\n\nfunction assertArgumentCheck(check: unknown, where: string): void {\n const c = check as ArgumentCheck\n if (c === null || typeof c !== 'object') {\n throw new ValidationError(`${where}: check must be an object`)\n }\n switch (c.op) {\n case 'exists':\n return\n case 'equals':\n if (!('value' in c)) throw new ValidationError(`${where}: equals needs a value`)\n return\n case 'oneOf':\n if (!Array.isArray(c.values) || c.values.length === 0) {\n throw new ValidationError(`${where}: oneOf needs a non-empty values array`)\n }\n return\n case 'type':\n if (!(ARGUMENT_TYPES as readonly string[]).includes(c.type)) {\n throw new ValidationError(`${where}: type must be one of ${ARGUMENT_TYPES.join(', ')}`)\n }\n return\n default:\n throw new ValidationError(`${where}: check.op must be exists, equals, oneOf, or type`)\n }\n}\n\nexport function assertRule(rule: ContractRule, where: string): void {\n switch (rule.kind) {\n case 'always':\n case 'never':\n case 'eventually':\n assertPredicate(rule.p, `${where} (p)`)\n return\n case 'precedes':\n assertPredicate(rule.a, `${where} (a)`)\n assertPredicate(rule.b, `${where} (b)`)\n assertOrder(rule.order, where)\n return\n case 'neverUnless':\n assertPredicate(rule.p, `${where} (p)`)\n assertPredicate(rule.prior, `${where} (prior)`)\n assertOrder(rule.order, where)\n return\n case 'atMost':\n case 'tokensAtMost':\n assertPredicate(rule.p, `${where} (p)`)\n assertCount(rule.max, where)\n return\n case 'run': {\n if (\n !rule.requireCompleted &&\n rule.allowedStatuses === undefined &&\n rule.maxDurationMs === undefined\n ) {\n throw new ValidationError(`${where}: run rule checks nothing`)\n }\n if (rule.requireCompleted !== undefined && typeof rule.requireCompleted !== 'boolean') {\n throw new ValidationError(`${where}: requireCompleted must be a boolean`)\n }\n if (rule.allowedStatuses !== undefined) {\n if (!Array.isArray(rule.allowedStatuses) || rule.allowedStatuses.length === 0) {\n throw new ValidationError(`${where}: allowedStatuses must be a non-empty array`)\n }\n for (const status of rule.allowedStatuses) {\n if (!RUN_STATUSES.includes(status)) {\n throw new ValidationError(\n `${where}: unknown run status \"${String(status)}\" — expected one of ${RUN_STATUSES.join(', ')}`,\n )\n }\n }\n }\n if (\n rule.maxDurationMs !== undefined &&\n (typeof rule.maxDurationMs !== 'number' ||\n !Number.isFinite(rule.maxDurationMs) ||\n rule.maxDurationMs <= 0)\n ) {\n throw new ValidationError(`${where}: maxDurationMs must be a positive number`)\n }\n return\n }\n case 'argument':\n assertPredicate(rule.p, `${where} (p)`)\n assertJsonPointer(rule.pointer, where)\n assertArgumentCheck(rule.check, where)\n if (\n rule.occurrence !== undefined &&\n !(ARGUMENT_OCCURRENCES as readonly string[]).includes(rule.occurrence)\n ) {\n throw new ValidationError(\n `${where}: occurrence must be one of ${ARGUMENT_OCCURRENCES.join(', ')}`,\n )\n }\n return\n case 'toolsOffered':\n if (rule.declared !== undefined) assertNames(rule.declared, `${where}: declared`)\n return\n case 'retrySafe': {\n const reads = rule.reads === undefined ? [] : assertNames(rule.reads, `${where}: reads`)\n if (rule.writes === undefined && rule.reads === undefined) {\n throw new ValidationError(`${where}: retrySafe needs reads or writes`)\n }\n if (rule.writes !== undefined) {\n if (!Array.isArray(rule.writes) || rule.writes.length === 0) {\n throw new ValidationError(`${where}: writes must be a non-empty array`)\n }\n const writes = assertNames(\n rule.writes.map((w) => w?.tool),\n `${where}: writes[].tool`,\n )\n for (const [i, w] of rule.writes.entries()) {\n if (w.idempotencyKey === undefined) continue\n assertJsonPointer(w.idempotencyKey, `${where}: writes[${i}].idempotencyKey`)\n if (w.idempotencyKey === '') {\n throw new ValidationError(\n `${where}: writes[${i}].idempotencyKey must name a member, not the whole arguments`,\n )\n }\n }\n const both = writes.find((t) => reads.includes(t))\n if (both !== undefined) {\n throw new ValidationError(`${where}: \"${both}\" is both a read and a write`)\n }\n }\n return\n }\n default:\n throw new ValidationError(\n `${where}: unknown rule kind \"${String((rule as { kind?: unknown }).kind)}\"`,\n )\n }\n}\n\nfunction assertRules(rules: unknown, where: string, allowEmpty = false): void {\n if (!Array.isArray(rules) || (rules.length === 0 && !allowEmpty)) {\n throw new ValidationError(`${where}: no rules — an empty contract would vacuously pass`)\n }\n const seen = new Set<string>()\n for (const rule of rules as ContractRule[]) {\n const ruleWhere = `${where} rule \"${rule?.label ?? '<unlabeled>'}\"`\n if (typeof rule?.label !== 'string' || rule.label.length === 0) {\n throw new ValidationError(`${ruleWhere}: label must be a non-empty string`)\n }\n if (seen.has(rule.label)) {\n throw new ValidationError(`${ruleWhere}: duplicate label would collapse per-rule scores`)\n }\n seen.add(rule.label)\n assertRule(rule, ruleWhere)\n }\n}\n\nexport function assertContract(contract: TraceContract, where: string): void {\n if (typeof contract?.name !== 'string' || contract.name.length === 0) {\n throw new ValidationError(`${where}: contract.name must be a non-empty string`)\n }\n const at = `${where} \"${contract.name}\"`\n // Base rules may be empty only when alternatives carry the checks: the\n // contract then passes exactly when one alternative passes.\n assertRules(\n contract.rules,\n at,\n Array.isArray(contract.alternatives) && contract.alternatives.length > 0,\n )\n if (contract.scope !== undefined) assertPredicate(contract.scope?.root, `${at} scope.root`)\n if (contract.alternatives !== undefined) {\n if (!Array.isArray(contract.alternatives) || contract.alternatives.length === 0) {\n throw new ValidationError(`${at}: alternatives must be a non-empty array`)\n }\n const ids = new Set<string>()\n for (const alternative of contract.alternatives) {\n if (typeof alternative?.id !== 'string' || alternative.id.length === 0) {\n throw new ValidationError(`${at}: every alternative needs a non-empty id`)\n }\n if (ids.has(alternative.id)) {\n throw new ValidationError(`${at}: duplicate alternative id \"${alternative.id}\"`)\n }\n ids.add(alternative.id)\n assertRules(alternative.rules, `${at} alternative \"${alternative.id}\"`)\n }\n }\n}\n","import { isOneOfMatcher, isRegexValue } from './predicates'\nimport type {\n ArgumentCheck,\n ContractRule,\n SpanPredicate,\n TextMatcher,\n TraceContract,\n} from './types'\nimport { assertContract } from './validate'\n\n// ── Descriptions ──────────────────────────────────────────────────────\n\nfunction describeMatcher(m: TextMatcher): string {\n if (typeof m === 'string') return m\n if (m instanceof RegExp) return `/${m.source}/${m.flags}`\n if (isOneOfMatcher(m)) return `oneOf(${m.oneOf.join('|')})`\n return `/${m.$regex}/${m.flags}`\n}\n\nexport function describePredicate(p: SpanPredicate): string {\n const parts: string[] = []\n if (p.kind !== undefined) parts.push(`kind=${p.kind}`)\n if (p.name !== undefined) parts.push(`name=${describeMatcher(p.name)}`)\n if (p.tool !== undefined) parts.push(`tool=${describeMatcher(p.tool)}`)\n if (p.model !== undefined) parts.push(`model=${describeMatcher(p.model)}`)\n if (p.attr !== undefined) {\n for (const [k, v] of Object.entries(p.attr)) {\n parts.push(`attr.${k}=${isRegexValue(v) ? describeMatcher(v) : JSON.stringify(v)}`)\n }\n }\n if (p.not !== undefined) parts.push(`not(${describePredicate(p.not)})`)\n if (typeof p.custom === 'function') parts.push(`custom=${p.custom.name || 'fn'}`)\n return parts.join(',')\n}\n\nexport function describeCheck(check: ArgumentCheck): string {\n switch (check.op) {\n case 'exists':\n return 'exists'\n case 'equals':\n return `equals ${JSON.stringify(check.value)}`\n case 'oneOf':\n return `oneOf ${JSON.stringify(check.values)}`\n case 'type':\n return `type ${check.type}`\n }\n}\n\n/** One line per rule, stating what it requires. */\nfunction describeRule(rule: ContractRule): string {\n switch (rule.kind) {\n case 'always':\n return `every span matches ${describePredicate(rule.p)}`\n case 'never':\n return `no span matches ${describePredicate(rule.p)}`\n case 'eventually':\n return `some span matches ${describePredicate(rule.p)}`\n case 'precedes':\n return `${describePredicate(rule.a)} and ${describePredicate(rule.b)} both occur, and the first comes before the second (${rule.order ?? 'start-order'})`\n case 'neverUnless':\n return `every ${describePredicate(rule.p)} has an earlier ${describePredicate(rule.prior)} (${rule.order ?? 'start-order'})`\n case 'atMost':\n return `at most ${rule.max} span(s) match ${describePredicate(rule.p)}`\n case 'tokensAtMost':\n return `spans matching ${describePredicate(rule.p)} use at most ${rule.max} tokens in total`\n case 'run': {\n const parts: string[] = []\n if (rule.requireCompleted) parts.push('the run completed and recorded its end')\n if (rule.allowedStatuses)\n parts.push(`its status is one of ${rule.allowedStatuses.join(', ')}`)\n if (rule.maxDurationMs !== undefined) parts.push(`it took at most ${rule.maxDurationMs} ms`)\n return parts.join('; ')\n }\n case 'argument':\n return `${rule.occurrence ?? 'all'} call(s) matching ${describePredicate(rule.p)} have argument ${rule.pointer || '(whole value)'} that ${describeCheck(rule.check)}`\n case 'toolsOffered':\n return `the trace records the tools offered to the model, every tool call is one of them${rule.declared ? `, and every offered tool is one of ${rule.declared.join(', ')}` : ''}`\n case 'retrySafe': {\n const parts = ['no tool is called twice with the same arguments']\n if (rule.reads) parts.push(`except the reads ${rule.reads.join(', ')}`)\n for (const w of rule.writes ?? []) {\n parts.push(\n w.idempotencyKey === undefined\n ? `write ${w.tool} may never repeat`\n : `write ${w.tool} may repeat only with one idempotency key at ${w.idempotencyKey}`,\n )\n }\n return parts.join('; ')\n }\n }\n}\n\n/** Plain-language statement of everything a contract checks, one rule per line. */\nexport function explainTraceContract(contract: TraceContract): string {\n assertContract(contract, 'explainTraceContract')\n const lines = [\n `Contract \"${contract.name}\"${contract.description ? ` — ${contract.description}` : ''}`,\n ]\n if (contract.scope) {\n lines.push(\n `Scope: only the span matching ${describePredicate(contract.scope.root)} and its descendants; exactly one span must match.`,\n )\n }\n lines.push('Every rule must pass:')\n for (const rule of contract.rules) lines.push(` - ${rule.label}: ${describeRule(rule)}`)\n if (contract.alternatives) {\n lines.push('And at least one alternative must pass completely:')\n for (const alternative of contract.alternatives) {\n lines.push(` ${alternative.id}:`)\n for (const rule of alternative.rules) lines.push(` - ${rule.label}: ${describeRule(rule)}`)\n }\n }\n return lines.join('\\n')\n}\n","import { ATTR } from '@tangle-network/agent-trace-contract'\nimport { CaptureIntegrityError } from '../errors'\nimport { canonicalString } from '../ledger-core/canonical'\nimport { describePredicate } from './explain'\nimport { predicateMatches } from './predicates'\nimport {\n type ArgumentEvidence,\n contractSpanKind,\n contractSpanToolName,\n finite,\n isSpanError,\n spanArguments,\n spanOfferedTools,\n spanTotalTokens,\n} from './spans'\nimport type {\n ArgumentCheck,\n ArgumentType,\n ContractRule,\n ContractRun,\n ContractSpan,\n ContractStatus,\n ContractViolation,\n OrderMode,\n SpanPredicate,\n} from './types'\n\n// ── Evaluation ────────────────────────────────────────────────────────\n\nexport interface RuleContext {\n spans: readonly ContractSpan[]\n run: { run: ContractRun } | { unknown: string }\n}\n\nexport interface RuleOutcome {\n status: ContractStatus\n violations: ContractViolation[]\n error?: string\n}\n\nfunction spanRef(span: ContractSpan, index: number): string {\n return span.spanId ?? `#${index}`\n}\n\n/**\n * Whether this trace shows any sign that spans of `kind` are actually\n * captured, independent of whether any span happens to match a given rule's\n * predicate. A `never`, `atMost`, `tokensAtMost` or `retrySafe` rule that\n * targets TOOL or LLM spans and finds zero matches cannot otherwise tell \"no\n * calls happened\" from \"calls were not recorded\": an exporter that silently\n * drops a span kind makes `forbidden`, `allowed`, `maxCalls` and `retries`\n * checks on that kind pass vacuously. Evidence is: a span of that kind\n * anywhere in the trace, or — for TOOL — a recorded offered-tool set\n * (`gen_ai.tool.definitions`), which proves the capture pipeline ran even on\n * a turn that called no tool.\n */\nfunction hasCaptureEvidence(spans: readonly ContractSpan[], kind: 'TOOL' | 'LLM'): boolean {\n if (spans.some((span) => contractSpanKind(span) === kind)) return true\n if (kind === 'TOOL') return spans.some((span) => spanOfferedTools(span).recorded)\n return false\n}\n\n/** Only `TOOL`/`LLM`-scoped predicates have capture evidence to check. */\nfunction capturedKindOf(p: SpanPredicate): 'TOOL' | 'LLM' | undefined {\n return p.kind === 'TOOL' || p.kind === 'LLM' ? p.kind : undefined\n}\n\nfunction requireCaptureEvidence(\n spans: readonly ContractSpan[],\n p: SpanPredicate,\n rule: string,\n situation: string,\n): void {\n const kind = capturedKindOf(p)\n if (kind === undefined) return\n if (hasCaptureEvidence(spans, kind)) return\n throw new CaptureIntegrityError(\n `rule '${rule}': ${situation} and the trace has no ${kind} capture evidence (no ${kind} span` +\n (kind === 'TOOL' ? `, no ${ATTR.toolDefinitions}` : '') +\n `) — cannot tell whether ${describePredicate(p)} never happened or was never recorded`,\n )\n}\n\nfunction indexed(\n spans: readonly ContractSpan[],\n p: SpanPredicate,\n): Array<{ span: ContractSpan; ref: string }> {\n const out: Array<{ span: ContractSpan; ref: string }> = []\n spans.forEach((span, i) => {\n if (predicateMatches(span, p)) out.push({ span, ref: spanRef(span, i) })\n })\n return out\n}\n\ntype Witness = { ok: true } | { ok: false; detail: string }\n\n/**\n * Is guarded span `b` preceded by the guard spans under `order`? A span never\n * witnesses itself. Missing timestamps fail: the checker cannot prove an\n * order it cannot see.\n */\nfunction witnessed(\n b: { span: ContractSpan; ref: string },\n guards: ReadonlyArray<{ span: ContractSpan; ref: string }>,\n order: OrderMode,\n): Witness {\n const bStart = finite(b.span.startedAt)\n if (bStart === undefined) {\n return { ok: false, detail: `span ${b.ref} has no startedAt, so its order cannot be proven` }\n }\n const candidates = guards.filter((a) => a.span !== b.span)\n if (candidates.length === 0) return { ok: false, detail: `span ${b.ref} has no earlier match` }\n const boundary = order === 'start-order' ? 'startedAt' : 'endedAt'\n const untimed = candidates.find((a) => finite(a.span[boundary]) === undefined)\n if (order === 'all-occurrences') {\n if (untimed) {\n return {\n ok: false,\n detail: `span ${untimed.ref} has no endedAt, so its order cannot be proven`,\n }\n }\n const late = candidates.find((a) => a.span.endedAt! > bStart)\n return late\n ? { ok: false, detail: `span ${late.ref} ends after span ${b.ref} starts` }\n : { ok: true }\n }\n const earlier = candidates.some((a) => {\n const t = finite(a.span[boundary])\n return t !== undefined && (order === 'start-order' ? t < bStart : t <= bStart)\n })\n if (earlier) return { ok: true }\n if (untimed) {\n return {\n ok: false,\n detail: `span ${untimed.ref} has no ${boundary}, so its order cannot be proven`,\n }\n }\n return {\n ok: false,\n detail:\n order === 'start-order'\n ? `span ${b.ref} has no match that started before it`\n : `span ${b.ref} has no match that finished before it started`,\n }\n}\n\nfunction orderViolations(\n label: string,\n guards: ReadonlyArray<{ span: ContractSpan; ref: string }>,\n guarded: ReadonlyArray<{ span: ContractSpan; ref: string }>,\n order: OrderMode,\n describe: string,\n): ContractViolation[] {\n const out: ContractViolation[] = []\n for (const b of guarded) {\n const w = witnessed(b, guards, order)\n if (!w.ok) out.push({ rule: label, spanId: b.span.spanId, detail: `${describe}: ${w.detail}` })\n }\n return out\n}\n\n/** RFC 6901 resolution. `found: false` when any reference token is absent. */\nfunction resolveJsonPointer(value: unknown, pointer: string): { found: boolean; value?: unknown } {\n if (pointer === '') return { found: true, value }\n let current: unknown = value\n for (const raw of pointer.slice(1).split('/')) {\n const token = raw.replace(/~1/g, '/').replace(/~0/g, '~')\n if (Array.isArray(current)) {\n if (!/^(?:0|[1-9]\\d*)$/.test(token) || Number(token) >= current.length)\n return { found: false }\n current = current[Number(token)]\n } else if (current !== null && typeof current === 'object' && Object.hasOwn(current, token)) {\n current = (current as Record<string, unknown>)[token]\n } else {\n return { found: false }\n }\n }\n return { found: true, value: current }\n}\n\nfunction jsonType(value: unknown): ArgumentType | 'undefined' {\n if (value === null) return 'null'\n if (Array.isArray(value)) return 'array'\n const t = typeof value\n return t === 'string' || t === 'number' || t === 'boolean' || t === 'object' ? t : 'undefined'\n}\n\nfunction jsonEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true\n const ta = jsonType(a)\n if (ta !== jsonType(b)) return false\n if (ta === 'array') {\n const x = a as unknown[]\n const y = b as unknown[]\n return x.length === y.length && x.every((v, i) => jsonEqual(v, y[i]))\n }\n if (ta === 'object') {\n const x = a as Record<string, unknown>\n const y = b as Record<string, unknown>\n const keys = Object.keys(x)\n return (\n keys.length === Object.keys(y).length &&\n keys.every((k) => Object.hasOwn(y, k) && jsonEqual(x[k], y[k]))\n )\n }\n return false\n}\n\n/** Why `value` fails `check`, or `undefined` when it passes. Never echoes the\n * actual argument value: arguments can carry customer data. */\nfunction argumentFailure(\n evidence: ArgumentEvidence,\n pointer: string,\n check: ArgumentCheck,\n): string | undefined {\n if (!evidence.known) return evidence.reason\n const resolved = resolveJsonPointer(evidence.value, pointer)\n if (!resolved.found) return `argument ${pointer || '(whole value)'} is absent`\n switch (check.op) {\n case 'exists':\n return undefined\n case 'equals':\n return jsonEqual(resolved.value, check.value)\n ? undefined\n : `argument ${pointer || '(whole value)'} (a ${jsonType(resolved.value)}) does not equal the expected value`\n case 'oneOf':\n return check.values.some((v) => jsonEqual(resolved.value, v))\n ? undefined\n : `argument ${pointer || '(whole value)'} (a ${jsonType(resolved.value)}) is not one of the expected values`\n case 'type':\n return jsonType(resolved.value) === check.type\n ? undefined\n : `argument ${pointer || '(whole value)'} is a ${jsonType(resolved.value)}, not a ${check.type}`\n }\n}\n\nfunction checkArgument(\n rule: Extract<ContractRule, { kind: 'argument' }>,\n spans: readonly ContractSpan[],\n): ContractViolation[] {\n const matches = indexed(spans, rule.p)\n if (matches.length === 0) {\n return [\n {\n rule: rule.label,\n detail: `no span matches ${describePredicate(rule.p)}, so there is no argument evidence to check`,\n },\n ]\n }\n const occurrence = rule.occurrence ?? 'all'\n let selected = matches\n if ((occurrence === 'first' || occurrence === 'last') && matches.length > 1) {\n const untimed = matches.find((m) => finite(m.span.startedAt) === undefined)\n if (untimed) {\n return [\n {\n rule: rule.label,\n spanId: untimed.span.spanId,\n detail: `span ${untimed.ref} has no startedAt, so the ${occurrence} call cannot be chosen`,\n },\n ]\n }\n const sorted = [...matches].sort((x, y) => x.span.startedAt! - y.span.startedAt!)\n selected = [occurrence === 'first' ? sorted[0]! : sorted[sorted.length - 1]!]\n }\n const failures = selected.map((m) => ({\n m,\n why: argumentFailure(spanArguments(m.span), rule.pointer, rule.check),\n }))\n const failed = failures.filter((f) => f.why !== undefined)\n if (occurrence === 'any' ? failed.length < failures.length : failed.length === 0) return []\n return failed.map((f) => ({\n rule: rule.label,\n spanId: f.m.span.spanId,\n detail: `span ${f.m.ref}: ${f.why}`,\n }))\n}\n\nfunction checkRun(\n rule: Extract<ContractRule, { kind: 'run' }>,\n context: RuleContext['run'],\n): ContractViolation[] {\n if ('unknown' in context) {\n return [{ rule: rule.label, detail: `run record unavailable: ${context.unknown}` }]\n }\n const run = context.run\n const out: ContractViolation[] = []\n if (rule.requireCompleted && (run.status !== 'completed' || finite(run.endedAt) === undefined)) {\n out.push({\n rule: rule.label,\n detail:\n run.status === 'completed'\n ? 'run status is completed but no end time was recorded'\n : `run status is ${run.status ?? 'unknown'}, not completed`,\n })\n }\n if (\n rule.allowedStatuses &&\n !(rule.allowedStatuses as readonly string[]).includes(run.status ?? '')\n ) {\n out.push({\n rule: rule.label,\n detail: `run status ${run.status ?? 'unknown'} is not one of ${rule.allowedStatuses.join(', ')}`,\n })\n }\n if (rule.maxDurationMs !== undefined) {\n const start = finite(run.startedAt)\n const end = finite(run.endedAt)\n if (start === undefined || end === undefined) {\n out.push({\n rule: rule.label,\n detail: 'run duration is unknown: start or end time is missing',\n })\n } else if (end - start > rule.maxDurationMs) {\n out.push({\n rule: rule.label,\n detail: `run took ${end - start} ms, over ${rule.maxDurationMs} ms`,\n })\n }\n }\n return out\n}\n\nconst listed = (names: readonly string[], max = 6): string =>\n names.length <= max\n ? names.join(', ')\n : `${names.slice(0, max).join(', ')} and ${names.length - max} more`\n\nfunction toolSpans(spans: readonly ContractSpan[]): Array<{ span: ContractSpan; ref: string }> {\n const out: Array<{ span: ContractSpan; ref: string }> = []\n spans.forEach((span, i) => {\n if (contractSpanKind(span) === 'TOOL') out.push({ span, ref: spanRef(span, i) })\n })\n return out\n}\n\n/** Declared, offered and called tools agree. */\nfunction checkToolsOffered(\n rule: Extract<ContractRule, { kind: 'toolsOffered' }>,\n spans: readonly ContractSpan[],\n): ContractViolation[] {\n const out: ContractViolation[] = []\n const offered = new Set<string>()\n let recorded = 0\n const declared = rule.declared ? new Set(rule.declared) : undefined\n spans.forEach((span, i) => {\n const tools = spanOfferedTools(span)\n if (!tools.recorded) return\n recorded += 1\n const ref = spanRef(span, i)\n if ('unreadable' in tools) {\n out.push({\n rule: rule.label,\n spanId: span.spanId,\n detail: `span ${ref}: ${tools.unreadable}`,\n })\n return\n }\n for (const name of tools.names) offered.add(name)\n const undeclared = declared ? [...new Set(tools.names)].filter((n) => !declared.has(n)) : []\n if (undeclared.length > 0) {\n out.push({\n rule: rule.label,\n spanId: span.spanId,\n detail: `span ${ref} offered the model ${undeclared.length} undeclared tool(s): ${listed(undeclared)}`,\n })\n }\n })\n if (recorded === 0) {\n return [\n {\n rule: rule.label,\n detail: `no span records the tools offered to the model (${ATTR.toolDefinitions}), so what the harness enforced is unknown`,\n },\n ]\n }\n for (const { span, ref } of toolSpans(spans)) {\n const name = contractSpanToolName(span)\n if (name === undefined) {\n out.push({\n rule: rule.label,\n spanId: span.spanId,\n detail: `span ${ref} has no tool name, so it cannot be matched to an offered tool`,\n })\n } else if (!offered.has(name)) {\n out.push({\n rule: rule.label,\n spanId: span.spanId,\n detail: `span ${ref} called ${name}, which was never offered: the harness did not enforce its tool set`,\n })\n }\n }\n return out\n}\n\n/** The call's idempotency key, or why it has none. */\nfunction idempotencyKey(\n span: ContractSpan,\n pointer: string,\n): { key: string } | { missing: string } {\n const evidence = spanArguments(span)\n if (!evidence.known) return { missing: evidence.reason }\n const resolved = resolveJsonPointer(evidence.value, pointer)\n const value = resolved.value\n if (resolved.found && typeof value === 'string' && value.length > 0) return { key: value }\n if (resolved.found && typeof value === 'number' && Number.isFinite(value)) {\n return { key: String(value) }\n }\n return { missing: `no idempotency key at ${pointer}` }\n}\n\n/** No call repeats a side effect that is not proven safe to repeat. */\nfunction checkRetrySafe(\n rule: Extract<ContractRule, { kind: 'retrySafe' }>,\n spans: readonly ContractSpan[],\n): ContractViolation[] {\n const reads = new Set(rule.reads ?? [])\n const writes = new Map((rule.writes ?? []).map((w) => [w.tool, w]))\n const out: ContractViolation[] = []\n const groups = new Map<string, Array<{ span: ContractSpan; ref: string }>>()\n const unseen = new Map<string, Array<{ span: ContractSpan; ref: string }>>()\n const calls = toolSpans(spans)\n if (calls.length === 0 && !hasCaptureEvidence(spans, 'TOOL')) {\n throw new CaptureIntegrityError(\n `rule '${rule.label}': retrySafe found 0 TOOL spans and the trace has no TOOL capture ` +\n `evidence (no TOOL span, no ${ATTR.toolDefinitions}) — cannot tell whether no reads or ` +\n 'writes happened or the trace lost its TOOL spans',\n )\n }\n for (const call of calls) {\n const name = contractSpanToolName(call.span)\n if (name === undefined) {\n out.push({\n rule: rule.label,\n spanId: call.span.spanId,\n detail: `span ${call.ref} has no tool name, so whether it repeats a call is unknown`,\n })\n continue\n }\n if (reads.has(name)) continue\n const args = spanArguments(call.span)\n if (!args.known) {\n const list = unseen.get(name) ?? []\n list.push(call)\n unseen.set(name, list)\n continue\n }\n // A write's key differs between tries that mean the same operation, so a\n // declared key is left out of the call's identity and checked below.\n const pointer = writes.get(name)?.idempotencyKey\n const identity = pointer === undefined ? args.value : withoutMember(args.value, pointer)\n const key = `${name}\\u0000${canonicalString(identity)}`\n const list = groups.get(key) ?? []\n list.push(call)\n groups.set(key, list)\n }\n // A call without arguments may repeat any other call of its tool.\n for (const [name, calls] of unseen) {\n const total =\n calls.length +\n [...groups].reduce((n, [k, list]) => (k.startsWith(`${name}\\u0000`) ? n + list.length : n), 0)\n if (total > 1) {\n out.push({\n rule: rule.label,\n spanId: calls[0]!.span.spanId,\n detail: `${name} was called ${total} times and span ${calls[0]!.ref} has no captured arguments, so whether a call repeats another is unknown`,\n })\n }\n }\n for (const [key, calls] of groups) {\n if (calls.length < 2) continue\n const name = key.slice(0, key.indexOf('\\u0000'))\n const refs = listed(calls.map((c) => c.ref))\n const write = writes.get(name)\n if (!write) {\n out.push({\n rule: rule.label,\n spanId: calls[1]!.span.spanId,\n detail: `${name} was called ${calls.length} times with the same arguments (spans ${refs}) and its side effect is not declared, so the repeat is not proven safe`,\n })\n continue\n }\n const pointer = write.idempotencyKey\n if (pointer === undefined) {\n out.push({\n rule: rule.label,\n spanId: calls[1]!.span.spanId,\n detail: `write ${name} was called ${calls.length} times with the same arguments (spans ${refs}) and declares no idempotency key, so it may have applied more than once`,\n })\n continue\n }\n const keyed = calls.map((c) => ({ c, k: idempotencyKey(c.span, pointer) }))\n const missing = keyed.find((x) => 'missing' in x.k)\n const keys = new Set(keyed.flatMap((x) => ('key' in x.k ? [x.k.key] : [])))\n if (missing) {\n out.push({\n rule: rule.label,\n spanId: missing.c.span.spanId,\n detail: `write ${name} was called ${calls.length} times with the same arguments (spans ${refs}); span ${missing.c.ref} has ${(missing.k as { missing: string }).missing}, so it may have applied more than once`,\n })\n } else if (keys.size > 1) {\n out.push({\n rule: rule.label,\n spanId: calls[1]!.span.spanId,\n detail: `write ${name} was called ${calls.length} times with the same arguments (spans ${refs}) under ${keys.size} different idempotency keys, so the target cannot tell they are one operation`,\n })\n }\n }\n // A declared write whose call errored (a timeout included: the target's\n // handling of the write is unknown) and carries no idempotency key is\n // unsafe to retry even when no repeat is detected — a retry that changes\n // the argument encoding, or one this trace never captured, would apply\n // the write twice with nothing to de-duplicate it by.\n const flagged = new Set(out.map((v) => v.spanId))\n for (const call of toolSpans(spans)) {\n const name = contractSpanToolName(call.span)\n if (name === undefined || flagged.has(call.span.spanId)) continue\n const write = writes.get(name)\n if (!write || !isSpanError(call.span)) continue\n const pointer = write.idempotencyKey\n const hasKey = pointer !== undefined && 'key' in idempotencyKey(call.span, pointer)\n if (!hasKey) {\n out.push({\n rule: rule.label,\n spanId: call.span.spanId,\n detail: `write ${name} (span ${call.ref}) errored and ${pointer === undefined ? 'declares no idempotency key' : `has ${(idempotencyKey(call.span, pointer) as { missing: string }).missing}`}; its outcome is unknown, so a retry cannot be proven safe`,\n })\n flagged.add(call.span.spanId)\n }\n }\n return out\n}\n\n/** A copy of `value` without the member `pointer` names (RFC 6901). */\nfunction withoutMember(value: unknown, pointer: string): unknown {\n const tokens = pointer\n .slice(1)\n .split('/')\n .map((t) => t.replace(/~1/g, '/').replace(/~0/g, '~'))\n const strip = (node: unknown, depth: number): unknown => {\n const token = tokens[depth]!\n const last = depth === tokens.length - 1\n if (Array.isArray(node)) {\n const index = /^(?:0|[1-9]\\d*)$/.test(token) ? Number(token) : -1\n if (index < 0 || index >= node.length) return node\n return last\n ? node.filter((_, i) => i !== index)\n : node.map((v, i) => (i === index ? strip(v, depth + 1) : v))\n }\n if (node === null || typeof node !== 'object' || !Object.hasOwn(node, token)) return node\n const copy = { ...(node as Record<string, unknown>) }\n if (last) delete copy[token]\n else copy[token] = strip(copy[token], depth + 1)\n return copy\n }\n return strip(value, 0)\n}\n\nfunction checkRule(rule: ContractRule, ctx: RuleContext): ContractViolation[] {\n const { spans } = ctx\n switch (rule.kind) {\n case 'always':\n return spans.flatMap((span, i) =>\n predicateMatches(span, rule.p)\n ? []\n : [\n {\n rule: rule.label,\n spanId: span.spanId,\n detail: `span ${spanRef(span, i)} (\"${span.name ?? ''}\") fails always(${describePredicate(rule.p)})`,\n },\n ],\n )\n case 'never': {\n const matches = indexed(spans, rule.p)\n if (matches.length === 0) {\n requireCaptureEvidence(\n spans,\n rule.p,\n rule.label,\n `never(${describePredicate(rule.p)}) matched 0 spans`,\n )\n }\n return matches.map(({ span, ref }) => ({\n rule: rule.label,\n spanId: span.spanId,\n detail: `span ${ref} (\"${span.name ?? ''}\") matches never(${describePredicate(rule.p)})`,\n }))\n }\n case 'eventually':\n return spans.some((span) => predicateMatches(span, rule.p))\n ? []\n : [\n {\n rule: rule.label,\n detail: `no span matches eventually(${describePredicate(rule.p)}) over ${spans.length} span(s)`,\n },\n ]\n case 'precedes': {\n const as = indexed(spans, rule.a)\n const bs = indexed(spans, rule.b)\n const out: ContractViolation[] = []\n if (as.length === 0) {\n out.push({\n rule: rule.label,\n detail: `required predecessor ${describePredicate(rule.a)} never occurred`,\n })\n }\n if (bs.length === 0) {\n out.push({\n rule: rule.label,\n detail: `required successor ${describePredicate(rule.b)} never occurred`,\n })\n }\n if (out.length > 0) return out\n return orderViolations(\n rule.label,\n as,\n bs,\n rule.order ?? 'start-order',\n `${describePredicate(rule.b)} is not preceded by ${describePredicate(rule.a)}`,\n )\n }\n case 'neverUnless':\n return orderViolations(\n rule.label,\n indexed(spans, rule.prior),\n indexed(spans, rule.p),\n rule.order ?? 'start-order',\n `${describePredicate(rule.p)} without an earlier ${describePredicate(rule.prior)}`,\n )\n case 'atMost': {\n const matches = indexed(spans, rule.p)\n if (matches.length === 0) {\n requireCaptureEvidence(\n spans,\n rule.p,\n rule.label,\n `atMost(${describePredicate(rule.p)}) matched 0 spans`,\n )\n }\n return matches.length <= rule.max\n ? []\n : [\n {\n rule: rule.label,\n spanId: matches[rule.max]?.span.spanId,\n detail: `${matches.length} span(s) match ${describePredicate(rule.p)}, over the limit of ${rule.max}`,\n },\n ]\n }\n case 'tokensAtMost': {\n const matches = indexed(spans, rule.p)\n if (matches.length === 0) {\n requireCaptureEvidence(\n spans,\n rule.p,\n rule.label,\n `tokensAtMost(${describePredicate(rule.p)}) matched 0 spans`,\n )\n }\n const unknown = matches.find((m) => spanTotalTokens(m.span) === undefined)\n if (unknown) {\n return [\n {\n rule: rule.label,\n spanId: unknown.span.spanId,\n detail: `span ${unknown.ref} has no recorded input and output token counts, so the total is unknown`,\n },\n ]\n }\n const total = matches.reduce((sum, m) => sum + spanTotalTokens(m.span)!, 0)\n return total <= rule.max\n ? []\n : [\n {\n rule: rule.label,\n detail: `${total} tokens across ${matches.length} span(s) matching ${describePredicate(rule.p)}, over the limit of ${rule.max}`,\n },\n ]\n }\n case 'run':\n return checkRun(rule, ctx.run)\n case 'argument':\n return checkArgument(rule, spans)\n case 'toolsOffered':\n return checkToolsOffered(rule, spans)\n case 'retrySafe':\n return checkRetrySafe(rule, spans)\n }\n}\n\nexport function executeRule(rule: ContractRule, ctx: RuleContext): RuleOutcome {\n try {\n const violations = checkRule(rule, ctx)\n return { status: violations.length === 0 ? 'pass' : 'fail', violations }\n } catch (error) {\n return {\n status: 'error',\n violations: [],\n error: error instanceof Error ? error.message : String(error),\n }\n }\n}\n","import { ValidationError } from '../errors'\nimport { packageVersion } from '../package-version'\nimport { certificationEvidenceDigest } from '../verdict'\nimport { describePredicate } from './explain'\nimport { predicateMatches } from './predicates'\nimport { executeRule, type RuleContext, type RuleOutcome } from './rules'\nimport { finite, isSpanError } from './spans'\nimport {\n type ContractCheckResult,\n type ContractRule,\n type ContractRuleExecution,\n type ContractRun,\n type ContractSpan,\n type ContractStatus,\n type ContractVerdict,\n type EvaluateTraceContractOptions,\n RUN_STATUSES,\n type SpanPredicate,\n type TraceContract,\n} from './types'\nimport { assertContract } from './validate'\n\n// ── Evaluation ────────────────────────────────────────────────────────\n\n/**\n * A run derived from one span: the `run.status` attribute a run-anchor span\n * carries (store-to-otlp writes it), else failed on an error status, else\n * unknown. An ended span with an OK status and no declared `run.status` is\n * NOT inferred as completed — a span exporter can end its root span cleanly\n * without ever learning whether the underlying run actually finished (for\n * example, a trace reader that saw no terminal record). `requireCompleted`\n * and `allowedStatuses` must fail closed on that gap rather than pass it.\n */\nfunction runOfSpan(span: ContractSpan): ContractRun {\n const declared = span.attributes?.['run.status']\n return {\n status:\n typeof declared === 'string' && (RUN_STATUSES as readonly string[]).includes(declared)\n ? declared\n : isSpanError(span)\n ? 'failed'\n : undefined,\n ...(finite(span.startedAt) === undefined ? {} : { startedAt: span.startedAt }),\n ...(finite(span.endedAt) === undefined ? {} : { endedAt: span.endedAt }),\n }\n}\n\nfunction rootsOf(spans: readonly ContractSpan[]): ContractSpan[] {\n const ids = new Set(\n spans.map((s) => s.spanId).filter((id): id is string => typeof id === 'string'),\n )\n return spans.filter((s) => !s.parentSpanId || !ids.has(s.parentSpanId))\n}\n\nfunction subtree(spans: readonly ContractSpan[], root: ContractSpan): ContractSpan[] {\n if (typeof root.spanId !== 'string') return [root]\n const children = new Map<string, ContractSpan[]>()\n for (const span of spans) {\n if (typeof span.parentSpanId === 'string') {\n const list = children.get(span.parentSpanId) ?? []\n list.push(span)\n children.set(span.parentSpanId, list)\n }\n }\n const members = new Set<ContractSpan>([root])\n const queue = [root]\n while (queue.length > 0) {\n const current = queue.shift()!\n for (const child of (typeof current.spanId === 'string' && children.get(current.spanId)) ||\n []) {\n if (!members.has(child)) {\n members.add(child)\n queue.push(child)\n }\n }\n }\n return spans.filter((s) => members.has(s))\n}\n\nfunction statusOf(outcomes: readonly RuleOutcome[]): ContractStatus {\n if (outcomes.some((o) => o.status === 'error')) return 'error'\n return outcomes.every((o) => o.status === 'pass') ? 'pass' : 'fail'\n}\n\n/**\n * Evaluate one contract over a span sequence. Pure and synchronous — works on\n * `Span[]` from a TraceStore, `contractSpansFromOtlp` output, or any array\n * satisfying `ContractSpan`. Throws\n * `ValidationError` for a malformed contract; a rule that cannot be evaluated\n * is reported as `error` in the verdict instead.\n */\nexport function evaluateTraceContract(\n contract: TraceContract,\n spans: readonly ContractSpan[],\n options: EvaluateTraceContractOptions = {},\n): ContractVerdict {\n assertContract(contract, 'evaluateTraceContract')\n if (!Array.isArray(spans)) {\n throw new ValidationError(`evaluateTraceContract: spans must be an array, got ${typeof spans}`)\n }\n let subject: readonly ContractSpan[] = spans\n let run: RuleContext['run']\n let scopeError: string | undefined\n if (contract.scope) {\n const roots = spans.filter((s) => predicateMatches(s, contract.scope!.root))\n if (roots.length === 1) {\n subject = subtree(spans, roots[0]!)\n run = { run: runOfSpan(roots[0]!) }\n } else {\n scopeError = `scope root ${describePredicate(contract.scope.root)} matched ${roots.length} spans; exactly one is required`\n run = { unknown: scopeError }\n }\n } else if (options.run) {\n run = { run: options.run }\n } else {\n const roots = rootsOf(spans)\n run =\n roots.length === 1\n ? { run: runOfSpan(roots[0]!) }\n : { unknown: `the trace has ${roots.length} root spans and no run record was passed` }\n }\n const ctx: RuleContext = { spans: subject, run }\n const execute = (rule: ContractRule): RuleOutcome =>\n scopeError === undefined\n ? executeRule(rule, ctx)\n : { status: 'error', violations: [], error: scopeError }\n\n const base = contract.rules.map(execute)\n const branches = (contract.alternatives ?? []).map((alternative) => ({\n alternative,\n outcomes: alternative.rules.map(execute),\n }))\n const passedBranch = branches.find((b) => statusOf(b.outcomes) === 'pass')\n\n const baseStatus = statusOf(base)\n let status: ContractStatus = baseStatus\n if (baseStatus === 'pass' && branches.length > 0 && !passedBranch) {\n status = branches.some((b) => statusOf(b.outcomes) === 'error') ? 'error' : 'fail'\n }\n\n const ruleExecutions: ContractRuleExecution[] = [\n ...contract.rules.map((rule, i) => execution(rule.label, undefined, base[i]!)),\n ...branches.flatMap((b) =>\n b.alternative.rules.map((rule, i) => execution(rule.label, b.alternative.id, b.outcomes[i]!)),\n ),\n ]\n const violations = base.flatMap((o) => o.violations)\n if (branches.length > 0 && !passedBranch) {\n for (const b of branches) {\n for (const o of b.outcomes) {\n violations.push(\n ...o.violations.map((v) => ({ ...v, rule: `${b.alternative.id}/${v.rule}` })),\n )\n }\n }\n }\n const errors = ruleExecutions\n .filter((e) => e.status === 'error')\n .map((e) => `${e.alternative ? `${e.alternative}/` : ''}${e.rule}: ${e.error}`)\n\n const scores: Record<string, number> = {}\n contract.rules.forEach((rule, i) => {\n const s = base[i]!.status\n if (s !== 'error') scores[rule.label] = s === 'pass' ? 1 : 0\n })\n if (branches.length > 0 && (passedBranch || status !== 'error'))\n scores.anyOf = passedBranch ? 1 : 0\n const total = contract.rules.length + (branches.length > 0 ? 1 : 0)\n const passCount = Object.values(scores).filter((s) => s === 1).length\n\n const assumptions: string[] = []\n for (const rule of [...contract.rules, ...branches.flatMap((b) => b.alternative.rules)]) {\n if (rulePredicates(rule).some(usesCustom)) {\n assumptions.push(`rule '${rule.label}' rests on a custom predicate function`)\n }\n }\n return {\n contract: contract.name,\n status,\n valid: status === 'pass',\n score: passCount / total,\n scores,\n violations,\n ruleExecutions,\n errors,\n notes:\n `${passCount}/${total} rules passed` +\n (errors.length > 0 ? `; ${errors.length} could not be evaluated` : ''),\n certification: {\n strategy: 'invariant',\n checker: { name: 'agent-eval:trace-contracts', version: packageVersion() },\n assumptions,\n evidenceDigest: certificationEvidenceDigest({\n contract: contract.name,\n status,\n scores,\n violations,\n ruleExecutions,\n }),\n },\n }\n}\n\nfunction execution(\n rule: string,\n alternative: string | undefined,\n outcome: RuleOutcome,\n): ContractRuleExecution {\n return {\n rule,\n ...(alternative === undefined ? {} : { alternative }),\n status: outcome.status,\n violations: outcome.violations.length,\n ...(outcome.error === undefined ? {} : { error: outcome.error }),\n }\n}\n\nfunction rulePredicates(rule: ContractRule): SpanPredicate[] {\n switch (rule.kind) {\n case 'precedes':\n return [rule.a, rule.b]\n case 'neverUnless':\n return [rule.p, rule.prior]\n case 'run':\n case 'toolsOffered':\n case 'retrySafe':\n return []\n default:\n return [rule.p]\n }\n}\n\nfunction usesCustom(p: SpanPredicate): boolean {\n return typeof p.custom === 'function' || (p.not !== undefined && usesCustom(p.not))\n}\n\n/**\n * Evaluate many contracts over one span sequence. Throws on an empty\n * contract list — `allValid: true` over zero contracts is a silent pass.\n */\nexport function checkTraceContracts(\n spans: readonly ContractSpan[],\n contracts: readonly TraceContract[],\n options: EvaluateTraceContractOptions = {},\n): ContractCheckResult {\n if (contracts.length === 0) {\n throw new ValidationError(\n 'checkTraceContracts: empty contract list would vacuously pass — supply at least one contract',\n )\n }\n const verdicts = contracts.map((c) => evaluateTraceContract(c, spans, options))\n const status: ContractStatus = verdicts.some((v) => v.status === 'error')\n ? 'error'\n : verdicts.every((v) => v.status === 'pass')\n ? 'pass'\n : 'fail'\n return { verdicts, status, allValid: status === 'pass' }\n}\n","/**\n * The spans a trace contract reads from a recorded harness session.\n *\n * A session becomes one root span for the session, one LLM span per assistant\n * message that answered with text, and one TOOL span per tool call, in the\n * session's recorded order. A tool span carries the call's arguments as `args`\n * and its input and result text as `input.value` and `output.value`; an LLM\n * span carries its text as `output.value`. Calls and messages a fork copied\n * from its parent are the parent's work and are left out.\n */\n\nimport type { HarnessSession } from '@tangle-network/harness-sessions'\nimport type { ContractSpan } from './types'\n\nfunction epochMs(at: string | null): number | undefined {\n if (at === null) return undefined\n const value = Date.parse(at)\n return Number.isFinite(value) ? value : undefined\n}\n\nfunction timed(\n start: string | null,\n end: string | null,\n): Pick<ContractSpan, 'startedAt' | 'endedAt'> {\n const startedAt = epochMs(start)\n const endedAt = epochMs(end) ?? startedAt\n return {\n ...(startedAt === undefined ? {} : { startedAt }),\n ...(endedAt === undefined ? {} : { endedAt }),\n }\n}\n\nexport function contractSpansFromHarnessSession(session: HarnessSession): ContractSpan[] {\n const root = `session:${session.nativeSessionId}`\n const spans: ContractSpan[] = [\n {\n spanId: root,\n parentSpanId: null,\n name: 'session',\n kind: 'AGENT',\n ...timed(session.startedAt, session.endedAt),\n attributes: { 'session.harness': session.harness },\n },\n ]\n const calls = new Map(session.toolCalls.map((call) => [call.id, call]))\n const placed = new Set<string>()\n const toolSpan = (id: string): void => {\n const call = calls.get(id)\n if (call === undefined || placed.has(id) || call.inherited === true) return\n placed.add(id)\n const input = call.inputText ?? JSON.stringify(call.input ?? null)\n spans.push({\n spanId: `tool:${call.id}`,\n parentSpanId: root,\n name: call.name,\n kind: 'TOOL',\n toolName: call.name,\n ...timed(call.startedAt, call.endedAt ?? call.result?.at ?? null),\n ...(call.status === 'error' || call.result?.isError === true\n ? { status: 'error' }\n : call.status === 'completed'\n ? { status: 'ok' }\n : {}),\n args: call.input,\n attributes: {\n 'input.value': input,\n ...(call.result?.text ? { 'output.value': call.result.text } : {}),\n },\n })\n }\n for (const message of session.messages) {\n if (message.inherited === true || message.role !== 'assistant') continue\n const text = message.parts\n .flatMap((part) => (part.type === 'text' ? [part.text] : []))\n .join('\\n')\n .trim()\n if (text !== '') {\n spans.push({\n spanId: `llm:${message.id}`,\n parentSpanId: root,\n name: 'llm.call',\n kind: 'LLM',\n ...timed(message.at, message.at),\n attributes: { 'output.value': text },\n })\n }\n for (const part of message.parts) if (part.type === 'tool-call') toolSpan(part.toolCallId)\n }\n for (const call of session.toolCalls) toolSpan(call.id)\n return spans\n}\n","/**\n * The raw-finding wire contract — one decoder for both sides of the process\n * boundary.\n *\n * A finding array crosses a process boundary twice: an optimizer bridge writes\n * it in Python, TypeScript reads it back. Two decoders written independently\n * accept different shapes, so Python could report a completed investigation\n * whose rows TypeScript then dropped — the paid work disappearing between two\n * \"successes\". This module is the TypeScript half; `finding_contract.json`\n * carries the same rules to the Python half, generated from the schema here.\n *\n * Decoding never invents an empty result. A value that is not an array of rows\n * fails with the exact type it was, and a malformed row is reported with its\n * index and path while its valid siblings survive.\n */\n\nimport { type RawAnalystFinding, RawAnalystFindingSchema } from './finding-signature'\nimport { parseFindingSubject } from './finding-subject'\nimport { coerceJson } from './parse-tolerant'\n\n/**\n * Version of the wire contract both languages implement. Bump when the\n * accepted row shape changes; the Python package pins the same value, and the\n * emitted contract carries it so a mismatched pair is visible.\n */\nexport const FINDING_WIRE_CONTRACT_VERSION = 1\n\n/** Why one row was refused. Stable across languages: Python reports the same codes. */\ntype FindingRejectionCode = 'not-an-object' | 'schema' | 'invalid-subject' | 'row-limit'\n\n/** A refused row, named precisely enough to repair or report. */\ninterface RejectedFindingRow {\n /** Position in the submitted array. */\n readonly index: number\n /** Dotted path to the offending field, `''` for the row itself. */\n readonly path: string\n readonly code: FindingRejectionCode\n readonly message: string\n}\n\ninterface DecodedFindingArray {\n readonly accepted: RawAnalystFinding[]\n readonly rejected: RejectedFindingRow[]\n /**\n * Set when the value was not a finding array at all — the array itself is\n * the failure, so `accepted` and `rejected` are both empty and a caller must\n * not read the result as \"no findings\".\n */\n readonly topLevelError?: string\n}\n\n/**\n * Rows past this count are refused rather than validated. A model that emits\n * thousands of rows has lost the plot, and the diagnostics for them would\n * dwarf the answer they came with.\n */\nexport const MAX_FINDING_ROWS = 500\n\n/**\n * Decode a submitted findings value into accepted rows plus per-row\n * diagnostics.\n *\n * Accepts an array of rows, or a string carrying one (a JSON array, possibly\n * fenced). Anything else — an object, a number, null, undefined — sets\n * `topLevelError` naming the type received: a caller that asked for findings\n * and got a number has a defect to report, not an empty result to record.\n */\nexport function decodeRawFindingArray(value: unknown): DecodedFindingArray {\n const rows = findingRows(value)\n if (typeof rows === 'string') return { accepted: [], rejected: [], topLevelError: rows }\n\n const accepted: RawAnalystFinding[] = []\n const rejected: RejectedFindingRow[] = []\n for (const [index, row] of rows.entries()) {\n if (index >= MAX_FINDING_ROWS) {\n rejected.push({\n index,\n path: '',\n code: 'row-limit',\n message: `findings array exceeds ${MAX_FINDING_ROWS} rows`,\n })\n continue\n }\n const decoded = decodeRow(row, index)\n if ('finding' in decoded) accepted.push(decoded.finding)\n else rejected.push(decoded.rejection)\n }\n return { accepted, rejected }\n}\n\nfunction decodeRow(\n row: unknown,\n index: number,\n): { finding: RawAnalystFinding } | { rejection: RejectedFindingRow } {\n if (row === null || typeof row !== 'object' || Array.isArray(row)) {\n return {\n rejection: {\n index,\n path: '',\n code: 'not-an-object',\n message: `finding row must be an object, received ${describe(row)}`,\n },\n }\n }\n const parsed = RawAnalystFindingSchema.safeParse(row)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n const path = (issue?.path ?? []).join('.')\n // The schema refines `subject` against the grammar; name that refusal\n // separately so a repair turn can be told which rule the row broke.\n const code: FindingRejectionCode =\n path === 'subject' && parseFindingSubject((row as { subject?: string }).subject) === null\n ? 'invalid-subject'\n : 'schema'\n return {\n rejection: { index, path, code, message: issue?.message ?? 'row does not match the schema' },\n }\n }\n return { finding: parsed.data }\n}\n\n/**\n * Narrow a submitted value to candidate rows, or return the message naming why\n * it is not a findings array at all.\n */\nfunction findingRows(value: unknown): unknown[] | string {\n if (Array.isArray(value)) return value\n if (typeof value === 'string') {\n const parsed = coerceJson(value)\n if (parsed === undefined) {\n return 'findings must be a JSON array; the string received is not JSON'\n }\n if (Array.isArray(parsed)) return parsed\n const unwrapped = findingsProperty(parsed)\n if (unwrapped !== undefined) return unwrapped\n return `findings must be a JSON array, received ${describe(parsed)}`\n }\n const unwrapped = findingsProperty(value)\n if (unwrapped !== undefined) return unwrapped\n return `findings must be an array, received ${describe(value)}`\n}\n\n/** `{ findings: [...] }` is the one wrapper models emit often enough to unwrap. */\nfunction findingsProperty(value: unknown): unknown[] | undefined {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined\n const inner = (value as Record<string, unknown>).findings\n return Array.isArray(inner) ? inner : undefined\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (Array.isArray(value)) return 'an array'\n return `a ${typeof value}`\n}\n","import { randomBytes } from 'node:crypto'\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport {\n type ExternalOptimizerCallbackLimits,\n resolveExternalOptimizerCallbackLimits,\n} from '../campaign/external-optimizer-contracts'\nimport {\n closeServer,\n listenLocal,\n sendJsonIfOpen,\n waitForActiveHandlers,\n} from '../campaign/external-optimizer-http'\nimport { isRecord } from '../llm-client/json'\nimport type { TraceAnalysisToolDescriptor } from '../trace-analyst/tools'\n\ninterface TraceToolCallback {\n url: string\n token: string\n calls: () => number\n close: () => Promise<void>\n}\n\nexport type TraceToolCallbackLimits = ExternalOptimizerCallbackLimits\n\n/** Expose one bounded trace-tool set only on an authenticated loopback socket. */\nexport async function startTraceToolCallback(args: {\n tools: readonly TraceAnalysisToolDescriptor[]\n maxCalls: number\n /** Trace-tool request/response byte limits. Omitted fields use finite defaults. */\n limits?: Partial<TraceToolCallbackLimits>\n signal?: AbortSignal\n}): Promise<TraceToolCallback> {\n if (!Number.isSafeInteger(args.maxCalls) || args.maxCalls <= 0) {\n throw new TypeError('trace tool callback maxCalls must be a positive safe integer')\n }\n const limits = resolveExternalOptimizerCallbackLimits(args.limits, 'trace tool callback limits')\n args.signal?.throwIfAborted()\n const byName = new Map(args.tools.map((tool) => [tool.name, tool]))\n if (byName.size !== args.tools.length) {\n throw new Error('trace tool callback received duplicate tool names')\n }\n\n const token = randomBytes(32).toString('hex')\n let calls = 0\n let accepting = true\n let closePromise: Promise<void> | undefined\n const activeControllers = new Set<AbortController>()\n const activeHandlers = new Set<Promise<void>>()\n const server = createServer((request, response) => {\n if (!accepting) {\n sendJsonIfOpen(response, 503, { error: 'trace tool callback is closing' })\n return\n }\n const controller = new AbortController()\n const abortRequest = (): void => {\n request.destroy()\n response.destroy()\n }\n activeControllers.add(controller)\n controller.signal.addEventListener('abort', abortRequest, { once: true })\n\n let handler!: Promise<void>\n handler = handleRequest(request, response, controller.signal).finally(() => {\n controller.signal.removeEventListener('abort', abortRequest)\n activeControllers.delete(controller)\n activeHandlers.delete(handler)\n })\n activeHandlers.add(handler)\n void handler.catch(() => undefined)\n })\n const port = await listenLocal(server)\n const close = (): Promise<void> => {\n closePromise ??= closeCallback()\n return closePromise\n }\n const onAbort = (): void => {\n void close().catch(() => undefined)\n }\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n\n return {\n url: `http://127.0.0.1:${port}/call`,\n token,\n calls: () => calls,\n close,\n }\n\n async function handleRequest(\n request: IncomingMessage,\n response: ServerResponse,\n signal: AbortSignal,\n ): Promise<void> {\n try {\n if (request.method !== 'POST' || request.url !== '/call') {\n sendJsonIfOpen(response, 404, { error: 'not found' })\n return\n }\n if (request.headers.authorization !== `Bearer ${token}`) {\n sendJsonIfOpen(response, 401, { error: 'unauthorized' })\n return\n }\n if (calls >= args.maxCalls) {\n sendJsonIfOpen(response, 429, { error: 'trace tool call limit reached' })\n return\n }\n const body = await readJson(request, limits.maxRequestBytes)\n if (!isRecord(body) || typeof body.name !== 'string' || !('args' in body)) {\n sendJsonIfOpen(response, 400, { error: 'name and args are required' })\n return\n }\n const tool = byName.get(body.name)\n if (!tool) {\n sendJsonIfOpen(response, 404, { error: `unknown trace tool '${body.name}'` })\n return\n }\n calls += 1\n const result = await tool.handler(body.args, { signal })\n const encoded = JSON.stringify({ result })\n if (Buffer.byteLength(encoded) > limits.maxResponseBytes) {\n sendJsonIfOpen(response, 413, { error: 'trace tool response too large' })\n return\n }\n response.writeHead(200, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': String(Buffer.byteLength(encoded)),\n })\n response.end(encoded)\n } catch (error) {\n sendJsonIfOpen(response, signal.aborted ? 499 : 400, {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n async function closeCallback(): Promise<void> {\n args.signal?.removeEventListener('abort', onAbort)\n accepting = false\n const closingServer = closeServer(server)\n server.closeIdleConnections?.()\n for (const controller of activeControllers) controller.abort()\n const [serverResult] = await Promise.allSettled([\n closingServer,\n waitForActiveHandlers(activeHandlers),\n ])\n if (activeControllers.size !== 0 || activeHandlers.size !== 0) {\n throw new Error('trace tool callback closed with active requests')\n }\n if (serverResult?.status === 'rejected') throw serverResult.reason\n }\n}\n\nfunction readJson(request: IncomingMessage, maxRequestBytes: number): Promise<unknown> {\n return new Promise((resolve, reject) => {\n let size = 0\n const chunks: Buffer[] = []\n request.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > maxRequestBytes) {\n reject(new Error('trace tool request too large'))\n request.destroy()\n return\n }\n chunks.push(chunk)\n })\n request.on('error', reject)\n request.on('end', () => {\n try {\n resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))\n } catch (error) {\n reject(error)\n }\n })\n })\n}\n","import {\n assertExternalOptimizerModelBudget,\n type ExternalOptimizerModelCall,\n type ExternalOptimizerModelExecutionObservation,\n type ExternalOptimizerModelProxy,\n type ExternalOptimizerRunnerCommand,\n removeCredentialEnvironment,\n resolveExternalOptimizerCallbackLimits,\n resolveExternalOptimizerProcessLimits,\n} from '../campaign/external-optimizer-contracts'\nimport { startExternalOptimizerModelProxy } from '../campaign/external-optimizer-model-proxy'\nimport { runWithCleanup } from '../campaign/external-optimizer-resources'\nimport { runExternalOptimizerProcess } from '../campaign/external-optimizer-subprocess'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport { isRecord } from '../llm-client/json'\nimport { resolveModelPricing } from '../metrics'\nimport {\n DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS,\n type TraceAnalysisEngine,\n type TraceAnalysisEngineResult,\n} from './engine'\nimport { decodeRawFindingArray } from './finding-codec'\nimport { startTraceToolCallback, type TraceToolCallbackLimits } from './trace-tool-callback'\n\nconst DEFAULT_TIMEOUT_MS = 10 * 60_000\nconst DEFAULT_MAX_COST_USD = 1\nconst DEFAULT_MAX_MODEL_REQUEST_BYTES = 16 * 1024 * 1024\nconst DEFAULT_MAX_MODEL_RESPONSE_BYTES = 4 * 1024 * 1024\nconst DEFAULT_TRACE_TOOL_TIMEOUT_MS = 60_000\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\nconst BRIDGE_MODULE = 'agent_eval_rpc.dspy_rlm_bridge'\n/** Bumped whenever this engine's execution behavior changes. */\nconst DSPY_RLM_ENGINE_VERSION = '2.0.2'\n\nexport interface DspyRlmTraceEngineOptions {\n /** Caller-owned execution path. Agent Eval never receives provider credentials. */\n call: ExternalOptimizerModelCall\n /** Stable public identity for the caller-owned path, such as an AgentProfile digest. */\n callRef: string\n /** Persist the finite execution record returned for every admitted call. */\n recordExecution: (observation: ExternalOptimizerModelExecutionObservation) => void\n model: string\n /** Exact provider rates. Required when the model is absent from the pricing table. */\n pricing?: CustomTokenPricing\n /** Maximum provider spend for one investigation. Default: 1 USD. */\n maxCostUsd?: number\n /** Controller response cap. Default: {@link DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS}. */\n maxOutputTokens?: number\n /**\n * Thinking tokens one controller turn may bill on top of its completion.\n * A reasoning model bills these beyond `maxOutputTokens`, so the cost\n * reservation must cover them. Default: four times the completion cap.\n */\n maxReasoningTokens?: number\n /** Maximum caller-owned model invocations. Default derives from the analysis limits. */\n maxModelRequests?: number\n /** Maximum model request bytes. Default: 16 MiB. */\n maxModelRequestBytes?: number\n /** Maximum model response bytes. Default: 4 MiB. */\n maxModelResponseBytes?: number\n /** Deadline for one caller-owned model invocation. Default: the whole analysis deadline. */\n modelRequestTimeoutMs?: number\n /** Trace-tool loopback request/response byte limits. */\n traceToolLimits?: Partial<TraceToolCallbackLimits>\n /** Deadline for one Python-to-Node trace-tool call. Default: 60 seconds. */\n traceToolTimeoutMs?: number\n /**\n * How the controller's reasoning and code fields are obtained.\n *\n * `tolerant` parses marker output strictly first, then recovers the fields\n * deterministically from prose plus a fenced code block — the shape coding\n * models naturally emit — at no extra model cost. `two-step` extracts with a\n * second call per turn. `chat` accepts marker output only. Default:\n * `tolerant`.\n */\n controlAdapter?: 'chat' | 'two-step' | 'tolerant'\n /** Python command used to load agent-eval-rpc[dspy]. Default: python. */\n runner?: ExternalOptimizerRunnerCommand\n /** Whole investigation deadline. Default: 10 minutes. */\n timeoutMs?: number\n}\n\n/** Use the official DSPy RLM as a bounded recursive trace-analysis engine. */\nexport function createDspyRlmTraceEngine(options: DspyRlmTraceEngineOptions): TraceAnalysisEngine {\n assertOptions(options)\n const maxOutputTokens = options.maxOutputTokens ?? DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS\n if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) {\n throw new TypeError('DSPy RLM maxOutputTokens must be a positive safe integer')\n }\n const controlAdapter = options.controlAdapter ?? 'tolerant'\n const maxReasoningTokens = options.maxReasoningTokens ?? maxOutputTokens * 4\n if (!Number.isSafeInteger(maxReasoningTokens) || maxReasoningTokens < 0) {\n throw new TypeError('DSPy RLM maxReasoningTokens must be a non-negative safe integer')\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n assertTimerDelay(timeoutMs, 'timeoutMs')\n const maxCostUsd = options.maxCostUsd ?? DEFAULT_MAX_COST_USD\n if (!Number.isFinite(maxCostUsd) || maxCostUsd <= 0) {\n throw new TypeError('DSPy RLM maxCostUsd must be positive and finite')\n }\n const pricing = options.pricing ?? pricingForModel(options.model)\n const maxModelRequestBytes = options.maxModelRequestBytes ?? DEFAULT_MAX_MODEL_REQUEST_BYTES\n const maxModelResponseBytes = options.maxModelResponseBytes ?? DEFAULT_MAX_MODEL_RESPONSE_BYTES\n const modelRequestTimeoutMs = options.modelRequestTimeoutMs ?? timeoutMs\n const traceToolTimeoutMs = options.traceToolTimeoutMs ?? DEFAULT_TRACE_TOOL_TIMEOUT_MS\n assertExternalOptimizerModelBudget(\n {\n maxCostUsd,\n maxRequests: options.maxModelRequests ?? 1,\n maxRequestBytes: maxModelRequestBytes,\n maxResponseBytes: maxModelResponseBytes,\n maxOutputTokensPerRequest: maxOutputTokens,\n maxReasoningTokensPerRequest: maxReasoningTokens,\n pricing,\n requestTimeoutMs: modelRequestTimeoutMs,\n },\n 'DSPy RLM model limits',\n )\n resolveExternalOptimizerCallbackLimits(options.traceToolLimits, 'DSPy RLM trace tool limits')\n assertTimerDelay(traceToolTimeoutMs, 'traceToolTimeoutMs')\n\n const runner = sanitizedRunner(options.runner)\n const processLimits = resolveExternalOptimizerProcessLimits(runner?.limits)\n return {\n id: 'dspy-rlm',\n description: 'Official DSPy RLM with bounded trace tools and metered model calls.',\n model: options.model,\n version: DSPY_RLM_ENGINE_VERSION,\n executionConfig: {\n bridge_module: BRIDGE_MODULE,\n call_ref: options.callRef,\n model: options.model,\n pricing: { ...pricing },\n max_cost_usd: maxCostUsd,\n max_output_tokens: maxOutputTokens,\n max_reasoning_tokens: maxReasoningTokens,\n control_adapter: controlAdapter,\n timeout_ms: timeoutMs,\n max_model_requests: options.maxModelRequests ?? null,\n max_request_bytes: maxModelRequestBytes,\n max_response_bytes: maxModelResponseBytes,\n model_request_timeout_ms: modelRequestTimeoutMs,\n trace_tool_limits: options.traceToolLimits ?? null,\n trace_tool_timeout_ms: traceToolTimeoutMs,\n process_limits: processLimits,\n runner: runner ? 'caller-supplied' : 'default',\n runner_command: runner?.command ?? null,\n },\n async analyze(request) {\n const callback = await startTraceToolCallback({\n tools: request.tools,\n maxCalls: request.limits.maxToolCalls,\n ...(options.traceToolLimits ? { limits: options.traceToolLimits } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n let modelProxy: ExternalOptimizerModelProxy | undefined\n const modelExecutions: ExternalOptimizerModelExecutionObservation[] = []\n const result = await runWithCleanup({\n label: 'DSPy RLM trace-analysis resources',\n run: async () => {\n modelProxy = await startExternalOptimizerModelProxy({\n call: options.call,\n callRef: options.callRef,\n recordExecution: (observation) => {\n modelExecutions.push(structuredClone(observation))\n options.recordExecution(observation)\n },\n model: options.model,\n budget: {\n maxCostUsd,\n maxRequests: resolveMaxModelRequests(options.maxModelRequests, request.limits),\n maxRequestBytes: maxModelRequestBytes,\n maxResponseBytes: maxModelResponseBytes,\n maxOutputTokensPerRequest: maxOutputTokens,\n maxReasoningTokensPerRequest: maxReasoningTokens,\n requestTimeoutMs: modelRequestTimeoutMs,\n pricing,\n },\n costLedger: request.costLedger,\n channel: 'analyst',\n phase: request.costPhase,\n actor: request.analystId,\n ...(request.costTags ? { tags: request.costTags } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n request.log?.('trace analyst engine started', {\n engine: 'dspy-rlm',\n model: options.model,\n tools: request.tools.map((tool) => tool.name),\n limits: request.limits,\n })\n const raw = await runExternalOptimizerProcess<unknown>({\n label: 'DSPy RLM trace analysis',\n tempPrefix: 'agent-eval-dspy-rlm-',\n module: BRIDGE_MODULE,\n input: {\n operation: 'analyze',\n question: request.question,\n instructions: request.instructions,\n modelProxy: {\n baseUrl: modelProxy.baseUrl,\n apiKey: modelProxy.apiKey,\n model: options.model,\n maxOutputTokens,\n },\n toolCallback: {\n url: callback.url,\n token: callback.token,\n timeoutMs: traceToolTimeoutMs,\n },\n toolSpecs: request.tools.map(({ name, description, parameters }) => ({\n name,\n description,\n parameters,\n })),\n controlAdapter,\n limits: {\n maxIterations: request.limits.maxIterations,\n maxLlmCalls: request.limits.maxLlmCalls,\n maxOutputChars: request.limits.maxOutputChars,\n },\n // Omitted entirely when the caller supplied none, so a request\n // without structured inputs sends the payload it always sent.\n ...(request.taskInputs ? { taskInputs: request.taskInputs } : {}),\n },\n ...(runner ? { runner } : {}),\n additionalArgs: ['--max-input-bytes', String(processLimits.maxInputBytes)],\n timeoutMs,\n ...(request.signal ? { signal: request.signal } : {}),\n })\n const parsed = parseBridgeOutput(raw, (index, reason) => {\n request.log?.('finding rejected: bridge row failed schema validation', {\n engine: 'dspy-rlm',\n index,\n reason,\n })\n })\n const successfulCompletions = modelProxy.successfulCompletions()\n const requestAttempts = modelProxy.requestAttempts()\n if (parsed.modelCalls !== successfulCompletions) {\n throw new Error(\n `DSPy RLM reported ${parsed.modelCalls} model calls, but the provider proxy recorded ${successfulCompletions}`,\n )\n }\n modelProxy.assertExecutionComplete()\n return {\n ...parsed,\n toolCalls: callback.calls(),\n runtime: {\n ...parsed.runtime,\n modelRequestAttempts: requestAttempts,\n modelSuccessfulCompletions: successfulCompletions,\n modelExecutions,\n },\n } satisfies TraceAnalysisEngineResult\n },\n cleanup: async () => {\n const results = await Promise.allSettled([\n ...(modelProxy ? [modelProxy.close()] : []),\n callback.close(),\n ])\n const errors = results.flatMap((entry) =>\n entry.status === 'rejected' ? [entry.reason] : [],\n )\n if (errors.length > 0) {\n throw new AggregateError(errors, 'DSPy RLM resource cleanup failed')\n }\n if (modelProxy) {\n request.recordActivity?.({\n modelCalls: modelProxy.successfulCompletions(),\n toolCalls: callback.calls(),\n })\n }\n },\n })\n request.log?.('trace analyst engine completed', {\n engine: 'dspy-rlm',\n model_calls: result.modelCalls,\n model_request_attempts: result.runtime.modelRequestAttempts,\n tool_calls: result.toolCalls,\n findings: result.findings.length,\n })\n return result\n },\n }\n}\n\nfunction parseBridgeOutput(\n value: unknown,\n onRejectedFinding: (index: number, reason: string) => void,\n): Omit<TraceAnalysisEngineResult, 'toolCalls'> {\n if (!isRecord(value)) throw new Error('DSPy RLM bridge output must be an object')\n if (typeof value.answer !== 'string' || !value.answer.trim()) {\n throw new Error('DSPy RLM bridge returned no answer')\n }\n // Findings are model output: one malformed row is model noise, not a bridge\n // fault, and the rest of the paid investigation must survive it. The codec\n // is the same decoder the Python side runs, so a row this bridge accepts is\n // a row the optimizer could report, and vice versa.\n const decoded = decodeRawFindingArray(value.findings)\n if (decoded.topLevelError !== undefined) {\n throw new Error(`DSPy RLM bridge findings must be an array: ${decoded.topLevelError}`)\n }\n const findings = decoded.accepted\n const rejectedFindings = decoded.rejected.length\n for (const rejection of decoded.rejected) {\n onRejectedFinding(\n rejection.index,\n `${rejection.code}${rejection.path ? ` at ${rejection.path}` : ''}: ${rejection.message}`,\n )\n }\n if (!Array.isArray(value.trajectory)) {\n throw new Error('DSPy RLM bridge trajectory must be an array')\n }\n if (!Number.isSafeInteger(value.modelCalls) || (value.modelCalls as number) <= 0) {\n throw new Error('DSPy RLM bridge modelCalls must be a positive safe integer')\n }\n if (!isRecord(value.runtime)) {\n throw new Error('DSPy RLM bridge runtime must be an object')\n }\n return {\n answer: value.answer,\n findings,\n trajectory: value.trajectory,\n modelCalls: value.modelCalls as number,\n runtime: { ...value.runtime, rejectedFindings },\n }\n}\n\nfunction assertOptions(options: DspyRlmTraceEngineOptions): void {\n for (const [name, value] of [\n ['callRef', options.callRef],\n ['model', options.model],\n ] as const) {\n if (typeof value !== 'string' || !value.trim() || value !== value.trim()) {\n throw new TypeError(`DSPy RLM ${name} must be a trimmed non-empty string`)\n }\n }\n if (typeof options.call !== 'function') {\n throw new TypeError('DSPy RLM call must be a function')\n }\n if (typeof options.recordExecution !== 'function') {\n throw new TypeError('DSPy RLM recordExecution must be a function')\n }\n if (\n options.maxModelRequests !== undefined &&\n (!Number.isSafeInteger(options.maxModelRequests) || options.maxModelRequests <= 0)\n ) {\n throw new TypeError('DSPy RLM maxModelRequests must be a positive safe integer')\n }\n}\n\nfunction resolveMaxModelRequests(\n configured: number | undefined,\n limits: { maxIterations: number; maxLlmCalls: number },\n): number {\n if (configured !== undefined) return configured\n const derived = limits.maxIterations + limits.maxLlmCalls + 1\n if (!Number.isSafeInteger(derived) || derived <= 0) {\n throw new Error('DSPy RLM analysis limits produce an invalid model request limit')\n }\n return derived\n}\n\nfunction assertTimerDelay(value: number, field: string): void {\n if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) {\n throw new TypeError(`DSPy RLM ${field} must be between 1 and ${MAX_TIMER_DELAY_MS}`)\n }\n}\n\nfunction pricingForModel(model: string): CustomTokenPricing {\n const pricing = resolveModelPricing(model)\n if (!pricing) {\n throw new Error(\n `no pricing is configured for '${model}'; provide DspyRlmTraceEngineOptions.pricing`,\n )\n }\n return {\n inputUsdPerMillion: pricing.input * 1_000,\n outputUsdPerMillion: pricing.output * 1_000,\n }\n}\n\nfunction sanitizedRunner(\n runner: ExternalOptimizerRunnerCommand | undefined,\n): ExternalOptimizerRunnerCommand | undefined {\n if (!runner) return undefined\n return {\n ...(runner.command ? { command: runner.command } : {}),\n ...(runner.args ? { args: runner.args } : {}),\n ...(runner.env ? { env: removeCredentialEnvironment(runner.env) } : {}),\n ...(runner.limits ? { limits: { ...runner.limits } } : {}),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAM,6CAA4D,IAAI,IAAI,CACxE,CAAC,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