@tangle-network/agent-eval 0.79.0 → 0.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +101 -169
  3. package/dist/adapters/http.d.ts +2 -2
  4. package/dist/adapters/langchain.d.ts +2 -2
  5. package/dist/adapters/otel.d.ts +4 -4
  6. package/dist/{agent-profile-aSEaJ9Pl.d.ts → agent-profile-D0PBIWlV.d.ts} +14 -2
  7. package/dist/analyst/index.d.ts +10 -10
  8. package/dist/analyst/index.js +3 -3
  9. package/dist/{analyst-t7zZS3TV.d.ts → analyst-C8HHvfJp.d.ts} +1 -1
  10. package/dist/belief-state/index.d.ts +524 -0
  11. package/dist/belief-state/index.js +1862 -0
  12. package/dist/belief-state/index.js.map +1 -0
  13. package/dist/benchmarks/index.d.ts +2 -2
  14. package/dist/calibration-Cpr3WaX3.d.ts +101 -0
  15. package/dist/campaign/index.d.ts +40 -120
  16. package/dist/campaign/index.js +129 -238
  17. package/dist/campaign/index.js.map +1 -1
  18. package/dist/chunk-4DIJWVUT.js +131 -0
  19. package/dist/chunk-4DIJWVUT.js.map +1 -0
  20. package/dist/{chunk-RPLZ4OIB.js → chunk-BABOZOSN.js} +7 -4
  21. package/dist/{chunk-RPLZ4OIB.js.map → chunk-BABOZOSN.js.map} +1 -1
  22. package/dist/{chunk-IHDHUN2X.js → chunk-CVVHBFGN.js} +3 -3
  23. package/dist/chunk-CVVHBFGN.js.map +1 -0
  24. package/dist/{chunk-B26KI423.js → chunk-FZWAFVAA.js} +2 -2
  25. package/dist/{chunk-ITBRCT73.js → chunk-IDVBLYCY.js} +2 -10
  26. package/dist/chunk-IDVBLYCY.js.map +1 -0
  27. package/dist/{chunk-5LVWPNS5.js → chunk-L5G7OUKD.js} +4 -4
  28. package/dist/{chunk-5LVWPNS5.js.map → chunk-L5G7OUKD.js.map} +1 -1
  29. package/dist/chunk-NPCTHQIO.js +91 -0
  30. package/dist/chunk-NPCTHQIO.js.map +1 -0
  31. package/dist/{chunk-GXHLRXDI.js → chunk-OTYQPHPL.js} +4 -4
  32. package/dist/{chunk-6REHLN5J.js → chunk-QS3RBQPI.js} +2 -2
  33. package/dist/{chunk-GWGO2K6Y.js → chunk-RBNA5AZT.js} +2 -2
  34. package/dist/chunk-S42AWHMP.js +697 -0
  35. package/dist/chunk-S42AWHMP.js.map +1 -0
  36. package/dist/chunk-VI2UW6B6.js +162 -0
  37. package/dist/chunk-VI2UW6B6.js.map +1 -0
  38. package/dist/{chunk-CF67I6QY.js → chunk-VIDQF3F5.js} +2 -2
  39. package/dist/{chunk-XXNIODOM.js → chunk-WJL2NJXN.js} +3 -3
  40. package/dist/{chunk-LB2UOI5F.js → chunk-YGYXHNAQ.js} +47 -160
  41. package/dist/chunk-YGYXHNAQ.js.map +1 -0
  42. package/dist/{chunk-KX6F6NCG.js → chunk-Z7VFTS2J.js} +2 -2
  43. package/dist/{chunk-ZPSKPT3V.js → chunk-ZZ2HOPME.js} +5 -2
  44. package/dist/chunk-ZZ2HOPME.js.map +1 -0
  45. package/dist/cli.js +2 -2
  46. package/dist/code-agent-session-BRXmavYv.d.ts +80 -0
  47. package/dist/contract/index.d.ts +132 -18
  48. package/dist/contract/index.js +139 -6
  49. package/dist/contract/index.js.map +1 -1
  50. package/dist/{control-CehLtoET.d.ts → control-GeE8OhpN.d.ts} +1 -1
  51. package/dist/control.d.ts +2 -2
  52. package/dist/governance/index.d.ts +1 -1
  53. package/dist/hosted/index.d.ts +4 -4
  54. package/dist/{index-B1RKber3.d.ts → index-DE3RXAXD.d.ts} +1 -1
  55. package/dist/index.d.ts +79 -288
  56. package/dist/index.js +87 -410
  57. package/dist/index.js.map +1 -1
  58. package/dist/{insight-report-dlpEzQDi.d.ts → insight-report-3ADTfClO.d.ts} +1 -1
  59. package/dist/{kind-factory-DqV2t1Xk.d.ts → kind-factory-CVecZZG_.d.ts} +2 -2
  60. package/dist/{llm-client-DbjLfz-K.d.ts → llm-client-CuUg2Mn3.d.ts} +1 -1
  61. package/dist/meta-eval/index.d.ts +6 -99
  62. package/dist/meta-eval/index.js +7 -76
  63. package/dist/meta-eval/index.js.map +1 -1
  64. package/dist/off-policy-DiwuKKg7.d.ts +132 -0
  65. package/dist/openapi.json +1 -1
  66. package/dist/{outcome-store-D6KWmYvj.d.ts → outcome-store-rnXLEqSn.d.ts} +1 -1
  67. package/dist/pipelines/index.js +2 -2
  68. package/dist/{provenance-CEAJI9rm.d.ts → provenance-B9Q4886D.d.ts} +4 -4
  69. package/dist/{registry-BmEuU94S.d.ts → registry-DrEQ3Luj.d.ts} +2 -2
  70. package/dist/{release-report-CXXZlR8g.d.ts → release-report-hlNtD12q.d.ts} +2 -2
  71. package/dist/reporting.d.ts +6 -6
  72. package/dist/reporting.js +3 -3
  73. package/dist/{researcher-rInLj9De.d.ts → researcher-BLPHBbNV.d.ts} +3 -3
  74. package/dist/rl.d.ts +11 -141
  75. package/dist/rl.js +10 -124
  76. package/dist/rl.js.map +1 -1
  77. package/dist/{rubric-predictive-validity-CWyWWLBg.d.ts → rubric-predictive-validity-CnEl9Jc8.d.ts} +2 -2
  78. package/dist/{run-campaign-OVEZF24D.js → run-campaign-4Y5V5CN3.js} +3 -3
  79. package/dist/{run-improvement-loop-Bgu4C59E.d.ts → run-improvement-loop-D6PZOoQL.d.ts} +2 -2
  80. package/dist/{run-record-sItO5ftF.d.ts → run-record-De9VarXR.d.ts} +1 -1
  81. package/dist/{semantic-concept-judge-Du4ZVyef.d.ts → semantic-concept-judge-DIEgr_6v.d.ts} +6 -6
  82. package/dist/{statistics-B7yCbi9i.d.ts → statistics-CnC1FMbx.d.ts} +3 -7
  83. package/dist/{store-GmBE2pZZ.d.ts → store-C1YxJDEK.d.ts} +1 -1
  84. package/dist/{summary-report-BTaXq1TS.d.ts → summary-report-Db0dDSWP.d.ts} +1 -1
  85. package/dist/traces.d.ts +5 -5
  86. package/dist/{types-DRvV0zRo.d.ts → types-Cu3u_x59.d.ts} +3 -3
  87. package/dist/{types-QHG0KnkF.d.ts → types-D7lLRYe9.d.ts} +2 -2
  88. package/dist/wire/index.js +2 -2
  89. package/dist/workflow/index.d.ts +7 -7
  90. package/dist/workflow/index.js +1 -1
  91. package/docs/concepts.md +1 -0
  92. package/docs/research/belief-state-agent-eval-roadmap.md +590 -0
  93. package/docs/research/research-roadmap.md +1 -0
  94. package/docs/self-improvement-map.md +111 -0
  95. package/package.json +7 -2
  96. package/dist/chunk-IHDHUN2X.js.map +0 -1
  97. package/dist/chunk-ITBRCT73.js.map +0 -1
  98. package/dist/chunk-LB2UOI5F.js.map +0 -1
  99. package/dist/chunk-ZPSKPT3V.js.map +0 -1
  100. /package/dist/{chunk-B26KI423.js.map → chunk-FZWAFVAA.js.map} +0 -0
  101. /package/dist/{chunk-GXHLRXDI.js.map → chunk-OTYQPHPL.js.map} +0 -0
  102. /package/dist/{chunk-6REHLN5J.js.map → chunk-QS3RBQPI.js.map} +0 -0
  103. /package/dist/{chunk-GWGO2K6Y.js.map → chunk-RBNA5AZT.js.map} +0 -0
  104. /package/dist/{chunk-CF67I6QY.js.map → chunk-VIDQF3F5.js.map} +0 -0
  105. /package/dist/{chunk-XXNIODOM.js.map → chunk-WJL2NJXN.js.map} +0 -0
  106. /package/dist/{chunk-KX6F6NCG.js.map → chunk-Z7VFTS2J.js.map} +0 -0
  107. /package/dist/{run-campaign-OVEZF24D.js.map → run-campaign-4Y5V5CN3.js.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  confidenceInterval
3
- } from "./chunk-ITBRCT73.js";
3
+ } from "./chunk-IDVBLYCY.js";
4
4
  import {
5
5
  AgentEvalError
6
6
  } from "./chunk-3BFEG2F6.js";
@@ -168,6 +168,9 @@ async function runCampaign(opts) {
168
168
  const now = opts.now ?? (() => /* @__PURE__ */ new Date());
169
169
  const judges = opts.judges ?? [];
170
170
  const storage = opts.storage ?? fsCampaignStorage();
171
+ if (typeof opts.runDir !== "string" || opts.runDir.trim().length === 0) {
172
+ throw new Error("runCampaign: runDir is required and must be a non-empty string");
173
+ }
171
174
  storage.ensureDir(opts.runDir);
172
175
  const manifestHash = computeManifestHash({
173
176
  scenarios: opts.scenarios,
@@ -535,4 +538,4 @@ export {
535
538
  inMemoryCampaignStorage,
536
539
  runCampaign
537
540
  };
538
- //# sourceMappingURL=chunk-ZPSKPT3V.js.map
541
+ //# sourceMappingURL=chunk-ZZ2HOPME.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/campaign/run-campaign.ts","../src/integrity/backend-integrity.ts","../src/campaign/storage.ts"],"sourcesContent":["/**\n * @experimental\n *\n * `runCampaign` — Pass A substrate primitive. ONE function that orchestrates\n * scenarios → dispatch → artifacts → judges → aggregates, with full\n * reproducibility (seed + manifest hash), cell-level resumability, bootstrap\n * CIs, and the `LabeledScenarioStore` capture flywheel.\n *\n * Improvement loops (optimizer / gate / autoOnPromote) ride on top of this\n * primitive but live in `presets/run-improvement-loop.ts`. This file keeps\n * the core orchestrator minimal — Phase 1 of the Pass A track.\n */\n\nimport { createHash } from 'node:crypto'\nimport { join } from 'node:path'\nimport { BackendIntegrityError, type BackendIntegrityReport } from '../integrity/backend-integrity'\nimport { confidenceInterval } from '../statistics'\nimport { type CampaignStorage, fsCampaignStorage } from './storage'\nimport type {\n CampaignAggregates,\n CampaignArtifactWriter,\n CampaignCellResult,\n CampaignCostMeter,\n CampaignResult,\n CampaignTokenUsage,\n CampaignTraceWriter,\n DispatchContext,\n DispatchFn,\n JudgeAggregate,\n JudgeConfig,\n JudgeScore,\n LabeledScenarioStore,\n Scenario,\n ScenarioAggregate,\n TraceSpan,\n} from './types'\n\nexport interface RunCampaignOptions<TScenario extends Scenario, TArtifact> {\n scenarios: TScenario[]\n dispatch: DispatchFn<TScenario, TArtifact>\n judges?: JudgeConfig<TArtifact, TScenario>[]\n /** Required for reproducibility. Default 42. */\n seed?: number\n /** Per-scenario replicates for CI bands. Default 1; raise to 5+ for\n * bootstrap-tight intervals on critical eval. */\n reps?: number\n /** When true (default), completed cells are cached by\n * (manifestHash, scenarioId, rep, generation). Re-runs skip cached cells. */\n resumable?: boolean\n /** Optional store — when present, every artifact + judge score is captured\n * with the configured `captureSource`. Capture is default ON; pass `'off'`\n * to disable. */\n labeledStore?: LabeledScenarioStore | 'off'\n captureSource?: 'production-trace' | 'eval-run' | 'manual' | 'red-team' | 'synthetic'\n captureSourceVersionHash?: string\n /** Wall-clock cost cap across all cells. Cells beyond ceiling are skipped. */\n costCeiling?: number\n /** Max concurrent cells. Default 2. */\n maxConcurrency?: number\n /**\n * Per-cell dispatch deadline in ms. A `dispatch` that neither resolves nor\n * rejects within this window is a hang (a stalled model request, an\n * exhausted runtime resource, a backend that never closes its stream). When\n * set, the cell's `ctx.signal` is aborted and the cell is recorded as a LOUD\n * error (`dispatch exceeded <N>ms`) so the campaign proceeds and the failure\n * is visible — instead of one wedged cell silently hanging the whole run (and\n * every loop/CI job above it) forever. `undefined`/`0` = unbounded (legacy).\n */\n dispatchTimeoutMs?: number\n /** Required: where artifacts + traces land. */\n runDir: string\n /** Tracing posture. Default is the substrate's `FileSystemTraceStore` rooted\n * at `<runDir>/traces/`. `'off'` disables capture entirely — substrate\n * refuses this when the caller wires `autoOnPromote !== 'none'`. */\n tracing?: 'on' | 'off'\n /**\n * Per-cell usage expectation — the early, fine-grained sibling of the\n * batch `assertRealBackend` guard. A cell that produced an artifact (no\n * error) but reported `costUsd === 0` AND zero tokens is a stub: the\n * dispatch never reported LLM activity via `ctx.cost`. Modes:\n * - `'warn'` (default) — log the offending cell loudly, keep going.\n * - `'assert'` — throw `BackendIntegrityError` on the first such cell\n * (fail-fast; recommended for CI campaigns expecting real LLM calls).\n * - `'off'` — no check (replay / deterministic-only / offline analysis).\n */\n expectUsage?: 'assert' | 'warn' | 'off'\n /** Test seam — override the wall clock for deterministic tests. */\n now?: () => Date\n /** Test seam — override per-cell trace writer factory. */\n buildTraceWriter?: (cellId: string, dir: string) => CampaignTraceWriter\n /** Storage backend for run/cell dirs, the resumability cache, artifacts,\n * and trace spans. Default: the Node filesystem (`fsCampaignStorage`).\n * Pass `inMemoryCampaignStorage()` to run in a filesystem-less runtime\n * (Cloudflare Workers, Deno, edge) — the `CampaignResult` is still\n * produced; artifacts/traces just aren't persisted to disk. */\n storage?: CampaignStorage\n /**\n * Optional per-cell placement strategy. Returns an opaque string the\n * substrate forwards as `ctx.placement` to the Dispatch — placement-aware\n * Dispatches (e.g. `httpDispatch` from `/adapters/http`) use it to route\n * each cell to the right worker, region, or sandbox. When unset, every\n * cell receives `ctx.placement = undefined` and behaves identically to\n * the in-process case.\n *\n * @example\n * cellPlacement: ({ scenario }) => scenario.tags?.includes('eu') ? 'eu-west' : 'us-east'\n */\n cellPlacement?: (input: {\n scenario: TScenario\n rep: number\n generation?: number\n }) => string | undefined\n}\n\nexport async function runCampaign<TScenario extends Scenario, TArtifact>(\n opts: RunCampaignOptions<TScenario, TArtifact>,\n): Promise<CampaignResult<TArtifact, TScenario>> {\n const seed = opts.seed ?? 42\n const reps = opts.reps ?? 1\n const resumable = opts.resumable ?? true\n const maxConcurrency = opts.maxConcurrency ?? 2\n const now = opts.now ?? (() => new Date())\n const judges = opts.judges ?? []\n const storage = opts.storage ?? fsCampaignStorage()\n\n if (typeof opts.runDir !== 'string' || opts.runDir.trim().length === 0) {\n throw new Error('runCampaign: runDir is required and must be a non-empty string')\n }\n storage.ensureDir(opts.runDir)\n\n const manifestHash = computeManifestHash({\n scenarios: opts.scenarios,\n judges: judges as unknown as JudgeConfig<unknown>[],\n dispatchRef: opts.dispatch.name || 'anonymous',\n seed,\n reps,\n })\n\n const startedAt = now()\n const cells: CampaignCellResult<TArtifact>[] = []\n const artifactsByPath: Record<string, string> = {}\n\n // Build the cell schedule (scenario × rep).\n const schedule: Array<{ scenario: TScenario; rep: number; cellId: string; cellSeed: number }> = []\n let cellIndex = 0\n for (const scenario of opts.scenarios) {\n for (let rep = 0; rep < reps; rep++) {\n const cellId = `${scenario.id}:${rep}`\n const cellSeed = seed + cellIndex\n schedule.push({ scenario, rep, cellId, cellSeed })\n cellIndex += 1\n }\n }\n\n // Concurrency-limited execution.\n let totalCostUsd = 0\n let costCeilingReached = false\n const abortController = new AbortController()\n // Concurrency lanes that drain the cell schedule. Named \"lanes\" — not\n // \"workers\" — to avoid clashing with the taxonomy's worker (= the agent\n // harness in a sandbox, invoked behind `dispatch`). See loop-taxonomy.md.\n const lanes: Promise<void>[] = []\n let nextIdx = 0\n const cellsRef = cells\n\n for (let i = 0; i < maxConcurrency; i++) {\n lanes.push(\n (async () => {\n while (true) {\n const myIdx = nextIdx++\n if (myIdx >= schedule.length) return\n const slot = schedule[myIdx]!\n if (costCeilingReached) {\n cellsRef.push(skippedCell(slot, 'cost_ceiling_reached'))\n continue\n }\n const result = await executeCell({\n slot,\n opts,\n manifestHash,\n resumable,\n now,\n storage,\n buildTraceWriter: opts.buildTraceWriter ?? defaultBuildTraceWriter(storage),\n signal: abortController.signal,\n dispatchTimeoutMs: opts.dispatchTimeoutMs,\n })\n cellsRef.push(result.cell)\n enforceCellUsage(result.cell, opts.expectUsage ?? 'warn')\n totalCostUsd += result.cell.costUsd\n Object.assign(artifactsByPath, result.artifactsByPath)\n if (opts.costCeiling !== undefined && totalCostUsd >= opts.costCeiling) {\n costCeilingReached = true\n }\n // Capture into LabeledScenarioStore unless explicitly disabled.\n if (opts.labeledStore && opts.labeledStore !== 'off' && !result.cell.error) {\n await captureToStore({\n store: opts.labeledStore,\n cell: result.cell,\n scenario: slot.scenario,\n opts,\n now,\n }).catch((err) => {\n // Capture failures are non-fatal — log but don't crash the campaign.\n // (Trace would normally land here.)\n console.warn(\n `[runCampaign] capture failed for ${result.cell.cellId}: ${err instanceof Error ? err.message : String(err)}`,\n )\n })\n }\n }\n })(),\n )\n }\n await Promise.all(lanes)\n\n const endedAt = now()\n cellsRef.sort((a, b) => a.cellId.localeCompare(b.cellId))\n\n const aggregates = computeAggregates(\n cellsRef,\n judges as unknown as JudgeConfig<TArtifact>[],\n seed,\n )\n\n return {\n manifestHash,\n seed,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n durationMs: endedAt.getTime() - startedAt.getTime(),\n cells: cellsRef,\n aggregates,\n runDir: opts.runDir,\n artifactsByPath,\n scenarios: opts.scenarios.map((s) => ({ id: s.id, kind: s.kind })),\n }\n}\n\n// ── Internals ─────────────────────────────────────────────────────────\n\ninterface ExecuteCellArgs<TScenario extends Scenario, TArtifact> {\n slot: { scenario: TScenario; rep: number; cellId: string; cellSeed: number }\n opts: RunCampaignOptions<TScenario, TArtifact>\n manifestHash: string\n resumable: boolean\n now: () => Date\n storage: CampaignStorage\n buildTraceWriter: (cellId: string, dir: string) => CampaignTraceWriter\n signal: AbortSignal\n dispatchTimeoutMs?: number\n}\n\nasync function executeCell<TScenario extends Scenario, TArtifact>(\n args: ExecuteCellArgs<TScenario, TArtifact>,\n): Promise<{ cell: CampaignCellResult<TArtifact>; artifactsByPath: Record<string, string> }> {\n const storage = args.storage\n const cellDir = join(args.opts.runDir, args.slot.cellId.replace(/[^a-zA-Z0-9_-]/g, '_'))\n storage.ensureDir(cellDir)\n\n // Resumability: cache key = (manifestHash, scenarioId, rep)\n const cachePath = join(cellDir, 'cached-result.json')\n if (args.resumable) {\n const raw = storage.read(cachePath)\n if (raw !== undefined) {\n try {\n const cached = JSON.parse(raw) as CampaignCellResult<TArtifact>\n if (cached.cellId === args.slot.cellId) {\n return { cell: { ...cached, cached: true }, artifactsByPath: {} }\n }\n } catch {\n // Corrupt cache — fall through to re-run.\n }\n }\n }\n\n const startMs = Date.now()\n const trace = args.buildTraceWriter(args.slot.cellId, cellDir)\n const artifactsByPath: Record<string, string> = {}\n const artifacts: CampaignArtifactWriter = {\n async write(path, content) {\n const fullPath = join(cellDir, path)\n storage.ensureDir(join(fullPath, '..'))\n storage.write(fullPath, content)\n artifactsByPath[`${args.slot.cellId}/${path}`] = fullPath\n return fullPath\n },\n async writeJson(path, value) {\n return artifacts.write(path, JSON.stringify(value, null, 2))\n },\n }\n let costSoFar = 0\n const tokensSoFar: CampaignTokenUsage = { input: 0, output: 0 }\n const cost: CampaignCostMeter = {\n observe(amount, source) {\n costSoFar += amount\n trace.span(`cost.${source}`, { amountUsd: amount }).end()\n },\n observeTokens(usage) {\n tokensSoFar.input += usage.input\n tokensSoFar.output += usage.output\n if (usage.cached) tokensSoFar.cached = (tokensSoFar.cached ?? 0) + usage.cached\n },\n current() {\n return costSoFar\n },\n tokens() {\n return { ...tokensSoFar }\n },\n }\n\n const placement = args.opts.cellPlacement?.({\n scenario: args.slot.scenario,\n rep: args.slot.rep,\n })\n\n // Per-cell abort signal, chained to the campaign signal. The dispatch sees\n // THIS signal so a timeout (below) can abort just this cell's in-flight work\n // without tearing down sibling cells — and a signal-honoring dispatch\n // releases its open request instead of leaking it past the deadline.\n const cellAbort = new AbortController()\n const onCampaignAbort = () => cellAbort.abort((args.signal as { reason?: unknown }).reason)\n if (args.signal.aborted) cellAbort.abort((args.signal as { reason?: unknown }).reason)\n else args.signal.addEventListener('abort', onCampaignAbort, { once: true })\n\n const ctx: DispatchContext = {\n cellId: args.slot.cellId,\n rep: args.slot.rep,\n seed: args.slot.cellSeed,\n signal: cellAbort.signal,\n trace,\n artifacts,\n cost,\n placement,\n }\n\n let artifact: TArtifact | undefined\n let errorMessage: string | undefined\n const timeoutMs = args.dispatchTimeoutMs\n let timeoutTimer: ReturnType<typeof setTimeout> | undefined\n try {\n const dispatched = args.opts.dispatch(args.slot.scenario, ctx)\n if (timeoutMs !== undefined && timeoutMs > 0) {\n // A dispatch that never settles (stalled model request, exhausted runtime\n // resource, a stream that never closes) must NOT hang the cell — and with\n // it the lane, the campaign, the loop, the CI job — forever. Race it\n // against the deadline; on timeout, abort the cell and fail it LOUD.\n artifact = await Promise.race([\n dispatched,\n new Promise<never>((_, reject) => {\n timeoutTimer = setTimeout(() => {\n cellAbort.abort(new Error('dispatch timeout'))\n reject(\n new Error(\n `dispatch exceeded ${timeoutMs}ms for cell '${args.slot.cellId}' — aborted and failed loud (no silent hang)`,\n ),\n )\n }, timeoutMs)\n if (typeof (timeoutTimer as { unref?: () => void }).unref === 'function')\n (timeoutTimer as { unref: () => void }).unref()\n }),\n ])\n } else {\n artifact = await dispatched\n }\n } catch (err) {\n errorMessage = err instanceof Error ? err.message : String(err)\n } finally {\n if (timeoutTimer) clearTimeout(timeoutTimer)\n args.signal.removeEventListener('abort', onCampaignAbort)\n }\n\n // Run judges (only if we have an artifact). A judge that throws invalidates\n // the cell — recorded as `error`, NOT folded into a fake composite:0 (a fake\n // zero is indistinguishable from a real zero and poisons every aggregate).\n const judgeScores: Record<string, JudgeScore> = {}\n if (artifact !== undefined) {\n for (const judge of args.opts.judges ?? []) {\n if (judge.appliesTo && !judge.appliesTo(args.slot.scenario)) continue\n try {\n judgeScores[judge.name] = await runJudgeCell(judge, {\n artifact,\n scenario: args.slot.scenario,\n signal: args.signal,\n })\n } catch (err) {\n errorMessage = `judge '${judge.name}' failed: ${err instanceof Error ? err.message : String(err)}`\n break\n }\n }\n }\n\n await trace.flush()\n\n const cell: CampaignCellResult<TArtifact> = {\n cellId: args.slot.cellId,\n scenarioId: args.slot.scenario.id,\n rep: args.slot.rep,\n artifact: (artifact ?? null) as TArtifact,\n judgeScores,\n costUsd: costSoFar,\n tokenUsage: { ...tokensSoFar },\n durationMs: Date.now() - startMs,\n seed: args.slot.cellSeed,\n cached: false,\n error: errorMessage,\n }\n\n if (!errorMessage && args.resumable) {\n storage.write(cachePath, JSON.stringify(cell))\n }\n\n return { cell, artifactsByPath }\n}\n\n/**\n * Per-cell stub guard. A cell that produced an artifact (no error) but reported\n * `costUsd === 0` AND zero tokens means the dispatch never called `ctx.cost` —\n * i.e. it ran against a stub or silently dropped its usage. `'warn'` logs it,\n * `'assert'` throws (fail-fast), `'off'` skips. An errored/skipped cell or a\n * deterministic judge-only run that genuinely made no LLM call is not flagged.\n */\nfunction enforceCellUsage<TArtifact>(\n cell: CampaignCellResult<TArtifact>,\n mode: 'assert' | 'warn' | 'off',\n): void {\n if (mode === 'off' || cell.error) return\n if (cell.artifact === null || cell.artifact === undefined) return\n const zeroTokens = cell.tokenUsage.input === 0 && cell.tokenUsage.output === 0\n if (cell.costUsd !== 0 || !zeroTokens) return\n const msg = `cell '${cell.cellId}' produced an artifact but reported zero cost and zero tokens — the dispatch never reported LLM usage via ctx.cost.observe/observeTokens (a stub cell)`\n if (mode === 'assert') {\n const report: BackendIntegrityReport = {\n totalRecords: 1,\n stubRecords: 1,\n realRecords: 0,\n uncostedRecords: 0,\n totalInputTokens: 0,\n totalOutputTokens: 0,\n totalCostUsd: 0,\n verdict: 'stub',\n diagnosis: msg,\n }\n throw new BackendIntegrityError(`expectUsage: ${msg}`, report)\n }\n // eslint-disable-next-line no-console\n console.warn(`[runCampaign] expectUsage: ${msg}`)\n}\n\nasync function runJudgeCell<TArtifact, TScenario extends Scenario>(\n judge: JudgeConfig<TArtifact, TScenario>,\n input: { artifact: TArtifact; scenario: TScenario; signal: AbortSignal },\n): Promise<JudgeScore> {\n return judge.score(input)\n}\n\nfunction defaultBuildTraceWriter(\n storage: CampaignStorage,\n): (cellId: string, dir: string) => CampaignTraceWriter {\n return (cellId, dir) => {\n const spans: Array<Record<string, unknown>> = []\n return {\n span(name, attributes) {\n const startMs = Date.now()\n const record: Record<string, unknown> = { name, cellId, startMs, ...(attributes ?? {}) }\n const finish: TraceSpan = {\n end(endAttrs) {\n record.durationMs = Date.now() - startMs\n if (endAttrs) Object.assign(record, endAttrs)\n spans.push(record)\n },\n setAttribute(key, value) {\n record[key] = value\n },\n }\n return finish\n },\n async flush() {\n storage.write(join(dir, 'spans.jsonl'), spans.map((s) => JSON.stringify(s)).join('\\n'))\n },\n }\n }\n}\n\nfunction skippedCell<TScenario extends Scenario, TArtifact>(\n slot: { scenario: TScenario; rep: number; cellId: string; cellSeed: number },\n reason: string,\n): CampaignCellResult<TArtifact> {\n return {\n cellId: slot.cellId,\n scenarioId: slot.scenario.id,\n rep: slot.rep,\n artifact: null as unknown as TArtifact,\n judgeScores: {},\n costUsd: 0,\n tokenUsage: { input: 0, output: 0 },\n durationMs: 0,\n seed: slot.cellSeed,\n cached: false,\n error: `skipped: ${reason}`,\n }\n}\n\ninterface CaptureArgs<TScenario extends Scenario, TArtifact> {\n store: LabeledScenarioStore\n cell: CampaignCellResult<TArtifact>\n scenario: TScenario\n opts: RunCampaignOptions<TScenario, TArtifact>\n now: () => Date\n}\n\nasync function captureToStore<TScenario extends Scenario, TArtifact>(\n args: CaptureArgs<TScenario, TArtifact>,\n): Promise<void> {\n await args.store.observe({\n scenario: args.scenario,\n artifact: args.cell.artifact,\n judgeScores: args.cell.judgeScores,\n source: args.opts.captureSource ?? 'eval-run',\n sourceVersionHash: args.opts.captureSourceVersionHash ?? 'unknown',\n capturedAt: args.now().toISOString(),\n redactionStatus: 'raw',\n })\n}\n\n// ── Aggregates + manifest hash ────────────────────────────────────────\n\nfunction computeManifestHash(input: {\n scenarios: Scenario[]\n judges: JudgeConfig<unknown>[]\n dispatchRef: string\n seed: number\n reps: number\n}): string {\n const canonical = {\n scenarios: input.scenarios.map((s) => ({ id: s.id, kind: s.kind })),\n judges: input.judges.map((j) => ({ name: j.name, dims: j.dimensions.map((d) => d.key) })),\n dispatch: input.dispatchRef,\n seed: input.seed,\n reps: input.reps,\n }\n return createHash('sha256').update(JSON.stringify(canonical)).digest('hex')\n}\n\nfunction computeAggregates<TArtifact>(\n cells: CampaignCellResult<TArtifact>[],\n judges: JudgeConfig<TArtifact>[],\n seed: number,\n): CampaignAggregates {\n const byJudge: Record<string, JudgeAggregate> = {}\n for (const judge of judges) {\n const scores: number[] = []\n for (const cell of cells) {\n const s = cell.judgeScores[judge.name]\n if (s !== undefined) scores.push(s.composite)\n }\n byJudge[judge.name] = aggregate(scores, seed)\n }\n const byScenario: Record<string, ScenarioAggregate> = {}\n const scenarioGroups = new Map<string, number[]>()\n for (const cell of cells) {\n const composites = Object.values(cell.judgeScores).map((s) => s.composite)\n if (composites.length === 0) continue\n const mean = composites.reduce((a, b) => a + b, 0) / composites.length\n const arr = scenarioGroups.get(cell.scenarioId) ?? []\n arr.push(mean)\n scenarioGroups.set(cell.scenarioId, arr)\n }\n for (const [scenarioId, samples] of scenarioGroups) {\n const ag = aggregate(samples, seed)\n byScenario[scenarioId] = { meanComposite: ag.mean, ci95: ag.ci95, n: ag.n }\n }\n return {\n byJudge,\n byScenario,\n totalCostUsd: cells.reduce((a, c) => a + c.costUsd, 0),\n cellsExecuted: cells.filter((c) => !c.error).length,\n cellsSkipped: cells.filter((c) => c.error?.startsWith('skipped:')).length,\n cellsCached: cells.filter((c) => c.cached).length,\n cellsFailed: cells.filter((c) => c.error && !c.error.startsWith('skipped:')).length,\n }\n}\n\n// Percentile bootstrap CI95 via seeded resampling. Deterministic for a given\n// seed — same campaign re-run produces identical CI bands. Falls back to\n// degenerate intervals at n<=1 (the bootstrap is undefined there).\nfunction aggregate(samples: number[], seed: number): JudgeAggregate {\n const n = samples.length\n if (n === 0) return { mean: 0, stdev: 0, ci95: [0, 0], n: 0 }\n const mean = samples.reduce((a, b) => a + b, 0) / n\n const variance = samples.reduce((a, b) => a + (b - mean) ** 2, 0) / Math.max(1, n - 1)\n const stdev = Math.sqrt(variance)\n const ci = confidenceInterval(samples, 0.95, { seed, resamples: 1000 })\n return { mean, stdev, ci95: [ci.lower, ci.upper], n }\n}\n","/**\n * Backend-integrity guard: distinguish \"agent failed\" from \"eval ran against\n * a stub / unconfigured backend.\" Without this guard a canonical eval can\n * silently report `0/N passed` and look like an agent-quality problem when\n * the LLM was never actually called — the failure mode we just hit running\n * the 4-vertical parallel eval (legal-sandbox-stub returned hard-coded 33-104\n * char strings; gtm/creative defaulted to a cli-bridge that wasn't running).\n *\n * The shape:\n *\n * const report = summarizeBackendIntegrity(records)\n * assertRealBackend(records) // throws BackendIntegrityError if 100% stub\n *\n * A record is \"stub-mode\" if its `tokenUsage.input === 0 && tokenUsage.output === 0`.\n * (`costUsd` alone is unreliable — some backends successfully call LLMs but\n * don't propagate pricing, producing real tokens with $0 cost.)\n *\n * Verdicts:\n * - `real` — at least one record has nonzero token usage\n * - `stub` — every record is stub-mode (eval ran blind)\n * - `mixed` — some records real, some stub (partial backend failure;\n * often the 429-cascade or auth-half-failed case)\n */\n\nimport { AgentEvalError } from '../errors'\nimport type { RunRecord } from '../run-record'\n\nexport interface BackendIntegrityReport {\n /** Total records inspected. */\n totalRecords: number\n /** Records with input=0 AND output=0 (a stub fingerprint). */\n stubRecords: number\n /** Records with nonzero token usage (real LLM activity). */\n realRecords: number\n /** Records where output>0 but costUsd=0 (real LLM, broken cost ledger). */\n uncostedRecords: number\n /** Sum of input tokens across all records. */\n totalInputTokens: number\n /** Sum of output tokens across all records. */\n totalOutputTokens: number\n /** Sum of costUsd across all records. */\n totalCostUsd: number\n /** Worst-case integrity verdict. */\n verdict: 'real' | 'mixed' | 'stub'\n /** Human-readable diagnosis suitable for terminal output. */\n diagnosis: string\n}\n\n/**\n * Error thrown when an integrity assertion fails. Caller can pattern-match\n * by `code === 'AGENT_EVAL_BACKEND_STUB'` to differentiate from other\n * errors.\n */\nexport class BackendIntegrityError extends AgentEvalError {\n constructor(\n message: string,\n public readonly report: BackendIntegrityReport,\n ) {\n super('backend_integrity', message)\n }\n}\n\nfunction isStubRecord(rec: RunRecord): boolean {\n return rec.tokenUsage.input === 0 && rec.tokenUsage.output === 0\n}\n\nfunction isUncostedRecord(rec: RunRecord): boolean {\n return rec.tokenUsage.output > 0 && rec.costUsd === 0\n}\n\n/**\n * Inspect a batch of RunRecords and return an integrity report. Pure\n * function — no I/O, no logging. The caller decides what to do with the\n * verdict (print warning, throw, gate CI, etc.).\n */\nexport function summarizeBackendIntegrity(\n records: ReadonlyArray<RunRecord>,\n): BackendIntegrityReport {\n const totalRecords = records.length\n let stubRecords = 0\n let realRecords = 0\n let uncostedRecords = 0\n let totalInputTokens = 0\n let totalOutputTokens = 0\n let totalCostUsd = 0\n for (const rec of records) {\n totalInputTokens += rec.tokenUsage.input\n totalOutputTokens += rec.tokenUsage.output\n totalCostUsd += rec.costUsd\n if (isStubRecord(rec)) stubRecords++\n else realRecords++\n if (isUncostedRecord(rec)) uncostedRecords++\n }\n const verdict: BackendIntegrityReport['verdict'] =\n totalRecords === 0\n ? 'stub'\n : stubRecords === totalRecords\n ? 'stub'\n : stubRecords === 0\n ? 'real'\n : 'mixed'\n const diagnosis = buildDiagnosis({\n totalRecords,\n stubRecords,\n realRecords,\n uncostedRecords,\n totalInputTokens,\n totalOutputTokens,\n totalCostUsd,\n verdict,\n })\n return {\n totalRecords,\n stubRecords,\n realRecords,\n uncostedRecords,\n totalInputTokens,\n totalOutputTokens,\n totalCostUsd,\n verdict,\n diagnosis,\n }\n}\n\nfunction buildDiagnosis(r: Omit<BackendIntegrityReport, 'diagnosis'>): string {\n if (r.totalRecords === 0) {\n return 'no records — eval produced zero runs; backend likely failed before first turn'\n }\n if (r.verdict === 'stub') {\n return [\n `all ${r.totalRecords} records have zero token usage — the LLM backend was never called.`,\n 'common causes: --backend sandbox without a sandbox bridge running; stub model returning hard-coded strings;',\n 'auth misconfigured so requests were silently dropped before the LLM. Re-run with --backend tcloud and TANGLE_API_KEY set,',\n 'or boot the cli-bridge / sandbox before invoking the eval.',\n ].join(' ')\n }\n if (r.verdict === 'mixed') {\n const pct = ((r.stubRecords / r.totalRecords) * 100).toFixed(0)\n return [\n `${r.stubRecords}/${r.totalRecords} records (${pct}%) have zero token usage — the backend partially failed.`,\n 'common causes: rate-limit cascade (429s after the first N personas);',\n 'transient auth expiry mid-run; provider outage. Treat the affected records as missing data, not agent failures.',\n ].join(' ')\n }\n // verdict === 'real'\n if (r.uncostedRecords > 0) {\n const pct = ((r.uncostedRecords / r.totalRecords) * 100).toFixed(0)\n return [\n `${r.totalRecords} records with real LLM activity (in=${r.totalInputTokens}, out=${r.totalOutputTokens} tokens).`,\n `${r.uncostedRecords} (${pct}%) have output tokens but costUsd=0. Two distinct roots:`,\n '(a) cost ledger mis-wired — no usage propagation from the runtime stream into RunRecord; or',\n '(b) the model is unpriced at the source (sandbox/router returned $0 despite real tokens).',\n 'For (b), price the measured tokens against the substrate table (estimateCost) instead of leaving $0.',\n ].join(' ')\n }\n return `${r.totalRecords} records with real LLM activity (in=${r.totalInputTokens}, out=${r.totalOutputTokens} tokens, $${r.totalCostUsd.toFixed(4)}).`\n}\n\n/**\n * Throw BackendIntegrityError if the verdict is 'stub' — i.e. every record\n * shows zero LLM activity. Non-strict callers can pass `{ allowMixed: false }`\n * to also reject mixed verdicts (recommended for CI gates).\n *\n * Real backends pass through silently.\n */\nexport function assertRealBackend(\n records: ReadonlyArray<RunRecord>,\n opts: { allowMixed?: boolean } = {},\n): BackendIntegrityReport {\n const report = summarizeBackendIntegrity(records)\n const allowMixed = opts.allowMixed ?? true\n if (report.verdict === 'stub') {\n throw new BackendIntegrityError(\n `backend-integrity: ran against a stub or unconfigured backend — ${report.diagnosis}`,\n report,\n )\n }\n if (!allowMixed && report.verdict === 'mixed') {\n throw new BackendIntegrityError(\n `backend-integrity: partial backend failure rejected — ${report.diagnosis}`,\n report,\n )\n }\n return report\n}\n","import { createRequire } from 'node:module'\n\n/**\n * @experimental\n *\n * `CampaignStorage` — the filesystem seam `runCampaign` writes through\n * (run/cell dirs, the resumability cache, per-cell artifacts, trace spans).\n *\n * The default (`fsCampaignStorage`) is the Node filesystem — identical\n * behavior to the inline `node:fs` calls it replaces, so existing CLI\n * consumers are unaffected. `inMemoryCampaignStorage` keeps everything in a\n * `Map`, so the substrate runs in environments WITHOUT a filesystem\n * (Cloudflare Workers, Deno Deploy, other edge runtimes) — the campaign\n * still produces its `CampaignResult` (cells + aggregates) in memory;\n * artifacts/traces simply aren't persisted to disk.\n *\n * Paths are opaque keys to the in-memory adapter — it does not parse them,\n * so the same `join(...)`-built paths work unchanged across both adapters.\n */\nexport interface CampaignStorage {\n /** Ensure a directory exists (recursive). No-op for in-memory. */\n ensureDir(dir: string): void\n /** Does this path exist (as a written file or an ensured dir)? */\n exists(path: string): boolean\n /** Read a UTF-8 file; `undefined` when missing or unreadable. */\n read(path: string): string | undefined\n /** Write a file (string or bytes). Parent dir is assumed ensured. */\n write(path: string, content: string | Uint8Array): void\n}\n\n/** Node-filesystem storage — the default. Lazily requires `node:fs` so the\n * module imports cleanly in non-Node runtimes (where the caller passes\n * `inMemoryCampaignStorage` instead and never constructs this).\n *\n * `createRequire(import.meta.url)` is the ESM-native lazy require — a bare\n * `require` is a ReferenceError under `\"type\": \"module\"`, which is exactly\n * the shape this package publishes. */\nexport function fsCampaignStorage(): CampaignStorage {\n const nodeRequire = createRequire(import.meta.url)\n const { existsSync, mkdirSync, readFileSync, writeFileSync } = nodeRequire(\n 'node:fs',\n ) as typeof import('node:fs')\n return {\n ensureDir(dir) {\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n },\n exists(path) {\n return existsSync(path)\n },\n read(path) {\n try {\n return readFileSync(path, 'utf8')\n } catch {\n return undefined\n }\n },\n write(path, content) {\n writeFileSync(path, content as Uint8Array)\n },\n }\n}\n\n/** In-memory storage for filesystem-less runtimes. Artifacts + trace spans\n * live in a `Map` for the duration of the run; the `CampaignResult` is\n * fully populated, but nothing is persisted to disk. */\nexport function inMemoryCampaignStorage(): CampaignStorage {\n const files = new Map<string, string | Uint8Array>()\n const dirs = new Set<string>()\n return {\n ensureDir(dir) {\n dirs.add(dir)\n },\n exists(path) {\n return files.has(path) || dirs.has(path)\n },\n read(path) {\n const value = files.get(path)\n if (value === undefined) return undefined\n return typeof value === 'string' ? value : new TextDecoder().decode(value)\n },\n write(path, content) {\n files.set(path, content)\n },\n }\n}\n"],"mappings":";;;;;;;;AAaA,SAAS,kBAAkB;AAC3B,SAAS,YAAY;;;ACuCd,IAAM,wBAAN,cAAoC,eAAe;AAAA,EACxD,YACE,SACgB,QAChB;AACA,UAAM,qBAAqB,OAAO;AAFlB;AAAA,EAGlB;AAAA,EAHkB;AAIpB;AAEA,SA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,GAAG,IAAI,CAAC;AACrF,QAAM,QAAQ,KAAK,KAAK,QAAQ;AAChC,QAAM,KAAK,mBAAmB,SAAS,MAAM,EAAE,MAAM,WAAW,IAAK,CAAC;AACtE,SAAO,EAAE,MAAM,OAAO,MAAM,CAAC,GAAG,OAAO,GAAG,KAAK,GAAG,EAAE;AACtD;","names":[]}
package/dist/cli.js CHANGED
@@ -5,8 +5,8 @@ import {
5
5
  runRpcBatch,
6
6
  runRpcOnce,
7
7
  startServer
8
- } from "./chunk-6REHLN5J.js";
9
- import "./chunk-IHDHUN2X.js";
8
+ } from "./chunk-QS3RBQPI.js";
9
+ import "./chunk-CVVHBFGN.js";
10
10
  import "./chunk-PC4UYEBM.js";
11
11
  import "./chunk-3BFEG2F6.js";
12
12
  import "./chunk-PZ5AY32C.js";
@@ -0,0 +1,80 @@
1
+ import { a as RunSplitTag, R as RunRecord } from './run-record-De9VarXR.js';
2
+
3
+ type CodeAgentSessionSource = 'codex' | 'claude-code' | 'opencode' | 'kimi-code' | 'pi';
4
+ interface ParsedCodeAgentJsonl {
5
+ entries: unknown[];
6
+ malformedLines: number;
7
+ }
8
+ interface CodeAgentSessionMetrics {
9
+ entries: number;
10
+ userMessages: number;
11
+ assistantMessages: number;
12
+ reasoningItems: number;
13
+ toolCalls: number;
14
+ toolOutputs: number;
15
+ toolErrors: number;
16
+ patchAttempts: number;
17
+ patchSuccesses: number;
18
+ patchFailures: number;
19
+ turnsStarted: number;
20
+ turnsCompleted: number;
21
+ turnsAborted: number;
22
+ contextCompactions: number;
23
+ prLinks: number;
24
+ fileSnapshots: number;
25
+ graphNodes: number;
26
+ graphEdges: number;
27
+ actionCandidates: number;
28
+ verificationReports: number;
29
+ completionDecisions: number;
30
+ reliabilityRows: number;
31
+ reliabilityLift: number;
32
+ inputTokens: number;
33
+ outputTokens: number;
34
+ cachedTokens: number;
35
+ observedCostUsd: number;
36
+ wallMs: number;
37
+ processScore: number;
38
+ }
39
+ interface CodeAgentSessionDiagnostic {
40
+ source: CodeAgentSessionSource;
41
+ sessionId: string;
42
+ sourcePath?: string;
43
+ entries: number;
44
+ malformedLines: number;
45
+ inferredScore: boolean;
46
+ hasExplicitTerminalSignal: boolean;
47
+ hasQualityLabel: boolean;
48
+ hasTokenUsage: boolean;
49
+ hasCost: boolean;
50
+ warnings: string[];
51
+ }
52
+ interface CodeAgentSessionIntakeResult {
53
+ runs: RunRecord[];
54
+ diagnostics: CodeAgentSessionDiagnostic[];
55
+ metrics: CodeAgentSessionMetrics[];
56
+ }
57
+ interface CodeAgentSessionIntakeOptions {
58
+ entries: unknown[];
59
+ malformedLines?: number;
60
+ sourcePath?: string;
61
+ experimentId?: string;
62
+ candidateId?: string;
63
+ seed?: number;
64
+ splitTag?: RunSplitTag;
65
+ scenarioId?: string;
66
+ model?: string;
67
+ promptHash?: string;
68
+ configHash?: string;
69
+ commitSha?: string;
70
+ score?: number;
71
+ }
72
+ declare function parseCodeAgentJsonl(jsonl: string): ParsedCodeAgentJsonl;
73
+ declare function fromCodexSession(options: CodeAgentSessionIntakeOptions): CodeAgentSessionIntakeResult;
74
+ declare function fromClaudeCodeSession(options: CodeAgentSessionIntakeOptions): CodeAgentSessionIntakeResult;
75
+ declare function fromOpenCodeSession(options: CodeAgentSessionIntakeOptions): CodeAgentSessionIntakeResult;
76
+ declare function fromKimiCodeSession(options: CodeAgentSessionIntakeOptions): CodeAgentSessionIntakeResult;
77
+ declare function fromPiSession(options: CodeAgentSessionIntakeOptions): CodeAgentSessionIntakeResult;
78
+ declare const fromPigraphSession: typeof fromPiSession;
79
+
80
+ export { type CodeAgentSessionDiagnostic as C, type ParsedCodeAgentJsonl as P, type CodeAgentSessionIntakeOptions as a, type CodeAgentSessionIntakeResult as b, type CodeAgentSessionMetrics as c, type CodeAgentSessionSource as d, fromCodexSession as e, fromClaudeCodeSession as f, fromKimiCodeSession as g, fromOpenCodeSession as h, fromPiSession as i, fromPigraphSession as j, parseCodeAgentJsonl as p };
@@ -1,31 +1,32 @@
1
- import { S as Scenario, M as MutableSurface, b as DispatchContext, a as JudgeConfig, I as ImprovementDriver, G as Gate } from '../types-QHG0KnkF.js';
2
- export { C as CampaignAggregates, c as CampaignArtifactWriter, d as CampaignCellResult, e as CampaignCostMeter, f as CampaignResult, g as CampaignTraceWriter, h as CodeSurface, D as Dispatch, i as GateContext, j as GateDecision, k as GateResult, l as GenerationCandidate, m as GenerationRecord, n as JudgeDimension, J as JudgeScore, o as Mutator, O as OptimizerConfig, p as SessionScript } from '../types-QHG0KnkF.js';
3
- import { L as LoopProvenanceRecord } from '../provenance-CEAJI9rm.js';
4
- export { A as AxisEvidence, a as AxisVerdict, B as BuildEvidenceVectorOptions, D as DefaultProductionGateOptions, E as EvidenceVector, b as EvolutionaryDriverOptions, H as HeldOutGateOptions, O as ObjectiveSource, P as ParetoSignificanceGateOptions, c as PromotionObjective, d as PromotionPolicy, R as RunEvalOptions, e as buildEvidenceVector, f as composeGate, g as defaultProductionGate, h as evolutionaryDriver, i as heldOutGate, p as paretoPolicy, j as paretoSignificanceGate, r as runEval } from '../provenance-CEAJI9rm.js';
5
- import { C as CampaignStorage, R as RunImprovementLoopResult } from '../run-improvement-loop-Bgu4C59E.js';
6
- export { G as GepaDriverOptions, a as RunCampaignOptions, b as RunImprovementLoopOptions, f as fsCampaignStorage, g as gepaDriver, i as inMemoryCampaignStorage, r as runCampaign, c as runImprovementLoop } from '../run-improvement-loop-Bgu4C59E.js';
7
- export { D as DeploymentOutcome, F as FileSystemOutcomeStore, b as FileSystemOutcomeStoreOptions, I as InMemoryOutcomeStore, O as OutcomeStore } from '../outcome-store-D6KWmYvj.js';
8
- import { HostedTenant, TraceSpanEvent } from '../hosted/index.js';
9
- import { R as RunRecord, b as RunSplitTag } from '../run-record-sItO5ftF.js';
10
- import { I as InsightReport } from '../insight-report-dlpEzQDi.js';
11
- export { F as FailureClusterInsight, a as InterRaterInsight, J as JudgeInsight, L as LiftInsight, O as OutcomeCorrelationInsight, R as Recommendation, b as ReleaseSummary, S as ScalarDistribution } from '../insight-report-dlpEzQDi.js';
12
- import { A as AnalystRegistry } from '../registry-BmEuU94S.js';
1
+ import { S as Scenario, M as MutableSurface, b as DispatchContext, a as JudgeConfig, I as ImprovementDriver, G as Gate, c as GateDecision } from '../types-D7lLRYe9.js';
2
+ export { C as CampaignAggregates, d as CampaignArtifactWriter, e as CampaignCellResult, f as CampaignCostMeter, g as CampaignResult, h as CampaignTraceWriter, i as CodeSurface, D as Dispatch, j as GateContext, k as GateResult, l as GenerationCandidate, m as GenerationRecord, n as JudgeDimension, J as JudgeScore, o as Mutator, O as OptimizerConfig, p as SessionScript } from '../types-D7lLRYe9.js';
3
+ import { L as LoopProvenanceRecord } from '../provenance-B9Q4886D.js';
4
+ export { A as AxisEvidence, a as AxisVerdict, B as BuildEvidenceVectorOptions, D as DefaultProductionGateOptions, E as EvidenceVector, b as EvolutionaryDriverOptions, H as HeldOutGateOptions, O as ObjectiveSource, P as ParetoSignificanceGateOptions, c as PromotionObjective, d as PromotionPolicy, R as RunEvalOptions, e as buildEvidenceVector, f as composeGate, g as defaultProductionGate, h as evolutionaryDriver, i as heldOutGate, p as paretoPolicy, j as paretoSignificanceGate, r as runEval } from '../provenance-B9Q4886D.js';
5
+ import { C as CampaignStorage, R as RunImprovementLoopResult } from '../run-improvement-loop-D6PZOoQL.js';
6
+ export { G as GepaDriverOptions, a as RunCampaignOptions, b as RunImprovementLoopOptions, f as fsCampaignStorage, g as gepaDriver, i as inMemoryCampaignStorage, r as runCampaign, c as runImprovementLoop } from '../run-improvement-loop-D6PZOoQL.js';
7
+ export { D as DeploymentOutcome, F as FileSystemOutcomeStore, a as FileSystemOutcomeStoreOptions, I as InMemoryOutcomeStore, b as OutcomeStore } from '../outcome-store-rnXLEqSn.js';
8
+ import { HostedTenant, EvalRunCellScore, EvalRunGenerationSnapshot, EvalRunEvent, TraceSpanEvent } from '../hosted/index.js';
9
+ import { R as RunRecord, a as RunSplitTag } from '../run-record-De9VarXR.js';
10
+ import { I as InsightReport } from '../insight-report-3ADTfClO.js';
11
+ export { F as FailureClusterInsight, a as InterRaterInsight, J as JudgeInsight, L as LiftInsight, O as OutcomeCorrelationInsight, R as Recommendation, b as ReleaseSummary, S as ScalarDistribution } from '../insight-report-3ADTfClO.js';
12
+ import { a as AnalystRegistry } from '../registry-DrEQ3Luj.js';
13
13
  import { a as DatasetScenario } from '../dataset-B2kL-fSM.js';
14
+ export { C as CodeAgentSessionDiagnostic, a as CodeAgentSessionIntakeOptions, b as CodeAgentSessionIntakeResult, c as CodeAgentSessionMetrics, d as CodeAgentSessionSource, P as ParsedCodeAgentJsonl, f as fromClaudeCodeSession, e as fromCodexSession, g as fromKimiCodeSession, h as fromOpenCodeSession, i as fromPiSession, j as fromPigraphSession, p as parseCodeAgentJsonl } from '../code-agent-session-BRXmavYv.js';
14
15
  import '../red-team-DW9Ca_tj.js';
15
16
  import '../store-CKUAgsJz.js';
16
17
  import '../schema-m0gsnbt3.js';
17
18
  import '../pareto-E-pembql.js';
18
- import '../statistics-B7yCbi9i.js';
19
+ import '../statistics-CnC1FMbx.js';
19
20
  import '../judge-calibration-DilmB3Ml.js';
20
21
  import '../types-Croy5h7V.js';
21
22
  import '@tangle-network/tcloud';
22
- import '../llm-client-DbjLfz-K.js';
23
+ import '../llm-client-CuUg2Mn3.js';
23
24
  import '../errors-Dwqw-T_m.js';
24
25
  import '../raw-provider-sink-C46HDghv.js';
25
- import '../summary-report-BTaXq1TS.js';
26
+ import '../summary-report-Db0dDSWP.js';
26
27
  import '../failure-cluster-CL7IVgkJ.js';
27
- import '../types-DRvV0zRo.js';
28
- import '../store-GmBE2pZZ.js';
28
+ import '../types-Cu3u_x59.js';
29
+ import '../store-C1YxJDEK.js';
29
30
 
30
31
  /**
31
32
  * # `selfImprove()` — the LAND-tier one-shot.
@@ -351,6 +352,119 @@ interface AnalyzeRunsOptions {
351
352
  }
352
353
  declare function analyzeRuns(opts: AnalyzeRunsOptions): Promise<InsightReport>;
353
354
 
355
+ /**
356
+ * # `@tangle-network/agent-eval/contract` — eval-run diff primitive.
357
+ *
358
+ * The substrate side of the v-N-versus-v-N+1 dashboard view. Given two
359
+ * `EvalRunEvent`s (or two `EvalRunGenerationSnapshot`s from one run), this
360
+ * returns a normalised diff: per-cell composite + per-judge/per-dimension
361
+ * deltas, surface-hash change, aggregate cost + duration shifts.
362
+ *
363
+ * Consumed by:
364
+ * - The hosted-tier dashboard (intelligence-web) — renders v3 vs v4
365
+ * comparisons of cells × judges × dimensions.
366
+ * - CI reporting — emits a "shipped: composite +0.07, cost +$1.20" line
367
+ * in PR review for autonomous-improvement runs.
368
+ * - Any downstream consumer that needs "what actually changed" without
369
+ * reimplementing the matching + arithmetic.
370
+ *
371
+ * Cells are matched on the natural composite key `(scenarioId, rep)`.
372
+ * Unmatched cells surface as `removed` / `added` so callers can tell
373
+ * "this cell got worse" from "this cell wasn't run."
374
+ */
375
+
376
+ /** Per-dimension delta. `before` / `after` are null when the judge did not
377
+ * emit a value for that side. `delta` is `after - before`; null when
378
+ * either side is null. */
379
+ interface EvalDimensionDelta {
380
+ before: number | null;
381
+ after: number | null;
382
+ delta: number | null;
383
+ }
384
+ /** Per-cell delta, keyed on `(scenarioId, rep)`. */
385
+ interface EvalCellScoreDelta {
386
+ scenarioId: string;
387
+ rep: number;
388
+ compositeBefore: number;
389
+ compositeAfter: number;
390
+ compositeDelta: number;
391
+ /** Per-judge → per-dimension deltas. Outer key = judge name from
392
+ * `EvalRunCellScore.dimensions`; inner key = dimension name. */
393
+ dimensions: Record<string, Record<string, EvalDimensionDelta>>;
394
+ }
395
+ /** Diff between two generation snapshots — the unit the dashboard renders
396
+ * for a single "v3 vs v4" comparison. */
397
+ interface EvalGenerationDiff {
398
+ beforeIndex: number;
399
+ afterIndex: number;
400
+ beforeSurfaceHash: string;
401
+ afterSurfaceHash: string;
402
+ surfaceChanged: boolean;
403
+ /** Cells present in both snapshots, matched on `(scenarioId, rep)`. */
404
+ matched: EvalCellScoreDelta[];
405
+ /** Cells present in `before` but missing from `after`. */
406
+ removed: EvalRunCellScore[];
407
+ /** Cells present in `after` but missing from `before`. */
408
+ added: EvalRunCellScore[];
409
+ /** Aggregate composite mean across all cells in the snapshot. */
410
+ compositeBefore: number;
411
+ compositeAfter: number;
412
+ compositeDelta: number;
413
+ costUsdBefore: number;
414
+ costUsdAfter: number;
415
+ costUsdDelta: number;
416
+ durationMsBefore: number;
417
+ durationMsAfter: number;
418
+ durationMsDelta: number;
419
+ }
420
+ /** Diff between two full eval-runs. Includes both baseline-vs-baseline and
421
+ * winner-vs-winner generation diffs when both sides expose them, plus
422
+ * run-level metadata. */
423
+ interface EvalRunDiff {
424
+ beforeRunId: string;
425
+ afterRunId: string;
426
+ beforeTimestamp: string;
427
+ afterTimestamp: string;
428
+ beforeGateDecision: GateDecision | null;
429
+ afterGateDecision: GateDecision | null;
430
+ beforeHoldoutLift: number | null;
431
+ afterHoldoutLift: number | null;
432
+ holdoutLiftDelta: number | null;
433
+ beforeTotalCostUsd: number;
434
+ afterTotalCostUsd: number;
435
+ totalCostUsdDelta: number;
436
+ beforeTotalDurationMs: number;
437
+ afterTotalDurationMs: number;
438
+ totalDurationMsDelta: number;
439
+ /** Baseline-vs-baseline diff. Null when either run has no baseline. */
440
+ baselineDiff: EvalGenerationDiff | null;
441
+ /** Highest-index-generation comparison. Null when either run has no
442
+ * recorded generations (e.g. baseline-only or errored before any
443
+ * generation completed). */
444
+ winnersDiff: EvalGenerationDiff | null;
445
+ }
446
+ /**
447
+ * Diff two generation snapshots. Cells are matched on `(scenarioId, rep)`;
448
+ * unmatched cells surface in `added` / `removed`. Aggregate fields are
449
+ * recomputed from the snapshot's stored fields, not re-derived from cells —
450
+ * this keeps the diff consistent with whatever aggregation the substrate
451
+ * actually reported.
452
+ */
453
+ declare function diffGenerations(before: EvalRunGenerationSnapshot, after: EvalRunGenerationSnapshot): EvalGenerationDiff;
454
+ /**
455
+ * Diff two full eval-runs. Produces baseline-vs-baseline and
456
+ * winner-vs-winner generation diffs when both sides expose them, plus
457
+ * run-level cost / lift / gate-decision deltas.
458
+ */
459
+ declare function diffRuns(before: EvalRunEvent, after: EvalRunEvent): EvalRunDiff;
460
+ /**
461
+ * Within-run baseline → winning-generation diff. The natural "what did the
462
+ * improvement loop produce" view for a single run. Returns null when the
463
+ * run never reached a generation past baseline (errored early, or the gate
464
+ * shipped the baseline as-is).
465
+ */
466
+ declare function diffRunBaselineToWinner(run: EvalRunEvent): EvalGenerationDiff | null;
467
+
354
468
  /**
355
469
  * `fromAgentTrace` — provenance correlation from Cursor's Agent Trace spec
356
470
  * (https://github.com/cursor/agent-trace, RFC v0.1.0).
@@ -567,4 +681,4 @@ interface FromOtelSpansOptions {
567
681
  }
568
682
  declare function fromOtelSpans(opts: FromOtelSpansOptions): RunRecord[];
569
683
 
570
- export { type AgentTraceContributor, type AgentTraceContributorType, type AgentTraceConversation, type AgentTraceFile, type AgentTraceIndex, type AgentTraceRange, type AgentTraceRecord, type AnalyzeRunsOptions, type AuthoringProvenance, CampaignStorage, DispatchContext, type FeedbackTableMeta, type FeedbackTableRow, type FromFeedbackTableOptions, type FromFeedbackTableResult, type FromOtelSpansOptions, Gate, ImprovementDriver, InsightReport, JudgeConfig, MutableSurface, type PartitionByAuthoringModelResult, RunImprovementLoopResult, Scenario, type SelfImproveBudget, type SelfImproveLlm, type SelfImproveOptions, type SelfImproveProgressEvent, type SelfImproveResult, analyzeRuns, fromFeedbackTable, fromOtelSpans, parseAgentTrace, partitionRunsByAuthoringModel, selfImprove };
684
+ export { type AgentTraceContributor, type AgentTraceContributorType, type AgentTraceConversation, type AgentTraceFile, type AgentTraceIndex, type AgentTraceRange, type AgentTraceRecord, type AnalyzeRunsOptions, type AuthoringProvenance, CampaignStorage, DispatchContext, type EvalCellScoreDelta, type EvalDimensionDelta, type EvalGenerationDiff, type EvalRunDiff, type FeedbackTableMeta, type FeedbackTableRow, type FromFeedbackTableOptions, type FromFeedbackTableResult, type FromOtelSpansOptions, Gate, GateDecision, ImprovementDriver, InsightReport, JudgeConfig, MutableSurface, type PartitionByAuthoringModelResult, RunImprovementLoopResult, Scenario, type SelfImproveBudget, type SelfImproveLlm, type SelfImproveOptions, type SelfImproveProgressEvent, type SelfImproveResult, analyzeRuns, diffGenerations, diffRunBaselineToWinner, diffRuns, fromFeedbackTable, fromOtelSpans, parseAgentTrace, partitionRunsByAuthoringModel, selfImprove };
@@ -9,7 +9,16 @@ import {
9
9
  paretoPolicy,
10
10
  paretoSignificanceGate,
11
11
  runEval
12
- } from "../chunk-GXHLRXDI.js";
12
+ } from "../chunk-OTYQPHPL.js";
13
+ import {
14
+ fromClaudeCodeSession,
15
+ fromCodexSession,
16
+ fromKimiCodeSession,
17
+ fromOpenCodeSession,
18
+ fromPiSession,
19
+ fromPigraphSession,
20
+ parseCodeAgentJsonl
21
+ } from "../chunk-S42AWHMP.js";
13
22
  import {
14
23
  checkCanaries
15
24
  } from "../chunk-SHTXZ4O2.js";
@@ -19,29 +28,30 @@ import {
19
28
  heldOutGate,
20
29
  runImprovementLoop,
21
30
  surfaceContentHash
22
- } from "../chunk-RPLZ4OIB.js";
31
+ } from "../chunk-BABOZOSN.js";
23
32
  import {
24
33
  fsCampaignStorage,
25
34
  inMemoryCampaignStorage,
26
35
  runCampaign,
27
36
  summarizeBackendIntegrity
28
- } from "../chunk-ZPSKPT3V.js";
37
+ } from "../chunk-ZZ2HOPME.js";
38
+ import "../chunk-VI2UW6B6.js";
29
39
  import "../chunk-YV7J7X5N.js";
30
40
  import {
31
41
  FileSystemOutcomeStore,
32
42
  InMemoryOutcomeStore
33
43
  } from "../chunk-3RF76KTD.js";
34
- import "../chunk-IHDHUN2X.js";
44
+ import "../chunk-CVVHBFGN.js";
35
45
  import {
36
46
  paretoChart
37
- } from "../chunk-KX6F6NCG.js";
47
+ } from "../chunk-Z7VFTS2J.js";
38
48
  import {
39
49
  cohensD,
40
50
  pairedBootstrap,
41
51
  pairedMde,
42
52
  pairedTTest,
43
53
  requiredSampleSize
44
- } from "../chunk-ITBRCT73.js";
54
+ } from "../chunk-IDVBLYCY.js";
45
55
  import "../chunk-GGE4NNQT.js";
46
56
  import "../chunk-47X6LRCE.js";
47
57
  import "../chunk-5BKGXME7.js";
@@ -1087,6 +1097,119 @@ function cellsToRunRecords(cells, candidateId, runId, surface) {
1087
1097
  });
1088
1098
  }
1089
1099
 
1100
+ // src/contract/diff.ts
1101
+ function keyForCell(cell) {
1102
+ return JSON.stringify([cell.scenarioId, cell.rep]);
1103
+ }
1104
+ function diffDimensions(before, after) {
1105
+ const out = {};
1106
+ const judges = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)]);
1107
+ for (const judge of judges) {
1108
+ const beforeDims = before[judge] ?? {};
1109
+ const afterDims = after[judge] ?? {};
1110
+ const dims = /* @__PURE__ */ new Set([...Object.keys(beforeDims), ...Object.keys(afterDims)]);
1111
+ const judgeOut = {};
1112
+ for (const dim of dims) {
1113
+ const rawBefore = beforeDims[dim];
1114
+ const rawAfter = afterDims[dim];
1115
+ const b = typeof rawBefore === "number" && Number.isFinite(rawBefore) ? rawBefore : null;
1116
+ const a = typeof rawAfter === "number" && Number.isFinite(rawAfter) ? rawAfter : null;
1117
+ judgeOut[dim] = {
1118
+ before: b,
1119
+ after: a,
1120
+ delta: b !== null && a !== null ? a - b : null
1121
+ };
1122
+ }
1123
+ out[judge] = judgeOut;
1124
+ }
1125
+ return out;
1126
+ }
1127
+ function diffGenerations(before, after) {
1128
+ const beforeMap = new Map(before.cells.map((c) => [keyForCell(c), c]));
1129
+ const afterMap = new Map(after.cells.map((c) => [keyForCell(c), c]));
1130
+ const matched = [];
1131
+ const removed = [];
1132
+ const added = [];
1133
+ for (const [key, beforeCell] of beforeMap) {
1134
+ const afterCell = afterMap.get(key);
1135
+ if (!afterCell) {
1136
+ removed.push(beforeCell);
1137
+ continue;
1138
+ }
1139
+ matched.push({
1140
+ scenarioId: beforeCell.scenarioId,
1141
+ rep: beforeCell.rep,
1142
+ compositeBefore: beforeCell.compositeMean,
1143
+ compositeAfter: afterCell.compositeMean,
1144
+ compositeDelta: afterCell.compositeMean - beforeCell.compositeMean,
1145
+ dimensions: diffDimensions(beforeCell.dimensions, afterCell.dimensions)
1146
+ });
1147
+ }
1148
+ for (const [key, afterCell] of afterMap) {
1149
+ if (!beforeMap.has(key)) added.push(afterCell);
1150
+ }
1151
+ return {
1152
+ beforeIndex: before.index,
1153
+ afterIndex: after.index,
1154
+ beforeSurfaceHash: before.surfaceHash,
1155
+ afterSurfaceHash: after.surfaceHash,
1156
+ surfaceChanged: before.surfaceHash !== after.surfaceHash,
1157
+ matched,
1158
+ removed,
1159
+ added,
1160
+ compositeBefore: before.compositeMean,
1161
+ compositeAfter: after.compositeMean,
1162
+ compositeDelta: after.compositeMean - before.compositeMean,
1163
+ costUsdBefore: before.costUsd,
1164
+ costUsdAfter: after.costUsd,
1165
+ costUsdDelta: after.costUsd - before.costUsd,
1166
+ durationMsBefore: before.durationMs,
1167
+ durationMsAfter: after.durationMs,
1168
+ durationMsDelta: after.durationMs - before.durationMs
1169
+ };
1170
+ }
1171
+ function winnerOf(run) {
1172
+ if (run.generations.length === 0) return null;
1173
+ let winner = run.generations[0];
1174
+ for (const gen of run.generations) {
1175
+ if (gen.index > winner.index) winner = gen;
1176
+ }
1177
+ return winner;
1178
+ }
1179
+ function diffRuns(before, after) {
1180
+ const beforeWinner = winnerOf(before);
1181
+ const afterWinner = winnerOf(after);
1182
+ const baselineDiff = before.baseline && after.baseline ? diffGenerations(before.baseline, after.baseline) : null;
1183
+ const winnersDiff = beforeWinner && afterWinner ? diffGenerations(beforeWinner, afterWinner) : null;
1184
+ const beforeLift = before.holdoutLift ?? null;
1185
+ const afterLift = after.holdoutLift ?? null;
1186
+ return {
1187
+ beforeRunId: before.runId,
1188
+ afterRunId: after.runId,
1189
+ beforeTimestamp: before.timestamp,
1190
+ afterTimestamp: after.timestamp,
1191
+ beforeGateDecision: before.gateDecision ?? null,
1192
+ afterGateDecision: after.gateDecision ?? null,
1193
+ beforeHoldoutLift: beforeLift,
1194
+ afterHoldoutLift: afterLift,
1195
+ holdoutLiftDelta: beforeLift !== null && afterLift !== null ? afterLift - beforeLift : null,
1196
+ beforeTotalCostUsd: before.totalCostUsd,
1197
+ afterTotalCostUsd: after.totalCostUsd,
1198
+ totalCostUsdDelta: after.totalCostUsd - before.totalCostUsd,
1199
+ beforeTotalDurationMs: before.totalDurationMs,
1200
+ afterTotalDurationMs: after.totalDurationMs,
1201
+ totalDurationMsDelta: after.totalDurationMs - before.totalDurationMs,
1202
+ baselineDiff,
1203
+ winnersDiff
1204
+ };
1205
+ }
1206
+ function diffRunBaselineToWinner(run) {
1207
+ if (!run.baseline) return null;
1208
+ const winner = winnerOf(run);
1209
+ if (!winner || winner.index === run.baseline.index) return null;
1210
+ return diffGenerations(run.baseline, winner);
1211
+ }
1212
+
1090
1213
  // src/contract/intake/agent-trace.ts
1091
1214
  function rangeLines(r) {
1092
1215
  return Math.max(0, r.end_line - r.start_line + 1);
@@ -1328,9 +1451,18 @@ export {
1328
1451
  buildEvidenceVector,
1329
1452
  composeGate,
1330
1453
  defaultProductionGate,
1454
+ diffGenerations,
1455
+ diffRunBaselineToWinner,
1456
+ diffRuns,
1331
1457
  evolutionaryDriver,
1458
+ fromClaudeCodeSession,
1459
+ fromCodexSession,
1332
1460
  fromFeedbackTable,
1461
+ fromKimiCodeSession,
1462
+ fromOpenCodeSession,
1333
1463
  fromOtelSpans,
1464
+ fromPiSession,
1465
+ fromPigraphSession,
1334
1466
  fsCampaignStorage,
1335
1467
  gepaDriver,
1336
1468
  heldOutGate,
@@ -1338,6 +1470,7 @@ export {
1338
1470
  paretoPolicy,
1339
1471
  paretoSignificanceGate,
1340
1472
  parseAgentTrace,
1473
+ parseCodeAgentJsonl,
1341
1474
  partitionRunsByAuthoringModel,
1342
1475
  runCampaign,
1343
1476
  runEval,