@tangle-network/agent-eval 0.109.1 → 0.110.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 (174) hide show
  1. package/dist/analyst/index.d.ts +10 -12
  2. package/dist/analyst/index.js +8 -11
  3. package/dist/analyst/index.js.map +1 -1
  4. package/dist/{analyze-runs-DJYpep3L.d.ts → analyze-runs-Dmz6LA9e.d.ts} +4 -4
  5. package/dist/{baseline-Bbid3WoO.d.ts → baseline-DsNteOgR.d.ts} +32 -2
  6. package/dist/belief-state/index.d.ts +6 -6
  7. package/dist/benchmarks/index.d.ts +4 -4
  8. package/dist/benchmarks/index.js +7 -8
  9. package/dist/builder-eval/index.d.ts +4 -4
  10. package/dist/builder-eval/index.js +1 -2
  11. package/dist/builder-eval/index.js.map +1 -1
  12. package/dist/{calibration-BPmzuVPk.d.ts → calibration-Dz8TQV4y.d.ts} +2 -2
  13. package/dist/campaign/index.d.ts +16 -19
  14. package/dist/campaign/index.js +7 -8
  15. package/dist/{chunk-LOJ2QVCE.js → chunk-2IY4ILP4.js} +2 -2
  16. package/dist/{chunk-LIEJUH2I.js → chunk-6PL5MGDL.js} +9 -9
  17. package/dist/{chunk-2OGPXHOB.js → chunk-7NX6ZSBG.js} +36 -7
  18. package/dist/chunk-7NX6ZSBG.js.map +1 -0
  19. package/dist/{chunk-OVPVM4JC.js → chunk-GTERJI6Q.js} +4 -4
  20. package/dist/{chunk-YEHAEDUD.js → chunk-IMWDSFUM.js} +604 -2
  21. package/dist/chunk-IMWDSFUM.js.map +1 -0
  22. package/dist/{chunk-JZXGWLK5.js → chunk-MHNQWM4I.js} +62 -6
  23. package/dist/chunk-MHNQWM4I.js.map +1 -0
  24. package/dist/{chunk-QRVS7MX4.js → chunk-OW47B5WA.js} +3 -5
  25. package/dist/{chunk-QRVS7MX4.js.map → chunk-OW47B5WA.js.map} +1 -1
  26. package/dist/{chunk-DBDRR6GF.js → chunk-PLOMR3HP.js} +48 -2
  27. package/dist/chunk-PLOMR3HP.js.map +1 -0
  28. package/dist/{chunk-GDZAWO2I.js → chunk-QFGTU7MT.js} +2 -2
  29. package/dist/{chunk-R6D7NEYJ.js → chunk-RNB2NICW.js} +11 -11
  30. package/dist/{chunk-V7HNA47Z.js → chunk-RSVSSZKF.js} +5 -5
  31. package/dist/{chunk-5PK3626Q.js → chunk-XRGOKCMO.js} +88 -17
  32. package/dist/chunk-XRGOKCMO.js.map +1 -0
  33. package/dist/{code-agent-session-rnJKlqmT.d.ts → code-agent-session-yitf9I-F.d.ts} +1 -1
  34. package/dist/contract/index.d.ts +20 -23
  35. package/dist/contract/index.js +11 -13
  36. package/dist/contract/index.js.map +1 -1
  37. package/dist/{control-B8UthSBL.d.ts → control-U8LBKUES.d.ts} +5 -6
  38. package/dist/control.d.ts +8 -9
  39. package/dist/control.js +6 -8
  40. package/dist/{dataset-DS7ytHZU.d.ts → dataset-NENEzRgk.d.ts} +1 -1
  41. package/dist/{default-registry-BswHCXnU.d.ts → default-registry-Bcf1uKVI.d.ts} +1 -2
  42. package/dist/{emitter-C2rqGH_l.d.ts → emitter-BRchAAAx.d.ts} +2 -2
  43. package/dist/{failure-cluster-DH9Flgcf.d.ts → failure-cluster-C48PiReX.d.ts} +2 -2
  44. package/dist/feedback-trajectory-pDcz1lQ1.d.ts +348 -0
  45. package/dist/{gepa-B3x5Ulcv.d.ts → gepa-BUNP3606.d.ts} +143 -2
  46. package/dist/hosted/index.d.ts +7 -7
  47. package/dist/{index-pPtfoIJO.d.ts → index-Dc3VLGhp.d.ts} +2 -2
  48. package/dist/index.d.ts +645 -61
  49. package/dist/index.js +1282 -190
  50. package/dist/index.js.map +1 -1
  51. package/dist/{insight-report-B4xrdwEK.d.ts → insight-report-D4cXFsLt.d.ts} +1 -1
  52. package/dist/{integrity-DqGZg3st.d.ts → integrity-qemeBAyx.d.ts} +1 -1
  53. package/dist/{types-D1ytG0Yg.d.ts → kind-factory-20hcaYpf.d.ts} +169 -2
  54. package/dist/meta-eval/index.d.ts +5 -5
  55. package/dist/meta-eval/index.js +1 -2
  56. package/dist/meta-eval/index.js.map +1 -1
  57. package/dist/{multi-layer-verifier-CI4jdX-q.d.ts → multi-layer-verifier-BsqKuLyN.d.ts} +1 -1
  58. package/dist/multishot/index.d.ts +3 -3
  59. package/dist/openapi.json +1 -1
  60. package/dist/pipelines/index.d.ts +6 -7
  61. package/dist/pipelines/index.js +3 -6
  62. package/dist/pipelines/index.js.map +1 -1
  63. package/dist/{policy-edit-DQUXYMDm.d.ts → policy-edit-D2bBDZDf.d.ts} +2 -2
  64. package/dist/{pre-registration-BUhVPzE7.d.ts → pre-registration-BepVVa6P.d.ts} +3 -3
  65. package/dist/{provenance-DdDhf6cg.d.ts → provenance-DMvsfknv.d.ts} +3 -5
  66. package/dist/{query-0aTmbmQe.d.ts → query-Ck190MOd.d.ts} +2 -2
  67. package/dist/{release-report-DeJpsBiA.d.ts → release-report-oBfOz8ku.d.ts} +3 -3
  68. package/dist/reporting.d.ts +8 -8
  69. package/dist/{researcher-Wc7dx6GM.d.ts → researcher-CaH0CwFC.d.ts} +6 -6
  70. package/dist/rl.d.ts +568 -15
  71. package/dist/rl.js +4 -4
  72. package/dist/{rubric-predictive-validity-DPnyG-CE.d.ts → rubric-predictive-validity-C-fMteAW.d.ts} +1 -1
  73. package/dist/{run-record-I-Z3JNvO.d.ts → run-record-DksGsfgv.d.ts} +1 -1
  74. package/dist/{runtime-trajectory-iW9IhV3e.d.ts → runtime-trajectory-h5i0SZUj.d.ts} +1 -1
  75. package/dist/{schema-m0gsnbt3.d.ts → schema-SGWcK9wa.d.ts} +1 -1
  76. package/dist/{semantic-concept-judge-BmNZPB_j.d.ts → semantic-concept-judge-D7z6JCLZ.d.ts} +57 -4
  77. package/dist/{store-BcFXE6LG.d.ts → store-BsVi7ncX.d.ts} +1 -1
  78. package/dist/storyboard/index.d.ts +1 -1
  79. package/dist/{summary-report-QMZVe3P-.d.ts → summary-report-Bz-0-t8v.d.ts} +2 -2
  80. package/dist/{test-graded-scenario-DeODGLra.d.ts → test-graded-scenario-mzYBKspu.d.ts} +3 -3
  81. package/dist/traces.d.ts +54 -11
  82. package/dist/traces.js +25 -27
  83. package/dist/{types-BdIv5dvA.d.ts → types-v--ctu-b.d.ts} +2 -2
  84. package/dist/wire/index.d.ts +5 -6
  85. package/package.json +1 -71
  86. package/dist/adapters/http.d.ts +0 -142
  87. package/dist/adapters/http.js +0 -203
  88. package/dist/adapters/http.js.map +0 -1
  89. package/dist/adapters/langchain.d.ts +0 -95
  90. package/dist/adapters/langchain.js +0 -34
  91. package/dist/adapters/langchain.js.map +0 -1
  92. package/dist/adapters/otel.d.ts +0 -112
  93. package/dist/adapters/otel.js +0 -110
  94. package/dist/adapters/otel.js.map +0 -1
  95. package/dist/chunk-2OGPXHOB.js.map +0 -1
  96. package/dist/chunk-45EEMHTC.js +0 -35
  97. package/dist/chunk-45EEMHTC.js.map +0 -1
  98. package/dist/chunk-5BKGXME7.js +0 -65
  99. package/dist/chunk-5BKGXME7.js.map +0 -1
  100. package/dist/chunk-5PK3626Q.js.map +0 -1
  101. package/dist/chunk-6SK5VFYK.js +0 -100
  102. package/dist/chunk-6SK5VFYK.js.map +0 -1
  103. package/dist/chunk-DBDRR6GF.js.map +0 -1
  104. package/dist/chunk-DJWX3GVS.js +0 -81
  105. package/dist/chunk-DJWX3GVS.js.map +0 -1
  106. package/dist/chunk-FOUG2VVS.js +0 -855
  107. package/dist/chunk-FOUG2VVS.js.map +0 -1
  108. package/dist/chunk-JZXGWLK5.js.map +0 -1
  109. package/dist/chunk-K7QEIHHJ.js +0 -613
  110. package/dist/chunk-K7QEIHHJ.js.map +0 -1
  111. package/dist/chunk-KKHDIONI.js +0 -414
  112. package/dist/chunk-KKHDIONI.js.map +0 -1
  113. package/dist/chunk-KMPRBJK4.js +0 -74
  114. package/dist/chunk-KMPRBJK4.js.map +0 -1
  115. package/dist/chunk-Q2JRAWRI.js +0 -196
  116. package/dist/chunk-Q2JRAWRI.js.map +0 -1
  117. package/dist/chunk-RZTMDUO7.js +0 -49
  118. package/dist/chunk-RZTMDUO7.js.map +0 -1
  119. package/dist/chunk-STGVSCDH.js +0 -202
  120. package/dist/chunk-STGVSCDH.js.map +0 -1
  121. package/dist/chunk-YEHAEDUD.js.map +0 -1
  122. package/dist/control-runtime-Acf9CGhw.d.ts +0 -182
  123. package/dist/corpus-eBVwhCp1.d.ts +0 -560
  124. package/dist/counterfactual-DlOz8PBx.d.ts +0 -85
  125. package/dist/diagnose.d.ts +0 -252
  126. package/dist/diagnose.js +0 -382
  127. package/dist/diagnose.js.map +0 -1
  128. package/dist/feedback-trajectory-C9KCo8ag.d.ts +0 -169
  129. package/dist/governance/index.d.ts +0 -135
  130. package/dist/governance/index.js +0 -18
  131. package/dist/governance/index.js.map +0 -1
  132. package/dist/groundedness/index.d.ts +0 -112
  133. package/dist/groundedness/index.js +0 -77
  134. package/dist/groundedness/index.js.map +0 -1
  135. package/dist/harness-optimizer-mOl9XX_O.d.ts +0 -106
  136. package/dist/kind-factory-DvIGo_cP.d.ts +0 -171
  137. package/dist/knowledge/index.d.ts +0 -103
  138. package/dist/knowledge/index.js +0 -18
  139. package/dist/knowledge/index.js.map +0 -1
  140. package/dist/pareto-E-pembql.d.ts +0 -81
  141. package/dist/perf/index.d.ts +0 -123
  142. package/dist/perf/index.js +0 -18
  143. package/dist/perf/index.js.map +0 -1
  144. package/dist/prm/index.d.ts +0 -104
  145. package/dist/prm/index.js +0 -265
  146. package/dist/prm/index.js.map +0 -1
  147. package/dist/product-benchmark/index.d.ts +0 -247
  148. package/dist/product-benchmark/index.js +0 -37
  149. package/dist/product-benchmark/index.js.map +0 -1
  150. package/dist/red-team-KmmiqBlY.d.ts +0 -63
  151. package/dist/redact-B40YG2M_.d.ts +0 -45
  152. package/dist/rubric-Cc6UHvUb.d.ts +0 -73
  153. package/dist/run-critic-CmMf05uV.d.ts +0 -56
  154. package/dist/sink-fetch-B1Yg4Til.d.ts +0 -101
  155. package/dist/telemetry/file.d.ts +0 -19
  156. package/dist/telemetry/file.js +0 -45
  157. package/dist/telemetry/file.js.map +0 -1
  158. package/dist/telemetry/index.d.ts +0 -38
  159. package/dist/telemetry/index.js +0 -130
  160. package/dist/telemetry/index.js.map +0 -1
  161. package/dist/testing-C21CHsq2.d.ts +0 -20
  162. package/dist/testing.d.ts +0 -1
  163. package/dist/testing.js +0 -8
  164. package/dist/testing.js.map +0 -1
  165. package/dist/trajectory-2TkpSEVh.d.ts +0 -33
  166. package/dist/workflow/index.d.ts +0 -496
  167. package/dist/workflow/index.js +0 -2178
  168. package/dist/workflow/index.js.map +0 -1
  169. /package/dist/{chunk-LOJ2QVCE.js.map → chunk-2IY4ILP4.js.map} +0 -0
  170. /package/dist/{chunk-LIEJUH2I.js.map → chunk-6PL5MGDL.js.map} +0 -0
  171. /package/dist/{chunk-OVPVM4JC.js.map → chunk-GTERJI6Q.js.map} +0 -0
  172. /package/dist/{chunk-GDZAWO2I.js.map → chunk-QFGTU7MT.js.map} +0 -0
  173. /package/dist/{chunk-R6D7NEYJ.js.map → chunk-RNB2NICW.js.map} +0 -0
  174. /package/dist/{chunk-V7HNA47Z.js.map → chunk-RSVSSZKF.js.map} +0 -0
@@ -1,6 +1,76 @@
1
1
  import {
2
2
  TraceEmitter
3
3
  } from "./chunk-TVVP3ZZQ.js";
4
+ import {
5
+ validateRunRecord
6
+ } from "./chunk-VK6HBGAE.js";
7
+
8
+ // src/action-policy.ts
9
+ function evaluateActionPolicy(action, policy = {}, options = {}) {
10
+ const reasons = [];
11
+ let blocked = false;
12
+ let requiresApproval = Boolean(action.requiresApproval);
13
+ if (policy.allowedTypes?.length && !policy.allowedTypes.includes(action.type)) {
14
+ blocked = true;
15
+ reasons.push(`action type "${action.type}" is not allowed`);
16
+ }
17
+ if (policy.blockedTypes?.includes(action.type)) {
18
+ blocked = true;
19
+ reasons.push(`action type "${action.type}" is blocked`);
20
+ }
21
+ if (policy.alwaysRequireApprovalTypes?.includes(action.type)) {
22
+ requiresApproval = true;
23
+ reasons.push(`action type "${action.type}" requires approval`);
24
+ }
25
+ if (policy.requireApprovalForExternalSideEffects && action.externalSideEffect) {
26
+ requiresApproval = true;
27
+ reasons.push("external side effect requires approval");
28
+ }
29
+ if (policy.requireApprovalAboveCostUsd !== void 0 && (action.costUsd ?? 0) > policy.requireApprovalAboveCostUsd) {
30
+ requiresApproval = true;
31
+ reasons.push(
32
+ `cost ${action.costUsd} exceeds approval threshold ${policy.requireApprovalAboveCostUsd}`
33
+ );
34
+ }
35
+ if (policy.maxActionCostUsd !== void 0 && (action.costUsd ?? 0) > policy.maxActionCostUsd) {
36
+ blocked = true;
37
+ reasons.push(`cost ${action.costUsd} exceeds max action cost ${policy.maxActionCostUsd}`);
38
+ }
39
+ if (policy.remainingBudgetUsd !== void 0 && (action.costUsd ?? 0) > policy.remainingBudgetUsd) {
40
+ blocked = true;
41
+ reasons.push(`cost ${action.costUsd} exceeds remaining budget ${policy.remainingBudgetUsd}`);
42
+ }
43
+ if (policy.expectedOutcomeRequired && !action.metadata?.expectedOutcome) {
44
+ blocked = true;
45
+ reasons.push("expected outcome is required");
46
+ }
47
+ if (policy.killCriteriaRequired && !action.metadata?.killCriteria) {
48
+ blocked = true;
49
+ reasons.push("kill criteria are required");
50
+ }
51
+ if (policy.autoApproveTypes?.includes(action.type) && requiresApproval) {
52
+ reasons.push(
53
+ `action type "${action.type}" is auto-approved only when no approval policy applies`
54
+ );
55
+ }
56
+ if (!reasons.length) reasons.push(requiresApproval ? "approval required" : "action allowed");
57
+ const label = blocked || requiresApproval ? {
58
+ source: "policy",
59
+ kind: blocked ? "policy_block" : "comment",
60
+ value: { actionType: action.type, blocked, requiresApproval },
61
+ reason: reasons.join("; "),
62
+ severity: blocked ? "critical" : "warning",
63
+ createdAt: options.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
64
+ metadata: { action, policy }
65
+ } : void 0;
66
+ return {
67
+ allowed: !blocked,
68
+ blocked,
69
+ requiresApproval: !blocked && requiresApproval,
70
+ reasons,
71
+ label
72
+ };
73
+ }
4
74
 
5
75
  // src/detectors/index.ts
6
76
  function repeatedActionDetector(opts = {}) {
@@ -909,7 +979,531 @@ async function finish(emitter, result) {
909
979
  return result;
910
980
  }
911
981
 
982
+ // src/run-evidence.ts
983
+ function controlRunToRunRecord(run, options) {
984
+ const score = clampScore(
985
+ options.score ?? run.score ?? scoreFromEvals(run.finalEvals) ?? (run.pass ? 1 : 0)
986
+ );
987
+ const outcome = options.splitTag === "holdout" ? { holdoutScore: score, raw: normalizeRawMetrics(options.raw, run, score) } : { searchScore: score, raw: normalizeRawMetrics(options.raw, run, score) };
988
+ return validateRunRecord({
989
+ runId: options.runId ?? run.runId ?? `control:${options.experimentId}:${options.candidateId}:${options.seed}:${options.splitTag}`,
990
+ experimentId: options.experimentId,
991
+ candidateId: options.candidateId,
992
+ seed: options.seed,
993
+ model: options.model,
994
+ promptHash: options.promptHash,
995
+ configHash: options.configHash,
996
+ commitSha: options.commitSha,
997
+ wallMs: run.wallMs,
998
+ ...options.queueMs !== void 0 ? { queueMs: options.queueMs } : {},
999
+ costUsd: run.spentCostUsd,
1000
+ tokenUsage: options.tokenUsage,
1001
+ ...options.judgeMetadata ? { judgeMetadata: options.judgeMetadata } : {},
1002
+ outcome,
1003
+ failureMode: options.failureMode ?? failureModeFromRun(run),
1004
+ splitTag: options.splitTag
1005
+ });
1006
+ }
1007
+ function scoreFromEvals(evals) {
1008
+ const scores = evals.map((e) => e.score).filter((score) => typeof score === "number" && Number.isFinite(score));
1009
+ if (scores.length === 0) return void 0;
1010
+ return clampScore(scores.reduce((sum, score) => sum + score, 0) / scores.length);
1011
+ }
1012
+ function normalizeRawMetrics(raw, run, score) {
1013
+ return {
1014
+ ...finiteOnly(raw ?? {}),
1015
+ score,
1016
+ pass: run.pass ? 1 : 0,
1017
+ completed: run.completed ? 1 : 0,
1018
+ steps: run.steps.length,
1019
+ runtimeErrors: run.runtimeErrors.length
1020
+ };
1021
+ }
1022
+ function finiteOnly(values) {
1023
+ const out = {};
1024
+ for (const [key, value] of Object.entries(values)) {
1025
+ if (Number.isFinite(value)) out[key] = value;
1026
+ }
1027
+ return out;
1028
+ }
1029
+ function failureModeFromRun(run) {
1030
+ if (run.pass) return void 0;
1031
+ return run.failureClass ?? "unknown";
1032
+ }
1033
+ function clampScore(value) {
1034
+ if (!Number.isFinite(value)) return 0;
1035
+ return Math.max(0, Math.min(1, value));
1036
+ }
1037
+
1038
+ // src/propose-review.ts
1039
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
1040
+ import { dirname } from "path";
1041
+ function inMemoryReviewStore(initial = []) {
1042
+ const entries = [...initial];
1043
+ return {
1044
+ async load() {
1045
+ return [...entries];
1046
+ },
1047
+ async append(entry) {
1048
+ entries.push(entry);
1049
+ }
1050
+ };
1051
+ }
1052
+ function jsonlReviewStore(path) {
1053
+ return {
1054
+ async load() {
1055
+ if (!existsSync(path)) return [];
1056
+ const raw = readFileSync(path, "utf8");
1057
+ const out = [];
1058
+ for (const line of raw.split("\n")) {
1059
+ const trimmed = line.trim();
1060
+ if (!trimmed) continue;
1061
+ try {
1062
+ out.push(JSON.parse(trimmed));
1063
+ } catch {
1064
+ }
1065
+ }
1066
+ return out;
1067
+ },
1068
+ async append(entry) {
1069
+ mkdirSync(dirname(path), { recursive: true });
1070
+ appendFileSync(path, `${JSON.stringify(entry)}
1071
+ `);
1072
+ }
1073
+ };
1074
+ }
1075
+ var DEFAULT_FALLBACK_INSTRUCTION = "Inspect the verification failures above. Fix the critical issues first, then the major ones. Do not restate the failures \u2014 act on them.";
1076
+ async function runProposeReview(config) {
1077
+ const maxShots = config.maxShots ?? 10;
1078
+ const maxWallMs = config.maxWallMs ?? 10 * 60 * 1e3;
1079
+ const confidenceFloor = config.confidenceFloor ?? 0.3;
1080
+ const confidenceFloorWindow = config.confidenceFloorWindow ?? 2;
1081
+ const memory = config.memory ?? inMemoryReviewStore();
1082
+ const fallbackInstruction = config.fallbackInstruction ?? DEFAULT_FALLBACK_INSTRUCTION;
1083
+ const emitter = config.store ? new TraceEmitter(config.store) : null;
1084
+ if (emitter) {
1085
+ await emitter.startRun({
1086
+ scenarioId: config.scenarioId ?? "propose-review",
1087
+ projectId: config.projectId,
1088
+ variantId: config.variantId,
1089
+ layer: "meta",
1090
+ tags: {
1091
+ goal: config.goal.slice(0, 120),
1092
+ maxShots: String(maxShots)
1093
+ }
1094
+ });
1095
+ }
1096
+ const abort = new AbortController();
1097
+ const wallStart = Date.now();
1098
+ const wallTimer = setTimeout(
1099
+ () => abort.abort(new Error("propose-review wall timeout")),
1100
+ maxWallMs
1101
+ );
1102
+ const shots = [];
1103
+ let state = config.initialState;
1104
+ let priorReview = null;
1105
+ let lastVerification = { pass: false };
1106
+ let failureClass;
1107
+ let completed = false;
1108
+ let lowConfidenceStreak = 0;
1109
+ try {
1110
+ for (let shot = 1; shot <= maxShots; shot++) {
1111
+ if (abort.signal.aborted) {
1112
+ failureClass = "timeout";
1113
+ break;
1114
+ }
1115
+ const shotStart = Date.now();
1116
+ const shotHandle = emitter ? await emitter.span({ kind: "tool", name: `shot-${shot}` }) : null;
1117
+ let proposeOut;
1118
+ try {
1119
+ proposeOut = await config.propose({
1120
+ shot,
1121
+ goal: config.goal,
1122
+ state,
1123
+ priorReview,
1124
+ abortSignal: abort.signal,
1125
+ emitter: emitter ?? void 0
1126
+ });
1127
+ } catch (err) {
1128
+ await shotHandle?.fail(err instanceof Error ? err : String(err));
1129
+ failureClass = "unknown";
1130
+ throw err;
1131
+ }
1132
+ state = proposeOut.state;
1133
+ const traceSummary = proposeOut.traceSummary;
1134
+ let verification;
1135
+ try {
1136
+ verification = await config.verify(state);
1137
+ } catch (err) {
1138
+ await shotHandle?.fail(err instanceof Error ? err : String(err));
1139
+ failureClass = "unknown";
1140
+ throw err;
1141
+ }
1142
+ lastVerification = verification;
1143
+ const memorySnapshot = await memory.load();
1144
+ const verificationDigest = {
1145
+ pass: verification.pass,
1146
+ score: verification.score,
1147
+ failingLayers: verification.failingLayers ?? []
1148
+ };
1149
+ let review;
1150
+ let reviewAvailable = true;
1151
+ let reviewError;
1152
+ if (verification.pass) {
1153
+ review = {
1154
+ observations: "verification passed \u2014 skipping reviewer LLM call",
1155
+ diagnosis: "no failures to diagnose",
1156
+ nextShotInstruction: "(done)",
1157
+ shouldContinue: false,
1158
+ confidence: 1
1159
+ };
1160
+ } else {
1161
+ try {
1162
+ review = await config.review({
1163
+ shot,
1164
+ goal: config.goal,
1165
+ state,
1166
+ verification,
1167
+ traceSummary,
1168
+ memory: memorySnapshot
1169
+ });
1170
+ review = coerceReview(review);
1171
+ } catch (err) {
1172
+ reviewAvailable = false;
1173
+ reviewError = err instanceof Error ? err.message : String(err);
1174
+ const lastInstruction = memorySnapshot.length > 0 ? memorySnapshot[memorySnapshot.length - 1].nextShotInstruction : fallbackInstruction;
1175
+ review = {
1176
+ observations: "(reviewer unavailable \u2014 using last-known instruction)",
1177
+ diagnosis: reviewError,
1178
+ nextShotInstruction: lastInstruction,
1179
+ shouldContinue: true,
1180
+ confidence: 0.3
1181
+ };
1182
+ }
1183
+ }
1184
+ const entry = {
1185
+ shot,
1186
+ timestamp: Date.now(),
1187
+ ...review,
1188
+ verification: verificationDigest
1189
+ };
1190
+ await memory.append(entry);
1191
+ const shotRecord = {
1192
+ shot,
1193
+ state,
1194
+ verification,
1195
+ traceSummary,
1196
+ review,
1197
+ reviewAvailable,
1198
+ reviewError,
1199
+ durationMs: Date.now() - shotStart
1200
+ };
1201
+ shots.push(shotRecord);
1202
+ await shotHandle?.end({
1203
+ attributes: {
1204
+ verificationPass: verification.pass,
1205
+ verificationScore: verification.score ?? null,
1206
+ reviewShouldContinue: review.shouldContinue,
1207
+ reviewConfidence: review.confidence,
1208
+ reviewAvailable
1209
+ }
1210
+ });
1211
+ if (verification.pass) {
1212
+ completed = true;
1213
+ break;
1214
+ }
1215
+ if (!review.shouldContinue) {
1216
+ break;
1217
+ }
1218
+ if (confidenceFloorWindow > 0 && review.confidence <= confidenceFloor) {
1219
+ lowConfidenceStreak += 1;
1220
+ if (lowConfidenceStreak >= confidenceFloorWindow) break;
1221
+ } else {
1222
+ lowConfidenceStreak = 0;
1223
+ }
1224
+ priorReview = review;
1225
+ }
1226
+ if (!completed && !failureClass) {
1227
+ failureClass = shots.length >= maxShots ? "budget_exceeded" : "unknown";
1228
+ }
1229
+ } finally {
1230
+ clearTimeout(wallTimer);
1231
+ }
1232
+ const score = lastVerification.pass ? 1 : typeof lastVerification.score === "number" ? lastVerification.score : 0;
1233
+ if (emitter) {
1234
+ await emitter.endRun({
1235
+ pass: completed,
1236
+ score,
1237
+ failureClass,
1238
+ notes: `${shots.length} shot(s); final pass=${lastVerification.pass}`
1239
+ });
1240
+ }
1241
+ return {
1242
+ runId: emitter?.runId ?? null,
1243
+ completed,
1244
+ shots,
1245
+ finalState: state,
1246
+ finalVerification: lastVerification,
1247
+ failureClass,
1248
+ wallMs: Date.now() - wallStart,
1249
+ score
1250
+ };
1251
+ }
1252
+ var REVIEWER_SYSTEM_PROMPT = `You are a senior reviewer directing a multi-shot build loop.
1253
+ You do NOT grade \u2014 the verifier already did. Your job is to direct the worker's next shot.
1254
+ You are blind to the worker's inner monologue. You see what it DID, not what it thought.
1255
+ Return STRICT JSON matching the schema. No prose outside the JSON.`;
1256
+ function createLlmReviewer(cfg) {
1257
+ const renderState = cfg.renderState ?? ((s) => safeJson(s));
1258
+ const renderTraceSummary = cfg.renderTraceSummary ?? ((s) => s === void 0 ? "(none)" : safeJson(s));
1259
+ const system = cfg.systemPromptAddendum ? `${REVIEWER_SYSTEM_PROMPT}
1260
+
1261
+ ${cfg.systemPromptAddendum}` : REVIEWER_SYSTEM_PROMPT;
1262
+ return async (input) => {
1263
+ const memoryBlock = input.memory.length === 0 ? "(no prior shots \u2014 this is shot 1)" : input.memory.map(
1264
+ (m) => [
1265
+ `shot ${m.shot} \u2014 verification.pass=${m.verification.pass}` + (typeof m.verification.score === "number" ? ` score=${m.verification.score.toFixed(2)}` : "") + ` confidence=${m.confidence.toFixed(2)} failing=[${(m.verification.failingLayers ?? []).join(",")}]`,
1266
+ ` observations: ${m.observations.slice(0, 400)}`,
1267
+ ` diagnosis: ${m.diagnosis.slice(0, 400)}`,
1268
+ ` instruction given: ${m.nextShotInstruction.slice(0, 400)}`
1269
+ ].join("\n")
1270
+ ).join("\n\n");
1271
+ const user = [
1272
+ `=== GOAL ===`,
1273
+ input.goal,
1274
+ ``,
1275
+ `=== SHOT NUMBER ===`,
1276
+ String(input.shot),
1277
+ ``,
1278
+ `=== CURRENT STATE ===`,
1279
+ renderState(input.state),
1280
+ ``,
1281
+ `=== TRACE SUMMARY ===`,
1282
+ renderTraceSummary(input.traceSummary),
1283
+ ``,
1284
+ `=== VERIFICATION ===`,
1285
+ summarizeVerification(input.verification),
1286
+ ``,
1287
+ `=== REVIEWER MEMORY (prior shots) ===`,
1288
+ memoryBlock,
1289
+ ``,
1290
+ `=== YOUR TASK ===`,
1291
+ `Return STRICT JSON:`,
1292
+ `{`,
1293
+ ` "observations": string (20..2000 chars, first-person worker behavior \u2014 quote counts, errors, loops)`,
1294
+ ` "diagnosis": string (20..1500 chars, root cause, NOT a restatement of verification)`,
1295
+ ` "nextShotInstruction": string (40..3000 chars, concrete directive to the worker)`,
1296
+ ` "shouldContinue": boolean (false if verification.pass, or if thrashing, or unachievable)`,
1297
+ ` "confidence": number in [0,1]`,
1298
+ `}`
1299
+ ].join("\n");
1300
+ const raw = await cfg.callJson({ system, user });
1301
+ return coerceReview(raw);
1302
+ };
1303
+ }
1304
+ function coerceReview(raw) {
1305
+ if (!raw || typeof raw !== "object") {
1306
+ throw new Error("reviewer returned non-object");
1307
+ }
1308
+ const observations = typeof raw.observations === "string" ? raw.observations : "";
1309
+ const diagnosis = typeof raw.diagnosis === "string" ? raw.diagnosis : "";
1310
+ const nextShotInstruction = typeof raw.nextShotInstruction === "string" ? raw.nextShotInstruction : "";
1311
+ if (!observations || !diagnosis || !nextShotInstruction) {
1312
+ throw new Error("reviewer missing required string fields");
1313
+ }
1314
+ if (typeof raw.shouldContinue !== "boolean") {
1315
+ throw new Error("reviewer missing shouldContinue boolean");
1316
+ }
1317
+ const confidenceRaw = Number(raw.confidence);
1318
+ if (!Number.isFinite(confidenceRaw)) {
1319
+ throw new Error("reviewer confidence not finite");
1320
+ }
1321
+ return {
1322
+ observations,
1323
+ diagnosis,
1324
+ nextShotInstruction,
1325
+ shouldContinue: raw.shouldContinue,
1326
+ confidence: Math.max(0, Math.min(1, confidenceRaw))
1327
+ };
1328
+ }
1329
+ function summarizeVerification(v) {
1330
+ const header = `pass=${v.pass}` + (typeof v.score === "number" ? ` score=${v.score.toFixed(3)}` : "") + (v.failingLayers && v.failingLayers.length > 0 ? ` failing=[${v.failingLayers.join(", ")}]` : "");
1331
+ const details = v.details === void 0 ? "" : `
1332
+ ${safeJson(v.details).slice(0, 1500)}`;
1333
+ return header + details;
1334
+ }
1335
+ function safeJson(x) {
1336
+ try {
1337
+ return JSON.stringify(x, null, 2);
1338
+ } catch {
1339
+ return String(x);
1340
+ }
1341
+ }
1342
+
1343
+ // src/propose-review-control.ts
1344
+ var DEFAULT_FALLBACK_INSTRUCTION2 = "Inspect the verification failures above. Fix the critical issues first, then the major ones. Do not restate the failures \u2014 act on them.";
1345
+ async function runProposeReviewAsControlLoop(config) {
1346
+ const maxShots = config.maxShots ?? 10;
1347
+ const confidenceFloor = config.confidenceFloor ?? 0.3;
1348
+ const confidenceFloorWindow = config.confidenceFloorWindow ?? 2;
1349
+ const memory = config.memory ?? inMemoryReviewStore();
1350
+ const fallbackInstruction = config.fallbackInstruction ?? DEFAULT_FALLBACK_INSTRUCTION2;
1351
+ const failureClassFromVerification = config.failureClassFromVerification ?? controlFailureClassFromVerification;
1352
+ let lowConfidenceStreak = 0;
1353
+ let current = {
1354
+ shot: 0,
1355
+ state: config.initialState,
1356
+ priorReview: null,
1357
+ verification: { pass: false },
1358
+ memory: await memory.load(),
1359
+ completed: false,
1360
+ reviewAvailable: false
1361
+ };
1362
+ return runAgentControlLoop({
1363
+ intent: config.goal,
1364
+ budget: { maxSteps: maxShots, maxWallMs: config.maxWallMs },
1365
+ store: config.store,
1366
+ scenarioId: config.scenarioId ?? "propose-review-control",
1367
+ projectId: config.projectId,
1368
+ variantId: config.variantId,
1369
+ actionFailure: config.actionFailure ?? "stop",
1370
+ observe: () => current,
1371
+ validate: ({ state }) => [
1372
+ objectiveEval({
1373
+ id: "verification",
1374
+ passed: state.verification.pass,
1375
+ score: state.verification.score,
1376
+ severity: "critical",
1377
+ detail: state.verification.pass ? "verification passed" : `verification failed${state.verification.failingLayers?.length ? `: ${state.verification.failingLayers.join(", ")}` : ""}`
1378
+ })
1379
+ ],
1380
+ shouldStop: ({ state }) => {
1381
+ if (state.verification.pass) {
1382
+ return {
1383
+ stop: true,
1384
+ pass: true,
1385
+ reason: "verification passed",
1386
+ score: state.verification.score
1387
+ };
1388
+ }
1389
+ if (state.completed) {
1390
+ return {
1391
+ stop: true,
1392
+ pass: false,
1393
+ reason: "reviewer stopped continuation",
1394
+ score: state.verification.score,
1395
+ failureClass: failureClassFromVerification(state.verification)
1396
+ };
1397
+ }
1398
+ return {
1399
+ stop: false,
1400
+ pass: false,
1401
+ reason: "verification still failing",
1402
+ score: state.verification.score
1403
+ };
1404
+ },
1405
+ decide: ({ state }) => ({
1406
+ type: "continue",
1407
+ action: { type: "propose-review-shot", shot: state.shot + 1 },
1408
+ reason: state.priorReview?.nextShotInstruction ?? fallbackInstruction
1409
+ }),
1410
+ act: async (action, ctx) => {
1411
+ const shot = action.shot;
1412
+ const proposeOut = await config.propose({
1413
+ shot,
1414
+ goal: config.goal,
1415
+ state: current.state,
1416
+ priorReview: current.priorReview,
1417
+ abortSignal: ctx.abortSignal,
1418
+ emitter: ctx.emitter
1419
+ });
1420
+ const nextState = proposeOut.state;
1421
+ const verification = await config.verify(nextState);
1422
+ let review = null;
1423
+ let reviewAvailable = false;
1424
+ let reviewError;
1425
+ let shouldContinue = !verification.pass;
1426
+ if (!verification.pass) {
1427
+ try {
1428
+ review = await config.review({
1429
+ shot,
1430
+ goal: config.goal,
1431
+ state: nextState,
1432
+ verification,
1433
+ traceSummary: proposeOut.traceSummary,
1434
+ memory: await memory.load()
1435
+ });
1436
+ reviewAvailable = true;
1437
+ shouldContinue = review.shouldContinue;
1438
+ lowConfidenceStreak = review.confidence <= confidenceFloor ? lowConfidenceStreak + 1 : 0;
1439
+ if (confidenceFloorWindow > 0 && lowConfidenceStreak >= confidenceFloorWindow)
1440
+ shouldContinue = false;
1441
+ } catch (err) {
1442
+ reviewError = err instanceof Error ? err.message : String(err);
1443
+ review = current.priorReview ?? {
1444
+ observations: "Reviewer unavailable.",
1445
+ diagnosis: reviewError,
1446
+ nextShotInstruction: fallbackInstruction,
1447
+ shouldContinue: true,
1448
+ confidence: 0
1449
+ };
1450
+ shouldContinue = true;
1451
+ }
1452
+ } else {
1453
+ review = {
1454
+ observations: "Verification passed.",
1455
+ diagnosis: "No further revision needed.",
1456
+ nextShotInstruction: "",
1457
+ shouldContinue: false,
1458
+ confidence: 1
1459
+ };
1460
+ }
1461
+ const entry = {
1462
+ ...review ?? {
1463
+ observations: "No review.",
1464
+ diagnosis: "",
1465
+ nextShotInstruction: fallbackInstruction,
1466
+ shouldContinue,
1467
+ confidence: 0
1468
+ },
1469
+ shot,
1470
+ timestamp: Date.now(),
1471
+ verification: {
1472
+ pass: verification.pass,
1473
+ score: verification.score,
1474
+ failingLayers: verification.failingLayers
1475
+ }
1476
+ };
1477
+ await memory.append(entry);
1478
+ current = {
1479
+ shot,
1480
+ state: nextState,
1481
+ priorReview: review,
1482
+ verification,
1483
+ traceSummary: proposeOut.traceSummary,
1484
+ memory: await memory.load(),
1485
+ completed: verification.pass || !shouldContinue,
1486
+ reviewAvailable,
1487
+ reviewError
1488
+ };
1489
+ return {
1490
+ state: nextState,
1491
+ verification,
1492
+ traceSummary: proposeOut.traceSummary,
1493
+ review,
1494
+ reviewAvailable,
1495
+ reviewError
1496
+ };
1497
+ }
1498
+ });
1499
+ }
1500
+ function controlFailureClassFromVerification(verification) {
1501
+ if (verification.pass) return void 0;
1502
+ return verification.failingLayers?.length ? "instruction_following" : "unknown";
1503
+ }
1504
+
912
1505
  export {
1506
+ evaluateActionPolicy,
913
1507
  repeatedActionDetector,
914
1508
  noProgressDetector,
915
1509
  errorStreakDetector,
@@ -919,6 +1513,14 @@ export {
919
1513
  stopOnRepeatedAction,
920
1514
  objectiveEval,
921
1515
  subjectiveEval,
922
- allCriticalPassed
1516
+ allCriticalPassed,
1517
+ controlRunToRunRecord,
1518
+ scoreFromEvals,
1519
+ inMemoryReviewStore,
1520
+ jsonlReviewStore,
1521
+ runProposeReview,
1522
+ createLlmReviewer,
1523
+ runProposeReviewAsControlLoop,
1524
+ controlFailureClassFromVerification
923
1525
  };
924
- //# sourceMappingURL=chunk-YEHAEDUD.js.map
1526
+ //# sourceMappingURL=chunk-IMWDSFUM.js.map