@tangle-network/agent-eval 0.203.2 → 0.205.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 (126) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/analyst/index.d.ts +1 -1
  3. package/dist/analyst/index.d.ts.map +1 -1
  4. package/dist/analyst/index.js +5 -5
  5. package/dist/{analyze-runs-BrIibNd0.js → analyze-runs-d5dcMlxi.js} +9 -9
  6. package/dist/{analyze-runs-BrIibNd0.js.map → analyze-runs-d5dcMlxi.js.map} +1 -1
  7. package/dist/baseline-Dm8966du.js +259 -0
  8. package/dist/baseline-Dm8966du.js.map +1 -0
  9. package/dist/{benchmark-command-6OBcB0sG.js → benchmark-command-BQhi_BVO.js} +9 -6
  10. package/dist/benchmark-command-BQhi_BVO.js.map +1 -0
  11. package/dist/benchmarks/index.js +2 -2
  12. package/dist/builder-eval/index.js +1 -1
  13. package/dist/campaign/index.js +9 -9
  14. package/dist/{campaign-DYhg4SjN.js → campaign-0lmkAMpE.js} +11 -11
  15. package/dist/{campaign-DYhg4SjN.js.map → campaign-0lmkAMpE.js.map} +1 -1
  16. package/dist/{campaign-evidence-Dt_rWPk2.js → campaign-evidence-C__cUpCt.js} +2 -2
  17. package/dist/{campaign-evidence-Dt_rWPk2.js.map → campaign-evidence-C__cUpCt.js.map} +1 -1
  18. package/dist/cli.js +5 -5
  19. package/dist/contract/index.js +10 -10
  20. package/dist/{default-registry-wInsQWlQ.js → default-registry-BthquIoC.js} +2 -2
  21. package/dist/{default-registry-wInsQWlQ.js.map → default-registry-BthquIoC.js.map} +1 -1
  22. package/dist/{define-agent-eval-B25Cc3ki.js → define-agent-eval-CeYrXpl7.js} +4 -4
  23. package/dist/{define-agent-eval-B25Cc3ki.js.map → define-agent-eval-CeYrXpl7.js.map} +1 -1
  24. package/dist/{descriptive-D9LUFk1-.js → descriptive-CnU8Yq29.js} +2 -2
  25. package/dist/{descriptive-D9LUFk1-.js.map → descriptive-CnU8Yq29.js.map} +1 -1
  26. package/dist/diagnosis/index.js +1 -1
  27. package/dist/{dspy-rlm-engine-D0h-P2Mz.js → dspy-rlm-engine-DCQKNQMn.js} +2 -2
  28. package/dist/{dspy-rlm-engine-D0h-P2Mz.js.map → dspy-rlm-engine-DCQKNQMn.js.map} +1 -1
  29. package/dist/{eval-campaign-ha_aWtk7.js → eval-campaign-DsRmYsQI.js} +2 -2
  30. package/dist/{eval-campaign-ha_aWtk7.js.map → eval-campaign-DsRmYsQI.js.map} +1 -1
  31. package/dist/experiment/index.js +9 -9
  32. package/dist/index.d.ts +61 -3
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +102 -25
  35. package/dist/index.js.map +1 -1
  36. package/dist/{internal-BOe3zmjQ.js → internal-CRHwS9iz.js} +3 -3
  37. package/dist/internal-CRHwS9iz.js.map +1 -0
  38. package/dist/jev.js +1 -1
  39. package/dist/judge-calibration-DFtEMlde.d.ts.map +1 -1
  40. package/dist/{judge-calibration-C5zgtiJT.js → judge-calibration-N44V04Se.js} +7 -17
  41. package/dist/judge-calibration-N44V04Se.js.map +1 -0
  42. package/dist/{kind-factory-CdPPHtGZ.js → kind-factory-Cn1lbsAd.js} +5 -5
  43. package/dist/kind-factory-Cn1lbsAd.js.map +1 -0
  44. package/dist/{llm-judge-DyZdrp6I.js → llm-judge-Bka5q-ds.js} +8 -8
  45. package/dist/{llm-judge-DyZdrp6I.js.map → llm-judge-Bka5q-ds.js.map} +1 -1
  46. package/dist/matrix/index.js +1 -1
  47. package/dist/{matrix-DnlHn5x1.js → matrix-_BV9-Lk5.js} +12 -9
  48. package/dist/matrix-_BV9-Lk5.js.map +1 -0
  49. package/dist/meta-eval/index.js +2 -2
  50. package/dist/multishot/golden/index.js +1 -1
  51. package/dist/multishot/index.js +1 -1
  52. package/dist/normal-DsJZtrJc.js +25 -0
  53. package/dist/normal-DsJZtrJc.js.map +1 -0
  54. package/dist/openapi.json +1 -1
  55. package/dist/{paired-arms-DpS_h8ON.js → paired-arms-Dsu-r6xd.js} +6 -27
  56. package/dist/paired-arms-Dsu-r6xd.js.map +1 -0
  57. package/dist/{paired-binary-OMBVRtc-.js → paired-binary-DpwwK1fU.js} +2 -2
  58. package/dist/{paired-binary-OMBVRtc-.js.map → paired-binary-DpwwK1fU.js.map} +1 -1
  59. package/dist/{paired-promotion-decision-DhrmjdV8.js → paired-promotion-decision-CO0kA0bq.js} +3 -3
  60. package/dist/{paired-promotion-decision-DhrmjdV8.js.map → paired-promotion-decision-CO0kA0bq.js.map} +1 -1
  61. package/dist/{paired-tests-Ccr16gcW.js → paired-tests-jbwPdSz5.js} +3 -3
  62. package/dist/{paired-tests-Ccr16gcW.js.map → paired-tests-jbwPdSz5.js.map} +1 -1
  63. package/dist/pipelines/index.d.ts +1 -1
  64. package/dist/pipelines/index.js +2 -2
  65. package/dist/{power-and-mde-bie6i965.js → power-and-mde-fK5Qocwo.js} +3 -3
  66. package/dist/{power-and-mde-bie6i965.js.map → power-and-mde-fK5Qocwo.js.map} +1 -1
  67. package/dist/{produced-state-DLToUXrD.js → produced-state-FdbE-88t.js} +3 -3
  68. package/dist/{produced-state-DLToUXrD.js.map → produced-state-FdbE-88t.js.map} +1 -1
  69. package/dist/{promotion-policy-BI1RxzwD.js → promotion-policy-BSbTAMtE.js} +4 -4
  70. package/dist/{promotion-policy-BI1RxzwD.js.map → promotion-policy-BSbTAMtE.js.map} +1 -1
  71. package/dist/quantile--0yb07pD.js +15 -0
  72. package/dist/quantile--0yb07pD.js.map +1 -0
  73. package/dist/{report-command-D0XL2Cvi.js → report-command-JrjiWReS.js} +2 -2
  74. package/dist/{report-command-D0XL2Cvi.js.map → report-command-JrjiWReS.js.map} +1 -1
  75. package/dist/reporting.js +4 -4
  76. package/dist/{reward-hacking-C-a__ShZ.js → reward-hacking-BFcQgkux.js} +2 -2
  77. package/dist/{reward-hacking-C-a__ShZ.js.map → reward-hacking-BFcQgkux.js.map} +1 -1
  78. package/dist/rl.js +7 -7
  79. package/dist/{rubric-predictive-validity-B0Pg-3I5.js → rubric-predictive-validity-BsgkBfT0.js} +3 -3
  80. package/dist/{rubric-predictive-validity-B0Pg-3I5.js.map → rubric-predictive-validity-BsgkBfT0.js.map} +1 -1
  81. package/dist/search/index.js +2 -2
  82. package/dist/{search-kernel-Dpniloks.js → search-kernel-CsISc5t8.js} +5 -5
  83. package/dist/{search-kernel-Dpniloks.js.map → search-kernel-CsISc5t8.js.map} +1 -1
  84. package/dist/{search-summary-C1nAHgkB.js → search-summary-BZkoLwbB.js} +4 -4
  85. package/dist/{search-summary-C1nAHgkB.js.map → search-summary-BZkoLwbB.js.map} +1 -1
  86. package/dist/{semantic-concept-judge-BgWxa4L_.js → semantic-concept-judge-BbiYuv7U.js} +3 -3
  87. package/dist/{semantic-concept-judge-BgWxa4L_.js.map → semantic-concept-judge-BbiYuv7U.js.map} +1 -1
  88. package/dist/{sequential-DWn_np6P.js → sequential-7uxpO0Vm.js} +2 -2
  89. package/dist/{sequential-DWn_np6P.js.map → sequential-7uxpO0Vm.js.map} +1 -1
  90. package/dist/{skillopt-optimization-method-Dz5CGZb8.js → skillopt-optimization-method-bEm4jYV4.js} +4 -4
  91. package/dist/{skillopt-optimization-method-Dz5CGZb8.js.map → skillopt-optimization-method-bEm4jYV4.js.map} +1 -1
  92. package/dist/{statistical-heldout-CNLOvRq_.js → statistical-heldout-C26hOFWD.js} +3 -3
  93. package/dist/{statistical-heldout-CNLOvRq_.js.map → statistical-heldout-C26hOFWD.js.map} +1 -1
  94. package/dist/{store-otlp-yd9lDziN.js → store-otlp-BA7G1Du-.js} +44 -11
  95. package/dist/store-otlp-BA7G1Du-.js.map +1 -0
  96. package/dist/{store-tool-spans-CAF3T-BS.d.ts → store-tool-spans-BYIarVrG.d.ts} +17 -8
  97. package/dist/{store-tool-spans-CAF3T-BS.d.ts.map → store-tool-spans-BYIarVrG.d.ts.map} +1 -1
  98. package/dist/{store-tool-spans-D5kOU0mr.js → store-tool-spans-DKoVbE-w.js} +3 -3
  99. package/dist/{store-tool-spans-D5kOU0mr.js.map → store-tool-spans-DKoVbE-w.js.map} +1 -1
  100. package/dist/{student-t-BBZYka0E.js → student-t-BQeKJx2N.js} +2 -2
  101. package/dist/{student-t-BBZYka0E.js.map → student-t-BQeKJx2N.js.map} +1 -1
  102. package/dist/{summary-report-DLzptLSA.js → summary-report-BG6-hOkm.js} +6 -6
  103. package/dist/{summary-report-DLzptLSA.js.map → summary-report-BG6-hOkm.js.map} +1 -1
  104. package/dist/supervisor-run/index.js +1 -1
  105. package/dist/{tool-waste-CP5DO383.d.ts → tool-waste-DxlebQkx.d.ts} +42 -2
  106. package/dist/tool-waste-DxlebQkx.d.ts.map +1 -0
  107. package/dist/{tool-waste-B-u3rzCz.js → tool-waste-x_E8h9Ih.js} +3 -3
  108. package/dist/{tool-waste-B-u3rzCz.js.map → tool-waste-x_E8h9Ih.js.map} +1 -1
  109. package/dist/trace-repair/index.js +1 -1
  110. package/dist/traces.d.ts +2 -2
  111. package/dist/traces.js +4 -4
  112. package/dist/{tree-D48IJUK0.js → tree-CAQflhLR.js} +5 -5
  113. package/dist/{tree-D48IJUK0.js.map → tree-CAQflhLR.js.map} +1 -1
  114. package/docs/concepts.md +21 -0
  115. package/docs/trace-analysis.md +10 -0
  116. package/package.json +1 -1
  117. package/dist/baseline-CVKsfWTg.js +0 -150
  118. package/dist/baseline-CVKsfWTg.js.map +0 -1
  119. package/dist/benchmark-command-6OBcB0sG.js.map +0 -1
  120. package/dist/internal-BOe3zmjQ.js.map +0 -1
  121. package/dist/judge-calibration-C5zgtiJT.js.map +0 -1
  122. package/dist/kind-factory-CdPPHtGZ.js.map +0 -1
  123. package/dist/matrix-DnlHn5x1.js.map +0 -1
  124. package/dist/paired-arms-DpS_h8ON.js.map +0 -1
  125. package/dist/store-otlp-yd9lDziN.js.map +0 -1
  126. package/dist/tool-waste-CP5DO383.d.ts.map +0 -1
@@ -1,7 +1,7 @@
1
- import "./paired-tests-Ccr16gcW.js";
2
- import { r as minimumPairsForPairedDeltaTest } from "./paired-promotion-decision-DhrmjdV8.js";
1
+ import "./paired-tests-jbwPdSz5.js";
2
+ import { r as minimumPairsForPairedDeltaTest } from "./paired-promotion-decision-CO0kA0bq.js";
3
3
  import { a as SearchLedgerError } from "./search-ledger-file-DY0AXX3W.js";
4
- import { b as estimateNode } from "./search-kernel-Dpniloks.js";
4
+ import { b as estimateNode } from "./search-kernel-CsISc5t8.js";
5
5
  //#region src/campaign/search-summary.ts
6
6
  /**
7
7
  * The agent's view of a search: the same projection a human reads.
@@ -130,4 +130,4 @@ function formatEstimate(estimate) {
130
130
  //#endregion
131
131
  export { searchProposerView as n, renderSearchSummary as t };
132
132
 
133
- //# sourceMappingURL=search-summary-C1nAHgkB.js.map
133
+ //# sourceMappingURL=search-summary-BZkoLwbB.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"search-summary-C1nAHgkB.js","names":[],"sources":["../src/campaign/search-summary.ts"],"sourcesContent":["/**\n * The agent's view of a search: the same projection a human reads.\n *\n * `renderSearchSummary` turns a `SearchStateView` into compact text — the\n * leading nodes with their estimates, the most recently discarded ideas with\n * why they were discarded, and a log of recent proposals — as AIDE's journal\n * summary does for its own search. `agent-eval search show <ledger>` prints\n * the same text for a terminal; `runOptimization` puts it on every\n * `ProposeContext` a proposer receives.\n *\n * `searchProposerView` is the train-only read `ProposeContext.train` carries.\n * It has no parameter that can select another split, so a proposer built on\n * it cannot reach the selection or test split even by mistake: the sealed\n * splits (§6.6 of the search-tree design) are unreachable by construction,\n * not by convention.\n */\n\nimport { minimumPairsForPairedDeltaTest } from '../paired-delta-test'\nimport { BOOTSTRAP_GATE_MIN_N } from '../statistics'\nimport { estimateNode } from './estimate-node'\nimport { SearchLedgerError } from './search-ledger-errors'\nimport type { NodeEstimate, SearchSplit } from './search-ledger-types'\nimport type { SearchNode, SearchScoredCell, SearchStateView, SearchUnitScore } from './search-state'\n\nconst DESCRIPTIVE_FROM = minimumPairsForPairedDeltaTest(0.95)\n\n/** The proposer's own read of a search: its node's cells on the train split,\n * the only split a proposer may ever see. */\nexport interface SearchProposerView {\n readonly searchId: string\n readonly direction: 'maximize' | 'minimize'\n /** `nodeId`'s scored train cells. Unscored cells (errored, cancelled or in\n * flight) are absent, never zero. */\n scoredCells(nodeId: string): readonly SearchScoredCell[]\n /** Per-unit train-split means of `nodeId`, in unitId order. */\n unitScores(nodeId: string): readonly SearchUnitScore[]\n}\n\n/** The train-only view `ProposeContext.train` carries. */\nexport function searchProposerView(state: SearchStateView): SearchProposerView {\n const header = state.header\n if (!header) throw new SearchLedgerError(`search ${state.searchId} has not been opened`)\n return {\n searchId: state.searchId,\n direction: header.objective.direction,\n scoredCells: (nodeId) => state.scoredCells(nodeId, 'train'),\n unitScores: (nodeId) => state.unitScores(nodeId, 'train'),\n }\n}\n\nexport interface SearchSummaryOptions {\n /**\n * The split every estimate in the summary is computed on. A proposer's\n * context must always pass `'train'`: the selection and test splits stay\n * unread by anything a proposer's text can reach. The CLI passes the\n * search's own ranking split, `'selection'` when the search declares one\n * else `'train'`, matching `searchPolicyView`.\n */\n split: SearchSplit\n /** Nodes shown under \"Leading\" and under \"Recently discarded\". Default 5. */\n limit?: number\n}\n\n/**\n * `SearchState` as compact text: a header line with the search's shape and\n * spend, the leading nodes against the root with their estimates, the most\n * recently discarded nodes with the measurement that discarded them, and a\n * log of recent proposals (operator and label — the ledger's inline,\n * redacted summary of each rationale; the full rationale is a blob this\n * function never reads, so it stays a pure, I/O-free projection of the\n * state already in hand).\n */\nexport function renderSearchSummary(state: SearchStateView, options: SearchSummaryOptions): string {\n const header = state.header\n if (!header) return `search ${state.searchId}: not yet opened`\n const limit = options.limit ?? 5\n if (limit < 1 || !Number.isInteger(limit)) {\n throw new SearchLedgerError(\n `renderSearchSummary: limit must be a positive integer, got ${limit}`,\n )\n }\n const split = options.split\n const direction = header.objective.direction\n const root = state.rootNodeId\n const lines: string[] = [headerLine(state), spendLine(state), statusLine(state)]\n\n if (root === null) {\n lines.push('', 'No nodes yet.')\n return lines.join('\\n')\n }\n\n const others = state.nodes().filter((node) => node.nodeId !== root)\n const estimated = others\n .filter((node) => node.status !== 'invalid')\n .map((node) => ({ node, estimate: estimateNode(state, node.nodeId, { against: root, split }) }))\n\n const leading = estimated\n .filter(({ estimate }) => estimate.delta !== null)\n .sort((a, b) => signed(b.estimate, direction) - signed(a.estimate, direction))\n .slice(0, limit)\n lines.push('', `Leading nodes (vs root, ${split} split):`)\n if (leading.length === 0) lines.push(' none measured yet')\n for (const { node, estimate } of leading)\n lines.push(` ${nodeLine(node)}: ${formatEstimate(estimate)}`)\n\n const discarded = others\n .filter(\n (node) => node.status === 'pruned' || node.status === 'rejected' || node.status === 'invalid',\n )\n .sort((a, b) => b.updatedSequence - a.updatedSequence)\n .slice(0, limit)\n lines.push('', 'Recently discarded:')\n if (discarded.length === 0) lines.push(' none yet')\n for (const node of discarded) lines.push(` ${nodeLine(node)}: ${discardLine(node)}`)\n\n const recent = [...state.edges()].reverse().slice(0, limit)\n lines.push('', 'Recent proposals:')\n if (recent.length === 0) lines.push(' none yet')\n for (const edge of recent) {\n const childId = edge.childNodeId\n const label = edge.label.length > 0 ? edge.label : '(no label)'\n lines.push(` ${edge.operator} → ${childId}: ${label}`)\n }\n\n return lines.join('\\n')\n}\n\nfunction headerLine(state: SearchStateView): string {\n const header = state.header!\n return `search ${state.searchId} — ${header.subject} — ${header.objective.direction} ${header.objective.metric}`\n}\n\nfunction spendLine(state: SearchStateView): string {\n const { audit } = state\n const known = audit.spend.knownUsd.toFixed(2)\n const floor = audit.spend.floorUsd.toFixed(2)\n const unknown = audit.spend.unknownCostCells\n const floorPart =\n unknown > 0\n ? ` + floor $${floor} across ${unknown} unknown-cost cell${unknown === 1 ? '' : 's'}`\n : ''\n return ` ${audit.nodes} nodes · ${audit.cells.settled} settled cells (${audit.cells.open} open) · $${known} known${floorPart}`\n}\n\nfunction statusLine(state: SearchStateView): string {\n if (!state.closed) return ' status: open'\n const claim = state.closed.claim\n const claimText =\n claim === null\n ? ''\n : claim.decision === 'ship'\n ? ` · claim: ship ${claim.selected}`\n : ` · claim: ${claim.decision}`\n return ` status: closed (${state.closed.reason})${claimText}`\n}\n\nfunction nodeLine(node: SearchNode): string {\n const rung = node.status === 'advanced' ? ` rung ${node.rung}` : ''\n return `${node.nodeId} (${node.status ?? 'undecided'}${rung})`\n}\n\nfunction discardLine(node: SearchNode): string {\n const decision = node.decisions.at(-1)\n if (!decision) return 'no decision recorded'\n const basis = decision.basis === null ? 'no measured basis' : formatEstimate(decision.basis)\n return `${basis} — ${decision.rule}: ${decision.reason}`\n}\n\n/** `estimate.delta` in the objective's own units; positive is always better. */\nfunction signed(estimate: NodeEstimate, direction: 'maximize' | 'minimize'): number {\n if (estimate.delta === null) return Number.NEGATIVE_INFINITY\n return direction === 'maximize' ? estimate.delta : -estimate.delta\n}\n\n/** The display rules of search-tree-design §6.4: no whisker below 6 shared\n * units, a dashed descriptive interval with its exact sign p from 6 to 19,\n * a decision-grade whisker from `BOOTSTRAP_GATE_MIN_N`. */\nfunction formatEstimate(estimate: NodeEstimate): string {\n const unit = (n: number) => `${n} unit${n === 1 ? '' : 's'}`\n if (estimate.method === 'none') return `unknown (${unit(estimate.pairs)})`\n if (estimate.indeterminate)\n return `no measurable difference (indeterminate, ${unit(estimate.pairs)})`\n const delta =\n estimate.delta === null ? 'null' : (estimate.delta >= 0 ? '+' : '') + estimate.delta.toFixed(4)\n if (estimate.method === 'insufficient') {\n return `Δ=${delta} (${estimate.pairs} of ${DESCRIPTIVE_FROM} units, insufficient)`\n }\n const interval = estimate.interval\n ? ` [${estimate.interval[0].toFixed(4)}, ${estimate.interval[1].toFixed(4)}]`\n : ''\n if (estimate.method === 'descriptive') {\n const signP = estimate.exactSignP === null ? 'null' : estimate.exactSignP.toPrecision(3)\n return `Δ=${delta}${interval} dashed, sign p=${signP} (${unit(estimate.pairs)})`\n }\n return `Δ=${delta}${interval} (${unit(estimate.pairs)}, ≥${BOO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;CAC1E,MAAM,QACJ,SAAS,UAAU,OAAO,UAAU,SAAS,SAAS,IAAI,MAAM,MAAM,SAAS,MAAM,QAAQ,CAAC;CAChG,IAAI,SAAS,WAAW,gBACtB,OAAO,KAAK,MAAM,IAAI,SAAS,MAAM,MAAM,iBAAiB;CAE9D,MAAM,WAAW,SAAS,WACtB,KAAK,SAAS,SAAS,EAAE,CAAC,QAAQ,CAAC,EAAE,IAAI,SAAS,SAAS,EAAE,CAAC,QAAQ,CAAC,EAAE,KACzE;CACJ,IAAI,SAAS,WAAW,eAEtB,OAAO,KAAK,QAAQ,SAAS,kBADf,SAAS,eAAe,OAAO,SAAS,SAAS,WAAW,YAAY,CAAC,EAClC,IAAI,KAAK,SAAS,KAAK,EAAE;CAEhF,OAAO,KAAK,QAAQ,SAAS,IAAI,KAAK,SAAS,KAAK,EAAE;AACxD"}
1
+ {"version":3,"file":"search-summary-BZkoLwbB.js","names":[],"sources":["../src/campaign/search-summary.ts"],"sourcesContent":["/**\n * The agent's view of a search: the same projection a human reads.\n *\n * `renderSearchSummary` turns a `SearchStateView` into compact text — the\n * leading nodes with their estimates, the most recently discarded ideas with\n * why they were discarded, and a log of recent proposals — as AIDE's journal\n * summary does for its own search. `agent-eval search show <ledger>` prints\n * the same text for a terminal; `runOptimization` puts it on every\n * `ProposeContext` a proposer receives.\n *\n * `searchProposerView` is the train-only read `ProposeContext.train` carries.\n * It has no parameter that can select another split, so a proposer built on\n * it cannot reach the selection or test split even by mistake: the sealed\n * splits (§6.6 of the search-tree design) are unreachable by construction,\n * not by convention.\n */\n\nimport { minimumPairsForPairedDeltaTest } from '../paired-delta-test'\nimport { BOOTSTRAP_GATE_MIN_N } from '../statistics'\nimport { estimateNode } from './estimate-node'\nimport { SearchLedgerError } from './search-ledger-errors'\nimport type { NodeEstimate, SearchSplit } from './search-ledger-types'\nimport type { SearchNode, SearchScoredCell, SearchStateView, SearchUnitScore } from './search-state'\n\nconst DESCRIPTIVE_FROM = minimumPairsForPairedDeltaTest(0.95)\n\n/** The proposer's own read of a search: its node's cells on the train split,\n * the only split a proposer may ever see. */\nexport interface SearchProposerView {\n readonly searchId: string\n readonly direction: 'maximize' | 'minimize'\n /** `nodeId`'s scored train cells. Unscored cells (errored, cancelled or in\n * flight) are absent, never zero. */\n scoredCells(nodeId: string): readonly SearchScoredCell[]\n /** Per-unit train-split means of `nodeId`, in unitId order. */\n unitScores(nodeId: string): readonly SearchUnitScore[]\n}\n\n/** The train-only view `ProposeContext.train` carries. */\nexport function searchProposerView(state: SearchStateView): SearchProposerView {\n const header = state.header\n if (!header) throw new SearchLedgerError(`search ${state.searchId} has not been opened`)\n return {\n searchId: state.searchId,\n direction: header.objective.direction,\n scoredCells: (nodeId) => state.scoredCells(nodeId, 'train'),\n unitScores: (nodeId) => state.unitScores(nodeId, 'train'),\n }\n}\n\nexport interface SearchSummaryOptions {\n /**\n * The split every estimate in the summary is computed on. A proposer's\n * context must always pass `'train'`: the selection and test splits stay\n * unread by anything a proposer's text can reach. The CLI passes the\n * search's own ranking split, `'selection'` when the search declares one\n * else `'train'`, matching `searchPolicyView`.\n */\n split: SearchSplit\n /** Nodes shown under \"Leading\" and under \"Recently discarded\". Default 5. */\n limit?: number\n}\n\n/**\n * `SearchState` as compact text: a header line with the search's shape and\n * spend, the leading nodes against the root with their estimates, the most\n * recently discarded nodes with the measurement that discarded them, and a\n * log of recent proposals (operator and label — the ledger's inline,\n * redacted summary of each rationale; the full rationale is a blob this\n * function never reads, so it stays a pure, I/O-free projection of the\n * state already in hand).\n */\nexport function renderSearchSummary(state: SearchStateView, options: SearchSummaryOptions): string {\n const header = state.header\n if (!header) return `search ${state.searchId}: not yet opened`\n const limit = options.limit ?? 5\n if (limit < 1 || !Number.isInteger(limit)) {\n throw new SearchLedgerError(\n `renderSearchSummary: limit must be a positive integer, got ${limit}`,\n )\n }\n const split = options.split\n const direction = header.objective.direction\n const root = state.rootNodeId\n const lines: string[] = [headerLine(state), spendLine(state), statusLine(state)]\n\n if (root === null) {\n lines.push('', 'No nodes yet.')\n return lines.join('\\n')\n }\n\n const others = state.nodes().filter((node) => node.nodeId !== root)\n const estimated = others\n .filter((node) => node.status !== 'invalid')\n .map((node) => ({ node, estimate: estimateNode(state, node.nodeId, { against: root, split }) }))\n\n const leading = estimated\n .filter(({ estimate }) => estimate.delta !== null)\n .sort((a, b) => signed(b.estimate, direction) - signed(a.estimate, direction))\n .slice(0, limit)\n lines.push('', `Leading nodes (vs root, ${split} split):`)\n if (leading.length === 0) lines.push(' none measured yet')\n for (const { node, estimate } of leading)\n lines.push(` ${nodeLine(node)}: ${formatEstimate(estimate)}`)\n\n const discarded = others\n .filter(\n (node) => node.status === 'pruned' || node.status === 'rejected' || node.status === 'invalid',\n )\n .sort((a, b) => b.updatedSequence - a.updatedSequence)\n .slice(0, limit)\n lines.push('', 'Recently discarded:')\n if (discarded.length === 0) lines.push(' none yet')\n for (const node of discarded) lines.push(` ${nodeLine(node)}: ${discardLine(node)}`)\n\n const recent = [...state.edges()].reverse().slice(0, limit)\n lines.push('', 'Recent proposals:')\n if (recent.length === 0) lines.push(' none yet')\n for (const edge of recent) {\n const childId = edge.childNodeId\n const label = edge.label.length > 0 ? edge.label : '(no label)'\n lines.push(` ${edge.operator} → ${childId}: ${label}`)\n }\n\n return lines.join('\\n')\n}\n\nfunction headerLine(state: SearchStateView): string {\n const header = state.header!\n return `search ${state.searchId} — ${header.subject} — ${header.objective.direction} ${header.objective.metric}`\n}\n\nfunction spendLine(state: SearchStateView): string {\n const { audit } = state\n const known = audit.spend.knownUsd.toFixed(2)\n const floor = audit.spend.floorUsd.toFixed(2)\n const unknown = audit.spend.unknownCostCells\n const floorPart =\n unknown > 0\n ? ` + floor $${floor} across ${unknown} unknown-cost cell${unknown === 1 ? '' : 's'}`\n : ''\n return ` ${audit.nodes} nodes · ${audit.cells.settled} settled cells (${audit.cells.open} open) · $${known} known${floorPart}`\n}\n\nfunction statusLine(state: SearchStateView): string {\n if (!state.closed) return ' status: open'\n const claim = state.closed.claim\n const claimText =\n claim === null\n ? ''\n : claim.decision === 'ship'\n ? ` · claim: ship ${claim.selected}`\n : ` · claim: ${claim.decision}`\n return ` status: closed (${state.closed.reason})${claimText}`\n}\n\nfunction nodeLine(node: SearchNode): string {\n const rung = node.status === 'advanced' ? ` rung ${node.rung}` : ''\n return `${node.nodeId} (${node.status ?? 'undecided'}${rung})`\n}\n\nfunction discardLine(node: SearchNode): string {\n const decision = node.decisions.at(-1)\n if (!decision) return 'no decision recorded'\n const basis = decision.basis === null ? 'no measured basis' : formatEstimate(decision.basis)\n return `${basis} — ${decision.rule}: ${decision.reason}`\n}\n\n/** `estimate.delta` in the objective's own units; positive is always better. */\nfunction signed(estimate: NodeEstimate, direction: 'maximize' | 'minimize'): number {\n if (estimate.delta === null) return Number.NEGATIVE_INFINITY\n return direction === 'maximize' ? estimate.delta : -estimate.delta\n}\n\n/** The display rules of search-tree-design §6.4: no whisker below 6 shared\n * units, a dashed descriptive interval with its exact sign p from 6 to 19,\n * a decision-grade whisker from `BOOTSTRAP_GATE_MIN_N`. */\nfunction formatEstimate(estimate: NodeEstimate): string {\n const unit = (n: number) => `${n} unit${n === 1 ? '' : 's'}`\n if (estimate.method === 'none') return `unknown (${unit(estimate.pairs)})`\n if (estimate.indeterminate)\n return `no measurable difference (indeterminate, ${unit(estimate.pairs)})`\n const delta =\n estimate.delta === null ? 'null' : (estimate.delta >= 0 ? '+' : '') + estimate.delta.toFixed(4)\n if (estimate.method === 'insufficient') {\n return `Δ=${delta} (${estimate.pairs} of ${DESCRIPTIVE_FROM} units, insufficient)`\n }\n const interval = estimate.interval\n ? ` [${estimate.interval[0].toFixed(4)}, ${estimate.interval[1].toFixed(4)}]`\n : ''\n if (estimate.method === 'descriptive') {\n const signP = estimate.exactSignP === null ? 'null' : estimate.exactSignP.toPrecision(3)\n return `Δ=${delta}${interval} dashed, sign p=${signP} (${unit(estimate.pairs)})`\n }\n return `Δ=${delta}${interval} (${unit(estimate.pairs)}, ≥${B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AE;CAC1E,MAAM,QACJ,SAAS,UAAU,OAAO,UAAU,SAAS,SAAS,IAAI,MAAM,MAAM,SAAS,MAAM,QAAQ,CAAC;CAChG,IAAI,SAAS,WAAW,gBACtB,OAAO,KAAK,MAAM,IAAI,SAAS,MAAM,MAAM,iBAAiB;CAE9D,MAAM,WAAW,SAAS,WACtB,KAAK,SAAS,SAAS,EAAE,CAAC,QAAQ,CAAC,EAAE,IAAI,SAAS,SAAS,EAAE,CAAC,QAAQ,CAAC,EAAE,KACzE;CACJ,IAAI,SAAS,WAAW,eAEtB,OAAO,KAAK,QAAQ,SAAS,kBADf,SAAS,eAAe,OAAO,SAAS,SAAS,WAAW,YAAY,CAAC,EAClC,IAAI,KAAK,SAAS,KAAK,EAAE;CAEhF,OAAO,KAAK,QAAQ,SAAS,IAAI,KAAK,SAAS,KAAK,EAAE;AACxD"}
@@ -1,9 +1,9 @@
1
1
  import { i as CostLedger } from "./cost-ledger-_IbkejCF.js";
2
2
  import { p as Mutex } from "./journal-DvKCvjty.js";
3
3
  import { c as extractJsonPayload } from "./llm-client-DmCNzrc9.js";
4
- import { N as RawAnalystFindingSchema } from "./kind-factory-CdPPHtGZ.js";
4
+ import { P as RawAnalystFindingSchema } from "./kind-factory-Cn1lbsAd.js";
5
5
  import { n as paidJsonChat, t as paidChat } from "./chat-json-call-Digk-pfF.js";
6
- import { n as decodeRawFindingArray } from "./dspy-rlm-engine-D0h-P2Mz.js";
6
+ import { n as decodeRawFindingArray } from "./dspy-rlm-engine-DCQKNQMn.js";
7
7
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
8
8
  import { z } from "zod";
9
9
  import { dirname } from "node:path";
@@ -777,4 +777,4 @@ async function runSemanticConceptJudge(input, options) {
777
777
  //#endregion
778
778
  export { diffFindings as a, defaultIsMaterial as i, runSemanticConceptJudge as n, createChatTraceEngine as o, FindingsStore as r, SEMANTIC_CONCEPT_JUDGE_VERSION as t };
779
779
 
780
- //# sourceMappingURL=semantic-concept-judge-BgWxa4L_.js.map
780
+ //# sourceMappingURL=semantic-concept-judge-BbiYuv7U.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"semantic-concept-judge-BgWxa4L_.js","names":[],"sources":["../src/analyst/chat-trace-engine.ts","../src/locked-jsonl-appender.ts","../src/analyst/findings-store.ts","../src/semantic-concept-judge.ts"],"sourcesContent":["/**\n * A `TraceAnalysisEngine` that runs entirely inside Node against a\n * caller-owned `ChatClient`.\n *\n * The other engine in this package, `createDspyRlmTraceEngine`, reaches the\n * DSPy RLM through a Python subprocess. That made every model-backed analyst\n * unreachable for a consumer that already owns a model seam and no Python:\n * `createTraceAnalyst` requires an engine, the only exported constructor\n * required a Python runner, so `buildDefaultAnalystRegistry()` registered the\n * deterministic analyst alone and `analystsFromRegistry` refused the result.\n *\n * This engine closes that path. It drives the same investigation contract —\n * bounded trace tools, a prose answer, a strict findings array — with native\n * function calls over the transport the caller already bound with\n * `createChatClient`. A caller holding a bare\n * `(request: LlmCallRequest) => Promise<LlmCallResult>` adapts it in one line:\n *\n * createChatClient({ transport: 'custom', chat: call, defaultModel, maximumAttempts })\n *\n * agent-eval still executes no paid model and holds no provider credential.\n * Every call goes through `paidChat`, so the shared cost ledger reserves the\n * priced maximum before the call and settles the receipt after it.\n *\n * Shape of one investigation:\n * 1. Investigation turns. The model reads the trace store through the tools\n * its analyst kind was given. A turn that requests no tool ends the\n * phase; an exhausted iteration or tool budget also ends it.\n * 2. One report turn. The model returns `{ answer, findings }` as JSON,\n * decoded by the same `decodeRawFindingArray` the Python bridge uses, so\n * a row this engine accepts is a row that engine could report.\n */\n\nimport { z } from 'zod'\nimport { paidChat } from '../chat-json-call'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport {\n extractJsonPayload,\n type LlmCallRequest,\n type LlmMessage,\n type LlmThinkingMode,\n type LlmToolCall,\n type LlmToolDefinition,\n} from '../llm-client'\nimport type { TraceAnalysisToolDescriptor } from '../trace-analyst/tools'\nimport type { ChatClient } from './chat-client'\nimport {\n DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS,\n type TraceAnalysisEngine,\n type TraceAnalysisEngineRequest,\n type TraceAnalysisEngineResult,\n} from './engine'\nimport { decodeRawFindingArray } from './finding-codec'\nimport { RawAnalystFindingSchema } from './finding-signature'\n\n/** Bumped whenever this engine's execution behavior changes. */\nconst CHAT_TRACE_ENGINE_VERSION = '1.0.0'\nconst ENGINE_ID = 'chat-trace'\n\n/** Marker appended to a tool result cut down to the retained-output budget. */\nconst TRUNCATION_MARKER = '\\n…[truncated to the analyst maxOutputChars budget]'\n\nexport interface ChatTraceEngineOptions {\n /**\n * Caller-owned transport. Build it with `createChatClient`; agent-eval never\n * receives the provider credential.\n */\n chat: ChatClient\n /** Model for every call. Defaults to the client's `defaultModel`. */\n model?: string\n /** Endpoint rates used when the transport reports no billed amount. */\n pricing?: CustomTokenPricing\n /** Completion cap per turn. Default: {@link DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS}. */\n maxOutputTokens?: number\n /** Sampling temperature. Omitted from the request when absent. */\n temperature?: number\n /** Provider reasoning mode. Omitted when the provider default should apply. */\n thinking?: LlmThinkingMode\n /** Per-call deadline handed to the transport. */\n requestTimeoutMs?: number\n /**\n * How the report turn asks for structured output.\n *\n * `json-object` sends JSON mode, which every OpenAI-compatible endpoint\n * accepts, and relies on the finding grammar the analyst kind already puts\n * in its instructions. `json-schema` sends the generated response schema as\n * well, which stricter endpoints honour and older ones reject. Default:\n * `json-object`.\n */\n reportFormat?: 'json-object' | 'json-schema'\n}\n\n/**\n * The report envelope. Its `findings` rows are generated from\n * `RawAnalystFindingSchema`, so the schema offered to a provider and the\n * decoder that accepts the answer cannot drift apart.\n */\nfunction buildReportJsonSchema(): { name: string; schema: Record<string, unknown> } {\n const row = z.toJSONSchema(RawAnalystFindingSchema, { target: 'draft-7' }) as Record<\n string,\n unknown\n >\n delete row.$schema\n return {\n name: 'trace_analysis_report',\n schema: {\n type: 'object',\n additionalProperties: false,\n required: ['answer', 'findings'],\n properties: {\n answer: { type: 'string', description: 'Direct prose answer to the question.' },\n findings: { type: 'array', items: row },\n },\n },\n }\n}\n\nconst REPORT_JSON_SCHEMA = buildReportJsonSchema()\n\n/**\n * Run bounded recursive trace analysis in-process over a caller-owned chat\n * transport. No Python, no subprocess, no loopback proxy.\n */\nexport function createChatTraceEngine(options: ChatTraceEngineOptions): TraceAnalysisEngine {\n const model = resolveModel(options)\n const maxOutputTokens = options.maxOutputTokens ?? DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS\n if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) {\n throw new TypeError('chat trace engine maxOutputTokens must be a positive safe integer')\n }\n if (\n options.temperature !== undefined &&\n (!Number.isFinite(options.temperature) || options.temperature < 0)\n ) {\n throw new TypeError('chat trace engine temperature must be a non-negative finite number')\n }\n if (\n options.requestTimeoutMs !== undefined &&\n (!Number.isSafeInteger(options.requestTimeoutMs) || options.requestTimeoutMs <= 0)\n ) {\n throw new TypeError('chat trace engine requestTimeoutMs must be a positive safe integer')\n }\n const reportFormat = options.reportFormat ?? 'json-object'\n if (reportFormat !== 'json-object' && reportFormat !== 'json-schema') {\n throw new TypeError(`chat trace engine reportFormat must be json-object or json-schema`)\n }\n\n return {\n id: ENGINE_ID,\n description:\n 'In-process recursive trace analysis over a caller-owned ChatClient with native tool calls.',\n model,\n version: CHAT_TRACE_ENGINE_VERSION,\n executionConfig: {\n kind: ENGINE_ID,\n model,\n transport: options.chat.transport,\n maximum_attempts: options.chat.maximumAttempts ?? null,\n pricing: options.pricing ? { ...options.pricing } : null,\n max_output_tokens: maxOutputTokens,\n temperature: options.temperature ?? null,\n thinking: options.thinking ?? null,\n request_timeout_ms: options.requestTimeoutMs ?? null,\n report_format: reportFormat,\n report_schema_name: REPORT_JSON_SCHEMA.name,\n },\n analyze: (request) => analyze(request, { ...options, model, maxOutputTokens, reportFormat }),\n }\n}\n\ninterface ResolvedOptions extends ChatTraceEngineOptions {\n model: string\n maxOutputTokens: number\n reportFormat: 'json-object' | 'json-schema'\n}\n\nasync function analyze(\n request: TraceAnalysisEngineRequest,\n options: ResolvedOptions,\n): Promise<TraceAnalysisEngineResult> {\n // One model call is spent on the report, so a budget of one call would buy\n // an answer with no investigation behind it. Refuse instead of pretending.\n if (request.limits.maxLlmCalls < 2) {\n throw new Error(\n `chat trace engine reserves one model call for the report, so maxLlmCalls must be at least 2 (analyst '${request.analystId}' declared ${request.limits.maxLlmCalls})`,\n )\n }\n const toolsByName = new Map(request.tools.map((tool) => [tool.name, tool]))\n if (toolsByName.size !== request.tools.length) {\n throw new Error(`chat trace engine received duplicate tool names for '${request.analystId}'`)\n }\n const toolDefinitions: LlmToolDefinition[] = request.tools.map((tool) => ({\n type: 'function',\n function: { name: tool.name, description: tool.description, parameters: tool.parameters },\n }))\n const investigationTurns = Math.max(\n 1,\n Math.min(request.limits.maxIterations, request.limits.maxLlmCalls - 1),\n )\n\n const messages: LlmMessage[] = [\n { role: 'system', content: systemPrompt(request, investigationTurns) },\n ]\n if (request.taskInputs) {\n messages.push({ role: 'user', content: renderTaskInputs(request.taskInputs) })\n }\n messages.push({ role: 'user', content: request.question })\n\n request.log?.('trace analyst engine started', {\n engine: ENGINE_ID,\n model: options.model,\n transport: options.chat.transport,\n tools: request.tools.map((tool) => tool.name),\n limits: request.limits,\n })\n\n const trajectory: unknown[] = []\n const servedModels = new Set<string>()\n let modelCalls = 0\n let toolCalls = 0\n let truncatedToolResults = 0\n let toolBudgetExhausted = false\n let turnsUsed = 0\n let stoppedOnAnswer = false\n\n for (let turn = 0; turn < investigationTurns; turn++) {\n turnsUsed = turn + 1\n const response = await callModel(request, options, {\n messages,\n tools: toolDefinitions,\n toolChoice: 'auto',\n purpose: 'investigation',\n })\n modelCalls += 1\n servedModels.add(response.servedModel ?? 'unreported')\n const requested = response.toolCalls ?? []\n messages.push({\n role: 'assistant',\n content: response.content,\n ...(requested.length > 0 ? { toolCalls: requested } : {}),\n })\n trajectory.push({\n turn: turnsUsed,\n phase: 'investigation',\n content: response.content,\n tool_calls: requested.map((call) => ({ id: call.id, name: call.name })),\n finish_reason: response.finishReason ?? null,\n })\n if (requested.length === 0) {\n stoppedOnAnswer = true\n break\n }\n for (const call of requested) {\n if (toolCalls >= request.limits.maxToolCalls) {\n toolBudgetExhausted = true\n // Every requested id still needs an answer: a provider rejects the\n // next turn when one tool call is left unanswered.\n messages.push(toolMessage(call, exhaustedToolBudget(request.limits.maxToolCalls)))\n continue\n }\n toolCalls += 1\n const executed = await executeTool(call, toolsByName, request)\n if (executed.truncated) truncatedToolResults += 1\n messages.push(toolMessage(call, executed.payload))\n trajectory.push({\n turn: turnsUsed,\n phase: 'tool',\n name: call.name,\n ok: executed.ok,\n truncated: executed.truncated,\n result_chars: executed.payload.length,\n })\n }\n if (toolBudgetExhausted) break\n }\n\n messages.push({ role: 'user', content: reportPrompt(options.reportFormat) })\n const report = await callModel(request, options, {\n messages,\n purpose: 'report',\n json: options.reportFormat,\n })\n modelCalls += 1\n servedModels.add(report.servedModel ?? 'unreported')\n trajectory.push({\n turn: turnsUsed + 1,\n phase: 'report',\n content: report.content,\n finish_reason: report.finishReason ?? null,\n })\n\n const parsed = parseReport(report.content, request.analystId, (index, reason) => {\n request.log?.('finding rejected: report row failed schema validation', {\n engine: ENGINE_ID,\n index,\n reason,\n })\n })\n\n const result: TraceAnalysisEngineResult = {\n answer: parsed.answer,\n findings: parsed.findings,\n trajectory,\n modelCalls,\n toolCalls,\n runtime: {\n engine: ENGINE_ID,\n model: options.model,\n transport: options.chat.transport,\n report_format: options.reportFormat,\n investigation_turns: turnsUsed,\n investigation_stopped_on_answer: stoppedOnAnswer,\n tool_budget_exhausted: toolBudgetExhausted,\n truncated_tool_results: truncatedToolResults,\n rejected_findings: parsed.rejectedFindings,\n // A gateway can answer `model: X` from another model on HTTP 200, so the\n // ids the provider echoed travel with the result as evidence.\n served_models: [...servedModels].sort(),\n task_inputs: request.taskInputs ? 'prompt-delivered' : 'none',\n },\n }\n request.log?.('trace analyst engine completed', {\n engine: ENGINE_ID,\n model_calls: result.modelCalls,\n tool_calls: result.toolCalls,\n findings: result.findings.length,\n })\n return result\n}\n\ninterface ModelTurn {\n content: string\n toolCalls?: LlmToolCall[]\n servedModel?: string | null\n finishReason?: string | null\n}\n\nasync function callModel(\n request: TraceAnalysisEngineRequest,\n options: ResolvedOptions,\n turn: {\n messages: LlmMessage[]\n tools?: LlmToolDefinition[]\n toolChoice?: LlmCallRequest['toolChoice']\n purpose: 'investigation' | 'report'\n json?: 'json-object' | 'json-schema'\n },\n): Promise<ModelTurn> {\n const chatRequest: LlmCallRequest = {\n model: options.model,\n // The transport may mutate what it is handed; the conversation is ours.\n messages: turn.messages.map((message) => ({ ...message })),\n maxTokens: options.maxOutputTokens,\n ...(turn.tools && turn.tools.length > 0\n ? { tools: turn.tools, ...(turn.toolChoice ? { toolChoice: turn.toolChoice } : {}) }\n : {}),\n ...(turn.json ? { jsonMode: true } : {}),\n ...(turn.json === 'json-schema' ? { jsonSchema: REPORT_JSON_SCHEMA } : {}),\n ...(options.temperature === undefined ? {} : { temperature: options.temperature }),\n ...(options.thinking === undefined ? {} : { thinking: options.thinking }),\n ...(options.requestTimeoutMs === undefined ? {} : { timeoutMs: options.requestTimeoutMs }),\n }\n const paid = await paidChat({\n chat: options.chat,\n request: chatRequest,\n ledger: request.costLedger,\n channel: 'analyst',\n phase: request.costPhase,\n actor: request.analystId,\n ...(request.costTags ? { tags: request.costTags } : {}),\n ...(options.pricing ? { pricing: options.pricing } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n if (!paid.succeeded) {\n // The transport already spent its own attempts. A failure here ends the\n // investigation: continuing would report an answer the model never gave.\n throw new Error(\n `chat trace engine ${turn.purpose} call failed for '${request.analystId}': ${paid.error.message}`,\n { cause: paid.error },\n )\n }\n return {\n content: paid.response.content,\n ...(paid.response.toolCalls ? { toolCalls: paid.response.toolCalls } : {}),\n ...(paid.response.servedModel === undefined ? {} : { servedModel: paid.response.servedModel }),\n ...(paid.response.finishReason === undefined\n ? {}\n : { finishReason: paid.response.finishReason }),\n }\n}\n\ninterface ExecutedTool {\n ok: boolean\n truncated: boolean\n payload: string\n}\n\nasync function executeTool(\n call: LlmToolCall,\n toolsByName: ReadonlyMap<string, TraceAnalysisToolDescriptor>,\n request: TraceAnalysisEngineRequest,\n): Promise<ExecutedTool> {\n const descriptor = toolsByName.get(call.name)\n if (!descriptor) {\n return {\n ok: false,\n truncated: false,\n payload: toolError(\n `unknown tool '${call.name}'; available tools are ${[...toolsByName.keys()].sort().join(', ')}`,\n ),\n }\n }\n let args: unknown\n try {\n args = call.argumentsJson.trim() === '' ? {} : JSON.parse(call.argumentsJson)\n } catch (error) {\n return {\n ok: false,\n truncated: false,\n payload: toolError(\n `arguments for '${call.name}' were not JSON: ${messageOf(error)}. Send valid JSON arguments.`,\n ),\n }\n }\n try {\n const value = await descriptor.handler(\n args,\n request.signal ? { signal: request.signal } : undefined,\n )\n return truncateToolPayload(JSON.stringify(value ?? null), request.limits.maxOutputChars)\n } catch (error) {\n // A bounded store refuses an oversized or malformed read by design. That\n // refusal is the model's next instruction, not the run's failure.\n if (request.signal?.aborted) throw error\n request.log?.('trace tool failed', {\n engine: ENGINE_ID,\n analyst_id: request.analystId,\n tool: call.name,\n reason: messageOf(error),\n })\n return { ok: false, truncated: false, payload: toolError(messageOf(error)) }\n }\n}\n\nfunction truncateToolPayload(payload: string, maxOutputChars: number): ExecutedTool {\n if (payload.length <= maxOutputChars) return { ok: true, truncated: false, payload }\n const keep = Math.max(0, maxOutputChars - TRUNCATION_MARKER.length)\n return { ok: true, truncated: true, payload: `${payload.slice(0, keep)}${TRUNCATION_MARKER}` }\n}\n\nfunction toolMessage(call: LlmToolCall, content: string): LlmMessage {\n return { role: 'tool', toolCallId: call.id, content }\n}\n\nfunction toolError(reason: string): string {\n return JSON.stringify({ error: reason })\n}\n\nfunction exhaustedToolBudget(maxToolCalls: number): string {\n return toolError(\n `the trace-tool budget of ${maxToolCalls} calls is spent; answer from the evidence already read`,\n )\n}\n\nfunction systemPrompt(request: TraceAnalysisEngineRequest, investigationTurns: number): string {\n return [\n request.instructions.trim(),\n [\n 'HOW THIS INVESTIGATION RUNS:',\n `- You have ${investigationTurns} investigation turns and at most ${request.limits.maxToolCalls} trace-tool calls.`,\n '- Call the trace tools to read the store. Never state a trace fact you did not read.',\n `- A tool result longer than ${request.limits.maxOutputChars} characters is truncated; narrow the query instead of asking again.`,\n '- A tool result carrying an \"error\" field is feedback: fix the call or take another route.',\n '- Answer with no tool call once you have the evidence. You are then asked for the final report.',\n ].join('\\n'),\n ].join('\\n\\n')\n}\n\nfunction reportPrompt(reportFormat: 'json-object' | 'json-schema'): string {\n return [\n 'Report now. Do not call any more tools.',\n 'Return one JSON object with exactly two fields:',\n ' \"answer\": a direct prose answer to the question.',\n ' \"findings\": an array of findings in the schema above. Emit [] when there is nothing to report.',\n reportFormat === 'json-object'\n ? 'Return the object alone, with no surrounding prose and no code fence.'\n : 'Return the object in the response schema you were given.',\n ].join('\\n')\n}\n\nfunction renderTaskInputs(taskInputs: Readonly<Record<string, unknown>>): string {\n // The engine contract forbids dropping structured inputs. This engine has no\n // code environment to bind them as variables, so they are delivered whole as\n // conversation material and the runtime record says which way they arrived.\n return [\n 'TASK INPUTS — structured material delivered with the question, not fetched through tools:',\n JSON.stringify(taskInputs, null, 2),\n ].join('\\n')\n}\n\ninterface ParsedReport {\n answer: string\n findings: TraceAnalysisEngineResult['findings']\n rejectedFindings: number\n}\n\nfunction parseReport(\n content: string,\n analystId: string,\n onRejectedFinding: (index: number, reason: string) => void,\n): ParsedReport {\n const envelope = coerceReportEnvelope(content, analystId)\n if (typeof envelope.answer !== 'string' || !envelope.answer.trim()) {\n throw new Error(`chat trace engine report for '${analystId}' carried no answer`)\n }\n // Findings are model output: one malformed row is model noise, not an engine\n // fault, and the rest of the paid investigation must survive it.\n const decoded = decodeRawFindingArray(envelope.findings)\n if (decoded.topLevelError !== undefined) {\n throw new Error(\n `chat trace engine report for '${analystId}' had a malformed findings array: ${decoded.topLevelError}`,\n )\n }\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 return {\n answer: envelope.answer,\n findings: decoded.accepted,\n rejectedFindings: decoded.rejected.length,\n }\n}\n\nfunction coerceReportEnvelope(content: string, analystId: string): Record<string, unknown> {\n let value: unknown\n try {\n value = JSON.parse(extractJsonPayload(content))\n } catch (error) {\n throw new Error(`chat trace engine report for '${analystId}' was not JSON: ${messageOf(error)}`)\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`chat trace engine report for '${analystId}' was not a JSON object`)\n }\n return value as Record<string, unknown>\n}\n\nfunction resolveModel(options: ChatTraceEngineOptions): string {\n const model = options.model ?? options.chat.defaultModel\n if (typeof model !== 'string' || !model.trim() || model !== model.trim()) {\n throw new TypeError(\n 'chat trace engine needs a model: pass ChatTraceEngineOptions.model or bind defaultModel on the ChatClient',\n )\n }\n return model\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * LockedJsonlAppender — mutex-serialized JSONL append helper for arbitrary\n * payloads. The reference-replay store does the same thing for typed\n * `ReferenceReplayRun` rows; this is the generic version used by\n * `MutationTelemetry`, `TrialTelemetry`, and any other consumer that wants\n * append-only durable telemetry without rolling its own lock.\n *\n * Locks are per absolute file path (process-local). Cross-process\n * concurrency is NOT addressed — that's an fcntl/flock problem.\n */\n\nimport { appendFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { Mutex } from './concurrency'\n\nconst mutexes = new Map<string, Mutex>()\n\nfunction getMutex(path: string): Mutex {\n let m = mutexes.get(path)\n if (!m) {\n m = new Mutex()\n mutexes.set(path, m)\n }\n return m\n}\n\nexport class LockedJsonlAppender {\n private readonly mutex: Mutex\n constructor(public readonly path: string) {\n this.mutex = getMutex(path)\n if (!existsSync(dirname(path))) {\n mkdirSync(dirname(path), { recursive: true })\n }\n }\n\n async append(entry: unknown): Promise<void> {\n const line = `${JSON.stringify(entry)}\\n`\n await this.mutex.runExclusive(() => {\n appendFileSync(this.path, line)\n })\n }\n}\n\n/** Reset all internal mutex state — tests only. */\nexport function resetLockedAppendersForTesting(): void {\n mutexes.clear()\n}\n","/**\n * FindingsStore — durable persistence for AnalystFinding rows + a diff\n * helper so we can answer \"what changed since the last run?\" without\n * recomputing analysts.\n *\n * On-disk shape is JSONL: one finding per line, append-only, locked via\n * LockedJsonlAppender. Operators get crash-safety (no partial JSON),\n * cheap reads (sequential parse), and trivial backup (rsync the file).\n *\n * Reads are non-locking: a reader sees a consistent snapshot of all\n * fully-written lines and skips an incomplete trailing line if the\n * writer is mid-append. Cross-process locking is intentionally out of\n * scope (see locked-jsonl-appender.ts).\n *\n * The store is run-scoped: callers pass `runId` on append and on load,\n * which keeps multi-run files cleanly partitioned. The `diffFindings`\n * helper compares two run-id sets using stable `finding_id` semantics —\n * the diff is the cross-run signal the regression dashboard renders.\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\n\nimport { LockedJsonlAppender } from '../locked-jsonl-appender'\nimport type { AnalystFinding } from './types'\n\n/**\n * One persisted row. We attach `run_id` on disk so a single file can\n * hold multiple runs and the diff helper can query without re-walking\n * separate files.\n */\nexport interface PersistedFinding extends AnalystFinding {\n run_id: string\n}\n\nexport class FindingsStore {\n private readonly appender: LockedJsonlAppender\n\n constructor(public readonly path: string) {\n this.appender = new LockedJsonlAppender(path)\n }\n\n async append(runId: string, findings: AnalystFinding[]): Promise<void> {\n for (const f of findings) {\n const row: PersistedFinding = { ...f, run_id: runId }\n await this.appender.append(row)\n }\n }\n\n /** Load every persisted finding. Discards malformed trailing lines silently. */\n loadAll(): PersistedFinding[] {\n if (!existsSync(this.path)) return []\n const raw = readFileSync(this.path, 'utf8')\n if (!raw) return []\n const out: PersistedFinding[] = []\n for (const line of raw.split('\\n')) {\n if (!line) continue\n try {\n out.push(JSON.parse(line) as PersistedFinding)\n } catch {\n // Skip torn trailing line — the lock guarantees no torn lines\n // mid-file, only at EOF when a writer is in-flight.\n }\n }\n return out\n }\n\n /** Filter to a single run. */\n loadRun(runId: string): PersistedFinding[] {\n return this.loadAll().filter((r) => r.run_id === runId)\n }\n}\n\n// ── Cross-run diff ──────────────────────────────────────────────────\n\nexport interface FindingsDiff {\n /** New finding ids in `current` that weren't in `previous`. */\n appeared: PersistedFinding[]\n /** Finding ids in `previous` that aren't in `current`. */\n disappeared: PersistedFinding[]\n /** Same finding id present in both runs and unchanged per the materiality test. */\n persisted: PersistedFinding[]\n /**\n * Same finding id in both runs but at least one non-identity field\n * shifted per `DiffPolicy.isMaterial`. Reported as [previous, current].\n */\n changed: Array<{ previous: PersistedFinding; current: PersistedFinding }>\n}\n\nexport interface DiffPolicy {\n /**\n * Predicate that decides whether two findings (same finding_id) count\n * as a material change. Defaults to {@link defaultIsMaterial}: severity\n * shift, confidence Δ > 0.05, or evidence count change. Compliance /\n * perf consumers MAY supply a stricter predicate (e.g. rationale text\n * diff, metric Δ thresholds).\n */\n isMaterial?: (previous: AnalystFinding, current: AnalystFinding) => boolean\n}\n\n/**\n * Default materiality test. Deliberately narrow so LLM-reword churn\n * doesn't flood the diff. Stricter tests are opt-in via DiffPolicy.\n */\nexport function defaultIsMaterial(a: AnalystFinding, b: AnalystFinding): boolean {\n if (a.severity !== b.severity) return true\n if (Math.abs((a.confidence ?? 0) - (b.confidence ?? 0)) > 0.05) return true\n if (a.evidence_refs.length !== b.evidence_refs.length) return true\n return false\n}\n\n/**\n * Diff two findings sets by stable finding_id. Callers typically load\n * the two run-id slices from the same store and pass them in.\n */\nexport function diffFindings(\n previous: PersistedFinding[],\n current: PersistedFinding[],\n policy: DiffPolicy = {},\n): FindingsDiff {\n const isMaterial = policy.isMaterial ?? defaultIsMaterial\n const prevById = new Map(previous.map((f) => [f.finding_id, f]))\n const curById = new Map(current.map((f) => [f.finding_id, f]))\n\n const appeared: PersistedFinding[] = []\n const disappeared: PersistedFinding[] = []\n const persisted: PersistedFinding[] = []\n const changed: FindingsDiff['changed'] = []\n\n for (const [id, cur] of curById) {\n const prev = prevById.get(id)\n if (!prev) {\n appeared.push(cur)\n continue\n }\n if (isMaterial(prev, cur)) {\n changed.push({ previous: prev, current: cur })\n } else {\n persisted.push(cur)\n }\n }\n for (const [id, prev] of prevById) {\n if (!curById.has(id)) disappeared.push(prev)\n }\n return { appeared, disappeared, persisted, changed }\n}\n","/**\n * Semantic concept judge — \"does the built artifact actually implement\n * the features the user asked for?\"\n *\n * Distinct from the domain/code/coherence judges in `judges.ts`:\n * - those judges score free-form conversational agent outputs along\n * quality dimensions (accuracy, depth, etc.)\n * - this judge scores a *built artifact* (served HTML + source files)\n * against an explicit list of expected concepts, returning per-concept\n * {present, score 0-10, evidence, severity}.\n *\n * The judge is strict about distinguishing (a) a working implementation\n * from (b) a keyword-present stub. \"// TODO: mint button\" is NOT present.\n * Only real, functional, wired-up code counts.\n *\n * Use via {@link createSemanticConceptJudge} or directly via\n * {@link runSemanticConceptJudge}. Soft-fails (available=false) on LLM\n * or JSON-parse errors so the caller can treat that as \"layer skipped\"\n * rather than \"layer failed\" in a multi-layer pipeline.\n */\n\nimport type { ChatClient } from './analyst/chat-client'\nimport { paidJsonChat } from './chat-json-call'\nimport {\n CostLedger,\n type CostLedgerHandle,\n type CostReceipt,\n type CustomTokenPricing,\n} from './cost-ledger'\nimport type { LlmCallRequest } from './llm-client'\nimport type { Severity } from './multi-layer-verifier'\n\n// ─── Types ──────────────────────────────────────────────────────────────\n\n/**\n * Implementation complexity class for weighted scoring.\n *\n * - `render` (default): the concept is a UI surface that displays static\n * data — render a list, show a counter, lay out a button. Single-file\n * work, no external integration.\n * - `integrate`: the concept requires wiring a real external system —\n * wallet connect (wagmi + RainbowKit + chain config), payment provider\n * (Stripe Elements + intent + webhook), an API client with auth.\n * Multi-file, library-knowledge, runtime correctness matters.\n * - `compute`: the concept requires algorithmic work — solver, simulator,\n * constraint propagation, ML inference. Correctness > UI polish.\n *\n * Default weights (when applied via `weightConcepts: 'complexity'`):\n * render=1.0, integrate=2.0, compute=2.5\n *\n * Cross-vertical scoring without complexity weighting silently inflates\n * the rate of UI-heavy verticals (healthcare, fintech dashboards) vs\n * integration-heavy verticals (DeFi, wallets) — all concepts treated\n * equally even though the agent does 2-3x the work for `integrate`.\n */\nexport type ConceptComplexity = 'render' | 'integrate' | 'compute'\n\nexport interface ConceptSpec {\n name: string\n /** Short hints that help the judge; not used for matching. */\n keywords?: string[]\n /** Optional explicit weight; default 1.0. Overrides complexity-derived weight. */\n weight?: number\n /** Implementation complexity class. Default `render`. */\n complexity?: ConceptComplexity\n}\n\nexport interface ConceptFinding {\n concept: string\n present: boolean\n /** 0..10. 10 = production-ready; 7 = functional thin; 4 = partial; 0 = absent. */\n score: number\n evidence: string\n severity: Severity\n}\n\nexport interface SemanticConceptJudgeInput {\n /** Full natural-language prompt the agent was handed. */\n userRequest: string\n /** Rendered HTML the preview returns (UI artifacts). Optional. */\n servedHtml?: string\n /** Top-level source files from the agent's workdir. */\n sourceFiles: Array<{ path: string; content: string }>\n /** The expected concept list. */\n expectedConcepts: ConceptSpec[]\n /** Free-form metadata (id, difficulty) to inject into the prompt. */\n artifactLabel?: string\n artifactDescription?: string\n}\n\nexport interface SemanticConceptJudgeResult {\n kind: 'semantic-concept'\n version: string\n /** Normalized 0..1 score — mean of per-concept scores / 10. */\n score: number\n presentCount: number\n totalCount: number\n findings: ConceptFinding[]\n summary: string\n durationMs: number\n costUsd: number | null\n /** False on LLM/JSON error — treat as \"skipped / unable to judge\" in pipelines. */\n available: boolean\n error?: string\n}\n\n/**\n * Score-aggregation strategy. `mean` averages 0-10 scores uniformly.\n * `complexity` applies the default weight table (render=1, integrate=2,\n * compute=2.5) unless a concept has an explicit `weight`. `explicit`\n * honors only `weight` (defaulting to 1 for unspecified).\n */\nexport type ConceptWeightStrategy = 'mean' | 'complexity' | 'explicit'\n\nexport const DEFAULT_COMPLEXITY_WEIGHTS: Record<ConceptComplexity, number> = {\n render: 1.0,\n integrate: 2.0,\n compute: 2.5,\n}\n\nexport interface SemanticConceptJudgeOptions {\n /** Model id to call. Default 'claude-sonnet-4-6' via agent-eval defaults. */\n model?: string\n /** Per-call timeout. Default 300s. */\n timeoutMs?: number\n /** Provider-enforced output limit. Default 16000. */\n maxTokens?: number\n /** Pipeline budget for the prompt (source blob truncation). Default 45000. */\n maxSourceChars?: number\n /** Per-file cap before inclusion. Default 20000. */\n maxPerFileChars?: number\n /** HTML cap. Default 30000. */\n maxHtmlChars?: number\n /** Caller-owned transport. Required: agent-eval executes no paid model. */\n chat: ChatClient\n /** Endpoint rates used when the transport reports no billed amount. */\n pricing?: CustomTokenPricing\n costLedger?: CostLedgerHandle\n costPhase?: string\n costTags?: Record<string, string>\n signal?: AbortSignal\n /**\n * Score aggregation strategy. Default `mean` — uniform average across\n * concepts. Cross-vertical comparisons should use `complexity` to\n * neutralize the integrate-vs-render asymmetry.\n */\n weightConcepts?: ConceptWeightStrategy\n /** Override the default complexity → weight table. */\n complexityWeights?: Partial<Record<ConceptComplexity, number>>\n}\n\n// ─── Prompt assembly ────────────────────────────────────────────────────\n\nexport const SEMANTIC_CONCEPT_JUDGE_VERSION = 'semantic-concept-judge-v1-2026-04-24'\n\nconst DEFAULT_MAX_SOURCE = 45_000\nconst DEFAULT_MAX_HTML = 30_000\nconst DEFAULT_MAX_PER_FILE = 20_000\nconst DEFAULT_TIMEOUT = 300_000\nconst DEFAULT_MAX_TOKENS = 16_000\nconst DEFAULT_MODEL = 'claude-sonnet-4-6'\n\nconst SEMANTIC_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n required: ['summary', 'concepts'],\n properties: {\n summary: { type: 'string', minLength: 20, maxLength: 600 },\n concepts: {\n type: 'array',\n minItems: 1,\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['concept', 'present', 'score', 'evidence', 'severity'],\n properties: {\n concept: { type: 'string', minLength: 1, maxLength: 120 },\n present: { type: 'boolean' },\n score: { type: 'number', minimum: 0, maximum: 10 },\n evidence: { type: 'string', minLength: 5, maxLength: 400 },\n severity: { type: 'string', enum: ['critical', 'major', 'minor', 'info'] },\n },\n },\n },\n },\n}\n\nfunction truncate(body: string, cap: number, label: string): string {\n if (body.length <= cap) return body\n return `${body.slice(0, cap)}\\n… [truncated ${body.length - cap} chars of ${label}]`\n}\n\nfunction buildPrompt(\n input: SemanticConceptJudgeInput,\n opts: { maxPerFileChars: number; maxSourceChars: number; maxHtmlChars: number },\n): string {\n const sourceBlob = input.sourceFiles\n .filter((f) => f.content.length <= opts.maxPerFileChars)\n .map((f) => `--- FILE: ${f.path} ---\\n${f.content}`)\n .join('\\n\\n')\n\n const html = input.servedHtml ?? ''\n\n return `You are a strict code-review judge evaluating whether an agent's 0-to-1 build actually implements the features the user asked for.\n\nYou MUST distinguish:\n (a) WORKING code that implements the concept (rendered UI, wired handler, real API call),\n (b) KEYWORD-PRESENT stub (comments mentioning the concept, variable names, TODOs),\n (c) ABSENT (concept nowhere).\n\nA comment like \"// TODO: add mint button\" is NOT present — score 2-3. Only count a concept as present if there is real functional code: a rendered component, a call handler wired to state or a network call, a computed value actually used.\n\nUSER REQUEST (what the agent was asked to build):\n${input.userRequest}\n\n${input.artifactLabel ? `ARTIFACT METADATA:\\n name: ${input.artifactLabel}\\n description: ${input.artifactDescription ?? ''}\\n\\n` : ''}EXPECTED CONCEPTS (each must be graded independently):\n${input.expectedConcepts\n .map(\n (c, i) =>\n ` ${i + 1}. \"${c.name}\"${c.keywords?.length ? ` — hints: [${c.keywords.slice(0, 6).join(' | ')}]` : ''}`,\n )\n .join('\\n')}\n\n${html ? `SERVED HTML (what the preview returns when hit):\\n${truncate(html, opts.maxHtmlChars, 'HTML')}\\n\\n` : ''}SOURCE FILES (the agent's workdir):\n${truncate(sourceBlob, opts.maxSourceChars, 'source')}\n\nFor EACH concept, return:\n - concept: the concept name as given (match exactly)\n - present: boolean — does a working implementation exist?\n - score: 0-10 — 10 = production-ready; 7 = functional but thin; 4 = partial/stubbed; 2 = keyword-only comment; 0 = absent\n - evidence: cite \"<file>:<line>\" or \"served-html:<selector>\" pointing at the strongest supporting code. If the concept is absent or stubbed, explain what's missing.\n - severity:\n \"info\" when present: true AND score >= 7\n \"minor\" when present: true AND 4 <= score < 7\n \"major\" when present: false OR score < 4\n \"critical\" when the concept is not only absent but a core user flow depends on it\n\nAlso produce a \"summary\" (one sentence, 20-600 chars): overall verdict on whether this is a shippable implementation of the user request vs a keyword-dense placeholder.\n\nBE SKEPTICAL. Keyword matching already passed — your job is to catch what keyword matching misses. If the agent shipped a working build, say so. If it shipped a stub, say so. Don't grade on effort.\n\nReturn STRICT JSON. No prose outside the JSON.`\n}\n\n// ─── Runner ─────────────────────────────────────────────────────────────\n\n/**\n * Run the semantic concept judge. Soft-fails to available=false on\n * LLM/JSON errors — callers in a MultiLayerVerifier pipeline can treat\n * that as \"skip\" rather than \"fail.\"\n */\nexport async function runSemanticConceptJudge(\n input: SemanticConceptJudgeInput,\n options: SemanticConceptJudgeOptions,\n): Promise<SemanticConceptJudgeResult> {\n const start = Date.now()\n const totalCount = input.expectedConcepts.length\n\n if (totalCount === 0) {\n return {\n kind: 'semantic-concept',\n version: SEMANTIC_CONCEPT_JUDGE_VERSION,\n score: 0,\n presentCount: 0,\n totalCount: 0,\n findings: [],\n summary: 'no expected concepts declared',\n durationMs: 0,\n costUsd: null,\n available: false,\n error: 'no expected concepts declared',\n }\n }\n\n const opts = {\n chat: options.chat,\n model: options.model ?? options.chat.defaultModel ?? DEFAULT_MODEL,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT,\n maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,\n maxSourceChars: options.maxSourceChars ?? DEFAULT_MAX_SOURCE,\n maxPerFileChars: options.maxPerFileChars ?? DEFAULT_MAX_PER_FILE,\n maxHtmlChars: options.maxHtmlChars ?? DEFAULT_MAX_HTML,\n ...(options.pricing ? { pricing: options.pricing } : {}),\n costLedger: options.costLedger ?? new CostLedger(),\n costPhase: options.costPhase ?? 'judge.semantic-concept',\n costTags: options.costTags ?? {},\n signal: options.signal ?? new AbortController().signal,\n weightConcepts: options.weightConcepts ?? 'mean',\n complexityWeights: { ...DEFAULT_COMPLEXITY_WEIGHTS, ...(options.complexityWeights ?? {}) },\n }\n\n // Build a name → weight map for aggregation. Mean strategy keeps every\n // weight at 1 (uniform average). Complexity strategy reads the table\n // and lets an explicit `weight` override. Explicit strategy uses ONLY\n // the spec's `weight` (defaulting to 1).\n const weightForConcept = (spec: ConceptSpec): number => {\n if (opts.weightConcepts === 'mean') return 1\n if (spec.weight != null) return spec.weight\n if (opts.weightConcepts === 'complexity') {\n return opts.complexityWeights[spec.complexity ?? 'render'] ?? 1\n }\n return 1\n }\n const weightByName = new Map<string, number>(\n input.expectedConcepts.map((c) => [c.name, weightForConcept(c)]),\n )\n\n let receipt: CostReceipt | undefined\n try {\n const request = {\n model: opts.model,\n messages: [\n {\n role: 'system' as const,\n content:\n 'You are a strict code-review judge. Return strict JSON only. No prose outside the JSON. A keyword in a comment is NOT a working implementation.',\n },\n { role: 'user' as const, content: buildPrompt(input, opts) },\n ],\n jsonSchema: { name: 'semantic_concept_judge', schema: SEMANTIC_SCHEMA },\n temperature: 0,\n maxTokens: opts.maxTokens,\n timeoutMs: opts.timeoutMs,\n } satisfies LlmCallRequest\n const paid = await paidJsonChat<{ summary: string; concepts: ConceptFinding[] }>({\n chat: opts.chat,\n request,\n ledger: opts.costLedger,\n channel: 'judge',\n phase: opts.costPhase,\n actor: 'semantic-concept',\n tags: opts.costTags,\n signal: opts.signal,\n ...(opts.pricing ? { pricing: opts.pricing } : {}),\n })\n receipt = paid.receipt\n if (!paid.succeeded) throw paid.error\n const { value } = paid\n\n if (!value?.concepts || !Array.isArray(value.concepts)) {\n throw new Error('judge returned malformed response — expected array under \"concepts\"')\n }\n\n const findings: ConceptFinding[] = value.concepts.map((c) => ({\n concept: String(c.concept),\n present: Boolean(c.present),\n score: Math.max(0, Math.min(10, Number(c.score ?? 0))),\n evidence: String(c.evidence ?? ''),\n severity: (['critical', 'major', 'minor', 'info'] as const).includes(c.severity)\n ? c.severity\n : 'info',\n }))\n\n const presentCount = findings.filter((f) => f.present && f.score >= 7).length\n let weightSum = 0\n let weightedScoreSum = 0\n for (const f of findings) {\n const w = weightByName.get(f.concept) ?? 1\n weightSum += w\n weightedScoreSum += w * f.score\n }\n const scoreAvg =\n weightSum > 0\n ? weightedScoreSum / weightSum\n : findings.reduce((a, f) => a + f.score, 0) / Math.max(1, findings.length)\n\n return {\n kind: 'semantic-concept',\n version: SEMANTIC_CONCEPT_JUDGE_VERSION,\n score: Number((scoreAvg / 10).toFixed(3)),\n presentCount,\n totalCount,\n findings,\n summary: String(value.summary ?? ''),\n durationMs: Date.now() - start,\n costUsd: paid.receipt.costUnknown ? null : paid.receipt.costUsd,\n available: true,\n }\n } catch (err) {\n return {\n kind: 'semantic-concept',\n version: SEMANTIC_CONCEPT_JUDGE_VERSION,\n score: 0,\n presentCount: 0,\n totalCount,\n findings: [],\n summary: '',\n durationMs: Date.now() - start,\n costUsd: receipt && !receipt.costUnknown ? receipt.costUsd : null,\n available: false,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n}\n\n/**\n * Factory: pin LLM options once, return a closure that accepts inputs.\n * Convenient for pipelines that want to share a single LlmClient config.\n */\nexport function createSemanticConceptJudge(\n options: SemanticConceptJudgeOptions,\n): (input: SemanticConceptJudgeInput) => Promise<SemanticConceptJudgeResult> {\n return (input) => runSemanticConceptJudge(input, options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,4BAA4B;AAClC,MAAM,YAAY;;AAGlB,MAAM,oBAAoB;;;;;;AAqC1B,SAAS,wBAA2E;CAClF,MAAM,MAAM,EAAE,aAAa,yBAAyB,EAAE,QAAQ,UAAU,CAAC;CAIzE,OAA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,EAAE,QAAQ,IAC3E,EAAE,WACF;EACN,EAAE;EAEF,MAAM,eAAe,SAAS,QAAQ,MAAM,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC,CAAC;EACvE,IAAI,YAAY;EAChB,IAAI,mBAAmB;EACvB,KAAK,MAAM,KAAK,UAAU;GACxB,MAAM,IAAI,aAAa,IAAI,EAAE,OAAO,KAAK;GACzC,aAAa;GACb,oBAAoB,IAAI,EAAE;EAC5B;EACA,MAAM,WACJ,YAAY,IACR,mBAAmB,YACnB,SAAS,QAAQ,GAAG,MAAM,IAAI,EAAE,OAAO,CAAC,IAAI,KAAK,IAAI,GAAG,SAAS,MAAM;EAE7E,OAAO;GACL,MAAM;GACN,SAAS;GACT,OAAO,QAAQ,WAAW,GAAA,CAAI,QAAQ,CAAC,CAAC;GACxC;GACA;GACA;GACA,SAAS,OAAO,MAAM,WAAW,EAAE;GACnC,YAAY,KAAK,IAAI,IAAI;GACzB,SAAS,KAAK,QAAQ,cAAc,OAAO,KAAK,QAAQ;GACxD,WAAW;EACb;CACF,SAAS,KAAK;EACZ,OAAO;GACL,MAAM;GACN,SAAS;GACT,OAAO;GACP,cAAc;GACd;GACA,UAAU,CAAC;GACX,SAAS;GACT,YAAY,KAAK,IAAI,IAAI;GACzB,SAAS,WAAW,CAAC,QAAQ,cAAc,QAAQ,UAAU;GAC7D,WAAW;GACX,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;EACxD;CACF;AACF"}
1
+ {"version":3,"file":"semantic-concept-judge-BbiYuv7U.js","names":[],"sources":["../src/analyst/chat-trace-engine.ts","../src/locked-jsonl-appender.ts","../src/analyst/findings-store.ts","../src/semantic-concept-judge.ts"],"sourcesContent":["/**\n * A `TraceAnalysisEngine` that runs entirely inside Node against a\n * caller-owned `ChatClient`.\n *\n * The other engine in this package, `createDspyRlmTraceEngine`, reaches the\n * DSPy RLM through a Python subprocess. That made every model-backed analyst\n * unreachable for a consumer that already owns a model seam and no Python:\n * `createTraceAnalyst` requires an engine, the only exported constructor\n * required a Python runner, so `buildDefaultAnalystRegistry()` registered the\n * deterministic analyst alone and `analystsFromRegistry` refused the result.\n *\n * This engine closes that path. It drives the same investigation contract —\n * bounded trace tools, a prose answer, a strict findings array — with native\n * function calls over the transport the caller already bound with\n * `createChatClient`. A caller holding a bare\n * `(request: LlmCallRequest) => Promise<LlmCallResult>` adapts it in one line:\n *\n * createChatClient({ transport: 'custom', chat: call, defaultModel, maximumAttempts })\n *\n * agent-eval still executes no paid model and holds no provider credential.\n * Every call goes through `paidChat`, so the shared cost ledger reserves the\n * priced maximum before the call and settles the receipt after it.\n *\n * Shape of one investigation:\n * 1. Investigation turns. The model reads the trace store through the tools\n * its analyst kind was given. A turn that requests no tool ends the\n * phase; an exhausted iteration or tool budget also ends it.\n * 2. One report turn. The model returns `{ answer, findings }` as JSON,\n * decoded by the same `decodeRawFindingArray` the Python bridge uses, so\n * a row this engine accepts is a row that engine could report.\n */\n\nimport { z } from 'zod'\nimport { paidChat } from '../chat-json-call'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport {\n extractJsonPayload,\n type LlmCallRequest,\n type LlmMessage,\n type LlmThinkingMode,\n type LlmToolCall,\n type LlmToolDefinition,\n} from '../llm-client'\nimport type { TraceAnalysisToolDescriptor } from '../trace-analyst/tools'\nimport type { ChatClient } from './chat-client'\nimport {\n DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS,\n type TraceAnalysisEngine,\n type TraceAnalysisEngineRequest,\n type TraceAnalysisEngineResult,\n} from './engine'\nimport { decodeRawFindingArray } from './finding-codec'\nimport { RawAnalystFindingSchema } from './finding-signature'\n\n/** Bumped whenever this engine's execution behavior changes. */\nconst CHAT_TRACE_ENGINE_VERSION = '1.0.0'\nconst ENGINE_ID = 'chat-trace'\n\n/** Marker appended to a tool result cut down to the retained-output budget. */\nconst TRUNCATION_MARKER = '\\n…[truncated to the analyst maxOutputChars budget]'\n\nexport interface ChatTraceEngineOptions {\n /**\n * Caller-owned transport. Build it with `createChatClient`; agent-eval never\n * receives the provider credential.\n */\n chat: ChatClient\n /** Model for every call. Defaults to the client's `defaultModel`. */\n model?: string\n /** Endpoint rates used when the transport reports no billed amount. */\n pricing?: CustomTokenPricing\n /** Completion cap per turn. Default: {@link DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS}. */\n maxOutputTokens?: number\n /** Sampling temperature. Omitted from the request when absent. */\n temperature?: number\n /** Provider reasoning mode. Omitted when the provider default should apply. */\n thinking?: LlmThinkingMode\n /** Per-call deadline handed to the transport. */\n requestTimeoutMs?: number\n /**\n * How the report turn asks for structured output.\n *\n * `json-object` sends JSON mode, which every OpenAI-compatible endpoint\n * accepts, and relies on the finding grammar the analyst kind already puts\n * in its instructions. `json-schema` sends the generated response schema as\n * well, which stricter endpoints honour and older ones reject. Default:\n * `json-object`.\n */\n reportFormat?: 'json-object' | 'json-schema'\n}\n\n/**\n * The report envelope. Its `findings` rows are generated from\n * `RawAnalystFindingSchema`, so the schema offered to a provider and the\n * decoder that accepts the answer cannot drift apart.\n */\nfunction buildReportJsonSchema(): { name: string; schema: Record<string, unknown> } {\n const row = z.toJSONSchema(RawAnalystFindingSchema, { target: 'draft-7' }) as Record<\n string,\n unknown\n >\n delete row.$schema\n return {\n name: 'trace_analysis_report',\n schema: {\n type: 'object',\n additionalProperties: false,\n required: ['answer', 'findings'],\n properties: {\n answer: { type: 'string', description: 'Direct prose answer to the question.' },\n findings: { type: 'array', items: row },\n },\n },\n }\n}\n\nconst REPORT_JSON_SCHEMA = buildReportJsonSchema()\n\n/**\n * Run bounded recursive trace analysis in-process over a caller-owned chat\n * transport. No Python, no subprocess, no loopback proxy.\n */\nexport function createChatTraceEngine(options: ChatTraceEngineOptions): TraceAnalysisEngine {\n const model = resolveModel(options)\n const maxOutputTokens = options.maxOutputTokens ?? DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS\n if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) {\n throw new TypeError('chat trace engine maxOutputTokens must be a positive safe integer')\n }\n if (\n options.temperature !== undefined &&\n (!Number.isFinite(options.temperature) || options.temperature < 0)\n ) {\n throw new TypeError('chat trace engine temperature must be a non-negative finite number')\n }\n if (\n options.requestTimeoutMs !== undefined &&\n (!Number.isSafeInteger(options.requestTimeoutMs) || options.requestTimeoutMs <= 0)\n ) {\n throw new TypeError('chat trace engine requestTimeoutMs must be a positive safe integer')\n }\n const reportFormat = options.reportFormat ?? 'json-object'\n if (reportFormat !== 'json-object' && reportFormat !== 'json-schema') {\n throw new TypeError(`chat trace engine reportFormat must be json-object or json-schema`)\n }\n\n return {\n id: ENGINE_ID,\n description:\n 'In-process recursive trace analysis over a caller-owned ChatClient with native tool calls.',\n model,\n version: CHAT_TRACE_ENGINE_VERSION,\n executionConfig: {\n kind: ENGINE_ID,\n model,\n transport: options.chat.transport,\n maximum_attempts: options.chat.maximumAttempts ?? null,\n pricing: options.pricing ? { ...options.pricing } : null,\n max_output_tokens: maxOutputTokens,\n temperature: options.temperature ?? null,\n thinking: options.thinking ?? null,\n request_timeout_ms: options.requestTimeoutMs ?? null,\n report_format: reportFormat,\n report_schema_name: REPORT_JSON_SCHEMA.name,\n },\n analyze: (request) => analyze(request, { ...options, model, maxOutputTokens, reportFormat }),\n }\n}\n\ninterface ResolvedOptions extends ChatTraceEngineOptions {\n model: string\n maxOutputTokens: number\n reportFormat: 'json-object' | 'json-schema'\n}\n\nasync function analyze(\n request: TraceAnalysisEngineRequest,\n options: ResolvedOptions,\n): Promise<TraceAnalysisEngineResult> {\n // One model call is spent on the report, so a budget of one call would buy\n // an answer with no investigation behind it. Refuse instead of pretending.\n if (request.limits.maxLlmCalls < 2) {\n throw new Error(\n `chat trace engine reserves one model call for the report, so maxLlmCalls must be at least 2 (analyst '${request.analystId}' declared ${request.limits.maxLlmCalls})`,\n )\n }\n const toolsByName = new Map(request.tools.map((tool) => [tool.name, tool]))\n if (toolsByName.size !== request.tools.length) {\n throw new Error(`chat trace engine received duplicate tool names for '${request.analystId}'`)\n }\n const toolDefinitions: LlmToolDefinition[] = request.tools.map((tool) => ({\n type: 'function',\n function: { name: tool.name, description: tool.description, parameters: tool.parameters },\n }))\n const investigationTurns = Math.max(\n 1,\n Math.min(request.limits.maxIterations, request.limits.maxLlmCalls - 1),\n )\n\n const messages: LlmMessage[] = [\n { role: 'system', content: systemPrompt(request, investigationTurns) },\n ]\n if (request.taskInputs) {\n messages.push({ role: 'user', content: renderTaskInputs(request.taskInputs) })\n }\n messages.push({ role: 'user', content: request.question })\n\n request.log?.('trace analyst engine started', {\n engine: ENGINE_ID,\n model: options.model,\n transport: options.chat.transport,\n tools: request.tools.map((tool) => tool.name),\n limits: request.limits,\n })\n\n const trajectory: unknown[] = []\n const servedModels = new Set<string>()\n let modelCalls = 0\n let toolCalls = 0\n let truncatedToolResults = 0\n let toolBudgetExhausted = false\n let turnsUsed = 0\n let stoppedOnAnswer = false\n\n for (let turn = 0; turn < investigationTurns; turn++) {\n turnsUsed = turn + 1\n const response = await callModel(request, options, {\n messages,\n tools: toolDefinitions,\n toolChoice: 'auto',\n purpose: 'investigation',\n })\n modelCalls += 1\n servedModels.add(response.servedModel ?? 'unreported')\n const requested = response.toolCalls ?? []\n messages.push({\n role: 'assistant',\n content: response.content,\n ...(requested.length > 0 ? { toolCalls: requested } : {}),\n })\n trajectory.push({\n turn: turnsUsed,\n phase: 'investigation',\n content: response.content,\n tool_calls: requested.map((call) => ({ id: call.id, name: call.name })),\n finish_reason: response.finishReason ?? null,\n })\n if (requested.length === 0) {\n stoppedOnAnswer = true\n break\n }\n for (const call of requested) {\n if (toolCalls >= request.limits.maxToolCalls) {\n toolBudgetExhausted = true\n // Every requested id still needs an answer: a provider rejects the\n // next turn when one tool call is left unanswered.\n messages.push(toolMessage(call, exhaustedToolBudget(request.limits.maxToolCalls)))\n continue\n }\n toolCalls += 1\n const executed = await executeTool(call, toolsByName, request)\n if (executed.truncated) truncatedToolResults += 1\n messages.push(toolMessage(call, executed.payload))\n trajectory.push({\n turn: turnsUsed,\n phase: 'tool',\n name: call.name,\n ok: executed.ok,\n truncated: executed.truncated,\n result_chars: executed.payload.length,\n })\n }\n if (toolBudgetExhausted) break\n }\n\n messages.push({ role: 'user', content: reportPrompt(options.reportFormat) })\n const report = await callModel(request, options, {\n messages,\n purpose: 'report',\n json: options.reportFormat,\n })\n modelCalls += 1\n servedModels.add(report.servedModel ?? 'unreported')\n trajectory.push({\n turn: turnsUsed + 1,\n phase: 'report',\n content: report.content,\n finish_reason: report.finishReason ?? null,\n })\n\n const parsed = parseReport(report.content, request.analystId, (index, reason) => {\n request.log?.('finding rejected: report row failed schema validation', {\n engine: ENGINE_ID,\n index,\n reason,\n })\n })\n\n const result: TraceAnalysisEngineResult = {\n answer: parsed.answer,\n findings: parsed.findings,\n trajectory,\n modelCalls,\n toolCalls,\n runtime: {\n engine: ENGINE_ID,\n model: options.model,\n transport: options.chat.transport,\n report_format: options.reportFormat,\n investigation_turns: turnsUsed,\n investigation_stopped_on_answer: stoppedOnAnswer,\n tool_budget_exhausted: toolBudgetExhausted,\n truncated_tool_results: truncatedToolResults,\n rejected_findings: parsed.rejectedFindings,\n // A gateway can answer `model: X` from another model on HTTP 200, so the\n // ids the provider echoed travel with the result as evidence.\n served_models: [...servedModels].sort(),\n task_inputs: request.taskInputs ? 'prompt-delivered' : 'none',\n },\n }\n request.log?.('trace analyst engine completed', {\n engine: ENGINE_ID,\n model_calls: result.modelCalls,\n tool_calls: result.toolCalls,\n findings: result.findings.length,\n })\n return result\n}\n\ninterface ModelTurn {\n content: string\n toolCalls?: LlmToolCall[]\n servedModel?: string | null\n finishReason?: string | null\n}\n\nasync function callModel(\n request: TraceAnalysisEngineRequest,\n options: ResolvedOptions,\n turn: {\n messages: LlmMessage[]\n tools?: LlmToolDefinition[]\n toolChoice?: LlmCallRequest['toolChoice']\n purpose: 'investigation' | 'report'\n json?: 'json-object' | 'json-schema'\n },\n): Promise<ModelTurn> {\n const chatRequest: LlmCallRequest = {\n model: options.model,\n // The transport may mutate what it is handed; the conversation is ours.\n messages: turn.messages.map((message) => ({ ...message })),\n maxTokens: options.maxOutputTokens,\n ...(turn.tools && turn.tools.length > 0\n ? { tools: turn.tools, ...(turn.toolChoice ? { toolChoice: turn.toolChoice } : {}) }\n : {}),\n ...(turn.json ? { jsonMode: true } : {}),\n ...(turn.json === 'json-schema' ? { jsonSchema: REPORT_JSON_SCHEMA } : {}),\n ...(options.temperature === undefined ? {} : { temperature: options.temperature }),\n ...(options.thinking === undefined ? {} : { thinking: options.thinking }),\n ...(options.requestTimeoutMs === undefined ? {} : { timeoutMs: options.requestTimeoutMs }),\n }\n const paid = await paidChat({\n chat: options.chat,\n request: chatRequest,\n ledger: request.costLedger,\n channel: 'analyst',\n phase: request.costPhase,\n actor: request.analystId,\n ...(request.costTags ? { tags: request.costTags } : {}),\n ...(options.pricing ? { pricing: options.pricing } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n if (!paid.succeeded) {\n // The transport already spent its own attempts. A failure here ends the\n // investigation: continuing would report an answer the model never gave.\n throw new Error(\n `chat trace engine ${turn.purpose} call failed for '${request.analystId}': ${paid.error.message}`,\n { cause: paid.error },\n )\n }\n return {\n content: paid.response.content,\n ...(paid.response.toolCalls ? { toolCalls: paid.response.toolCalls } : {}),\n ...(paid.response.servedModel === undefined ? {} : { servedModel: paid.response.servedModel }),\n ...(paid.response.finishReason === undefined\n ? {}\n : { finishReason: paid.response.finishReason }),\n }\n}\n\ninterface ExecutedTool {\n ok: boolean\n truncated: boolean\n payload: string\n}\n\nasync function executeTool(\n call: LlmToolCall,\n toolsByName: ReadonlyMap<string, TraceAnalysisToolDescriptor>,\n request: TraceAnalysisEngineRequest,\n): Promise<ExecutedTool> {\n const descriptor = toolsByName.get(call.name)\n if (!descriptor) {\n return {\n ok: false,\n truncated: false,\n payload: toolError(\n `unknown tool '${call.name}'; available tools are ${[...toolsByName.keys()].sort().join(', ')}`,\n ),\n }\n }\n let args: unknown\n try {\n args = call.argumentsJson.trim() === '' ? {} : JSON.parse(call.argumentsJson)\n } catch (error) {\n return {\n ok: false,\n truncated: false,\n payload: toolError(\n `arguments for '${call.name}' were not JSON: ${messageOf(error)}. Send valid JSON arguments.`,\n ),\n }\n }\n try {\n const value = await descriptor.handler(\n args,\n request.signal ? { signal: request.signal } : undefined,\n )\n return truncateToolPayload(JSON.stringify(value ?? null), request.limits.maxOutputChars)\n } catch (error) {\n // A bounded store refuses an oversized or malformed read by design. That\n // refusal is the model's next instruction, not the run's failure.\n if (request.signal?.aborted) throw error\n request.log?.('trace tool failed', {\n engine: ENGINE_ID,\n analyst_id: request.analystId,\n tool: call.name,\n reason: messageOf(error),\n })\n return { ok: false, truncated: false, payload: toolError(messageOf(error)) }\n }\n}\n\nfunction truncateToolPayload(payload: string, maxOutputChars: number): ExecutedTool {\n if (payload.length <= maxOutputChars) return { ok: true, truncated: false, payload }\n const keep = Math.max(0, maxOutputChars - TRUNCATION_MARKER.length)\n return { ok: true, truncated: true, payload: `${payload.slice(0, keep)}${TRUNCATION_MARKER}` }\n}\n\nfunction toolMessage(call: LlmToolCall, content: string): LlmMessage {\n return { role: 'tool', toolCallId: call.id, content }\n}\n\nfunction toolError(reason: string): string {\n return JSON.stringify({ error: reason })\n}\n\nfunction exhaustedToolBudget(maxToolCalls: number): string {\n return toolError(\n `the trace-tool budget of ${maxToolCalls} calls is spent; answer from the evidence already read`,\n )\n}\n\nfunction systemPrompt(request: TraceAnalysisEngineRequest, investigationTurns: number): string {\n return [\n request.instructions.trim(),\n [\n 'HOW THIS INVESTIGATION RUNS:',\n `- You have ${investigationTurns} investigation turns and at most ${request.limits.maxToolCalls} trace-tool calls.`,\n '- Call the trace tools to read the store. Never state a trace fact you did not read.',\n `- A tool result longer than ${request.limits.maxOutputChars} characters is truncated; narrow the query instead of asking again.`,\n '- A tool result carrying an \"error\" field is feedback: fix the call or take another route.',\n '- Answer with no tool call once you have the evidence. You are then asked for the final report.',\n ].join('\\n'),\n ].join('\\n\\n')\n}\n\nfunction reportPrompt(reportFormat: 'json-object' | 'json-schema'): string {\n return [\n 'Report now. Do not call any more tools.',\n 'Return one JSON object with exactly two fields:',\n ' \"answer\": a direct prose answer to the question.',\n ' \"findings\": an array of findings in the schema above. Emit [] when there is nothing to report.',\n reportFormat === 'json-object'\n ? 'Return the object alone, with no surrounding prose and no code fence.'\n : 'Return the object in the response schema you were given.',\n ].join('\\n')\n}\n\nfunction renderTaskInputs(taskInputs: Readonly<Record<string, unknown>>): string {\n // The engine contract forbids dropping structured inputs. This engine has no\n // code environment to bind them as variables, so they are delivered whole as\n // conversation material and the runtime record says which way they arrived.\n return [\n 'TASK INPUTS — structured material delivered with the question, not fetched through tools:',\n JSON.stringify(taskInputs, null, 2),\n ].join('\\n')\n}\n\ninterface ParsedReport {\n answer: string\n findings: TraceAnalysisEngineResult['findings']\n rejectedFindings: number\n}\n\nfunction parseReport(\n content: string,\n analystId: string,\n onRejectedFinding: (index: number, reason: string) => void,\n): ParsedReport {\n const envelope = coerceReportEnvelope(content, analystId)\n if (typeof envelope.answer !== 'string' || !envelope.answer.trim()) {\n throw new Error(`chat trace engine report for '${analystId}' carried no answer`)\n }\n // Findings are model output: one malformed row is model noise, not an engine\n // fault, and the rest of the paid investigation must survive it.\n const decoded = decodeRawFindingArray(envelope.findings)\n if (decoded.topLevelError !== undefined) {\n throw new Error(\n `chat trace engine report for '${analystId}' had a malformed findings array: ${decoded.topLevelError}`,\n )\n }\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 return {\n answer: envelope.answer,\n findings: decoded.accepted,\n rejectedFindings: decoded.rejected.length,\n }\n}\n\nfunction coerceReportEnvelope(content: string, analystId: string): Record<string, unknown> {\n let value: unknown\n try {\n value = JSON.parse(extractJsonPayload(content))\n } catch (error) {\n throw new Error(`chat trace engine report for '${analystId}' was not JSON: ${messageOf(error)}`)\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`chat trace engine report for '${analystId}' was not a JSON object`)\n }\n return value as Record<string, unknown>\n}\n\nfunction resolveModel(options: ChatTraceEngineOptions): string {\n const model = options.model ?? options.chat.defaultModel\n if (typeof model !== 'string' || !model.trim() || model !== model.trim()) {\n throw new TypeError(\n 'chat trace engine needs a model: pass ChatTraceEngineOptions.model or bind defaultModel on the ChatClient',\n )\n }\n return model\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * LockedJsonlAppender — mutex-serialized JSONL append helper for arbitrary\n * payloads. The reference-replay store does the same thing for typed\n * `ReferenceReplayRun` rows; this is the generic version used by\n * `MutationTelemetry`, `TrialTelemetry`, and any other consumer that wants\n * append-only durable telemetry without rolling its own lock.\n *\n * Locks are per absolute file path (process-local). Cross-process\n * concurrency is NOT addressed — that's an fcntl/flock problem.\n */\n\nimport { appendFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { Mutex } from './concurrency'\n\nconst mutexes = new Map<string, Mutex>()\n\nfunction getMutex(path: string): Mutex {\n let m = mutexes.get(path)\n if (!m) {\n m = new Mutex()\n mutexes.set(path, m)\n }\n return m\n}\n\nexport class LockedJsonlAppender {\n private readonly mutex: Mutex\n constructor(public readonly path: string) {\n this.mutex = getMutex(path)\n if (!existsSync(dirname(path))) {\n mkdirSync(dirname(path), { recursive: true })\n }\n }\n\n async append(entry: unknown): Promise<void> {\n const line = `${JSON.stringify(entry)}\\n`\n await this.mutex.runExclusive(() => {\n appendFileSync(this.path, line)\n })\n }\n}\n\n/** Reset all internal mutex state — tests only. */\nexport function resetLockedAppendersForTesting(): void {\n mutexes.clear()\n}\n","/**\n * FindingsStore — durable persistence for AnalystFinding rows + a diff\n * helper so we can answer \"what changed since the last run?\" without\n * recomputing analysts.\n *\n * On-disk shape is JSONL: one finding per line, append-only, locked via\n * LockedJsonlAppender. Operators get crash-safety (no partial JSON),\n * cheap reads (sequential parse), and trivial backup (rsync the file).\n *\n * Reads are non-locking: a reader sees a consistent snapshot of all\n * fully-written lines and skips an incomplete trailing line if the\n * writer is mid-append. Cross-process locking is intentionally out of\n * scope (see locked-jsonl-appender.ts).\n *\n * The store is run-scoped: callers pass `runId` on append and on load,\n * which keeps multi-run files cleanly partitioned. The `diffFindings`\n * helper compares two run-id sets using stable `finding_id` semantics —\n * the diff is the cross-run signal the regression dashboard renders.\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\n\nimport { LockedJsonlAppender } from '../locked-jsonl-appender'\nimport type { AnalystFinding } from './types'\n\n/**\n * One persisted row. We attach `run_id` on disk so a single file can\n * hold multiple runs and the diff helper can query without re-walking\n * separate files.\n */\nexport interface PersistedFinding extends AnalystFinding {\n run_id: string\n}\n\nexport class FindingsStore {\n private readonly appender: LockedJsonlAppender\n\n constructor(public readonly path: string) {\n this.appender = new LockedJsonlAppender(path)\n }\n\n async append(runId: string, findings: AnalystFinding[]): Promise<void> {\n for (const f of findings) {\n const row: PersistedFinding = { ...f, run_id: runId }\n await this.appender.append(row)\n }\n }\n\n /** Load every persisted finding. Discards malformed trailing lines silently. */\n loadAll(): PersistedFinding[] {\n if (!existsSync(this.path)) return []\n const raw = readFileSync(this.path, 'utf8')\n if (!raw) return []\n const out: PersistedFinding[] = []\n for (const line of raw.split('\\n')) {\n if (!line) continue\n try {\n out.push(JSON.parse(line) as PersistedFinding)\n } catch {\n // Skip torn trailing line — the lock guarantees no torn lines\n // mid-file, only at EOF when a writer is in-flight.\n }\n }\n return out\n }\n\n /** Filter to a single run. */\n loadRun(runId: string): PersistedFinding[] {\n return this.loadAll().filter((r) => r.run_id === runId)\n }\n}\n\n// ── Cross-run diff ──────────────────────────────────────────────────\n\nexport interface FindingsDiff {\n /** New finding ids in `current` that weren't in `previous`. */\n appeared: PersistedFinding[]\n /** Finding ids in `previous` that aren't in `current`. */\n disappeared: PersistedFinding[]\n /** Same finding id present in both runs and unchanged per the materiality test. */\n persisted: PersistedFinding[]\n /**\n * Same finding id in both runs but at least one non-identity field\n * shifted per `DiffPolicy.isMaterial`. Reported as [previous, current].\n */\n changed: Array<{ previous: PersistedFinding; current: PersistedFinding }>\n}\n\nexport interface DiffPolicy {\n /**\n * Predicate that decides whether two findings (same finding_id) count\n * as a material change. Defaults to {@link defaultIsMaterial}: severity\n * shift, confidence Δ > 0.05, or evidence count change. Compliance /\n * perf consumers MAY supply a stricter predicate (e.g. rationale text\n * diff, metric Δ thresholds).\n */\n isMaterial?: (previous: AnalystFinding, current: AnalystFinding) => boolean\n}\n\n/**\n * Default materiality test. Deliberately narrow so LLM-reword churn\n * doesn't flood the diff. Stricter tests are opt-in via DiffPolicy.\n */\nexport function defaultIsMaterial(a: AnalystFinding, b: AnalystFinding): boolean {\n if (a.severity !== b.severity) return true\n if (Math.abs((a.confidence ?? 0) - (b.confidence ?? 0)) > 0.05) return true\n if (a.evidence_refs.length !== b.evidence_refs.length) return true\n return false\n}\n\n/**\n * Diff two findings sets by stable finding_id. Callers typically load\n * the two run-id slices from the same store and pass them in.\n */\nexport function diffFindings(\n previous: PersistedFinding[],\n current: PersistedFinding[],\n policy: DiffPolicy = {},\n): FindingsDiff {\n const isMaterial = policy.isMaterial ?? defaultIsMaterial\n const prevById = new Map(previous.map((f) => [f.finding_id, f]))\n const curById = new Map(current.map((f) => [f.finding_id, f]))\n\n const appeared: PersistedFinding[] = []\n const disappeared: PersistedFinding[] = []\n const persisted: PersistedFinding[] = []\n const changed: FindingsDiff['changed'] = []\n\n for (const [id, cur] of curById) {\n const prev = prevById.get(id)\n if (!prev) {\n appeared.push(cur)\n continue\n }\n if (isMaterial(prev, cur)) {\n changed.push({ previous: prev, current: cur })\n } else {\n persisted.push(cur)\n }\n }\n for (const [id, prev] of prevById) {\n if (!curById.has(id)) disappeared.push(prev)\n }\n return { appeared, disappeared, persisted, changed }\n}\n","/**\n * Semantic concept judge — \"does the built artifact actually implement\n * the features the user asked for?\"\n *\n * Distinct from the domain/code/coherence judges in `judges.ts`:\n * - those judges score free-form conversational agent outputs along\n * quality dimensions (accuracy, depth, etc.)\n * - this judge scores a *built artifact* (served HTML + source files)\n * against an explicit list of expected concepts, returning per-concept\n * {present, score 0-10, evidence, severity}.\n *\n * The judge is strict about distinguishing (a) a working implementation\n * from (b) a keyword-present stub. \"// TODO: mint button\" is NOT present.\n * Only real, functional, wired-up code counts.\n *\n * Use via {@link createSemanticConceptJudge} or directly via\n * {@link runSemanticConceptJudge}. Soft-fails (available=false) on LLM\n * or JSON-parse errors so the caller can treat that as \"layer skipped\"\n * rather than \"layer failed\" in a multi-layer pipeline.\n */\n\nimport type { ChatClient } from './analyst/chat-client'\nimport { paidJsonChat } from './chat-json-call'\nimport {\n CostLedger,\n type CostLedgerHandle,\n type CostReceipt,\n type CustomTokenPricing,\n} from './cost-ledger'\nimport type { LlmCallRequest } from './llm-client'\nimport type { Severity } from './multi-layer-verifier'\n\n// ─── Types ──────────────────────────────────────────────────────────────\n\n/**\n * Implementation complexity class for weighted scoring.\n *\n * - `render` (default): the concept is a UI surface that displays static\n * data — render a list, show a counter, lay out a button. Single-file\n * work, no external integration.\n * - `integrate`: the concept requires wiring a real external system —\n * wallet connect (wagmi + RainbowKit + chain config), payment provider\n * (Stripe Elements + intent + webhook), an API client with auth.\n * Multi-file, library-knowledge, runtime correctness matters.\n * - `compute`: the concept requires algorithmic work — solver, simulator,\n * constraint propagation, ML inference. Correctness > UI polish.\n *\n * Default weights (when applied via `weightConcepts: 'complexity'`):\n * render=1.0, integrate=2.0, compute=2.5\n *\n * Cross-vertical scoring without complexity weighting silently inflates\n * the rate of UI-heavy verticals (healthcare, fintech dashboards) vs\n * integration-heavy verticals (DeFi, wallets) — all concepts treated\n * equally even though the agent does 2-3x the work for `integrate`.\n */\nexport type ConceptComplexity = 'render' | 'integrate' | 'compute'\n\nexport interface ConceptSpec {\n name: string\n /** Short hints that help the judge; not used for matching. */\n keywords?: string[]\n /** Optional explicit weight; default 1.0. Overrides complexity-derived weight. */\n weight?: number\n /** Implementation complexity class. Default `render`. */\n complexity?: ConceptComplexity\n}\n\nexport interface ConceptFinding {\n concept: string\n present: boolean\n /** 0..10. 10 = production-ready; 7 = functional thin; 4 = partial; 0 = absent. */\n score: number\n evidence: string\n severity: Severity\n}\n\nexport interface SemanticConceptJudgeInput {\n /** Full natural-language prompt the agent was handed. */\n userRequest: string\n /** Rendered HTML the preview returns (UI artifacts). Optional. */\n servedHtml?: string\n /** Top-level source files from the agent's workdir. */\n sourceFiles: Array<{ path: string; content: string }>\n /** The expected concept list. */\n expectedConcepts: ConceptSpec[]\n /** Free-form metadata (id, difficulty) to inject into the prompt. */\n artifactLabel?: string\n artifactDescription?: string\n}\n\nexport interface SemanticConceptJudgeResult {\n kind: 'semantic-concept'\n version: string\n /** Normalized 0..1 score — mean of per-concept scores / 10. */\n score: number\n presentCount: number\n totalCount: number\n findings: ConceptFinding[]\n summary: string\n durationMs: number\n costUsd: number | null\n /** False on LLM/JSON error — treat as \"skipped / unable to judge\" in pipelines. */\n available: boolean\n error?: string\n}\n\n/**\n * Score-aggregation strategy. `mean` averages 0-10 scores uniformly.\n * `complexity` applies the default weight table (render=1, integrate=2,\n * compute=2.5) unless a concept has an explicit `weight`. `explicit`\n * honors only `weight` (defaulting to 1 for unspecified).\n */\nexport type ConceptWeightStrategy = 'mean' | 'complexity' | 'explicit'\n\nexport const DEFAULT_COMPLEXITY_WEIGHTS: Record<ConceptComplexity, number> = {\n render: 1.0,\n integrate: 2.0,\n compute: 2.5,\n}\n\nexport interface SemanticConceptJudgeOptions {\n /** Model id to call. Default 'claude-sonnet-4-6' via agent-eval defaults. */\n model?: string\n /** Per-call timeout. Default 300s. */\n timeoutMs?: number\n /** Provider-enforced output limit. Default 16000. */\n maxTokens?: number\n /** Pipeline budget for the prompt (source blob truncation). Default 45000. */\n maxSourceChars?: number\n /** Per-file cap before inclusion. Default 20000. */\n maxPerFileChars?: number\n /** HTML cap. Default 30000. */\n maxHtmlChars?: number\n /** Caller-owned transport. Required: agent-eval executes no paid model. */\n chat: ChatClient\n /** Endpoint rates used when the transport reports no billed amount. */\n pricing?: CustomTokenPricing\n costLedger?: CostLedgerHandle\n costPhase?: string\n costTags?: Record<string, string>\n signal?: AbortSignal\n /**\n * Score aggregation strategy. Default `mean` — uniform average across\n * concepts. Cross-vertical comparisons should use `complexity` to\n * neutralize the integrate-vs-render asymmetry.\n */\n weightConcepts?: ConceptWeightStrategy\n /** Override the default complexity → weight table. */\n complexityWeights?: Partial<Record<ConceptComplexity, number>>\n}\n\n// ─── Prompt assembly ────────────────────────────────────────────────────\n\nexport const SEMANTIC_CONCEPT_JUDGE_VERSION = 'semantic-concept-judge-v1-2026-04-24'\n\nconst DEFAULT_MAX_SOURCE = 45_000\nconst DEFAULT_MAX_HTML = 30_000\nconst DEFAULT_MAX_PER_FILE = 20_000\nconst DEFAULT_TIMEOUT = 300_000\nconst DEFAULT_MAX_TOKENS = 16_000\nconst DEFAULT_MODEL = 'claude-sonnet-4-6'\n\nconst SEMANTIC_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n required: ['summary', 'concepts'],\n properties: {\n summary: { type: 'string', minLength: 20, maxLength: 600 },\n concepts: {\n type: 'array',\n minItems: 1,\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['concept', 'present', 'score', 'evidence', 'severity'],\n properties: {\n concept: { type: 'string', minLength: 1, maxLength: 120 },\n present: { type: 'boolean' },\n score: { type: 'number', minimum: 0, maximum: 10 },\n evidence: { type: 'string', minLength: 5, maxLength: 400 },\n severity: { type: 'string', enum: ['critical', 'major', 'minor', 'info'] },\n },\n },\n },\n },\n}\n\nfunction truncate(body: string, cap: number, label: string): string {\n if (body.length <= cap) return body\n return `${body.slice(0, cap)}\\n… [truncated ${body.length - cap} chars of ${label}]`\n}\n\nfunction buildPrompt(\n input: SemanticConceptJudgeInput,\n opts: { maxPerFileChars: number; maxSourceChars: number; maxHtmlChars: number },\n): string {\n const sourceBlob = input.sourceFiles\n .filter((f) => f.content.length <= opts.maxPerFileChars)\n .map((f) => `--- FILE: ${f.path} ---\\n${f.content}`)\n .join('\\n\\n')\n\n const html = input.servedHtml ?? ''\n\n return `You are a strict code-review judge evaluating whether an agent's 0-to-1 build actually implements the features the user asked for.\n\nYou MUST distinguish:\n (a) WORKING code that implements the concept (rendered UI, wired handler, real API call),\n (b) KEYWORD-PRESENT stub (comments mentioning the concept, variable names, TODOs),\n (c) ABSENT (concept nowhere).\n\nA comment like \"// TODO: add mint button\" is NOT present — score 2-3. Only count a concept as present if there is real functional code: a rendered component, a call handler wired to state or a network call, a computed value actually used.\n\nUSER REQUEST (what the agent was asked to build):\n${input.userRequest}\n\n${input.artifactLabel ? `ARTIFACT METADATA:\\n name: ${input.artifactLabel}\\n description: ${input.artifactDescription ?? ''}\\n\\n` : ''}EXPECTED CONCEPTS (each must be graded independently):\n${input.expectedConcepts\n .map(\n (c, i) =>\n ` ${i + 1}. \"${c.name}\"${c.keywords?.length ? ` — hints: [${c.keywords.slice(0, 6).join(' | ')}]` : ''}`,\n )\n .join('\\n')}\n\n${html ? `SERVED HTML (what the preview returns when hit):\\n${truncate(html, opts.maxHtmlChars, 'HTML')}\\n\\n` : ''}SOURCE FILES (the agent's workdir):\n${truncate(sourceBlob, opts.maxSourceChars, 'source')}\n\nFor EACH concept, return:\n - concept: the concept name as given (match exactly)\n - present: boolean — does a working implementation exist?\n - score: 0-10 — 10 = production-ready; 7 = functional but thin; 4 = partial/stubbed; 2 = keyword-only comment; 0 = absent\n - evidence: cite \"<file>:<line>\" or \"served-html:<selector>\" pointing at the strongest supporting code. If the concept is absent or stubbed, explain what's missing.\n - severity:\n \"info\" when present: true AND score >= 7\n \"minor\" when present: true AND 4 <= score < 7\n \"major\" when present: false OR score < 4\n \"critical\" when the concept is not only absent but a core user flow depends on it\n\nAlso produce a \"summary\" (one sentence, 20-600 chars): overall verdict on whether this is a shippable implementation of the user request vs a keyword-dense placeholder.\n\nBE SKEPTICAL. Keyword matching already passed — your job is to catch what keyword matching misses. If the agent shipped a working build, say so. If it shipped a stub, say so. Don't grade on effort.\n\nReturn STRICT JSON. No prose outside the JSON.`\n}\n\n// ─── Runner ─────────────────────────────────────────────────────────────\n\n/**\n * Run the semantic concept judge. Soft-fails to available=false on\n * LLM/JSON errors — callers in a MultiLayerVerifier pipeline can treat\n * that as \"skip\" rather than \"fail.\"\n */\nexport async function runSemanticConceptJudge(\n input: SemanticConceptJudgeInput,\n options: SemanticConceptJudgeOptions,\n): Promise<SemanticConceptJudgeResult> {\n const start = Date.now()\n const totalCount = input.expectedConcepts.length\n\n if (totalCount === 0) {\n return {\n kind: 'semantic-concept',\n version: SEMANTIC_CONCEPT_JUDGE_VERSION,\n score: 0,\n presentCount: 0,\n totalCount: 0,\n findings: [],\n summary: 'no expected concepts declared',\n durationMs: 0,\n costUsd: null,\n available: false,\n error: 'no expected concepts declared',\n }\n }\n\n const opts = {\n chat: options.chat,\n model: options.model ?? options.chat.defaultModel ?? DEFAULT_MODEL,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT,\n maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,\n maxSourceChars: options.maxSourceChars ?? DEFAULT_MAX_SOURCE,\n maxPerFileChars: options.maxPerFileChars ?? DEFAULT_MAX_PER_FILE,\n maxHtmlChars: options.maxHtmlChars ?? DEFAULT_MAX_HTML,\n ...(options.pricing ? { pricing: options.pricing } : {}),\n costLedger: options.costLedger ?? new CostLedger(),\n costPhase: options.costPhase ?? 'judge.semantic-concept',\n costTags: options.costTags ?? {},\n signal: options.signal ?? new AbortController().signal,\n weightConcepts: options.weightConcepts ?? 'mean',\n complexityWeights: { ...DEFAULT_COMPLEXITY_WEIGHTS, ...(options.complexityWeights ?? {}) },\n }\n\n // Build a name → weight map for aggregation. Mean strategy keeps every\n // weight at 1 (uniform average). Complexity strategy reads the table\n // and lets an explicit `weight` override. Explicit strategy uses ONLY\n // the spec's `weight` (defaulting to 1).\n const weightForConcept = (spec: ConceptSpec): number => {\n if (opts.weightConcepts === 'mean') return 1\n if (spec.weight != null) return spec.weight\n if (opts.weightConcepts === 'complexity') {\n return opts.complexityWeights[spec.complexity ?? 'render'] ?? 1\n }\n return 1\n }\n const weightByName = new Map<string, number>(\n input.expectedConcepts.map((c) => [c.name, weightForConcept(c)]),\n )\n\n let receipt: CostReceipt | undefined\n try {\n const request = {\n model: opts.model,\n messages: [\n {\n role: 'system' as const,\n content:\n 'You are a strict code-review judge. Return strict JSON only. No prose outside the JSON. A keyword in a comment is NOT a working implementation.',\n },\n { role: 'user' as const, content: buildPrompt(input, opts) },\n ],\n jsonSchema: { name: 'semantic_concept_judge', schema: SEMANTIC_SCHEMA },\n temperature: 0,\n maxTokens: opts.maxTokens,\n timeoutMs: opts.timeoutMs,\n } satisfies LlmCallRequest\n const paid = await paidJsonChat<{ summary: string; concepts: ConceptFinding[] }>({\n chat: opts.chat,\n request,\n ledger: opts.costLedger,\n channel: 'judge',\n phase: opts.costPhase,\n actor: 'semantic-concept',\n tags: opts.costTags,\n signal: opts.signal,\n ...(opts.pricing ? { pricing: opts.pricing } : {}),\n })\n receipt = paid.receipt\n if (!paid.succeeded) throw paid.error\n const { value } = paid\n\n if (!value?.concepts || !Array.isArray(value.concepts)) {\n throw new Error('judge returned malformed response — expected array under \"concepts\"')\n }\n\n const findings: ConceptFinding[] = value.concepts.map((c) => ({\n concept: String(c.concept),\n present: Boolean(c.present),\n score: Math.max(0, Math.min(10, Number(c.score ?? 0))),\n evidence: String(c.evidence ?? ''),\n severity: (['critical', 'major', 'minor', 'info'] as const).includes(c.severity)\n ? c.severity\n : 'info',\n }))\n\n const presentCount = findings.filter((f) => f.present && f.score >= 7).length\n let weightSum = 0\n let weightedScoreSum = 0\n for (const f of findings) {\n const w = weightByName.get(f.concept) ?? 1\n weightSum += w\n weightedScoreSum += w * f.score\n }\n const scoreAvg =\n weightSum > 0\n ? weightedScoreSum / weightSum\n : findings.reduce((a, f) => a + f.score, 0) / Math.max(1, findings.length)\n\n return {\n kind: 'semantic-concept',\n version: SEMANTIC_CONCEPT_JUDGE_VERSION,\n score: Number((scoreAvg / 10).toFixed(3)),\n presentCount,\n totalCount,\n findings,\n summary: String(value.summary ?? ''),\n durationMs: Date.now() - start,\n costUsd: paid.receipt.costUnknown ? null : paid.receipt.costUsd,\n available: true,\n }\n } catch (err) {\n return {\n kind: 'semantic-concept',\n version: SEMANTIC_CONCEPT_JUDGE_VERSION,\n score: 0,\n presentCount: 0,\n totalCount,\n findings: [],\n summary: '',\n durationMs: Date.now() - start,\n costUsd: receipt && !receipt.costUnknown ? receipt.costUsd : null,\n available: false,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n}\n\n/**\n * Factory: pin LLM options once, return a closure that accepts inputs.\n * Convenient for pipelines that want to share a single LlmClient config.\n */\nexport function createSemanticConceptJudge(\n options: SemanticConceptJudgeOptions,\n): (input: SemanticConceptJudgeInput) => Promise<SemanticConceptJudgeResult> {\n return (input) => runSemanticConceptJudge(input, options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,4BAA4B;AAClC,MAAM,YAAY;;AAGlB,MAAM,oBAAoB;;;;;;AAqC1B,SAAS,wBAA2E;CAClF,MAAM,MAAM,EAAE,aAAa,yBAAyB,EAAE,QAAQ,UAAU,CAAC;CAIzE,OAAO,IAAI;CACX,OAAO;EACL,MAAM;EACN,QAAQ;GACN,MAAM;GACN,sBAAsB;GACtB,UAAU,CAAC,UAAU,UAAU;GAC/B,YAAY;IACV,QAAQ;KAAE,MAAM;KAAU,aAAa;IAAuC;IAC9E,UAAU;KAAE,MAAM;KAAS,OAAO;IAAI;GACxC;EACF;CACF;AACF;AAEA,MAAM,qBAAqB,sBAAsB;;;;;AAMjD,SAAgB,sBAAsB,SAAsD;CAC1F,MAAM,QAAQ,aAAa,OAAO;CAClC,MAAM,kBAAkB,QAAQ,mBAAA;CAChC,IAAI,CAAC,OAAO,cAAc,eAAe,KAAK,mBAAmB,G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SAAS,MAAM;EAE7E,OAAO;GACL,MAAM;GACN,SAAS;GACT,OAAO,QAAQ,WAAW,GAAA,CAAI,QAAQ,CAAC,CAAC;GACxC;GACA;GACA;GACA,SAAS,OAAO,MAAM,WAAW,EAAE;GACnC,YAAY,KAAK,IAAI,IAAI;GACzB,SAAS,KAAK,QAAQ,cAAc,OAAO,KAAK,QAAQ;GACxD,WAAW;EACb;CACF,SAAS,KAAK;EACZ,OAAO;GACL,MAAM;GACN,SAAS;GACT,OAAO;GACP,cAAc;GACd;GACA,UAAU,CAAC;GACX,SAAS;GACT,YAAY,KAAK,IAAI,IAAI;GACzB,SAAS,WAAW,CAAC,QAAQ,cAAc,QAAQ,UAAU;GAC7D,WAAW;GACX,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;EACxD;CACF;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { h as manifestContentDigest } from "./agent-profile-cell-DcFW4vOc.js";
2
2
  import { t as mulberry32 } from "./random-Dn5fPWkt.js";
3
3
  import { t as eProcess } from "./sequential-eprocess-D1jKoihe.js";
4
- import { n as aggregatePairedHoldout, o as pairHoldout } from "./statistical-heldout-CNLOvRq_.js";
4
+ import { n as aggregatePairedHoldout, o as pairHoldout } from "./statistical-heldout-C26hOFWD.js";
5
5
  //#region src/campaign/gates/sequential.ts
6
6
  /**
7
7
  * Anytime-valid sequential promotion gate — an e-process (betting
@@ -338,4 +338,4 @@ function sequentialDecide(options = {}) {
338
338
  //#endregion
339
339
  export { sequentialPairedGate as n, sequentialDecide as t };
340
340
 
341
- //# sourceMappingURL=sequential-DWn_np6P.js.map
341
+ //# sourceMappingURL=sequential-7uxpO0Vm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sequential-DWn_np6P.js","names":[],"sources":["../src/campaign/gates/sequential.ts"],"sourcesContent":["/**\n * Anytime-valid sequential promotion gate — an e-process (betting\n * test-martingale, see `eProcess` in `statistics.ts`) over paired\n * per-scenario deltas, so a campaign stops the MOMENT evidence decides\n * instead of burning a fixed-n budget. Decisions remain valid at any\n * data-dependent stopping time (Ville's inequality), which is exactly what\n * fixed-n machinery cannot offer: peeking at a bootstrap CI after every\n * observation and stopping on the first significant peek inflates type-I\n * error far beyond alpha.\n *\n * REPLACES, never layers on, a fixed-n gate. Running `heldoutSignificance`\n * or `paretoSignificanceGate` repeatedly on a growing sample and stopping\n * early is optional stopping no matter how it is dressed up; this gate is\n * the valid way to stop early. Use one or the other per evidence stream.\n *\n * Pre-registration binding: anytime validity holds only for the\n * PRE-REGISTERED statistic. When a `SignedManifest` is bound, the gate takes\n * alpha from `manifest.alpha`, the observation budget from\n * `manifest.preRegisteredN`, orients deltas by `manifest.direction`, and\n * shifts the null boundary by `manifest.minEffect` — re-deciding the same\n * stream under different parameters after seeing data would reopen optional\n * stopping under a fancier name. The manifest's content hash is verified at\n * construction with the canonical RFC 8785 digest used by signManifest.\n *\n * The supermartingale guarantee requires E[delta_t | past] ≤ the null\n * boundary under H0. Independent sampling with that mean bound suffices.\n * Exchangeability or shuffling alone does not: one fair sign repeated many\n * times is exchangeable and has marginal mean zero, but its conditional mean\n * becomes the revealed sign. A seeded shuffle cannot remove that dependence.\n * `decide(ctx)` pairs cells, then averages repetitions within each scenario\n * before testing. Pass independentUnitByScenarioId for scenarios sharing a\n * latent source or incident. Units must still satisfy the conditional-mean null.\n * Direct `observe()` callers own this sampling and aggregation contract.\n */\n\nimport { manifestContentDigest, type SignedManifest } from '../../pre-registration'\nimport { type EProcessState, eProcess, mulberry32 } from '../../statistics'\nimport type { Gate, GateContext, GateResult, GenerationRecord, Scenario } from '../types'\nimport { aggregatePairedHoldout, pairHoldout } from './statistical-heldout'\n\nexport type SequentialDecision = 'promote' | 'continue' | 'undecided-at-maxN'\n\nexport interface SequentialObservation {\n decision: SequentialDecision\n /** Current e-value (the betting wealth) against H0. */\n eValue: number\n /** Paired deltas consumed so far. */\n n: number\n /** Names the decision basis. For 'undecided-at-maxN' it states explicitly\n * that exhausting the budget is NOT evidence of no effect. */\n reason: string\n}\n\nexport interface SequentialPairedGateOptions {\n /** Type-I budget. With `preRegistration` bound this MUST match\n * `manifest.alpha` (conflict throws). Default 0.05. */\n alpha?: number\n /** Minimum independent paired units before a promote may fire. The stopping rule is\n * \"first n ≥ minN with e-value ≥ 1/alpha\" — still a valid stopping time.\n * Default 5. */\n minN?: number\n /** Pre-registered independent-unit budget (scenarios by default in decide()). Required unless `preRegistration`\n * supplies it via `preRegisteredN` (conflict throws). */\n maxN?: number\n /** Bet truncation forwarded to `eProcess`. Default 0.5. */\n maxBet?: number\n /** Bound on |delta| in the judge's native scale; deltas are mapped to\n * x = (d/scale + 1)/2 ∈ [0,1]. A delta outside ±scale throws (use\n * `detectScale` to pick 1 vs 100 BEFORE streaming). Default 1. */\n scale?: number\n /** Seed for reproducible ordering of scenario deltas in decide().\n * Shuffling does not establish the conditional-mean null. Default 1337. */\n shuffleSeed?: number\n /** Independent unit for every scenario passed to decide(). Full cell pairs\n * are averaged within each unit before testing. Defaults to scenario IDs.\n * The mapping is copied at construction. Direct observe() is unchanged. */\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n /** Bind the pre-registered hypothesis. Verified (content hash) at\n * construction; alpha/maxN/direction/minEffect come FROM the manifest. */\n preRegistration?: SignedManifest\n /** Override the gate name in reports. */\n name?: string\n /** Continue the observe-stream from a `state()` snapshot taken before a\n * restart. The gate's parameters still resolve from this options object\n * (and the manifest); the snapshot must have been recorded under the same\n * alpha, maxBet, and null boundary, and its decision must be one this\n * configuration could have reached at its n, or construction throws.\n * `decide(ctx)` is unaffected — it always runs on a fresh stream. */\n resume?: SequentialStreamState\n}\n\n/** Snapshot of one observe-stream: the e-process state plus the gate's own\n * decision, which applies `minN` and `maxN` on top of the core latch. A\n * gate rebuilt with `resume` from this value continues exactly where the\n * snapshot was taken. */\nexport type SequentialStreamState = EProcessState & { decision: SequentialDecision }\n\nexport interface SequentialPairedGate<TArtifact = unknown, TScenario extends Scenario = Scenario>\n extends Gate<TArtifact, TScenario> {\n /** Streaming entry point: feed one paired independent-unit delta\n * (candidate − baseline, native scale). Aggregate correlated repetitions\n * before calling; the caller must justify E[delta_t | past] under H0.\n * Each gate instance carries ONE\n * observe-stream; `decide(ctx)` runs on its own fresh stream and never\n * consumes or advances this one. 'promote' is sticky; observing past the\n * pre-registered maxN throws (extending a finished stream after seeing\n * the result reopens optional stopping — start a NEW pre-registered\n * test). */\n observe(delta: number): SequentialObservation\n /** Read-only snapshot of the observe-stream. Pass it back as\n * `resume` to continue the stream after a restart. */\n state(): SequentialStreamState\n}\n\ninterface ResolvedConfig {\n alpha: number\n minN: number\n maxN: number\n maxBet: number\n scale: number\n shuffleSeed: number\n /** 'decrease' negates deltas so \"better\" is always positive. */\n direction: 'increase' | 'decrease'\n /** H0 boundary in x-space: 1/2 + minEffect/(2·scale). */\n nullMean: number\n minEffect: number\n}\n\n/** Sync twin of `verifyManifest`, so gate construction stays synchronous and\n * fails loud before any observation is consumed. The digest scheme belongs to\n * `pre-registration`; this gate only compares. */\nfunction verifyManifestSync(m: SignedManifest): boolean {\n return manifestContentDigest(m) === m.contentHash\n}\n\nfunction resolveConfig(opts: SequentialPairedGateOptions): ResolvedConfig {\n const m = opts.preRegistration\n let alpha: number\n let maxN: number\n let direction: 'increase' | 'decrease'\n let minEffect: number\n if (m) {\n if (!verifyManifestSync(m)) {\n throw new Error(\n `sequentialPairedGate: pre-registration manifest '${m.id}' content hash mismatch (tampered)`,\n )\n }\n if (opts.alpha !== undefined && opts.alpha !== m.alpha) {\n throw new Error(\n `sequentialPairedGate: alpha ${opts.alpha} conflicts with pre-registered alpha ${m.alpha} — ` +\n `the registered statistic is the only one anytime validity covers`,\n )\n }\n if (opts.maxN !== undefined && opts.maxN !== m.preRegisteredN) {\n throw new Error(\n `sequentialPairedGate: maxN ${opts.maxN} conflicts with pre-registered N ${m.preRegisteredN}`,\n )\n }\n alpha = m.alpha\n maxN = m.preRegisteredN\n direction = m.direction\n minEffect = m.minEffect\n } else {\n alpha = opts.alpha ?? 0.05\n if (opts.maxN === undefined) {\n throw new Error(\n 'sequentialPairedGate: maxN is required (or bind a preRegistration manifest whose ' +\n 'preRegisteredN is the budget) — an unbounded stream has no pre-registered budget',\n )\n }\n maxN = opts.maxN\n direction = 'increase'\n minEffect = 0\n }\n const scale = opts.scale ?? 1\n if (!Number.isFinite(scale) || scale <= 0) {\n throw new Error(`sequentialPairedGate: scale must be > 0, got ${scale}`)\n }\n if (!Number.isInteger(maxN) || maxN < 1) {\n throw new Error(`sequentialPairedGate: maxN must be a positive integer, got ${maxN}`)\n }\n const minN = opts.minN ?? 5\n if (!Number.isInteger(minN) || minN < 1 || minN > maxN) {\n throw new Error(\n `sequentialPairedGate: minN must be an integer in [1, maxN=${maxN}], got ${minN}`,\n )\n }\n if (!Number.isFinite(minEffect) || minEffect < 0 || minEffect >= scale) {\n throw new Error(\n `sequentialPairedGate: minEffect must be in [0, scale=${scale}), got ${minEffect}`,\n )\n }\n // H0: mean delta ≤ minEffect. In x = (d/scale + 1)/2 space that is\n // E[x] ≤ 1/2 + minEffect/(2·scale) — a shifted null boundary, NOT a clamp\n // of the observations (clamping is mean-distorting for skewed deltas).\n const nullMean = 0.5 + minEffect / (2 * scale)\n return {\n alpha,\n minN,\n maxN,\n maxBet: opts.maxBet ?? 0.5,\n scale,\n shuffleSeed: opts.shuffleSeed ?? 1337,\n direction,\n nullMean,\n minEffect,\n }\n}\n\ninterface SequentialStream {\n observe(delta: number): SequentialObservation\n state(): SequentialStreamState\n}\n\nconst SEQUENTIAL_DECISIONS: readonly SequentialDecision[] = [\n 'promote',\n 'continue',\n 'undecided-at-maxN',\n]\n\n/** Refuse a snapshot whose gate decision this configuration could not have\n * reached at the snapshot's n. The e-process parameters are checked by\n * `eProcess` itself; this covers the gate's own stopping rule. */\nfunction assertResumableStream(resume: SequentialStreamState, cfg: ResolvedConfig): void {\n const fail = (detail: string): never => {\n throw new Error(`sequentialPairedGate: cannot resume — ${detail}`)\n }\n if (!SEQUENTIAL_DECISIONS.includes(resume.decision)) {\n fail(`unknown decision '${String(resume.decision)}'`)\n }\n if (resume.n > cfg.maxN) {\n fail(`snapshot n=${resume.n} exceeds the pre-registered maxN=${cfg.maxN}`)\n }\n const threshold = 1 / cfg.alpha\n switch (resume.decision) {\n case 'promote':\n if (resume.n < cfg.minN) {\n fail(`decision 'promote' at n=${resume.n} is below minN=${cfg.minN}`)\n }\n break\n case 'undecided-at-maxN':\n if (resume.n !== cfg.maxN) {\n fail(`decision 'undecided-at-maxN' at n=${resume.n} does not match maxN=${cfg.maxN}`)\n }\n break\n case 'continue':\n if (resume.n >= cfg.maxN) {\n fail(`decision 'continue' at n=${resume.n} with maxN=${cfg.maxN}; the stream is finished`)\n }\n if (resume.n >= cfg.minN && resume.wealth >= threshold) {\n fail(\n `decision 'continue' at n=${resume.n} ≥ minN=${cfg.minN} with e-value ` +\n `${resume.wealth} ≥ 1/α=${threshold}; this stream would have promoted`,\n )\n }\n break\n }\n}\n\nfunction makeStream(cfg: ResolvedConfig, resume?: SequentialStreamState): SequentialStream {\n if (resume !== undefined) assertResumableStream(resume, cfg)\n const proc = eProcess({\n alpha: cfg.alpha,\n maxBet: cfg.maxBet,\n nullMean: cfg.nullMean,\n ...(resume === undefined ? {} : { resume }),\n })\n const threshold = 1 / cfg.alpha\n let terminal: SequentialDecision | undefined =\n resume === undefined || resume.decision === 'continue' ? undefined : resume.decision\n return {\n observe(delta: number): SequentialObservation {\n if (terminal === 'undecided-at-maxN') {\n throw new Error(\n `sequentialPairedGate: pre-registered maxN=${cfg.maxN} exhausted — extending the ` +\n 'stream after seeing the result reopens optional stopping; start a NEW ' +\n 'pre-registered test',\n )\n }\n if (!Number.isFinite(delta) || Math.abs(delta) > cfg.scale) {\n throw new Error(\n `sequentialPairedGate: delta ${delta} outside ±scale=${cfg.scale} — pass the judge's ` +\n `native scale explicitly (detectScale helps pick 1 vs 100)`,\n )\n }\n const d = cfg.direction === 'decrease' ? -delta : delta\n const step = proc.update((d / cfg.scale + 1) / 2)\n // Stopping rule: FIRST n ≥ minN with current wealth ≥ 1/alpha — a valid\n // stopping time (measurable w.r.t. the past), sticky once latched. The\n // core's own `decided` latch ignores minN, so the gate re-derives the\n // decision from current wealth here.\n if (terminal === undefined && step.n >= cfg.minN && step.wealth >= threshold) {\n terminal = 'promote'\n }\n if (terminal === 'promote') {\n return {\n decision: 'promote',\n eValue: step.wealth,\n n: step.n,\n reason:\n `e-value ${step.wealth.toFixed(2)} ≥ 1/α=${threshold.toFixed(2)} at n=${step.n} ` +\n `(minN=${cfg.minN}): the paired improvement exceeds ${cfg.minEffect} at anytime-valid ` +\n `level α=${cfg.alpha}`,\n }\n }\n if (step.n >= cfg.maxN) {\n terminal = 'undecided-at-maxN'\n return {\n decision: 'undecided-at-maxN',\n eValue: step.wealth,\n n: step.n,\n reason:\n `undecided at pre-registered maxN=${cfg.maxN} (e-value ${step.wealth.toFixed(2)} < ` +\n `1/α=${threshold.toFixed(2)}). This is NOT evidence of no effect — the effect may be ` +\n 'real but smaller than this budget can detect; re-register with a larger N to test that',\n }\n }\n return {\n decision: 'continue',\n eValue: step.wealth,\n n: step.n,\n reason: `e-value ${step.wealth.toFixed(2)} < 1/α=${threshold.toFixed(2)} at n=${step.n}/${cfg.maxN} — keep observing`,\n }\n },\n state() {\n return { ...proc.state(), decision: terminal ?? 'continue' }\n },\n }\n}\n\n/** Data-independent in-place Fisher–Yates with a seeded PRNG — the permutation\n * depends only on the seed, never the values, so bet predictability survives. */\nfunction seededShuffle<T>(items: T[], seed: number): T[] {\n const rng = mulberry32(seed)\n for (let i = items.length - 1; i > 0; i--) {\n const j = Math.floor(rng() * (i + 1))\n const tmp = items[i]!\n items[i] = items[j]!\n items[j] = tmp\n }\n return items\n}\n\n/**\n * Anytime-valid sequential paired gate. Conforms to the existing `Gate`\n * contract: decide(ctx) pairs candidate and baseline by full cellId, then\n * averages deltas within each configured unit (scenario by default). The\n * e-process consumes one observation per unit, with equal unit weights.\n * The streaming observe(delta) entry consumes caller-aggregated independent\n * units. Repetitions improve a unit's precision and do not increase n.\n *\n * Decision mapping onto the substrate's five-valued `GateDecision`:\n * - 'promote' → 'ship'\n * - 'continue' → 'need_more_work' (stream ended before maxN with\n * the e-value undecided — more independent units needed)\n * - 'undecided-at-maxN' → 'hold', with the reason stating it is NOT\n * evidence of no effect (never a silent default)\n */\nexport function sequentialPairedGate<TArtifact = unknown, TScenario extends Scenario = Scenario>(\n options: SequentialPairedGateOptions,\n): SequentialPairedGate<TArtifact, TScenario> {\n const cfg = resolveConfig(options)\n const name = options.name ?? 'sequentialPairedGate'\n const manifest = options.preRegistration\n const observeStream = makeStream(cfg, options.resume)\n const independentUnitByScenarioId =\n options.independentUnitByScenarioId === undefined\n ? undefined\n : new Map(options.independentUnitByScenarioId)\n\n return {\n name,\n observe(delta: number): SequentialObservation {\n return observeStream.observe(delta)\n },\n state() {\n return observeStream.state()\n },\n async decide(ctx: GateContext<TArtifact, TScenario>): Promise<GateResult> {\n if (!ctx.baselineJudgeScores) {\n throw new Error(\n `${name}: ctx.baselineJudgeScores is required — falling back to the candidate's own ` +\n 'scores would compare the candidate against itself (delta 0, silent no-op)',\n )\n }\n const scenarioIds = new Set(ctx.scenarios.map((s) => s.id))\n const unitMap = independentUnitByScenarioId ?? new Map([...scenarioIds].map((id) => [id, id]))\n for (const id of scenarioIds) {\n const unit = unitMap.get(id)\n if (typeof unit !== 'string' || unit.length === 0 || unit.trim() !== unit) {\n throw new Error(`${name}: missing independent unit for scenario '${id}'`)\n }\n }\n const paired = pairHoldout(\n ctx.judgeScores,\n ctx.baselineJudgeScores,\n scenarioIds,\n (s) => s.composite,\n )\n for (let i = 0; i < paired.cellIds.length; i++) {\n const delta = paired.after[i]! - paired.before[i]!\n if (Math.abs(delta) > cfg.scale) {\n throw new Error(\n `${name}: cell '${paired.cellIds[i]}' delta ${delta} outside ±scale=${cfg.scale}`,\n )\n }\n }\n const observations = aggregatePairedHoldout(paired, unitMap)\n const deltas = observations.after.map((after, i) => after - observations.before[i]!)\n seededShuffle(deltas, cfg.shuffleSeed)\n\n const stream = makeStream(cfg)\n let last: SequentialObservation | undefined\n for (const d of deltas) {\n last = stream.observe(d)\n if (last.decision !== 'continue') break\n }\n\n const detail = {\n ...stream.state(),\n minN: cfg.minN,\n maxN: cfg.maxN,\n scale: cfg.scale,\n shuffleSeed: cfg.shuffleSeed,\n direction: cfg.direction,\n minEffect: cfg.minEffect,\n pairedN: deltas.length,\n pairedCellN: paired.cellIds.length,\n observationUnit: independentUnitByScenarioId === undefined ? 'scenario' : 'registered',\n unitIds: observations.unitIds,\n ...(manifest ? { preRegisteredId: manifest.id, metric: manifest.metric } : {}),\n }\n const meanDelta =\n deltas.length === 0 ? undefined : deltas.reduce((s, d) => s + d, 0) / deltas.length\n\n if (last === undefined) {\n return {\n decision: 'need_more_work',\n reasons: [`${name}: no paired holdout observations — nothing to test`],\n contributingGates: [{ name, status: 'not_evaluated', detail }],\n }\n }\n const decision =\n last.decision === 'promote'\n ? 'ship'\n : last.decision === 'continue'\n ? 'need_more_work'\n : 'hold'\n return {\n decision,\n reasons: [`${name}: ${last.reason}`],\n contributingGates: [\n {\n name,\n status:\n decision === 'ship'\n ? 'pass'\n : decision === 'need_more_work'\n ? 'not_evaluated'\n : 'fail',\n detail,\n },\n ],\n delta: meanDelta,\n }\n },\n }\n}\n\nexport interface SequentialDecideOptions {\n /** Type-I budget for the early-stop evidence. Default 0.05. */\n alpha?: number\n /** Minimum paired deltas before a stop may fire. Default 5. */\n minN?: number\n /** Bet truncation forwarded to `eProcess`. Default 0.5. */\n maxBet?: number\n /** Bound on |per-scenario composite delta|. Default 1. */\n scale?: number\n}\n\nexport interface SequentialDecideFn {\n (args: { history: GenerationRecord[] }): { stop: boolean; reason?: string }\n /** Read-only snapshot of the accumulated e-process (observability + tests). */\n state(): EProcessState\n}\n\n/**\n * SurfaceProposer.decide adapter that stops exploration at an e-value threshold.\n * The selected candidate still requires an independent held-out decision.\n *\n * Stream: for each generation g ≥ 1, the per-scenario composite deltas of\n * generation g's top candidate vs the generation-0 top candidate (the\n * incumbent the loop set out to beat), paired by scenarioId. H0: no proposed\n * surface improves any scenario's expected composite over the incumbent —\n * under it every delta has conditional mean ≤ 0 and the e-process is valid.\n * Once wealth ≥ 1/alpha the loop stops and hands the winner to the promotion\n * gate (which re-scores on HELD-OUT data — this adapter only spends the\n * exploration budget, it never promotes).\n *\n * This is an exploration stopping heuristic. Selection of the best measured\n * candidate and reuse of measured incumbent scores generally violate the\n * conditional-mean null, even when the candidates have no true improvement.\n * More repetitions reduce noise but do not establish exact type-I control.\n * An UNDECIDED process never stops the loop — absence of a\n * crossing is NOT evidence of no effect, so the loop simply runs its normal\n * course. Calling the adapter repeatedly with a growing history consumes each\n * generation exactly once (re-feeding an already-seen record would double-count\n * evidence).\n */\nexport function sequentialDecide(options: SequentialDecideOptions = {}): SequentialDecideFn {\n const alpha = options.alpha ?? 0.05\n const minN = options.minN ?? 5\n const scale = options.scale ?? 1\n if (!Number.isFinite(scale) || scale <= 0) {\n throw new Error(`sequentialDecide: scale must be > 0, got ${scale}`)\n }\n const proc = eProcess({ alpha, maxBet: options.maxBet ?? 0.5, nullMean: 0.5 })\n const threshold = 1 / alpha\n let processedGenerations = 0\n let reference: Map<string, number> | undefined\n let stopped: { stop: true; reason: string } | undefined\n\n const topCandidate = (record: GenerationRecord) => {\n if (record.candidates.length === 0) {\n throw new Error(\n `sequentialDecide: generation ${record.generationIndex} has no candidates — ` +\n 'cannot extract a top candidate',\n )\n }\n return record.candidates.reduce((best, candidate) => {\n if (best.composite === null) return candidate\n if (candidate.composite === null) return best\n return candidate.composite > best.composite ? candidate : best\n })\n }\n\n const decide: SequentialDecideFn = ({ history }) => {\n if (stopped) return stopped\n if (history.length === 0) return { stop: false }\n if (reference === undefined) {\n reference = new Map(\n topCandidate(history[0]!).scenarios.map((s) => [s.scenarioId, s.composite]),\n )\n }\n // Consume only generations not yet seen; start at 1 — generation 0 IS the\n // reference and would contribute all-zero deltas (pure wealth dilution).\n for (let g = Math.max(1, processedGenerations); g < history.length; g++) {\n const top = topCandidate(history[g]!)\n const byScenario = new Map(top.scenarios.map((s) => [s.scenarioId, s.composite]))\n for (const [scenarioId, refComposite] of reference) {\n const candComposite = byScenario.get(scenarioId)\n if (candComposite === undefined) {\n throw new Error(\n `sequentialDecide: generation ${history[g]!.generationIndex} top candidate is missing ` +\n `scenario '${scenarioId}' — generations must score the same scenario set to pair`,\n )\n }\n const delta = candComposite - refComposite\n if (!Number.isFinite(delta) || Math.abs(delta) > scale) {\n throw new Error(\n `sequentialDecide: paired delta ${delta} outside ±scale=${scale} on scenario ` +\n `'${scenarioId}' — pass the composite scale explicitly`,\n )\n }\n const step = proc.update((delta / scale + 1) / 2)\n if (step.n >= minN && step.wealth >= threshold) {\n stopped = {\n stop: true,\n reason:\n `sequential e-process decided at generation ${history[g]!.generationIndex}: ` +\n `e-value ${step.wealth.toFixed(2)} ≥ 1/α=${threshold.toFixed(2)} after n=${step.n} ` +\n 'paired deltas vs the generation-0 incumbent; stop exploring and require ' +\n 'an independent held-out promotion decision',\n }\n processedGenerations = history.length\n return stopped\n }\n }\n }\n processedGenerations = history.length\n return { stop: false }\n }\n decide.state = () => proc.state()\n return decide\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmIA,SAAS,mBAAmB,GAA4B;CACtD,OAAO,sBAAsB,CAAC,MAAM,EAAE;AACxC;AAEA,SAAS,cAAc,MAAmD;CACxE,MAAM,IAAI,KAAK;CACf,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,GAAG;EACL,IAAI,CAAC,mBAAmB,CAAC,GACvB,MAAM,IAAI,MACR,oDAAoD,EAAE,GAAG,mCAC3D;EAEF,IAAI,KAAK,UAAU,KAAA,KAAa,KAAK,UAAU,EAAE,OAC/C,MAAM,IAAI,MACR,+BAA+B,KAAK,MAAM,uCAAuC,EAAE,MAAM,oEAE3F;EAE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,KAAK,CAAC;IAChD,IAAI,KAAK,KAAK,QAAQ,KAAK,UAAU,WAAW;KAC9C,UAAU;MACR,MAAM;MACN,QACE,8CAA8C,QAAQ,EAAE,CAAE,gBAAgB,YAC/D,KAAK,OAAO,QAAQ,CAAC,EAAE,SAAS,UAAU,QAAQ,CAAC,EAAE,WAAW,KAAK,EAAE;KAGtF;KACA,uBAAuB,QAAQ;KAC/B,OAAO;IACT;GACF;EACF;EACA,uBAAuB,QAAQ;EAC/B,OAAO,EAAE,MAAM,MAAM;CACvB;CACA,OAAO,cAAc,KAAK,MAAM;CAChC,OAAO;AACT"}
1
+ {"version":3,"file":"sequential-7uxpO0Vm.js","names":[],"sources":["../src/campaign/gates/sequential.ts"],"sourcesContent":["/**\n * Anytime-valid sequential promotion gate — an e-process (betting\n * test-martingale, see `eProcess` in `statistics.ts`) over paired\n * per-scenario deltas, so a campaign stops the MOMENT evidence decides\n * instead of burning a fixed-n budget. Decisions remain valid at any\n * data-dependent stopping time (Ville's inequality), which is exactly what\n * fixed-n machinery cannot offer: peeking at a bootstrap CI after every\n * observation and stopping on the first significant peek inflates type-I\n * error far beyond alpha.\n *\n * REPLACES, never layers on, a fixed-n gate. Running `heldoutSignificance`\n * or `paretoSignificanceGate` repeatedly on a growing sample and stopping\n * early is optional stopping no matter how it is dressed up; this gate is\n * the valid way to stop early. Use one or the other per evidence stream.\n *\n * Pre-registration binding: anytime validity holds only for the\n * PRE-REGISTERED statistic. When a `SignedManifest` is bound, the gate takes\n * alpha from `manifest.alpha`, the observation budget from\n * `manifest.preRegisteredN`, orients deltas by `manifest.direction`, and\n * shifts the null boundary by `manifest.minEffect` — re-deciding the same\n * stream under different parameters after seeing data would reopen optional\n * stopping under a fancier name. The manifest's content hash is verified at\n * construction with the canonical RFC 8785 digest used by signManifest.\n *\n * The supermartingale guarantee requires E[delta_t | past] ≤ the null\n * boundary under H0. Independent sampling with that mean bound suffices.\n * Exchangeability or shuffling alone does not: one fair sign repeated many\n * times is exchangeable and has marginal mean zero, but its conditional mean\n * becomes the revealed sign. A seeded shuffle cannot remove that dependence.\n * `decide(ctx)` pairs cells, then averages repetitions within each scenario\n * before testing. Pass independentUnitByScenarioId for scenarios sharing a\n * latent source or incident. Units must still satisfy the conditional-mean null.\n * Direct `observe()` callers own this sampling and aggregation contract.\n */\n\nimport { manifestContentDigest, type SignedManifest } from '../../pre-registration'\nimport { type EProcessState, eProcess, mulberry32 } from '../../statistics'\nimport type { Gate, GateContext, GateResult, GenerationRecord, Scenario } from '../types'\nimport { aggregatePairedHoldout, pairHoldout } from './statistical-heldout'\n\nexport type SequentialDecision = 'promote' | 'continue' | 'undecided-at-maxN'\n\nexport interface SequentialObservation {\n decision: SequentialDecision\n /** Current e-value (the betting wealth) against H0. */\n eValue: number\n /** Paired deltas consumed so far. */\n n: number\n /** Names the decision basis. For 'undecided-at-maxN' it states explicitly\n * that exhausting the budget is NOT evidence of no effect. */\n reason: string\n}\n\nexport interface SequentialPairedGateOptions {\n /** Type-I budget. With `preRegistration` bound this MUST match\n * `manifest.alpha` (conflict throws). Default 0.05. */\n alpha?: number\n /** Minimum independent paired units before a promote may fire. The stopping rule is\n * \"first n ≥ minN with e-value ≥ 1/alpha\" — still a valid stopping time.\n * Default 5. */\n minN?: number\n /** Pre-registered independent-unit budget (scenarios by default in decide()). Required unless `preRegistration`\n * supplies it via `preRegisteredN` (conflict throws). */\n maxN?: number\n /** Bet truncation forwarded to `eProcess`. Default 0.5. */\n maxBet?: number\n /** Bound on |delta| in the judge's native scale; deltas are mapped to\n * x = (d/scale + 1)/2 ∈ [0,1]. A delta outside ±scale throws (use\n * `detectScale` to pick 1 vs 100 BEFORE streaming). Default 1. */\n scale?: number\n /** Seed for reproducible ordering of scenario deltas in decide().\n * Shuffling does not establish the conditional-mean null. Default 1337. */\n shuffleSeed?: number\n /** Independent unit for every scenario passed to decide(). Full cell pairs\n * are averaged within each unit before testing. Defaults to scenario IDs.\n * The mapping is copied at construction. Direct observe() is unchanged. */\n independentUnitByScenarioId?: ReadonlyMap<string, string>\n /** Bind the pre-registered hypothesis. Verified (content hash) at\n * construction; alpha/maxN/direction/minEffect come FROM the manifest. */\n preRegistration?: SignedManifest\n /** Override the gate name in reports. */\n name?: string\n /** Continue the observe-stream from a `state()` snapshot taken before a\n * restart. The gate's parameters still resolve from this options object\n * (and the manifest); the snapshot must have been recorded under the same\n * alpha, maxBet, and null boundary, and its decision must be one this\n * configuration could have reached at its n, or construction throws.\n * `decide(ctx)` is unaffected — it always runs on a fresh stream. */\n resume?: SequentialStreamState\n}\n\n/** Snapshot of one observe-stream: the e-process state plus the gate's own\n * decision, which applies `minN` and `maxN` on top of the core latch. A\n * gate rebuilt with `resume` from this value continues exactly where the\n * snapshot was taken. */\nexport type SequentialStreamState = EProcessState & { decision: SequentialDecision }\n\nexport interface SequentialPairedGate<TArtifact = unknown, TScenario extends Scenario = Scenario>\n extends Gate<TArtifact, TScenario> {\n /** Streaming entry point: feed one paired independent-unit delta\n * (candidate − baseline, native scale). Aggregate correlated repetitions\n * before calling; the caller must justify E[delta_t | past] under H0.\n * Each gate instance carries ONE\n * observe-stream; `decide(ctx)` runs on its own fresh stream and never\n * consumes or advances this one. 'promote' is sticky; observing past the\n * pre-registered maxN throws (extending a finished stream after seeing\n * the result reopens optional stopping — start a NEW pre-registered\n * test). */\n observe(delta: number): SequentialObservation\n /** Read-only snapshot of the observe-stream. Pass it back as\n * `resume` to continue the stream after a restart. */\n state(): SequentialStreamState\n}\n\ninterface ResolvedConfig {\n alpha: number\n minN: number\n maxN: number\n maxBet: number\n scale: number\n shuffleSeed: number\n /** 'decrease' negates deltas so \"better\" is always positive. */\n direction: 'increase' | 'decrease'\n /** H0 boundary in x-space: 1/2 + minEffect/(2·scale). */\n nullMean: number\n minEffect: number\n}\n\n/** Sync twin of `verifyManifest`, so gate construction stays synchronous and\n * fails loud before any observation is consumed. The digest scheme belongs to\n * `pre-registration`; this gate only compares. */\nfunction verifyManifestSync(m: SignedManifest): boolean {\n return manifestContentDigest(m) === m.contentHash\n}\n\nfunction resolveConfig(opts: SequentialPairedGateOptions): ResolvedConfig {\n const m = opts.preRegistration\n let alpha: number\n let maxN: number\n let direction: 'increase' | 'decrease'\n let minEffect: number\n if (m) {\n if (!verifyManifestSync(m)) {\n throw new Error(\n `sequentialPairedGate: pre-registration manifest '${m.id}' content hash mismatch (tampered)`,\n )\n }\n if (opts.alpha !== undefined && opts.alpha !== m.alpha) {\n throw new Error(\n `sequentialPairedGate: alpha ${opts.alpha} conflicts with pre-registered alpha ${m.alpha} — ` +\n `the registered statistic is the only one anytime validity covers`,\n )\n }\n if (opts.maxN !== undefined && opts.maxN !== m.preRegisteredN) {\n throw new Error(\n `sequentialPairedGate: maxN ${opts.maxN} conflicts with pre-registered N ${m.preRegisteredN}`,\n )\n }\n alpha = m.alpha\n maxN = m.preRegisteredN\n direction = m.direction\n minEffect = m.minEffect\n } else {\n alpha = opts.alpha ?? 0.05\n if (opts.maxN === undefined) {\n throw new Error(\n 'sequentialPairedGate: maxN is required (or bind a preRegistration manifest whose ' +\n 'preRegisteredN is the budget) — an unbounded stream has no pre-registered budget',\n )\n }\n maxN = opts.maxN\n direction = 'increase'\n minEffect = 0\n }\n const scale = opts.scale ?? 1\n if (!Number.isFinite(scale) || scale <= 0) {\n throw new Error(`sequentialPairedGate: scale must be > 0, got ${scale}`)\n }\n if (!Number.isInteger(maxN) || maxN < 1) {\n throw new Error(`sequentialPairedGate: maxN must be a positive integer, got ${maxN}`)\n }\n const minN = opts.minN ?? 5\n if (!Number.isInteger(minN) || minN < 1 || minN > maxN) {\n throw new Error(\n `sequentialPairedGate: minN must be an integer in [1, maxN=${maxN}], got ${minN}`,\n )\n }\n if (!Number.isFinite(minEffect) || minEffect < 0 || minEffect >= scale) {\n throw new Error(\n `sequentialPairedGate: minEffect must be in [0, scale=${scale}), got ${minEffect}`,\n )\n }\n // H0: mean delta ≤ minEffect. In x = (d/scale + 1)/2 space that is\n // E[x] ≤ 1/2 + minEffect/(2·scale) — a shifted null boundary, NOT a clamp\n // of the observations (clamping is mean-distorting for skewed deltas).\n const nullMean = 0.5 + minEffect / (2 * scale)\n return {\n alpha,\n minN,\n maxN,\n maxBet: opts.maxBet ?? 0.5,\n scale,\n shuffleSeed: opts.shuffleSeed ?? 1337,\n direction,\n nullMean,\n minEffect,\n }\n}\n\ninterface SequentialStream {\n observe(delta: number): SequentialObservation\n state(): SequentialStreamState\n}\n\nconst SEQUENTIAL_DECISIONS: readonly SequentialDecision[] = [\n 'promote',\n 'continue',\n 'undecided-at-maxN',\n]\n\n/** Refuse a snapshot whose gate decision this configuration could not have\n * reached at the snapshot's n. The e-process parameters are checked by\n * `eProcess` itself; this covers the gate's own stopping rule. */\nfunction assertResumableStream(resume: SequentialStreamState, cfg: ResolvedConfig): void {\n const fail = (detail: string): never => {\n throw new Error(`sequentialPairedGate: cannot resume — ${detail}`)\n }\n if (!SEQUENTIAL_DECISIONS.includes(resume.decision)) {\n fail(`unknown decision '${String(resume.decision)}'`)\n }\n if (resume.n > cfg.maxN) {\n fail(`snapshot n=${resume.n} exceeds the pre-registered maxN=${cfg.maxN}`)\n }\n const threshold = 1 / cfg.alpha\n switch (resume.decision) {\n case 'promote':\n if (resume.n < cfg.minN) {\n fail(`decision 'promote' at n=${resume.n} is below minN=${cfg.minN}`)\n }\n break\n case 'undecided-at-maxN':\n if (resume.n !== cfg.maxN) {\n fail(`decision 'undecided-at-maxN' at n=${resume.n} does not match maxN=${cfg.maxN}`)\n }\n break\n case 'continue':\n if (resume.n >= cfg.maxN) {\n fail(`decision 'continue' at n=${resume.n} with maxN=${cfg.maxN}; the stream is finished`)\n }\n if (resume.n >= cfg.minN && resume.wealth >= threshold) {\n fail(\n `decision 'continue' at n=${resume.n} ≥ minN=${cfg.minN} with e-value ` +\n `${resume.wealth} ≥ 1/α=${threshold}; this stream would have promoted`,\n )\n }\n break\n }\n}\n\nfunction makeStream(cfg: ResolvedConfig, resume?: SequentialStreamState): SequentialStream {\n if (resume !== undefined) assertResumableStream(resume, cfg)\n const proc = eProcess({\n alpha: cfg.alpha,\n maxBet: cfg.maxBet,\n nullMean: cfg.nullMean,\n ...(resume === undefined ? {} : { resume }),\n })\n const threshold = 1 / cfg.alpha\n let terminal: SequentialDecision | undefined =\n resume === undefined || resume.decision === 'continue' ? undefined : resume.decision\n return {\n observe(delta: number): SequentialObservation {\n if (terminal === 'undecided-at-maxN') {\n throw new Error(\n `sequentialPairedGate: pre-registered maxN=${cfg.maxN} exhausted — extending the ` +\n 'stream after seeing the result reopens optional stopping; start a NEW ' +\n 'pre-registered test',\n )\n }\n if (!Number.isFinite(delta) || Math.abs(delta) > cfg.scale) {\n throw new Error(\n `sequentialPairedGate: delta ${delta} outside ±scale=${cfg.scale} — pass the judge's ` +\n `native scale explicitly (detectScale helps pick 1 vs 100)`,\n )\n }\n const d = cfg.direction === 'decrease' ? -delta : delta\n const step = proc.update((d / cfg.scale + 1) / 2)\n // Stopping rule: FIRST n ≥ minN with current wealth ≥ 1/alpha — a valid\n // stopping time (measurable w.r.t. the past), sticky once latched. The\n // core's own `decided` latch ignores minN, so the gate re-derives the\n // decision from current wealth here.\n if (terminal === undefined && step.n >= cfg.minN && step.wealth >= threshold) {\n terminal = 'promote'\n }\n if (terminal === 'promote') {\n return {\n decision: 'promote',\n eValue: step.wealth,\n n: step.n,\n reason:\n `e-value ${step.wealth.toFixed(2)} ≥ 1/α=${threshold.toFixed(2)} at n=${step.n} ` +\n `(minN=${cfg.minN}): the paired improvement exceeds ${cfg.minEffect} at anytime-valid ` +\n `level α=${cfg.alpha}`,\n }\n }\n if (step.n >= cfg.maxN) {\n terminal = 'undecided-at-maxN'\n return {\n decision: 'undecided-at-maxN',\n eValue: step.wealth,\n n: step.n,\n reason:\n `undecided at pre-registered maxN=${cfg.maxN} (e-value ${step.wealth.toFixed(2)} < ` +\n `1/α=${threshold.toFixed(2)}). This is NOT evidence of no effect — the effect may be ` +\n 'real but smaller than this budget can detect; re-register with a larger N to test that',\n }\n }\n return {\n decision: 'continue',\n eValue: step.wealth,\n n: step.n,\n reason: `e-value ${step.wealth.toFixed(2)} < 1/α=${threshold.toFixed(2)} at n=${step.n}/${cfg.maxN} — keep observing`,\n }\n },\n state() {\n return { ...proc.state(), decision: terminal ?? 'continue' }\n },\n }\n}\n\n/** Data-independent in-place Fisher–Yates with a seeded PRNG — the permutation\n * depends only on the seed, never the values, so bet predictability survives. */\nfunction seededShuffle<T>(items: T[], seed: number): T[] {\n const rng = mulberry32(seed)\n for (let i = items.length - 1; i > 0; i--) {\n const j = Math.floor(rng() * (i + 1))\n const tmp = items[i]!\n items[i] = items[j]!\n items[j] = tmp\n }\n return items\n}\n\n/**\n * Anytime-valid sequential paired gate. Conforms to the existing `Gate`\n * contract: decide(ctx) pairs candidate and baseline by full cellId, then\n * averages deltas within each configured unit (scenario by default). The\n * e-process consumes one observation per unit, with equal unit weights.\n * The streaming observe(delta) entry consumes caller-aggregated independent\n * units. Repetitions improve a unit's precision and do not increase n.\n *\n * Decision mapping onto the substrate's five-valued `GateDecision`:\n * - 'promote' → 'ship'\n * - 'continue' → 'need_more_work' (stream ended before maxN with\n * the e-value undecided — more independent units needed)\n * - 'undecided-at-maxN' → 'hold', with the reason stating it is NOT\n * evidence of no effect (never a silent default)\n */\nexport function sequentialPairedGate<TArtifact = unknown, TScenario extends Scenario = Scenario>(\n options: SequentialPairedGateOptions,\n): SequentialPairedGate<TArtifact, TScenario> {\n const cfg = resolveConfig(options)\n const name = options.name ?? 'sequentialPairedGate'\n const manifest = options.preRegistration\n const observeStream = makeStream(cfg, options.resume)\n const independentUnitByScenarioId =\n options.independentUnitByScenarioId === undefined\n ? undefined\n : new Map(options.independentUnitByScenarioId)\n\n return {\n name,\n observe(delta: number): SequentialObservation {\n return observeStream.observe(delta)\n },\n state() {\n return observeStream.state()\n },\n async decide(ctx: GateContext<TArtifact, TScenario>): Promise<GateResult> {\n if (!ctx.baselineJudgeScores) {\n throw new Error(\n `${name}: ctx.baselineJudgeScores is required — falling back to the candidate's own ` +\n 'scores would compare the candidate against itself (delta 0, silent no-op)',\n )\n }\n const scenarioIds = new Set(ctx.scenarios.map((s) => s.id))\n const unitMap = independentUnitByScenarioId ?? new Map([...scenarioIds].map((id) => [id, id]))\n for (const id of scenarioIds) {\n const unit = unitMap.get(id)\n if (typeof unit !== 'string' || unit.length === 0 || unit.trim() !== unit) {\n throw new Error(`${name}: missing independent unit for scenario '${id}'`)\n }\n }\n const paired = pairHoldout(\n ctx.judgeScores,\n ctx.baselineJudgeScores,\n scenarioIds,\n (s) => s.composite,\n )\n for (let i = 0; i < paired.cellIds.length; i++) {\n const delta = paired.after[i]! - paired.before[i]!\n if (Math.abs(delta) > cfg.scale) {\n throw new Error(\n `${name}: cell '${paired.cellIds[i]}' delta ${delta} outside ±scale=${cfg.scale}`,\n )\n }\n }\n const observations = aggregatePairedHoldout(paired, unitMap)\n const deltas = observations.after.map((after, i) => after - observations.before[i]!)\n seededShuffle(deltas, cfg.shuffleSeed)\n\n const stream = makeStream(cfg)\n let last: SequentialObservation | undefined\n for (const d of deltas) {\n last = stream.observe(d)\n if (last.decision !== 'continue') break\n }\n\n const detail = {\n ...stream.state(),\n minN: cfg.minN,\n maxN: cfg.maxN,\n scale: cfg.scale,\n shuffleSeed: cfg.shuffleSeed,\n direction: cfg.direction,\n minEffect: cfg.minEffect,\n pairedN: deltas.length,\n pairedCellN: paired.cellIds.length,\n observationUnit: independentUnitByScenarioId === undefined ? 'scenario' : 'registered',\n unitIds: observations.unitIds,\n ...(manifest ? { preRegisteredId: manifest.id, metric: manifest.metric } : {}),\n }\n const meanDelta =\n deltas.length === 0 ? undefined : deltas.reduce((s, d) => s + d, 0) / deltas.length\n\n if (last === undefined) {\n return {\n decision: 'need_more_work',\n reasons: [`${name}: no paired holdout observations — nothing to test`],\n contributingGates: [{ name, status: 'not_evaluated', detail }],\n }\n }\n const decision =\n last.decision === 'promote'\n ? 'ship'\n : last.decision === 'continue'\n ? 'need_more_work'\n : 'hold'\n return {\n decision,\n reasons: [`${name}: ${last.reason}`],\n contributingGates: [\n {\n name,\n status:\n decision === 'ship'\n ? 'pass'\n : decision === 'need_more_work'\n ? 'not_evaluated'\n : 'fail',\n detail,\n },\n ],\n delta: meanDelta,\n }\n },\n }\n}\n\nexport interface SequentialDecideOptions {\n /** Type-I budget for the early-stop evidence. Default 0.05. */\n alpha?: number\n /** Minimum paired deltas before a stop may fire. Default 5. */\n minN?: number\n /** Bet truncation forwarded to `eProcess`. Default 0.5. */\n maxBet?: number\n /** Bound on |per-scenario composite delta|. Default 1. */\n scale?: number\n}\n\nexport interface SequentialDecideFn {\n (args: { history: GenerationRecord[] }): { stop: boolean; reason?: string }\n /** Read-only snapshot of the accumulated e-process (observability + tests). */\n state(): EProcessState\n}\n\n/**\n * SurfaceProposer.decide adapter that stops exploration at an e-value threshold.\n * The selected candidate still requires an independent held-out decision.\n *\n * Stream: for each generation g ≥ 1, the per-scenario composite deltas of\n * generation g's top candidate vs the generation-0 top candidate (the\n * incumbent the loop set out to beat), paired by scenarioId. H0: no proposed\n * surface improves any scenario's expected composite over the incumbent —\n * under it every delta has conditional mean ≤ 0 and the e-process is valid.\n * Once wealth ≥ 1/alpha the loop stops and hands the winner to the promotion\n * gate (which re-scores on HELD-OUT data — this adapter only spends the\n * exploration budget, it never promotes).\n *\n * This is an exploration stopping heuristic. Selection of the best measured\n * candidate and reuse of measured incumbent scores generally violate the\n * conditional-mean null, even when the candidates have no true improvement.\n * More repetitions reduce noise but do not establish exact type-I control.\n * An UNDECIDED process never stops the loop — absence of a\n * crossing is NOT evidence of no effect, so the loop simply runs its normal\n * course. Calling the adapter repeatedly with a growing history consumes each\n * generation exactly once (re-feeding an already-seen record would double-count\n * evidence).\n */\nexport function sequentialDecide(options: SequentialDecideOptions = {}): SequentialDecideFn {\n const alpha = options.alpha ?? 0.05\n const minN = options.minN ?? 5\n const scale = options.scale ?? 1\n if (!Number.isFinite(scale) || scale <= 0) {\n throw new Error(`sequentialDecide: scale must be > 0, got ${scale}`)\n }\n const proc = eProcess({ alpha, maxBet: options.maxBet ?? 0.5, nullMean: 0.5 })\n const threshold = 1 / alpha\n let processedGenerations = 0\n let reference: Map<string, number> | undefined\n let stopped: { stop: true; reason: string } | undefined\n\n const topCandidate = (record: GenerationRecord) => {\n if (record.candidates.length === 0) {\n throw new Error(\n `sequentialDecide: generation ${record.generationIndex} has no candidates — ` +\n 'cannot extract a top candidate',\n )\n }\n return record.candidates.reduce((best, candidate) => {\n if (best.composite === null) return candidate\n if (candidate.composite === null) return best\n return candidate.composite > best.composite ? candidate : best\n })\n }\n\n const decide: SequentialDecideFn = ({ history }) => {\n if (stopped) return stopped\n if (history.length === 0) return { stop: false }\n if (reference === undefined) {\n reference = new Map(\n topCandidate(history[0]!).scenarios.map((s) => [s.scenarioId, s.composite]),\n )\n }\n // Consume only generations not yet seen; start at 1 — generation 0 IS the\n // reference and would contribute all-zero deltas (pure wealth dilution).\n for (let g = Math.max(1, processedGenerations); g < history.length; g++) {\n const top = topCandidate(history[g]!)\n const byScenario = new Map(top.scenarios.map((s) => [s.scenarioId, s.composite]))\n for (const [scenarioId, refComposite] of reference) {\n const candComposite = byScenario.get(scenarioId)\n if (candComposite === undefined) {\n throw new Error(\n `sequentialDecide: generation ${history[g]!.generationIndex} top candidate is missing ` +\n `scenario '${scenarioId}' — generations must score the same scenario set to pair`,\n )\n }\n const delta = candComposite - refComposite\n if (!Number.isFinite(delta) || Math.abs(delta) > scale) {\n throw new Error(\n `sequentialDecide: paired delta ${delta} outside ±scale=${scale} on scenario ` +\n `'${scenarioId}' — pass the composite scale explicitly`,\n )\n }\n const step = proc.update((delta / scale + 1) / 2)\n if (step.n >= minN && step.wealth >= threshold) {\n stopped = {\n stop: true,\n reason:\n `sequential e-process decided at generation ${history[g]!.generationIndex}: ` +\n `e-value ${step.wealth.toFixed(2)} ≥ 1/α=${threshold.toFixed(2)} after n=${step.n} ` +\n 'paired deltas vs the generation-0 incumbent; stop exploring and require ' +\n 'an independent held-out promotion decision',\n }\n processedGenerations = history.length\n return stopped\n }\n }\n }\n processedGenerations = history.length\n return { stop: false }\n }\n decide.state = () => proc.state()\n return decide\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmIA,SAAS,mBAAmB,GAA4B;CACtD,OAAO,sBAAsB,CAAC,MAAM,EAAE;AACxC;AAEA,SAAS,cAAc,MAAmD;CACxE,MAAM,IAAI,KAAK;CACf,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,GAAG;EACL,IAAI,CAAC,mBAAmB,CAAC,GACvB,MAAM,IAAI,MACR,oDAAoD,EAAE,GAAG,mCAC3D;EAEF,IAAI,KAAK,UAAU,KAAA,KAAa,KAAK,UAAU,EAAE,OAC/C,MAAM,IAAI,MACR,+BAA+B,KAAK,MAAM,uCAAuC,EAAE,MAAM,oEAE3F;EAEF,IAAI,KAAK,SAAS,KAAA,KAAa,KAAK,SAAS,EAAE,gBAC7C,MAAM,IAAI,MACR,8BAA8B,KAAK,KAAK,mCAAmC,EAAE,gBAC/E;EAEF,QAAQ,EAAE;EACV,OAAO,EAAE;EACT,YAAY,EAAE;EACd,YAAY,EAAE;CAChB,OAAO;EACL,QAAQ,KAAK,SAAS;EACtB,IAAI,KAAK,SAAS,KAAA,GAChB,MAAM,IAAI,MACR,mKAEF;EAEF,OAAO,KAAK;EACZ,YAAY;EACZ,YAAY;CACd;CACA,MAAM,QAAQ,KAAK,SAAS;CAC5B,IAAI,CAAC,OAAO,SAAS,KAAK,KAAK,SAAS,GACtC,MAAM,IAAI,MAAM,gDAAgD,OAAO;CAEzE,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,GACpC,MAAM,IAAI,MAAM,8DAA8D,MAAM;CAEtF,MAAM,OAAO,KAAK,QAAQ;CAC1B,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,MAChD,MAAM,IAAI,MACR,6DAA6D,KA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,IAAI,QAAQ,QAAQ,KAAK;GACvE,MAAM,MAAM,aAAa,QAAQ,EAAG;GACpC,MAAM,aAAa,IAAI,IAAI,IAAI,UAAU,KAAK,MAAM,CAAC,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;GAChF,KAAK,MAAM,CAAC,YAAY,iBAAiB,WAAW;IAClD,MAAM,gBAAgB,WAAW,IAAI,UAAU;IAC/C,IAAI,kBAAkB,KAAA,GACpB,MAAM,IAAI,MACR,gCAAgC,QAAQ,EAAE,CAAE,gBAAgB,sCAC7C,WAAW,yDAC5B;IAEF,MAAM,QAAQ,gBAAgB;IAC9B,IAAI,CAAC,OAAO,SAAS,KAAK,KAAK,KAAK,IAAI,KAAK,IAAI,OAC/C,MAAM,IAAI,MACR,kCAAkC,MAAM,kBAAkB,MAAM,gBAC1D,WAAW,wCACnB;IAEF,MAAM,OAAO,KAAK,QAAQ,QAAQ,QAAQ,KAAK,CAAC;IAChD,IAAI,KAAK,KAAK,QAAQ,KAAK,UAAU,WAAW;KAC9C,UAAU;MACR,MAAM;MACN,QACE,8CAA8C,QAAQ,EAAE,CAAE,gBAAgB,YAC/D,KAAK,OAAO,QAAQ,CAAC,EAAE,SAAS,UAAU,QAAQ,CAAC,EAAE,WAAW,KAAK,EAAE;KAGtF;KACA,uBAAuB,QAAQ;KAC/B,OAAO;IACT;GACF;EACF;EACA,uBAAuB,QAAQ;EAC/B,OAAO,EAAE,MAAM,MAAM;CACvB;CACA,OAAO,cAAc,KAAK,MAAM;CAChC,OAAO;AACT"}
@@ -1,8 +1,8 @@
1
1
  import { a as hashCanonical } from "./canonical-BsZVgBhW.js";
2
- import { a as heldoutSignificance, o as pairHoldout } from "./statistical-heldout-CNLOvRq_.js";
2
+ import { a as heldoutSignificance, o as pairHoldout } from "./statistical-heldout-C26hOFWD.js";
3
3
  import { n as contentHash, t as canonicalJson } from "./verdict-cache-BQEsVy9n.js";
4
- import { D as surfaceDiff, O as surfaceNode, T as developmentClaim, d as combineComparisonCosts, f as costFromLedgerSummary, l as optimizationTokenUsageFromSummary, m as readGepaCandidatePopulationArtifact, p as assertGepaCandidatePopulationSummary, rt as runCampaign, t as llmJudge, w as SearchRecorder } from "./llm-judge-DyZdrp6I.js";
5
- import { F as surfaceContentHash, b as campaignBreakdown } from "./campaign-evidence-Dt_rWPk2.js";
4
+ import { D as surfaceDiff, O as surfaceNode, T as developmentClaim, d as combineComparisonCosts, f as costFromLedgerSummary, l as optimizationTokenUsageFromSummary, m as readGepaCandidatePopulationArtifact, p as assertGepaCandidatePopulationSummary, rt as runCampaign, t as llmJudge, w as SearchRecorder } from "./llm-judge-Bka5q-ds.js";
5
+ import { F as surfaceContentHash, b as campaignBreakdown } from "./campaign-evidence-C__cUpCt.js";
6
6
  import { t as deepFreezeCanonicalJson } from "./deep-freeze-CurcOQg3.js";
7
7
  import { S as fsCampaignStorage, _ as removeCredentialEnvironment, b as safePathComponent, d as assertExternalOptimizerModelBudget, f as assertJsonValue, g as isRecord, h as isExternalTextCandidate, i as startExternalOptimizerModelProxy, m as isCandidateText, n as closeExternalOptimizerResources, p as assertNoCredentialValues, r as runWithCleanup, t as runExternalOptimizerProcess, v as resolveExternalOptimizerCallbackLimits, x as createRunCostLedger, y as resolveExternalOptimizerProcessLimits } from "./external-optimizer-subprocess-BmKtH3T6.js";
8
8
  import { n as openSearchLedger } from "./search-ledger-CXQPwdWz.js";
@@ -2583,4 +2583,4 @@ function skillOptOptimizationMethod(config) {
2583
2583
  //#endregion
2584
2584
  export { importGepaPopulation as a, heldOutGate as c, decodeExternalTextCandidate as d, readExternalOptimizerObservationArtifact as f, runReferenceEquivalenceJudge as g, createReferenceEquivalenceJudge as h, importExternalEvaluations as i, composeGate as l, REFERENCE_EQUIVALENCE_JUDGE_VERSION as m, gepaOptimizationMethod as n, recordGepaSearch as o, REFERENCE_EQUIVALENCE_INPUT_LIMITS as p, externalSurface as r, recordSkillOptSearch as s, skillOptOptimizationMethod as t, externalTextOptimizationMethod as u };
2585
2585
 
2586
- //# sourceMappingURL=skillopt-optimization-method-Dz5CGZb8.js.map
2586
+ //# sourceMappingURL=skillopt-optimization-method-bEm4jYV4.js.map