@tangle-network/agent-runtime 0.95.0 → 0.97.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 (86) hide show
  1. package/README.md +64 -15
  2. package/dist/activation-B0ZD7nfX.d.ts +63 -0
  3. package/dist/agent.d.ts +5 -169
  4. package/dist/agent.js +8 -229
  5. package/dist/agent.js.map +1 -1
  6. package/dist/analyst-loop.d.ts +6 -9
  7. package/dist/analyst-loop.js +1 -2
  8. package/dist/candidate-execution/index.js +6 -7
  9. package/dist/chunk-3XKSBI2U.js +474 -0
  10. package/dist/chunk-3XKSBI2U.js.map +1 -0
  11. package/dist/{chunk-6YBA64Z2.js → chunk-6XKPVJAZ.js} +5 -18
  12. package/dist/chunk-6XKPVJAZ.js.map +1 -0
  13. package/dist/{chunk-MKGRLDWB.js → chunk-BLQIYRVR.js} +17 -2
  14. package/dist/chunk-BLQIYRVR.js.map +1 -0
  15. package/dist/{chunk-QDSOD7RC.js → chunk-FD2MBMOH.js} +13 -101
  16. package/dist/chunk-FD2MBMOH.js.map +1 -0
  17. package/dist/{chunk-YLUOTX6U.js → chunk-FXF2OL34.js} +7 -7
  18. package/dist/{chunk-EP6RVHMX.js → chunk-HZDEXTSL.js} +848 -2
  19. package/dist/chunk-HZDEXTSL.js.map +1 -0
  20. package/dist/chunk-PSOCBNM3.js +2069 -0
  21. package/dist/chunk-PSOCBNM3.js.map +1 -0
  22. package/dist/{chunk-BPGXIKK7.js → chunk-SGQ4YIQW.js} +4 -4
  23. package/dist/{chunk-IADLKE7I.js → chunk-UQ6PNNXM.js} +5 -7
  24. package/dist/{chunk-IADLKE7I.js.map → chunk-UQ6PNNXM.js.map} +1 -1
  25. package/dist/{chunk-Z5I642SY.js → chunk-WYC2XJF2.js} +2 -2
  26. package/dist/{chunk-ZEYAT33L.js → chunk-Y3SRWZMP.js} +2 -2
  27. package/dist/{chunk-WTZ37EQY.js → chunk-YOLKCWRV.js} +197 -90
  28. package/dist/chunk-YOLKCWRV.js.map +1 -0
  29. package/dist/conversation.js +0 -1
  30. package/dist/environment-provider.js +0 -1
  31. package/dist/{agentic-generator-hCaQRAes.d.ts → improve-g75IE2Cx.d.ts} +152 -3
  32. package/dist/{improvement-adapter-BieWeK5J.d.ts → improvement-adapter-HAZz-7vK.d.ts} +8 -31
  33. package/dist/index.d.ts +41 -11
  34. package/dist/index.js +180 -51
  35. package/dist/index.js.map +1 -1
  36. package/dist/intelligence.d.ts +16 -9
  37. package/dist/intelligence.js +13 -8
  38. package/dist/intelligence.js.map +1 -1
  39. package/dist/knowledge.d.ts +30 -13
  40. package/dist/knowledge.js +11 -10
  41. package/dist/{loop-runner-bin-BIQldFS8.d.ts → loop-runner-bin-Cn1N2rRo.d.ts} +1 -1
  42. package/dist/loop-runner-bin.d.ts +2 -2
  43. package/dist/loop-runner-bin.js +6 -8
  44. package/dist/loops.d.ts +1 -1
  45. package/dist/loops.js +4 -6
  46. package/dist/mcp/bin.js +3 -5
  47. package/dist/mcp/bin.js.map +1 -1
  48. package/dist/mcp/index.js +10 -12
  49. package/dist/mcp/index.js.map +1 -1
  50. package/dist/platform.js +0 -2
  51. package/dist/platform.js.map +1 -1
  52. package/dist/primeintellect/index.js +0 -1
  53. package/dist/primeintellect/index.js.map +1 -1
  54. package/dist/profiles.js +0 -1
  55. package/dist/profiles.js.map +1 -1
  56. package/dist/{types-BC3bZpH0.d.ts → types-CmYCMbFT.d.ts} +12 -54
  57. package/package.json +8 -13
  58. package/skills/build-with-agent-runtime/SKILL.md +122 -213
  59. package/dist/chunk-6O73TRHW.js +0 -142
  60. package/dist/chunk-6O73TRHW.js.map +0 -1
  61. package/dist/chunk-6YBA64Z2.js.map +0 -1
  62. package/dist/chunk-AP7CPGMZ.js +0 -334
  63. package/dist/chunk-AP7CPGMZ.js.map +0 -1
  64. package/dist/chunk-DGUM43GV.js +0 -11
  65. package/dist/chunk-DGUM43GV.js.map +0 -1
  66. package/dist/chunk-DHCHL6OG.js +0 -625
  67. package/dist/chunk-DHCHL6OG.js.map +0 -1
  68. package/dist/chunk-EP6RVHMX.js.map +0 -1
  69. package/dist/chunk-G55QE4IQ.js +0 -1137
  70. package/dist/chunk-G55QE4IQ.js.map +0 -1
  71. package/dist/chunk-ISTDY47H.js +0 -849
  72. package/dist/chunk-ISTDY47H.js.map +0 -1
  73. package/dist/chunk-MKGRLDWB.js.map +0 -1
  74. package/dist/chunk-QDSOD7RC.js.map +0 -1
  75. package/dist/chunk-WTZ37EQY.js.map +0 -1
  76. package/dist/generator-YkAQrOoD.d.ts +0 -382
  77. package/dist/improve-B-UYaEH5.d.ts +0 -172
  78. package/dist/lifecycle.d.ts +0 -870
  79. package/dist/lifecycle.js +0 -981
  80. package/dist/lifecycle.js.map +0 -1
  81. package/dist/mcp-serve-verifier-Bs_n0xPc.d.ts +0 -34
  82. package/skills/agent-runtime-adoption/SKILL.md +0 -246
  83. /package/dist/{chunk-YLUOTX6U.js.map → chunk-FXF2OL34.js.map} +0 -0
  84. /package/dist/{chunk-BPGXIKK7.js.map → chunk-SGQ4YIQW.js.map} +0 -0
  85. /package/dist/{chunk-Z5I642SY.js.map → chunk-WYC2XJF2.js.map} +0 -0
  86. /package/dist/{chunk-ZEYAT33L.js.map → chunk-Y3SRWZMP.js.map} +0 -0
@@ -0,0 +1,2069 @@
1
+ import {
2
+ agentCandidateProfileAsAgentProfile,
3
+ assertCandidateProfileBinding,
4
+ candidateMaterializerHarness,
5
+ canonicalCandidateBytes,
6
+ canonicalCandidateDigest,
7
+ canonicalCandidateDocument,
8
+ createAgentCandidateProfileActivation,
9
+ executePreparedAgentCandidate,
10
+ immutableCandidateValue,
11
+ omitTopLevelDigest,
12
+ parseAgentCandidateProfileActivation,
13
+ prepareAgentCandidateExecution,
14
+ verifiedResourceTextByDigest,
15
+ verifyAgentCandidateBundle,
16
+ verifyCanonicalCandidateDocument
17
+ } from "./chunk-YOLKCWRV.js";
18
+ import {
19
+ assertModelAllowed,
20
+ harnessInvocation,
21
+ runLocalHarness
22
+ } from "./chunk-HZDEXTSL.js";
23
+ import {
24
+ runAnalystLoop
25
+ } from "./chunk-FD2MBMOH.js";
26
+ import {
27
+ ConfigError
28
+ } from "./chunk-YEJR7IXO.js";
29
+
30
+ // src/improvement/agentic-generator.ts
31
+ import { spawnSync } from "child_process";
32
+ import { createHash } from "crypto";
33
+ import { existsSync, readFileSync, rmSync } from "fs";
34
+ import { join, resolve, sep } from "path";
35
+ import {
36
+ applyWorkspacePlan,
37
+ materializeProfile
38
+ } from "@tangle-network/agent-profile-materialize";
39
+ var RAW_TRACE_ANALYST_ID = "raw-trace-distiller";
40
+ var RAW_TRACE_AREA = "raw-trace-context";
41
+ var RAW_TRACE_DIAGNOSIS_PATH = ".improve/raw-trace-diagnosis.md";
42
+ var AGENTIC_PROFILE_RESOURCE_ROOT = ".agent-runtime-profile-resources";
43
+ function agenticGenerator(opts = {}) {
44
+ const harness = opts.harness ?? "claude";
45
+ if (opts.codexReproducible && harness !== "codex") {
46
+ throw new Error("agenticGenerator: codexReproducible requires harness 'codex'");
47
+ }
48
+ if (opts.codexReproducible && !opts.profile) {
49
+ throw new Error("agenticGenerator: codexReproducible requires an explicit author profile");
50
+ }
51
+ if (opts.codexReadDeniedPaths && !opts.codexReproducible) {
52
+ throw new Error("agenticGenerator: codexReadDeniedPaths requires codexReproducible");
53
+ }
54
+ if (opts.maximumCharge && !opts.codexReproducible) {
55
+ throw new Error("agenticGenerator: maximumCharge requires codexReproducible");
56
+ }
57
+ const profileResourcePlan = opts.codexReproducible ? authorProfileResourcePlan(opts.profile) : null;
58
+ const buildPrompt = opts.buildPrompt ?? defaultBuildPrompt;
59
+ const run = opts.runHarness ?? runLocalHarness;
60
+ const dirty = opts.isDirty ?? worktreeDirty;
61
+ const verify = opts.verify;
62
+ return {
63
+ kind: `agentic:${harness}`,
64
+ // The seed repo + (in rawTraceContext mode) the raw-trace filesystem context
65
+ // are the change signal — an agentic coder proposes from them even when the
66
+ // distiller yielded zero findings. Without this, the improvementDriver's
67
+ // empty-findings guard short-circuits and generates ZERO candidates on the
68
+ // first (and, for a single-generation run, only) proposal round.
69
+ proposesWithoutFindings: true,
70
+ async generate({
71
+ worktreePath,
72
+ report,
73
+ findings,
74
+ maxShots,
75
+ signal,
76
+ generation,
77
+ candidateIndex,
78
+ costLedger,
79
+ costPhase
80
+ }) {
81
+ let reproducibleCostLedger;
82
+ if (opts.codexReproducible) {
83
+ if (!costLedger) {
84
+ throw new Error(
85
+ "agenticGenerator: reproducible Codex requires the run-wide CostLedger supplied by agent-eval"
86
+ );
87
+ }
88
+ reproducibleCostLedger = costLedger;
89
+ }
90
+ const basePrompt = appendProfileResourcePaths(
91
+ buildPrompt({ report, findings }),
92
+ profileResourcePlan
93
+ );
94
+ const needsRawTraceEvidence = requiresRawTraceEvidence(findings);
95
+ const shots = Math.max(1, maxShots);
96
+ let attemptNote = "";
97
+ for (let shot = 0; shot < shots; shot++) {
98
+ if (signal.aborted) break;
99
+ const taskPrompt = attemptNote ? `${basePrompt}
100
+
101
+ ${attemptNote}` : basePrompt;
102
+ const invocation = opts.profile ? harnessInvocation(harness, opts.profile, taskPrompt, {
103
+ dangerouslySkipPermissions: harness === "claude",
104
+ ...opts.codexReproducible ? { codexReproducible: true } : {}
105
+ }) : void 0;
106
+ const exactPrompt = invocation?.prompt ?? taskPrompt;
107
+ const readDeniedPaths = typeof opts.codexReadDeniedPaths === "function" ? opts.codexReadDeniedPaths(worktreePath) : opts.codexReadDeniedPaths;
108
+ const startedAt = /* @__PURE__ */ new Date();
109
+ let harnessResult = null;
110
+ let profileWorkspaceReceipt = null;
111
+ let costReceipt = null;
112
+ let costCallId = null;
113
+ let shotError = null;
114
+ try {
115
+ const execute = async (executionSignal) => {
116
+ harnessResult = await withAuthorProfileResources(
117
+ profileResourcePlan,
118
+ worktreePath,
119
+ async (receipt2) => {
120
+ profileWorkspaceReceipt = receipt2;
121
+ const result2 = await run({
122
+ harness,
123
+ cwd: worktreePath,
124
+ taskPrompt,
125
+ ...invocation ? { invocation: { command: invocation.command, args: invocation.args } } : {},
126
+ // The candidate worktree is isolated and must be editable without an
127
+ // interactive permission prompt. Other runLocalHarness callers remain
128
+ // permission-safe by default.
129
+ dangerouslySkipPermissions: harness === "claude",
130
+ ...opts.codexReproducible ? { codexReproducible: true } : {},
131
+ ...readDeniedPaths ? { codexReadDeniedPaths: readDeniedPaths } : {},
132
+ timeoutMs: opts.timeoutMs,
133
+ signal: executionSignal
134
+ });
135
+ harnessResult = result2;
136
+ return result2;
137
+ }
138
+ );
139
+ const failure = shotFailure(harnessResult, exactPrompt, opts.codexReproducible === true);
140
+ if (failure) throw failure;
141
+ return harnessResult;
142
+ };
143
+ if (reproducibleCostLedger) {
144
+ const model = opts.profile?.model?.default;
145
+ if (!model) {
146
+ throw new Error("agenticGenerator: reproducible Codex requires profile.model.default");
147
+ }
148
+ const paid = await reproducibleCostLedger.runPaidCall({
149
+ channel: "driver",
150
+ phase: costPhase ?? "search.proposal",
151
+ actor: `agentic-generator:${harness}`,
152
+ model,
153
+ tags: {
154
+ generation: String(generation ?? -1),
155
+ candidateIndex: String(candidateIndex ?? -1),
156
+ shot: String(shot + 1)
157
+ },
158
+ signal,
159
+ ...opts.maximumCharge ? { maximumCharge: opts.maximumCharge } : {},
160
+ execute,
161
+ receipt: (result2) => costReceiptFromHarness(result2, model),
162
+ receiptFromError: () => harnessResult?.usage ? costReceiptFromHarness(harnessResult, model) : void 0
163
+ });
164
+ costCallId = paid.callId ?? null;
165
+ costReceipt = paid.receipt ?? null;
166
+ if (!paid.succeeded) throw paid.error;
167
+ harnessResult = paid.value;
168
+ } else {
169
+ harnessResult = await execute(signal);
170
+ }
171
+ } catch (cause) {
172
+ shotError = cause instanceof Error ? cause : new Error(String(cause));
173
+ }
174
+ const execution = shotExecutionSnapshot(harnessResult);
175
+ const receipt = shotReceipt({
176
+ generation,
177
+ candidateIndex,
178
+ shot,
179
+ maxShots: shots,
180
+ harness,
181
+ profile: opts.profile,
182
+ prompt: exactPrompt,
183
+ startedAt,
184
+ completedAt: /* @__PURE__ */ new Date(),
185
+ result: execution,
186
+ profileWorkspaceReceipt,
187
+ costCallId,
188
+ costReceipt,
189
+ error: shotError
190
+ });
191
+ await emitShotReceipt(opts.onShotCompleted, receipt, execution, shotError);
192
+ if (!execution) {
193
+ throw new Error("agenticGenerator: author shot completed without a harness result");
194
+ }
195
+ let worktreeChanged;
196
+ try {
197
+ worktreeChanged = dirty(worktreePath);
198
+ } catch (cause) {
199
+ return rethrowShotSetupError(
200
+ opts.onShotDisposition,
201
+ receipt,
202
+ worktreePath,
203
+ "worktree-inspection",
204
+ cause
205
+ );
206
+ }
207
+ if (!worktreeChanged) {
208
+ await emitShotDisposition(opts.onShotDisposition, receipt, {
209
+ kind: "clean",
210
+ worktreePath
211
+ });
212
+ attemptNote = EMPTY_TREE_NOTE;
213
+ continue;
214
+ }
215
+ if (needsRawTraceEvidence) {
216
+ let problem;
217
+ try {
218
+ problem = rawTraceEvidenceProblem(worktreePath, findings);
219
+ } catch (cause) {
220
+ return rethrowShotSetupError(
221
+ opts.onShotDisposition,
222
+ receipt,
223
+ worktreePath,
224
+ "raw-trace-evidence",
225
+ cause
226
+ );
227
+ }
228
+ if (problem) {
229
+ await emitShotDisposition(opts.onShotDisposition, receipt, {
230
+ kind: "rejected",
231
+ worktreePath,
232
+ stage: "raw-trace-evidence",
233
+ feedback: problem
234
+ });
235
+ attemptNote = problem;
236
+ continue;
237
+ }
238
+ }
239
+ if (!verify) {
240
+ await emitShotDisposition(opts.onShotDisposition, receipt, {
241
+ kind: "accepted",
242
+ worktreePath,
243
+ verified: false
244
+ });
245
+ return { applied: true, summary: summarize(findings) };
246
+ }
247
+ let result;
248
+ try {
249
+ result = await verify(worktreePath);
250
+ } catch (cause) {
251
+ return rethrowShotSetupError(
252
+ opts.onShotDisposition,
253
+ receipt,
254
+ worktreePath,
255
+ "verification",
256
+ cause
257
+ );
258
+ }
259
+ if (result.ok) {
260
+ await emitShotDisposition(opts.onShotDisposition, receipt, {
261
+ kind: "accepted",
262
+ worktreePath,
263
+ verified: true
264
+ });
265
+ return { applied: true, summary: summarize(findings) };
266
+ }
267
+ await emitShotDisposition(opts.onShotDisposition, receipt, {
268
+ kind: "rejected",
269
+ worktreePath,
270
+ stage: "verification",
271
+ feedback: result.feedback ?? null
272
+ });
273
+ attemptNote = failureNote(result.feedback);
274
+ }
275
+ return { applied: false, summary: "" };
276
+ }
277
+ };
278
+ }
279
+ function authorProfileResourcePlan(profile) {
280
+ const resources = profile.resources;
281
+ if (!resources) return null;
282
+ const unsupportedKinds = [
283
+ resources.tools?.length ? "tools" : null,
284
+ resources.skills?.length ? "skills" : null,
285
+ resources.agents?.length ? "agents" : null
286
+ ].filter((kind) => kind !== null);
287
+ if (unsupportedKinds.length > 0) {
288
+ throw new Error(
289
+ `agenticGenerator: reproducible Codex author resources support files only; unsupported: ${unsupportedKinds.join(", ")}`
290
+ );
291
+ }
292
+ if (!resources.files || resources.files.length === 0) return null;
293
+ const plan = materializeProfile(
294
+ {
295
+ name: profile.name,
296
+ resources: { files: resources.files }
297
+ },
298
+ "codex"
299
+ );
300
+ if (plan.unsupported.length > 0) {
301
+ throw new Error(
302
+ `agenticGenerator: author profile files could not be materialized: ${plan.unsupported.map((item) => item.reason).join("; ")}`
303
+ );
304
+ }
305
+ if (Object.keys(plan.env).length > 0 || plan.flags.length > 0) {
306
+ throw new Error(
307
+ "agenticGenerator: generic author profile files unexpectedly changed spawn values"
308
+ );
309
+ }
310
+ const virtualRoot = resolve("/", AGENTIC_PROFILE_RESOURCE_ROOT);
311
+ const seen = /* @__PURE__ */ new Set();
312
+ for (const file of plan.files) {
313
+ const target = resolve("/", file.relPath);
314
+ if (!target.startsWith(`${virtualRoot}${sep}`)) {
315
+ throw new Error(
316
+ `agenticGenerator: author profile file must be below ${AGENTIC_PROFILE_RESOURCE_ROOT}: ${file.relPath}`
317
+ );
318
+ }
319
+ if (seen.has(target)) {
320
+ throw new Error(`agenticGenerator: duplicate author profile file path: ${file.relPath}`);
321
+ }
322
+ seen.add(target);
323
+ }
324
+ return plan;
325
+ }
326
+ function appendProfileResourcePaths(prompt, plan) {
327
+ if (!plan) return prompt;
328
+ return [
329
+ prompt,
330
+ "",
331
+ "Profile resource files available for this shot:",
332
+ ...plan.files.map((file) => `- ${file.relPath}`)
333
+ ].join("\n");
334
+ }
335
+ async function withAuthorProfileResources(plan, worktreePath, run) {
336
+ if (!plan) return run(null);
337
+ const rootPath = resolve(worktreePath, AGENTIC_PROFILE_RESOURCE_ROOT);
338
+ if (existsSync(rootPath)) {
339
+ throw new Error(
340
+ `agenticGenerator: ephemeral author profile root already exists: ${AGENTIC_PROFILE_RESOURCE_ROOT}`
341
+ );
342
+ }
343
+ let value;
344
+ let primaryError;
345
+ try {
346
+ const receipt = applyWorkspacePlan(plan, worktreePath);
347
+ value = await run(receipt);
348
+ } catch (cause) {
349
+ primaryError = cause;
350
+ }
351
+ let cleanupError;
352
+ try {
353
+ rmSync(rootPath, { recursive: true, force: true });
354
+ if (existsSync(rootPath)) {
355
+ throw new Error(
356
+ `agenticGenerator: ephemeral author profile root survived cleanup: ${AGENTIC_PROFILE_RESOURCE_ROOT}`
357
+ );
358
+ }
359
+ } catch (cause) {
360
+ cleanupError = cause;
361
+ }
362
+ if (primaryError !== void 0 && cleanupError !== void 0) {
363
+ throw new AggregateError(
364
+ [primaryError, cleanupError],
365
+ "agenticGenerator: author shot and profile resource cleanup both failed"
366
+ );
367
+ }
368
+ if (primaryError !== void 0) throw primaryError;
369
+ if (cleanupError !== void 0) throw cleanupError;
370
+ return value;
371
+ }
372
+ async function emitShotReceipt(callback, receipt, execution, primaryError) {
373
+ try {
374
+ await callback?.(receipt, execution);
375
+ } catch (callbackError) {
376
+ if (primaryError !== null) {
377
+ throw new AggregateError(
378
+ [primaryError, callbackError],
379
+ "agenticGenerator: author shot failed and its receipt could not be persisted"
380
+ );
381
+ }
382
+ throw callbackError;
383
+ }
384
+ if (primaryError !== null) throw primaryError;
385
+ }
386
+ async function emitShotDisposition(callback, receipt, disposition) {
387
+ await callback?.(receipt, disposition);
388
+ }
389
+ async function rethrowShotSetupError(callback, receipt, worktreePath, stage, cause) {
390
+ const error = cause instanceof Error ? cause : new Error(String(cause));
391
+ try {
392
+ await emitShotDisposition(callback, receipt, {
393
+ kind: "setup-error",
394
+ worktreePath,
395
+ stage,
396
+ error: { name: error.name, message: error.message }
397
+ });
398
+ } catch (callbackError) {
399
+ throw new AggregateError(
400
+ [cause, callbackError],
401
+ "agenticGenerator: shot processing failed and its worktree disposition could not be persisted"
402
+ );
403
+ }
404
+ throw cause;
405
+ }
406
+ function shotExecutionSnapshot(result) {
407
+ if (result === null) return null;
408
+ const usage = result.usage ? Object.freeze({ ...result.usage }) : void 0;
409
+ const evidence = result.evidence ? Object.freeze({
410
+ ...result.evidence,
411
+ readDeniedPaths: Object.freeze([...result.evidence.readDeniedPaths]),
412
+ policy: Object.freeze({ ...result.evidence.policy })
413
+ }) : void 0;
414
+ return Object.freeze({
415
+ exitCode: result.exitCode,
416
+ stdout: result.stdout,
417
+ stderr: result.stderr,
418
+ killedBySignal: result.killedBySignal,
419
+ durationMs: result.durationMs,
420
+ timedOut: result.timedOut,
421
+ ...usage ? { usage } : {},
422
+ ...evidence ? { evidence } : {}
423
+ });
424
+ }
425
+ function shotReceipt(input) {
426
+ const error = input.error ? {
427
+ name: input.error instanceof Error ? input.error.name : "Error",
428
+ message: input.error instanceof Error ? input.error.message : String(input.error)
429
+ } : null;
430
+ const result = input.result;
431
+ const costBasis = costBasisFor(input.costReceipt);
432
+ return {
433
+ generation: input.generation ?? null,
434
+ candidateIndex: input.candidateIndex ?? null,
435
+ shot: input.shot + 1,
436
+ maxShots: input.maxShots,
437
+ harness: input.harness,
438
+ model: input.profile?.model?.default ?? null,
439
+ reasoningEffort: input.profile?.model?.reasoningEffort ?? null,
440
+ promptSha256: sha256(input.prompt),
441
+ startedAt: input.startedAt.toISOString(),
442
+ completedAt: input.completedAt.toISOString(),
443
+ durationMs: result?.durationMs ?? input.completedAt.getTime() - input.startedAt.getTime(),
444
+ exitCode: result?.exitCode ?? null,
445
+ timedOut: result?.timedOut ?? false,
446
+ killedBySignal: result?.killedBySignal ?? null,
447
+ stdoutBytes: result ? Buffer.byteLength(result.stdout) : null,
448
+ stdoutSha256: result ? sha256(result.stdout) : null,
449
+ stderrBytes: result ? Buffer.byteLength(result.stderr) : null,
450
+ stderrSha256: result ? sha256(result.stderr) : null,
451
+ usage: result?.usage ? { ...result.usage } : null,
452
+ profileWorkspacePlanDigest: input.profileWorkspaceReceipt?.workspacePlanDigest ?? null,
453
+ profileWorkspaceFileCount: input.profileWorkspaceReceipt?.written.length ?? 0,
454
+ costCallId: input.costCallId,
455
+ costBasis,
456
+ costUsd: costBasis === "unknown" ? null : input.costReceipt?.costUsd ?? null,
457
+ costUsdKnown: costBasis === "provider-reported",
458
+ evidence: result?.evidence ? {
459
+ ...result.evidence,
460
+ readDeniedPaths: [...result.evidence.readDeniedPaths],
461
+ policy: { ...result.evidence.policy }
462
+ } : null,
463
+ error
464
+ };
465
+ }
466
+ function costBasisFor(receipt) {
467
+ if (receipt === null || receipt.costUnknown) return "unknown";
468
+ return receipt.actualCostUsd === void 0 ? "estimated-pricing" : "provider-reported";
469
+ }
470
+ function shotFailure(result, exactPrompt, codexReproducible) {
471
+ if (result.timedOut) {
472
+ return new Error("agenticGenerator: author shot timed out");
473
+ }
474
+ if (result.killedBySignal) {
475
+ return new Error(`agenticGenerator: author shot was killed by ${result.killedBySignal}`);
476
+ }
477
+ if (result.exitCode !== 0) {
478
+ return new Error(`agenticGenerator: author shot exited with code ${String(result.exitCode)}`);
479
+ }
480
+ if (!codexReproducible) return null;
481
+ if (!result.usage || !result.evidence) {
482
+ return new Error(
483
+ "agenticGenerator: reproducible Codex shot completed without usage or execution evidence"
484
+ );
485
+ }
486
+ const expectedPromptSha256 = sha256(exactPrompt).slice("sha256:".length);
487
+ if (result.evidence.requestedPromptSha256 !== expectedPromptSha256) {
488
+ return new Error(
489
+ "agenticGenerator: reproducible Codex prompt evidence does not match the exact authored prompt"
490
+ );
491
+ }
492
+ return null;
493
+ }
494
+ function costReceiptFromHarness(result, model) {
495
+ if (!result.usage) {
496
+ throw new Error("agenticGenerator: author shot did not report terminal token usage");
497
+ }
498
+ return {
499
+ model,
500
+ inputTokens: result.usage.inputTokens - result.usage.cachedInputTokens,
501
+ outputTokens: result.usage.outputTokens,
502
+ ...result.usage.cachedInputTokens > 0 ? { cachedTokens: result.usage.cachedInputTokens } : {}
503
+ };
504
+ }
505
+ function sha256(value) {
506
+ return `sha256:${createHash("sha256").update(value).digest("hex")}`;
507
+ }
508
+ function defaultBuildPrompt(args) {
509
+ const lines = [
510
+ "You are improving this codebase based on an evaluation analysis.",
511
+ "Make the smallest set of edits that addresses the findings below, then stop.",
512
+ "Do not change unrelated code. Do not commit \u2014 leave changes in the working tree.",
513
+ "",
514
+ "Findings:"
515
+ ];
516
+ for (const f of args.findings) {
517
+ const where = f.subject ? ` [${f.subject}]` : "";
518
+ lines.push(`- (${f.severity})${where} ${f.claim}`);
519
+ if (f.recommended_action) lines.push(` \u2192 ${f.recommended_action}`);
520
+ }
521
+ if (requiresRawTraceEvidence(args.findings)) {
522
+ lines.push(
523
+ "",
524
+ "Raw trace evidence requirement:",
525
+ `- Inspect at least one raw trace path named above before editing.`,
526
+ `- Write ${RAW_TRACE_DIAGNOSIS_PATH} in this worktree.`,
527
+ "- Include the exact trace path(s) inspected, the failure mechanism, and the code change made.",
528
+ "- A candidate without this file, or with only this file changed, is discarded."
529
+ );
530
+ }
531
+ return lines.join("\n");
532
+ }
533
+ var EMPTY_TREE_NOTE = "NOTE: your previous attempt left the working tree unchanged. Make the concrete file edits now.";
534
+ function failureNote(feedback) {
535
+ const detail = feedback?.trim();
536
+ return [
537
+ "NOTE: your edits are in the working tree but verification FAILED.",
538
+ "Fix the problem in place \u2014 build on your existing edits, do not revert them.",
539
+ detail ? `Verifier output:
540
+ ${truncate(detail, 4e3)}` : "No verifier detail was captured."
541
+ ].join("\n");
542
+ }
543
+ function rawTraceEvidenceProblem(worktreePath, findings) {
544
+ const changedPaths = worktreeChangedPaths(worktreePath);
545
+ const substantive = changedPaths.filter((path) => path !== RAW_TRACE_DIAGNOSIS_PATH);
546
+ if (substantive.length === 0) {
547
+ return [
548
+ `NOTE: raw-trace mode requires a real code/config edit in addition to ${RAW_TRACE_DIAGNOSIS_PATH}.`,
549
+ "Your previous attempt only changed the diagnosis artifact. Inspect the cited traces and make the causal code change."
550
+ ].join("\n");
551
+ }
552
+ const diagnosisPath = join(worktreePath, RAW_TRACE_DIAGNOSIS_PATH);
553
+ if (!existsSync(diagnosisPath)) {
554
+ return [
555
+ `NOTE: raw-trace mode requires ${RAW_TRACE_DIAGNOSIS_PATH}.`,
556
+ "Before retrying, inspect at least one cited spans.jsonl/cached-result.json/artifact path, then write the diagnosis file with the exact path, failure mechanism, and code change."
557
+ ].join("\n");
558
+ }
559
+ const body = readFileSync(diagnosisPath, "utf8");
560
+ const evidencePaths = traceEvidencePaths(findings);
561
+ if (evidencePaths.length > 0 && !evidencePaths.some((path) => body.includes(path))) {
562
+ return [
563
+ `${RAW_TRACE_DIAGNOSIS_PATH} exists, but it does not cite any exact raw trace path from the findings.`,
564
+ `Cite at least one of these inspected paths exactly: ${evidencePaths.slice(0, 5).join(", ")}`
565
+ ].join("\n");
566
+ }
567
+ return null;
568
+ }
569
+ function requiresRawTraceEvidence(findings) {
570
+ return findings.some((finding) => {
571
+ const f = finding;
572
+ return f.analyst_id === RAW_TRACE_ANALYST_ID || f.area === RAW_TRACE_AREA;
573
+ });
574
+ }
575
+ function traceEvidencePaths(findings) {
576
+ const out = [];
577
+ for (const finding of findings) {
578
+ const refs = finding.evidence_refs;
579
+ if (!Array.isArray(refs)) continue;
580
+ for (const ref of refs) {
581
+ if (!ref || typeof ref !== "object") continue;
582
+ const uri = ref.uri;
583
+ if (typeof uri === "string" && uri.length > 0) out.push(uri);
584
+ }
585
+ }
586
+ return [...new Set(out)];
587
+ }
588
+ function commandVerifier(command, args = [], timeoutMs = 3e5) {
589
+ return (worktreePath) => {
590
+ const result = spawnSync(command, args, {
591
+ cwd: worktreePath,
592
+ encoding: "utf-8",
593
+ timeout: timeoutMs
594
+ });
595
+ if (result.signal) {
596
+ return {
597
+ ok: false,
598
+ feedback: `verifier '${command}' killed by ${result.signal} (likely timeout after ${timeoutMs}ms)`
599
+ };
600
+ }
601
+ if (result.error) {
602
+ const code = result.error.code;
603
+ if (code === "ENOENT") {
604
+ throw new Error(
605
+ `commandVerifier: '${command}' not found in PATH (setup bug, not a failed candidate)`
606
+ );
607
+ }
608
+ throw new Error(`commandVerifier: '${command}' failed to spawn: ${result.error.message}`);
609
+ }
610
+ if (result.status === 0) return { ok: true };
611
+ const out = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim();
612
+ return { ok: false, feedback: out.length > 0 ? out : `exit ${result.status}` };
613
+ };
614
+ }
615
+ function summarize(findings) {
616
+ if (findings.length === 0) return "agentic improvement";
617
+ if (findings.length === 1) return `agentic: ${truncate(findings[0].claim, 64)}`;
618
+ return `agentic: ${findings.length} findings addressed`;
619
+ }
620
+ function truncate(s, n) {
621
+ return s.length <= n ? s : `${s.slice(0, n - 1)}\u2026`;
622
+ }
623
+ function worktreeDirty(worktreePath) {
624
+ return worktreeChangedPaths(worktreePath).length > 0;
625
+ }
626
+ function worktreeChangedPaths(worktreePath) {
627
+ const result = spawnSync("git", ["status", "--porcelain", "--untracked-files=all"], {
628
+ cwd: worktreePath,
629
+ encoding: "utf-8"
630
+ });
631
+ if (result.error) {
632
+ throw new Error(
633
+ `agenticGenerator: git status failed to spawn in ${worktreePath}: ${result.error.message}`
634
+ );
635
+ }
636
+ if (result.status !== 0) {
637
+ throw new Error(
638
+ `agenticGenerator: git status exited ${result.status} in ${worktreePath}: ${result.stderr.trim()}`
639
+ );
640
+ }
641
+ return result.stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0).map((line) => line.slice(3).trim());
642
+ }
643
+
644
+ // src/improvement/improvement-driver.ts
645
+ import { spawnSync as spawnSync2 } from "child_process";
646
+ import {
647
+ verifyCodeSurface
648
+ } from "@tangle-network/agent-eval/campaign";
649
+
650
+ // src/improvement/cleanup.ts
651
+ async function rethrowAfterCleanup(cause, cleanup, context) {
652
+ const cleanupErrors = [];
653
+ for (let attempt = 0; attempt < 2; attempt += 1) {
654
+ try {
655
+ await cleanup();
656
+ } catch (cleanupCause) {
657
+ cleanupErrors.push(cleanupCause);
658
+ continue;
659
+ }
660
+ if (cleanupErrors.length === 0) throw cause;
661
+ throw new AggregateError([cause, ...cleanupErrors], `${context}; cleanup retry succeeded`);
662
+ }
663
+ throw new AggregateError([cause, ...cleanupErrors], `${context}; cleanup failed`);
664
+ }
665
+
666
+ // src/improvement/improvement-driver.ts
667
+ function improvementDriver(opts) {
668
+ const baseRef = opts.baseRef ?? "main";
669
+ const owned = /* @__PURE__ */ new Map();
670
+ return {
671
+ kind: `improvement:${opts.generator.kind}`,
672
+ async propose(ctx) {
673
+ const findings = resolveFindings(ctx);
674
+ if (findings.length === 0 && ctx.report === void 0 && !opts.generator.proposesWithoutFindings) {
675
+ return [];
676
+ }
677
+ const surfaces = [];
678
+ const incumbent = verifiedCodeIncumbent(ctx.currentSurface);
679
+ const proposalBaseRef = incumbent?.baseCommit ?? baseRef;
680
+ for (let i = 0; i < ctx.populationSize; i++) {
681
+ if (ctx.signal.aborted) break;
682
+ const wt = await opts.worktree.create({
683
+ baseRef: proposalBaseRef,
684
+ label: `${opts.generator.kind}-gen${ctx.generation}-cand${i}`
685
+ });
686
+ owned.set(wt.path, wt);
687
+ try {
688
+ if (incumbent) advanceToIncumbent(wt, incumbent);
689
+ const { applied, summary } = await opts.generator.generate({
690
+ worktreePath: wt.path,
691
+ report: ctx.report,
692
+ findings,
693
+ dataset: ctx.dataset,
694
+ maxShots: ctx.maxImprovementShots ?? 1,
695
+ signal: ctx.signal,
696
+ generation: ctx.generation,
697
+ candidateIndex: i,
698
+ ...ctx.costLedger ? { costLedger: ctx.costLedger } : {},
699
+ ...ctx.costPhase ? { costPhase: ctx.costPhase } : {}
700
+ });
701
+ if (!applied) {
702
+ await opts.worktree.discard(wt);
703
+ owned.delete(wt.path);
704
+ continue;
705
+ }
706
+ const surface = await opts.worktree.finalize(wt, summary);
707
+ surfaces.push(surface);
708
+ owned.delete(wt.path);
709
+ owned.set(surface.worktreeRef, wt);
710
+ } catch (err) {
711
+ const failure = err instanceof Error ? err.message : String(err);
712
+ return rethrowAfterCleanup(
713
+ err,
714
+ async () => {
715
+ await opts.worktree.discard(wt);
716
+ owned.delete(wt.path);
717
+ },
718
+ `improvementDriver: ${failure}`
719
+ );
720
+ }
721
+ }
722
+ return surfaces;
723
+ },
724
+ async cleanup(retainWorktreeRefs = []) {
725
+ const retained = new Set(retainWorktreeRefs);
726
+ const errors = [];
727
+ for (const [worktreeRef, worktree] of owned) {
728
+ if (retained.has(worktreeRef)) continue;
729
+ try {
730
+ await opts.worktree.discard(worktree);
731
+ owned.delete(worktreeRef);
732
+ } catch (cause) {
733
+ errors.push(cause);
734
+ }
735
+ }
736
+ if (errors.length > 0) {
737
+ throw new AggregateError(errors, "improvementDriver: failed to discard candidate worktrees");
738
+ }
739
+ }
740
+ };
741
+ }
742
+ function verifiedCodeIncumbent(surface) {
743
+ if (typeof surface !== "object" || surface.kind !== "code") return void 0;
744
+ verifyCodeSurface(surface);
745
+ return surface;
746
+ }
747
+ function advanceToIncumbent(worktree, incumbent) {
748
+ if (worktree.baseCommit !== incumbent.baseCommit || worktree.baseTree !== incumbent.baseTree) {
749
+ throw new Error("improvementDriver: candidate worktree does not match incumbent base identity");
750
+ }
751
+ if (worktree.baseCommit === incumbent.candidateCommit) return;
752
+ const merge = spawnSync2("git", ["merge", "--ff-only", incumbent.candidateCommit], {
753
+ cwd: worktree.path,
754
+ encoding: "utf8"
755
+ });
756
+ if (merge.error) {
757
+ throw new Error(
758
+ `improvementDriver: failed to start candidate from incumbent: ${merge.error.message}`
759
+ );
760
+ }
761
+ if (merge.status !== 0) {
762
+ throw new Error(
763
+ `improvementDriver: could not fast-forward candidate to incumbent ${incumbent.candidateCommit}: ${merge.stderr.trim()}`
764
+ );
765
+ }
766
+ const head = spawnSync2("git", ["rev-parse", "--verify", "HEAD"], {
767
+ cwd: worktree.path,
768
+ encoding: "utf8"
769
+ });
770
+ if (head.error || head.status !== 0 || head.stdout.trim() !== incumbent.candidateCommit) {
771
+ throw new Error("improvementDriver: candidate worktree did not reach the incumbent commit");
772
+ }
773
+ }
774
+ function resolveFindings(ctx) {
775
+ const report = ctx.report;
776
+ if (report && typeof report === "object" && "findings" in report) {
777
+ const f = report.findings;
778
+ if (Array.isArray(f) && f.length > 0) return f;
779
+ }
780
+ return ctx.findings;
781
+ }
782
+
783
+ // src/improvement/raw-trace-distiller.ts
784
+ import { existsSync as existsSync2, readdirSync } from "fs";
785
+ import { basename, join as join2, resolve as resolve2 } from "path";
786
+ import { makeFinding } from "@tangle-network/agent-eval";
787
+ var ANALYST_ID = "raw-trace-distiller";
788
+ var PASS_THRESHOLD = 0.999;
789
+ function rawTraceDistiller(options = {}) {
790
+ const maxCandidates = options.maxCandidates ?? 12;
791
+ const maxCellsPerCandidate = options.maxCellsPerCandidate ?? 8;
792
+ const maxFilesPerCell = options.maxFilesPerCell ?? 24;
793
+ return async (input) => {
794
+ const genRoot = absoluteRunDir(options.runDir ?? input.runDir);
795
+ const durable = isDurable(genRoot);
796
+ const ranked = [...input.candidates].map((c) => ({
797
+ surfaceHash: c.surfaceHash,
798
+ composite: c.composite,
799
+ campaignDir: absoluteRunDir(c.campaign.runDir),
800
+ cells: failingCells(c.campaign, maxCellsPerCandidate, maxFilesPerCell)
801
+ })).sort((a, b) => a.composite - b.composite).slice(0, maxCandidates);
802
+ const totalFailingCells = ranked.reduce((n, c) => n + c.cells.length, 0);
803
+ if (totalFailingCells === 0) {
804
+ if (options.fallbackFindings && options.fallbackFindings.length > 0) {
805
+ return options.fallbackFindings;
806
+ }
807
+ return [
808
+ makeFinding({
809
+ analyst_id: ANALYST_ID,
810
+ severity: "info",
811
+ area: "raw-trace-context",
812
+ confidence: 1,
813
+ claim: `Generation ${input.generation} had no failing cells. The full raw run traces are on disk under ${genRoot}.`,
814
+ recommended_action: `To keep improving, grep/cat the raw traces under ${genRoot} (per-cell spans.jsonl + cached-result.json) to find the weakest passing runs, then make a targeted harness-code edit.`,
815
+ evidence_refs: [{ kind: "artifact", uri: genRoot }],
816
+ metadata: { generation: input.generation, runDir: genRoot, failingCells: 0 }
817
+ })
818
+ ];
819
+ }
820
+ const findings = [];
821
+ findings.push(
822
+ makeFinding({
823
+ analyst_id: ANALYST_ID,
824
+ severity: "high",
825
+ area: "raw-trace-context",
826
+ confidence: 1,
827
+ claim: `Generation ${input.generation} produced ${totalFailingCells} failing/low-scoring cell(s) across ${ranked.length} candidate(s). Their FULL RAW run traces are on disk under ${genRoot} \u2014 the actual event logs (spans.jsonl), scores (cached-result.json), and artifacts, not a summary.${durable ? "" : " (WARNING: this run root does not exist on disk \u2014 it looks like an in-memory run; pass a real runDir to improve() to get raw-trace context.)"}`,
828
+ recommended_action: `Do NOT rely on a pre-summarized finding. Before editing, DIAGNOSE from the raw traces: run \`grep\`/\`cat\`/\`ls\` over the trace files and directories named in the following findings to see exactly what each failing run did and why it scored low, then make the smallest harness-code edit that fixes the dominant failure. Start with \`grep -rIn "error" ${genRoot}\` then \`cat\` the spans.jsonl of the worst cell.`,
829
+ evidence_refs: [{ kind: "artifact", uri: genRoot }],
830
+ metadata: {
831
+ generation: input.generation,
832
+ runDir: genRoot,
833
+ failingCells: totalFailingCells,
834
+ candidates: ranked.length
835
+ }
836
+ })
837
+ );
838
+ for (const cand of ranked) {
839
+ if (cand.cells.length === 0) continue;
840
+ const scenarioList = cand.cells.map((c) => c.scenarioId).join(", ");
841
+ const fileLines = cand.cells.map((c) => {
842
+ const header = ` cell ${c.scenarioId} (composite ${c.composite.toFixed(3)}${c.error ? `, error: ${truncate2(c.error, 160)}` : ""}) \u2014 dir ${c.cellDir}`;
843
+ const files = c.files.map((f) => ` - ${f}`).join("\n");
844
+ const more = c.truncatedFiles ? `
845
+ - \u2026(ls ${c.cellDir} for the rest)` : "";
846
+ return c.files.length > 0 ? `${header}
847
+ ${files}${more}` : header;
848
+ }).join("\n");
849
+ findings.push(
850
+ makeFinding({
851
+ analyst_id: ANALYST_ID,
852
+ severity: cand.composite < 0.5 ? "critical" : "high",
853
+ area: "raw-trace-context",
854
+ confidence: 1,
855
+ subject: cand.surfaceHash,
856
+ claim: `Candidate ${cand.surfaceHash} scored composite ${cand.composite.toFixed(3)} with ${cand.cells.length} failing cell(s) [${scenarioList}]. Its raw traces are under ${cand.campaignDir}.`,
857
+ recommended_action: `grep/cat these raw trace files to diagnose WHY this candidate failed before editing:
858
+ ${fileLines}
859
+ Or scan the whole candidate at once: \`grep -rIn . ${cand.campaignDir}\` and \`ls -R ${cand.campaignDir}\`.`,
860
+ evidence_refs: [
861
+ { kind: "artifact", uri: cand.campaignDir },
862
+ ...cand.cells.flatMap(
863
+ (c) => c.files.map((f) => ({ kind: "artifact", uri: f }))
864
+ )
865
+ ],
866
+ metadata: {
867
+ surfaceHash: cand.surfaceHash,
868
+ composite: cand.composite,
869
+ campaignDir: cand.campaignDir,
870
+ cells: cand.cells.map((c) => ({
871
+ scenarioId: c.scenarioId,
872
+ composite: c.composite,
873
+ cellDir: c.cellDir,
874
+ files: c.files,
875
+ ...c.error ? { error: c.error } : {}
876
+ }))
877
+ }
878
+ })
879
+ );
880
+ }
881
+ return findings;
882
+ };
883
+ }
884
+ function failingCells(campaign, maxCells, maxFiles) {
885
+ const campaignDir = absoluteRunDir(campaign.runDir);
886
+ const durable = isDurable(campaignDir);
887
+ const out = [];
888
+ for (const cell of campaign.cells) {
889
+ const scores = Object.values(cell.judgeScores ?? {});
890
+ const composite = scores.length === 0 ? 0 : scores.reduce((sum, s) => sum + (s.composite ?? 0), 0) / scores.length;
891
+ if (!cell.error && composite >= PASS_THRESHOLD) continue;
892
+ const cellDir = join2(campaignDir, sanitizeCellId(cell.cellId));
893
+ const artifactPaths = artifactPathsForCell(campaign.artifactsByPath, cell.cellId);
894
+ const discovered = durable ? listTraceFiles(cellDir) : [];
895
+ const canonical = [join2(cellDir, "spans.jsonl"), join2(cellDir, "cached-result.json")];
896
+ const files = dedupeSorted([...discovered, ...artifactPaths, ...canonical]);
897
+ out.push({
898
+ scenarioId: cell.scenarioId,
899
+ composite: Number(composite.toFixed(3)),
900
+ ...cell.error ? { error: cell.error } : {},
901
+ cellDir,
902
+ files: files.slice(0, maxFiles),
903
+ truncatedFiles: files.length > maxFiles
904
+ });
905
+ if (out.length >= maxCells) break;
906
+ }
907
+ return out;
908
+ }
909
+ function artifactPathsForCell(artifactsByPath, cellId) {
910
+ if (!artifactsByPath) return [];
911
+ const prefix = `${cellId}/`;
912
+ return Object.entries(artifactsByPath).filter(([key]) => key.startsWith(prefix)).map(([, absPath]) => resolve2(absPath));
913
+ }
914
+ function listTraceFiles(dir) {
915
+ const out = [];
916
+ for (const entry of safeReadDir(dir)) {
917
+ const full = join2(dir, entry.name);
918
+ if (entry.isFile()) {
919
+ out.push(full);
920
+ } else if (!entry.isSymbolicLink() && entry.isDirectory()) {
921
+ for (const sub of safeReadDir(full)) {
922
+ if (sub.isFile()) out.push(join2(full, sub.name));
923
+ }
924
+ }
925
+ }
926
+ return out;
927
+ }
928
+ function safeReadDir(dir) {
929
+ try {
930
+ return readdirSync(dir, { withFileTypes: true });
931
+ } catch {
932
+ return [];
933
+ }
934
+ }
935
+ function sanitizeCellId(cellId) {
936
+ return cellId.replace(/[^a-zA-Z0-9_-]/g, "_");
937
+ }
938
+ function isDurable(runDir) {
939
+ return !runDir.startsWith("mem://") && existsSync2(runDir);
940
+ }
941
+ function absoluteRunDir(runDir) {
942
+ return runDir.startsWith("mem://") ? runDir : resolve2(runDir);
943
+ }
944
+ function dedupeSorted(paths) {
945
+ return [...new Set(paths)].sort((a, b) => {
946
+ const da = a.slice(0, a.length - basename(a).length);
947
+ const db = b.slice(0, b.length - basename(b).length);
948
+ return da === db ? basename(a).localeCompare(basename(b)) : da.localeCompare(db);
949
+ });
950
+ }
951
+ function truncate2(s, n) {
952
+ return s.length <= n ? s : `${s.slice(0, n - 1)}\u2026`;
953
+ }
954
+
955
+ // src/improvement/improve.ts
956
+ import { canonicalJson } from "@tangle-network/agent-eval";
957
+ import {
958
+ gepaProposer,
959
+ gitWorktreeAdapter,
960
+ memoryCurationProposer,
961
+ skillOptProposer
962
+ } from "@tangle-network/agent-eval/campaign";
963
+ import {
964
+ selfImprove
965
+ } from "@tangle-network/agent-eval/contract";
966
+ import {
967
+ agentProfileSchema
968
+ } from "@tangle-network/agent-interface";
969
+ var defaultReflectionModel = "deepseek-v4-flash";
970
+ function llmClientOptions(llm) {
971
+ return { baseUrl: llm?.baseUrl, apiKey: llm?.apiKey };
972
+ }
973
+ function defaultGeneratorFor(surface, llm) {
974
+ const model = llm?.model ?? defaultReflectionModel;
975
+ switch (surface) {
976
+ case "prompt":
977
+ return gepaProposer({ llm: llmClientOptions(llm), model, target: "agent system prompt" });
978
+ case "skills":
979
+ return skillOptProposer({ llm: llmClientOptions(llm), model, target: "agent skill document" });
980
+ case "memory":
981
+ return memoryCurationProposer();
982
+ default:
983
+ return void 0;
984
+ }
985
+ }
986
+ function baselineSurfaceFor(profile, surface, skills) {
987
+ switch (surface) {
988
+ case "prompt":
989
+ return profile.prompt?.systemPrompt ?? "";
990
+ case "skills":
991
+ return inlineSkill(profile, skills).content;
992
+ case "tools":
993
+ return JSON.stringify(profile.tools ?? {});
994
+ case "mcp":
995
+ return JSON.stringify(profile.mcp ?? {});
996
+ case "hooks":
997
+ return JSON.stringify(profile.hooks ?? {});
998
+ case "subagents":
999
+ return JSON.stringify(profile.subagents ?? {});
1000
+ case "agent-profile":
1001
+ return canonicalJson(profile);
1002
+ case "memory":
1003
+ return profileInstructions(profile);
1004
+ case "code":
1005
+ throw new ConfigError(
1006
+ "improve(): code requires the isolated baseline created from opts.code.repoRoot"
1007
+ );
1008
+ }
1009
+ }
1010
+ var DISTILLED_NOTES_MAX_CHARS = 1500;
1011
+ var DISTILLED_ERROR_MAX_CHARS = 500;
1012
+ function generationFailureDistiller(staticFindings) {
1013
+ const CAP = 12;
1014
+ return async (input) => {
1015
+ const failures = [];
1016
+ for (const candidate of input.candidates) {
1017
+ for (const rawCell of candidate.campaign.cells) {
1018
+ const cell = rawCell;
1019
+ const scenario = String(cell.scenarioId ?? "unknown");
1020
+ const error = typeof cell.error === "string" ? cell.error : void 0;
1021
+ const judgeScores = cell.judgeScores && typeof cell.judgeScores === "object" ? Object.values(
1022
+ cell.judgeScores
1023
+ ) : [];
1024
+ const composite = judgeScores.length === 0 ? 0 : judgeScores.reduce((sum, j) => sum + (j.composite ?? 0), 0) / judgeScores.length;
1025
+ if (!error && composite >= 0.999) continue;
1026
+ const notes = judgeScores.map((j) => j.notes).filter((n) => typeof n === "string" && n.length > 0).join("; ").slice(0, DISTILLED_NOTES_MAX_CHARS);
1027
+ const claim = notes || (error ? `Scenario ${scenario} failed: ${error.slice(0, DISTILLED_ERROR_MAX_CHARS)}` : "");
1028
+ failures.push({
1029
+ scenario,
1030
+ composite: Number(composite.toFixed(3)),
1031
+ notes,
1032
+ ...claim ? { claim } : {},
1033
+ ...error ? { error: error.slice(0, DISTILLED_ERROR_MAX_CHARS) } : {}
1034
+ });
1035
+ }
1036
+ }
1037
+ if (failures.length === 0) return staticFindings;
1038
+ failures.sort((a, b) => a.composite - b.composite);
1039
+ return failures.slice(0, CAP);
1040
+ };
1041
+ }
1042
+ function memoryGenerationDistiller(staticFindings) {
1043
+ const distillFailures = generationFailureDistiller(staticFindings);
1044
+ return async (input) => {
1045
+ const fresh = await distillFailures(input);
1046
+ return fresh === staticFindings ? staticFindings : [...staticFindings, ...fresh];
1047
+ };
1048
+ }
1049
+ async function discardPreparedBaseline(worktree, baselineWorktree, cause) {
1050
+ return rethrowAfterCleanup(
1051
+ cause,
1052
+ () => worktree.discard(baselineWorktree),
1053
+ "improve(): code preparation failed"
1054
+ );
1055
+ }
1056
+ function isCodeSurface(surface) {
1057
+ return typeof surface === "object" && surface !== null && surface.kind === "code";
1058
+ }
1059
+ async function prepareCodeRun(code) {
1060
+ const baseRef = code.baseRef ?? "main";
1061
+ const worktree = code.worktree ?? gitWorktreeAdapter({
1062
+ repoRoot: code.repoRoot,
1063
+ ...code.worktreeDir ? { worktreeDir: code.worktreeDir } : {}
1064
+ });
1065
+ const baselineWorktree = await worktree.create({ baseRef, label: "incumbent-baseline" });
1066
+ try {
1067
+ const baseline = await worktree.finalize(baselineWorktree, "Incumbent code checkout");
1068
+ let baselineDiscarded = false;
1069
+ const generator = code.generator ?? agenticGenerator({
1070
+ ...code.harness ? { harness: code.harness } : {},
1071
+ ...code.verify ? { verify: code.verify } : {},
1072
+ ...code.timeoutMs ? { timeoutMs: code.timeoutMs } : {}
1073
+ });
1074
+ const managed = improvementDriver({ worktree, generator, baseRef });
1075
+ return {
1076
+ baseline,
1077
+ proposer: managed,
1078
+ async cleanup(retainedWinner) {
1079
+ const errors = [];
1080
+ const retainedWorktreeRef = isCodeSurface(retainedWinner) ? retainedWinner.worktreeRef : void 0;
1081
+ try {
1082
+ await managed?.cleanup(retainedWorktreeRef ? [retainedWorktreeRef] : []);
1083
+ } catch (cause) {
1084
+ errors.push(cause);
1085
+ }
1086
+ if (!baselineDiscarded && retainedWorktreeRef !== baseline.worktreeRef) {
1087
+ try {
1088
+ await worktree.discard(baselineWorktree);
1089
+ baselineDiscarded = true;
1090
+ } catch (cause) {
1091
+ errors.push(cause);
1092
+ }
1093
+ }
1094
+ if (errors.length > 0) {
1095
+ throw new AggregateError(errors, "improve(): failed to clean code improvement worktrees");
1096
+ }
1097
+ }
1098
+ };
1099
+ } catch (cause) {
1100
+ return discardPreparedBaseline(worktree, baselineWorktree, cause);
1101
+ }
1102
+ }
1103
+ function idempotentDispose(dispose) {
1104
+ let disposed = false;
1105
+ let inFlight;
1106
+ return async () => {
1107
+ if (disposed) return;
1108
+ if (inFlight) return inFlight;
1109
+ inFlight = (async () => {
1110
+ await dispose();
1111
+ disposed = true;
1112
+ })();
1113
+ try {
1114
+ await inFlight;
1115
+ } finally {
1116
+ inFlight = void 0;
1117
+ }
1118
+ };
1119
+ }
1120
+ function parseWinnerJson(winner, surface) {
1121
+ try {
1122
+ return JSON.parse(winner);
1123
+ } catch (cause) {
1124
+ throw new ConfigError(
1125
+ `improve(): the '${surface}' candidate is not valid JSON, so it cannot form a profile candidate: ${cause.message}`
1126
+ );
1127
+ }
1128
+ }
1129
+ function assertCandidateSurfaceKind(surface, winner) {
1130
+ if (surface === "code" ? typeof winner === "string" : typeof winner !== "string") {
1131
+ throw new ConfigError(
1132
+ `improve(): the '${surface}' candidate returned an incompatible surface value`
1133
+ );
1134
+ }
1135
+ }
1136
+ function materializeImprovementProfileCandidate(profile, surface, winner, skills) {
1137
+ if (typeof winner !== "string") return void 0;
1138
+ let candidate;
1139
+ switch (surface) {
1140
+ case "prompt":
1141
+ candidate = { ...profile, prompt: { ...profile.prompt, systemPrompt: winner } };
1142
+ break;
1143
+ case "skills": {
1144
+ const selectedSkill = inlineSkill(profile, skills);
1145
+ candidate = {
1146
+ ...profile,
1147
+ resources: {
1148
+ ...profile.resources,
1149
+ skills: profile.resources?.skills?.map(
1150
+ (resource) => resource === selectedSkill ? { ...resource, content: winner } : resource
1151
+ )
1152
+ }
1153
+ };
1154
+ break;
1155
+ }
1156
+ case "tools":
1157
+ candidate = { ...profile, tools: parseWinnerJson(winner, surface) };
1158
+ break;
1159
+ case "mcp":
1160
+ candidate = { ...profile, mcp: parseWinnerJson(winner, surface) };
1161
+ break;
1162
+ case "hooks":
1163
+ candidate = { ...profile, hooks: parseWinnerJson(winner, surface) };
1164
+ break;
1165
+ case "subagents":
1166
+ candidate = { ...profile, subagents: parseWinnerJson(winner, surface) };
1167
+ break;
1168
+ case "agent-profile":
1169
+ candidate = parseWinnerJson(winner, surface);
1170
+ break;
1171
+ case "memory":
1172
+ candidate = {
1173
+ ...profile,
1174
+ resources: {
1175
+ ...profile.resources,
1176
+ instructions: replaceProfileInstructions(profile, winner)
1177
+ }
1178
+ };
1179
+ break;
1180
+ case "code":
1181
+ return void 0;
1182
+ }
1183
+ const parsed = agentProfileSchema.safeParse(candidate);
1184
+ if (!parsed.success) {
1185
+ throw new ConfigError(
1186
+ `improve(): the '${surface}' candidate does not produce a valid AgentProfile: ${parsed.error.message}`
1187
+ );
1188
+ }
1189
+ return immutableCandidateValue(parsed.data);
1190
+ }
1191
+ function inlineSkill(profile, options) {
1192
+ const resourceName = options?.resourceName.trim();
1193
+ if (!resourceName) {
1194
+ throw new ConfigError(
1195
+ "improve(): surface 'skills' requires opts.skills.resourceName for one inline profile skill"
1196
+ );
1197
+ }
1198
+ assertFailClosedResources(profile, "skills");
1199
+ const matches = (profile.resources?.skills ?? []).filter(
1200
+ (resource) => resource.name === resourceName
1201
+ );
1202
+ if (matches.length !== 1 || matches[0]?.kind !== "inline") {
1203
+ throw new ConfigError(
1204
+ `improve(): skill '${resourceName}' must identify exactly one inline profile resource`
1205
+ );
1206
+ }
1207
+ return matches[0];
1208
+ }
1209
+ function profileInstructions(profile) {
1210
+ assertFailClosedResources(profile, "memory");
1211
+ const instructions = profile.resources?.instructions;
1212
+ if (instructions === void 0) return "";
1213
+ if (typeof instructions === "string") return instructions;
1214
+ if (instructions.kind === "inline") return instructions.content;
1215
+ throw new ConfigError(
1216
+ "improve(): surface 'memory' requires inline profile instructions so candidate bytes are exact"
1217
+ );
1218
+ }
1219
+ function replaceProfileInstructions(profile, content) {
1220
+ const instructions = profile.resources?.instructions;
1221
+ if (typeof instructions !== "object") return content;
1222
+ if (instructions.kind !== "inline") {
1223
+ throw new ConfigError(
1224
+ "improve(): surface 'memory' requires inline profile instructions so candidate bytes are exact"
1225
+ );
1226
+ }
1227
+ return { ...instructions, content };
1228
+ }
1229
+ function assertFailClosedResources(profile, surface) {
1230
+ if (profile.resources?.failOnError !== true) {
1231
+ throw new ConfigError(
1232
+ `improve(): surface '${surface}' requires profile.resources.failOnError: true`
1233
+ );
1234
+ }
1235
+ }
1236
+ async function improve(profile, findings, opts) {
1237
+ const {
1238
+ surface = "prompt",
1239
+ gate = "holdout",
1240
+ generator,
1241
+ allowedModels,
1242
+ rawTraceContext,
1243
+ code,
1244
+ skills,
1245
+ promotionGate,
1246
+ analyzeGeneration,
1247
+ ...sharedOptions
1248
+ } = opts;
1249
+ const parsedProfile = agentProfileSchema.safeParse(profile);
1250
+ if (!parsedProfile.success) {
1251
+ throw new ConfigError(
1252
+ `improve(): input is not a valid AgentProfile: ${parsedProfile.error.message}`
1253
+ );
1254
+ }
1255
+ if (surface === "code" && generator) {
1256
+ throw new ConfigError(
1257
+ "improve(): surface 'code' forbids opts.generator because an external SurfaceProposer cannot transfer checkout ownership; pass opts.code.generator instead"
1258
+ );
1259
+ }
1260
+ const usesReflectionModel = !generator && (surface === "prompt" || surface === "skills");
1261
+ if (usesReflectionModel) {
1262
+ assertModelAllowed(sharedOptions.llm?.model ?? defaultReflectionModel, allowedModels);
1263
+ }
1264
+ let preparedCode;
1265
+ if (surface === "code") {
1266
+ if (!code) {
1267
+ throw new ConfigError(
1268
+ "improve(): surface 'code' requires opts.code.repoRoot so the incumbent can run from an isolated checkout"
1269
+ );
1270
+ }
1271
+ preparedCode = await prepareCodeRun(code);
1272
+ }
1273
+ const proposer = preparedCode?.proposer ?? generator ?? defaultGeneratorFor(surface, sharedOptions.llm);
1274
+ if (!proposer) {
1275
+ throw new ConfigError(
1276
+ `improve(): surface '${surface}' has no default generator \u2014 pass opts.generator (a SurfaceProposer) explicitly`
1277
+ );
1278
+ }
1279
+ const budget = gate === "none" ? { ...sharedOptions.budget, generations: 0 } : { ...sharedOptions.budget };
1280
+ let raw;
1281
+ try {
1282
+ raw = await selfImprove({
1283
+ ...sharedOptions,
1284
+ baselineSurface: preparedCode?.baseline ?? baselineSurfaceFor(parsedProfile.data, surface, skills),
1285
+ proposer,
1286
+ budget,
1287
+ findings,
1288
+ ...promotionGate !== void 0 ? { gate: promotionGate } : {},
1289
+ ...analyzeGeneration === null ? {} : {
1290
+ analyzeGeneration: analyzeGeneration ?? (rawTraceContext ? rawTraceDistiller({ fallbackFindings: findings }) : surface === "memory" ? memoryGenerationDistiller(findings) : generationFailureDistiller(findings))
1291
+ }
1292
+ });
1293
+ } catch (cause) {
1294
+ if (!preparedCode) throw cause;
1295
+ return rethrowAfterCleanup(
1296
+ cause,
1297
+ () => preparedCode.cleanup(),
1298
+ "improve(): code improvement failed"
1299
+ );
1300
+ }
1301
+ const winnerSurface = raw.winner.surface;
1302
+ assertCandidateSurfaceKind(surface, winnerSurface);
1303
+ if (preparedCode) {
1304
+ try {
1305
+ await preparedCode.cleanup(winnerSurface);
1306
+ } catch (cleanupCause) {
1307
+ try {
1308
+ await preparedCode.cleanup();
1309
+ } catch (finalCleanupCause) {
1310
+ throw new AggregateError(
1311
+ [cleanupCause, finalCleanupCause],
1312
+ "improve(): code result cleanup failed, including the final all-worktree retry"
1313
+ );
1314
+ }
1315
+ throw new AggregateError(
1316
+ [cleanupCause],
1317
+ "improve(): code result cleanup failed; the final all-worktree retry succeeded"
1318
+ );
1319
+ }
1320
+ }
1321
+ const dispose = idempotentDispose(async () => preparedCode?.cleanup());
1322
+ const candidateProfile = materializeImprovementProfileCandidate(
1323
+ parsedProfile.data,
1324
+ surface,
1325
+ winnerSurface,
1326
+ skills
1327
+ );
1328
+ const candidate = immutableCandidateValue({
1329
+ surface,
1330
+ value: winnerSurface,
1331
+ ...candidateProfile ? { profile: candidateProfile } : {}
1332
+ });
1333
+ return {
1334
+ candidate,
1335
+ decision: raw.gateDecision,
1336
+ lift: raw.lift,
1337
+ raw,
1338
+ dispose
1339
+ };
1340
+ }
1341
+
1342
+ // src/intelligence/improvement-surfaces.ts
1343
+ var changedSurfaceOrder = [
1344
+ "prompt",
1345
+ "skills",
1346
+ "tools",
1347
+ "mcp",
1348
+ "hooks",
1349
+ "subagents",
1350
+ "agent-profile",
1351
+ "memory",
1352
+ "code",
1353
+ "knowledge"
1354
+ ];
1355
+ function deriveChangedSurfaces(baselineBundle, candidateBundle) {
1356
+ if (baselineBundle.knowledge || candidateBundle.knowledge) {
1357
+ assertKnowledgeCandidatePair(baselineBundle, candidateBundle);
1358
+ }
1359
+ assertCodeCandidatePair(baselineBundle, candidateBundle);
1360
+ const baseline = improvementSurfaceValues(baselineBundle);
1361
+ const candidate = improvementSurfaceValues(candidateBundle);
1362
+ const changed = changedSurfaceOrder.filter(
1363
+ (surface) => canonicalCandidateDigest(baseline[surface]) !== canonicalCandidateDigest(candidate[surface])
1364
+ );
1365
+ if (changed.length === 0) throw new Error("candidate experiment does not change an agent surface");
1366
+ return changed;
1367
+ }
1368
+ function assertAgentImprovementActivationTargets(surfaces, experiment, intent, targets) {
1369
+ const expected = new Set(surfaces);
1370
+ const actual = new Set(targets.map((target) => target.surface));
1371
+ const sourceArm = intent === "activate-candidate" ? "baseline" : "candidate";
1372
+ if (targets.some((target) => !target.identity.trim()) || targets.some(
1373
+ (target) => target.expectedBaseDigest !== agentImprovementTargetDigest(experiment, sourceArm, target.surface)
1374
+ ) || targets.length !== surfaces.length || expected.size !== actual.size || [...expected].some((surface) => !actual.has(surface))) {
1375
+ throw new Error("candidate activation targets must cover exactly the changed surfaces");
1376
+ }
1377
+ }
1378
+ function buildAgentImprovementActivationTargets(surfaces, experiment, intent, identities) {
1379
+ const sourceArm = intent === "activate-candidate" ? "baseline" : "candidate";
1380
+ const targets = identities.map((target) => ({
1381
+ ...target,
1382
+ expectedBaseDigest: agentImprovementTargetDigest(experiment, sourceArm, target.surface)
1383
+ }));
1384
+ assertAgentImprovementActivationTargets(surfaces, experiment, intent, targets);
1385
+ return targets;
1386
+ }
1387
+ function agentImprovementTargetDigest(experiment, arm, surface) {
1388
+ if (surface === "knowledge") {
1389
+ const knowledge = assertKnowledgeCandidatePair(experiment.baseline, experiment.candidate);
1390
+ return arm === "baseline" ? knowledge.candidate.baseHash : knowledge.candidate.candidateHash;
1391
+ }
1392
+ if (surface === "code") assertCodeCandidatePair(experiment.baseline, experiment.candidate);
1393
+ return canonicalCandidateDigest(improvementSurfaceValues(experiment[arm])[surface]);
1394
+ }
1395
+ function assertKnowledgeCandidatePair(baselineBundle, candidateBundle) {
1396
+ const baseline = baselineBundle.knowledge;
1397
+ const candidate = candidateBundle.knowledge;
1398
+ if (!baseline && !candidate) {
1399
+ throw new Error("knowledge candidate pair is not present");
1400
+ }
1401
+ if (!baseline || !candidate || canonicalCandidateDigest({ candidate: baseline.candidate, evaluation: baseline.evaluation }) !== canonicalCandidateDigest({ candidate: candidate.candidate, evaluation: candidate.evaluation })) {
1402
+ throw new Error(
1403
+ "knowledge experiment arms must share one measured candidate and evaluation identity"
1404
+ );
1405
+ }
1406
+ return candidate;
1407
+ }
1408
+ function assertCodeCandidatePair(baselineBundle, candidateBundle) {
1409
+ const baseline = baselineBundle.code;
1410
+ const candidate = candidateBundle.code;
1411
+ if (canonicalCandidateDigest(baseline) === canonicalCandidateDigest(candidate) || candidate.kind !== "git-patch") {
1412
+ return;
1413
+ }
1414
+ const baselineTree = baseline.kind === "no-op" ? baseline.baseTree : baseline.kind === "git-patch" ? baseline.candidateTree : void 0;
1415
+ const baselineRepository = baseline.kind === "disabled" ? void 0 : baseline.repository;
1416
+ if (baselineTree !== candidate.baseTree || !baselineRepository || canonicalCandidateDigest(baselineRepository) !== canonicalCandidateDigest(candidate.repository)) {
1417
+ throw new Error(
1418
+ "code candidate must be based on the exact repository tree measured by the baseline arm"
1419
+ );
1420
+ }
1421
+ }
1422
+ function improvementSurfaceValues(bundle) {
1423
+ const profile = agentCandidateProfileAsAgentProfile(bundle.profile);
1424
+ return {
1425
+ prompt: {
1426
+ prompt: profile.prompt ?? null
1427
+ },
1428
+ skills: profile.resources?.skills ?? null,
1429
+ tools: {
1430
+ tools: profile.tools ?? null,
1431
+ resources: profile.resources?.tools ?? null
1432
+ },
1433
+ mcp: profile.mcp ?? null,
1434
+ hooks: profile.hooks ?? null,
1435
+ subagents: {
1436
+ subagents: profile.subagents ?? null,
1437
+ resources: profile.resources?.agents ?? null
1438
+ },
1439
+ "agent-profile": { profile: opaqueProfileSlice(profile), execution: bundle.execution },
1440
+ memory: {
1441
+ instructions: profile.resources?.instructions ?? null,
1442
+ executionPolicy: bundle.memory
1443
+ },
1444
+ code: bundle.code,
1445
+ knowledge: bundle.knowledge ?? null
1446
+ };
1447
+ }
1448
+ function opaqueProfileSlice(profile) {
1449
+ const {
1450
+ prompt: _prompt,
1451
+ tools: _tools,
1452
+ mcp: _mcp,
1453
+ hooks: _hooks,
1454
+ subagents: _subagents,
1455
+ resources,
1456
+ ...opaqueProfile
1457
+ } = profile;
1458
+ const {
1459
+ instructions: _instructions,
1460
+ skills: _skills,
1461
+ tools: _resourceTools,
1462
+ agents: _agents,
1463
+ ...opaqueResources
1464
+ } = resources ?? {};
1465
+ return {
1466
+ ...opaqueProfile,
1467
+ ...Object.keys(opaqueResources).length > 0 ? { resources: opaqueResources } : {}
1468
+ };
1469
+ }
1470
+
1471
+ // src/intelligence/improvement-cycle.ts
1472
+ import { assertNoJudgeVerdict } from "@tangle-network/agent-eval/analyst";
1473
+ import {
1474
+ measuredComparisonFromCandidateExperiment,
1475
+ runCandidateExperiment,
1476
+ verifyCandidateExperiment,
1477
+ verifyCandidateExperimentComparison
1478
+ } from "@tangle-network/agent-eval/contract";
1479
+ import {
1480
+ agentCandidateMaterializationReceiptSchema,
1481
+ agentCandidateRunReceiptSchema,
1482
+ agentImprovementActivationSchema,
1483
+ agentImprovementProposalSchema,
1484
+ agentImprovementReviewSchema,
1485
+ candidateExecutionEvidenceSchema
1486
+ } from "@tangle-network/agent-interface";
1487
+ import { materializeCandidateProfile } from "@tangle-network/agent-profile-materialize";
1488
+ var AgentCandidateExperimentCellExecutionError = class extends Error {
1489
+ finalization;
1490
+ constructor(finalization) {
1491
+ super(`candidate experiment cell failed: ${finalization.reason}`);
1492
+ this.name = "AgentCandidateExperimentCellExecutionError";
1493
+ this.finalization = finalization;
1494
+ }
1495
+ };
1496
+ async function runAgentCandidateExperiment(options) {
1497
+ const experiment = verifyCandidateExperiment(options.experiment);
1498
+ const measurements = await runCandidateExperiment({
1499
+ experiment,
1500
+ ...options.maxConcurrency === void 0 ? {} : { maxConcurrency: options.maxConcurrency },
1501
+ ...options.signal ? { signal: options.signal } : {},
1502
+ execute: async (input) => {
1503
+ const placement = await options.placeCell(input);
1504
+ return await executeAgentCandidateExperimentCell({ ...input, ...placement });
1505
+ }
1506
+ });
1507
+ const evaluation = createAgentImprovementMeasuredComparison({
1508
+ experiment,
1509
+ measurements,
1510
+ runId: options.runId,
1511
+ ...options.candidate ? { candidate: options.candidate } : {},
1512
+ ...options.generationsExplored === void 0 ? {} : { generationsExplored: options.generationsExplored },
1513
+ ...options.searchDurationMs === void 0 ? {} : { searchDurationMs: options.searchDurationMs },
1514
+ ...options.searchCostUsd === void 0 ? {} : { searchCostUsd: options.searchCostUsd },
1515
+ ...options.metadata ? { metadata: options.metadata } : {}
1516
+ });
1517
+ return { experiment, measurements, evaluation };
1518
+ }
1519
+ async function executeAgentCandidateExperimentCell(options) {
1520
+ const experiment = verifyCandidateExperiment(options.experiment);
1521
+ const bundle = experiment[options.arm];
1522
+ assertExactExperimentInput(options, experiment, bundle);
1523
+ const attempt = options.attempt ?? 1;
1524
+ if (attempt > options.task.attempt.maxAttempts) {
1525
+ throw new Error("candidate experiment attempt exceeds the signed task policy");
1526
+ }
1527
+ const runCell = canonicalCandidateDocument({
1528
+ kind: "agent-candidate-run-cell",
1529
+ experimentDigest: experiment.digest,
1530
+ arm: options.arm,
1531
+ bundleDigest: bundle.digest,
1532
+ suiteDigest: options.benchmarkCell.suiteDigest,
1533
+ taskDigest: options.task.digest,
1534
+ taskIndex: options.benchmarkCell.taskIndex,
1535
+ repetition: options.benchmarkCell.repetition,
1536
+ seed: options.seed,
1537
+ attempt
1538
+ }).value;
1539
+ const verified = await verifyAgentCandidateBundle(bundle, options.ports);
1540
+ const prepared = await prepareAgentCandidateExecution(
1541
+ verified,
1542
+ {
1543
+ executionId: options.executionId,
1544
+ runCell,
1545
+ benchmarkSuite: experiment.benchmark.suite,
1546
+ task: options.task,
1547
+ executionRoots: options.executionRoots,
1548
+ stagingRoots: options.stagingRoots
1549
+ },
1550
+ options.ports,
1551
+ options.preparation
1552
+ );
1553
+ const finalization = await executePreparedAgentCandidate(prepared, options.execution);
1554
+ if (!finalization.succeeded) {
1555
+ throw new AgentCandidateExperimentCellExecutionError(finalization);
1556
+ }
1557
+ const evidence = canonicalCandidateDocument({
1558
+ kind: "agent-candidate-execution-evidence",
1559
+ materializationReceipt: prepared.materializationReceipt.value,
1560
+ receipt: finalization.receipt.value
1561
+ }).value;
1562
+ return verifyCandidateExecutionEvidence(evidence, {
1563
+ experiment,
1564
+ arm: options.arm,
1565
+ benchmarkCell: options.benchmarkCell,
1566
+ seed: options.seed,
1567
+ attempt,
1568
+ resolvedResources: verifiedResourceTextByDigest(verified)
1569
+ });
1570
+ }
1571
+ function createAgentImprovementMeasuredComparison(options) {
1572
+ return verifyCandidateExperimentComparison(measuredComparisonFromCandidateExperiment(options));
1573
+ }
1574
+ async function proposeAgentImprovement(options) {
1575
+ const analysis = await runAnalystLoop({ ...options.analysis, runId: options.runId });
1576
+ const findings = assertNoJudgeVerdict(
1577
+ analysis.analystResult.findings,
1578
+ "proposeAgentImprovement findings"
1579
+ );
1580
+ const improvement = await improve(options.profile, [...findings], options.improvement);
1581
+ try {
1582
+ if (improvement.decision !== "ship") {
1583
+ throw new Error("agent improvement search did not produce a promotable candidate");
1584
+ }
1585
+ const experiment = verifyCandidateExperiment(
1586
+ await options.buildExperiment({ analysis, improvement })
1587
+ );
1588
+ assertCandidateProfileBinding(options.profile, experiment.baseline.profile);
1589
+ assertImprovementCandidateBinding(improvement, experiment);
1590
+ const measured = await runAgentCandidateExperiment({
1591
+ experiment,
1592
+ runId: options.runId,
1593
+ placeCell: options.placeCell,
1594
+ ...options.maxConcurrency === void 0 ? {} : { maxConcurrency: options.maxConcurrency },
1595
+ ...options.signal ? { signal: options.signal } : {},
1596
+ ...options.candidate ? { candidate: options.candidate } : {},
1597
+ ...options.metadata ? { metadata: options.metadata } : {},
1598
+ generationsExplored: improvement.raw.generationsExplored,
1599
+ searchDurationMs: improvement.raw.durationMs,
1600
+ searchCostUsd: improvement.raw.totalCostUsd
1601
+ });
1602
+ const proposal = createAgentImprovementProposal({
1603
+ runId: options.runId,
1604
+ findings,
1605
+ evaluation: measured.evaluation,
1606
+ ...options.now ? { now: options.now } : {}
1607
+ });
1608
+ return {
1609
+ analysis,
1610
+ improvement,
1611
+ experiment,
1612
+ measurements: measured.measurements,
1613
+ proposal
1614
+ };
1615
+ } catch (cause) {
1616
+ return rethrowAfterCleanup(cause, () => improvement.dispose(), "proposeAgentImprovement failed");
1617
+ }
1618
+ }
1619
+ function assertImprovementCandidateBinding(improvement, experiment) {
1620
+ const candidate = improvement.candidate;
1621
+ if (candidate.surface !== "code") {
1622
+ if (!candidate.profile) {
1623
+ throw new Error(`improvement surface '${candidate.surface}' did not produce an exact profile`);
1624
+ }
1625
+ try {
1626
+ assertCandidateProfileBinding(candidate.profile, experiment.candidate.profile);
1627
+ } catch (cause) {
1628
+ throw new Error("candidate experiment does not contain the improvement winner", { cause });
1629
+ }
1630
+ return;
1631
+ }
1632
+ const surface = candidate.value;
1633
+ const code = experiment.candidate.code;
1634
+ if (typeof surface !== "object" || surface === null || surface.kind !== "code" || code.kind !== "git-patch" || code.baseCommit !== surface.baseCommit || code.baseTree !== surface.baseTree || code.candidateTree !== surface.candidateTree || code.patch.artifact.sha256 !== surface.patch.sha256 || code.patch.artifact.byteLength !== surface.patch.byteLength) {
1635
+ throw new Error("candidate experiment does not contain the improvement winner");
1636
+ }
1637
+ if (canonicalCandidateDigest(experiment.baseline.profile) !== canonicalCandidateDigest(experiment.candidate.profile)) {
1638
+ throw new Error("code improvement candidate changed the agent profile");
1639
+ }
1640
+ }
1641
+ function createAgentImprovementProposal(options) {
1642
+ const findings = assertNoJudgeVerdict(
1643
+ [...options.findings],
1644
+ "createAgentImprovementProposal findings"
1645
+ );
1646
+ const evaluation = verifyCandidateExperimentComparison(options.evaluation);
1647
+ if (evaluation.decision.outcome !== "ship") {
1648
+ throw new Error("agent improvement proposal requires a passing experiment");
1649
+ }
1650
+ if (options.runId !== evaluation.provenance.runId) {
1651
+ throw new Error("proposal runId does not match its measured experiment");
1652
+ }
1653
+ const changedSurfaces = deriveChangedSurfaces(
1654
+ evaluation.experiment.baseline,
1655
+ evaluation.experiment.candidate
1656
+ );
1657
+ return agentImprovementProposalSchema.parse(
1658
+ canonicalCandidateDocument({
1659
+ kind: "agent-improvement-proposal",
1660
+ runId: options.runId,
1661
+ changedSurfaces,
1662
+ proposedAt: (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
1663
+ findings: [...findings],
1664
+ evaluation
1665
+ }).value
1666
+ );
1667
+ }
1668
+ function reviewAgentImprovementProposal(inputProposal, input) {
1669
+ const proposal = verifyAgentImprovementProposal(inputProposal);
1670
+ if (!input.reviewedBy.trim()) throw new Error("candidate review requires reviewedBy");
1671
+ if (!input.reason.trim()) throw new Error("candidate review requires a reason");
1672
+ if (input.decision === "approve" && proposal.evaluation.decision.outcome !== "ship") {
1673
+ throw new Error("candidate cannot be approved without a passing experiment");
1674
+ }
1675
+ const reviewedAt = (input.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
1676
+ if (Date.parse(reviewedAt) < Date.parse(proposal.proposedAt)) {
1677
+ throw new Error("candidate review cannot predate its proposal");
1678
+ }
1679
+ return agentImprovementReviewSchema.parse(
1680
+ canonicalCandidateDocument({
1681
+ kind: "agent-improvement-review",
1682
+ proposalDigest: proposal.digest,
1683
+ decision: input.decision,
1684
+ reviewedBy: input.reviewedBy,
1685
+ reviewedAt,
1686
+ reason: input.reason,
1687
+ ...input.feedback === void 0 ? {} : { feedback: input.feedback }
1688
+ }).value
1689
+ );
1690
+ }
1691
+ function createAgentImprovementActivation(inputProposal, inputReview, options) {
1692
+ const proposal = verifyAgentImprovementProposal(inputProposal);
1693
+ const review = verifyAgentImprovementReview(inputReview);
1694
+ if (review.decision !== "approve" || review.proposalDigest !== proposal.digest) {
1695
+ throw new Error("candidate activation requires an approval for the exact proposal");
1696
+ }
1697
+ if (!options.fundingOwner.trim() || !options.authorizedBy.trim()) {
1698
+ throw new Error("candidate activation authority must be non-empty");
1699
+ }
1700
+ const experiment = proposal.evaluation.experiment;
1701
+ const authorizedAt = (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
1702
+ if (Date.parse(authorizedAt) < Date.parse(review.reviewedAt)) {
1703
+ throw new Error("candidate activation cannot predate its approval");
1704
+ }
1705
+ const targets = buildAgentImprovementActivationTargets(
1706
+ proposal.changedSurfaces,
1707
+ experiment,
1708
+ options.intent,
1709
+ options.targets
1710
+ );
1711
+ return agentImprovementActivationSchema.parse(
1712
+ canonicalCandidateDocument({
1713
+ kind: "agent-improvement-activation",
1714
+ proposalDigest: proposal.digest,
1715
+ reviewDigest: review.digest,
1716
+ experimentDigest: experiment.digest,
1717
+ candidateBundleDigest: experiment.candidate.digest,
1718
+ intent: options.intent,
1719
+ targets,
1720
+ fundingOwner: options.fundingOwner,
1721
+ authorizedBy: options.authorizedBy,
1722
+ authorizedAt,
1723
+ expiresAt: options.expiresAt
1724
+ }).value
1725
+ );
1726
+ }
1727
+ function verifyAgentImprovementProposal(input) {
1728
+ const proposal = verifyCanonicalCandidateDocument(
1729
+ agentImprovementProposalSchema.parse(input),
1730
+ "agent improvement proposal"
1731
+ );
1732
+ const evaluation = verifyCandidateExperimentComparison(proposal.evaluation);
1733
+ if (evaluation.decision.outcome !== "ship") {
1734
+ throw new Error("agent improvement proposal does not contain a passing experiment");
1735
+ }
1736
+ if (proposal.runId !== evaluation.provenance.runId) {
1737
+ throw new Error("proposal runId does not match its measured experiment");
1738
+ }
1739
+ const changedSurfaces = deriveChangedSurfaces(
1740
+ evaluation.experiment.baseline,
1741
+ evaluation.experiment.candidate
1742
+ );
1743
+ if (!sameOrderedValues(proposal.changedSurfaces, changedSurfaces)) {
1744
+ throw new Error("proposal changed surfaces do not match its exact experiment");
1745
+ }
1746
+ assertNoJudgeDerivedProposalFindings(proposal.findings);
1747
+ return proposal;
1748
+ }
1749
+ function verifyAgentImprovementReview(input) {
1750
+ return verifyCanonicalCandidateDocument(
1751
+ agentImprovementReviewSchema.parse(input),
1752
+ "agent improvement review"
1753
+ );
1754
+ }
1755
+ function verifyAgentImprovementActivation(input) {
1756
+ const proposal = verifyAgentImprovementProposal(input.proposal);
1757
+ const review = verifyAgentImprovementReview(input.review);
1758
+ const activation = verifyCanonicalCandidateDocument(
1759
+ agentImprovementActivationSchema.parse(input.activation),
1760
+ "agent improvement activation"
1761
+ );
1762
+ const experiment = proposal.evaluation.experiment;
1763
+ if (review.decision !== "approve" || review.proposalDigest !== proposal.digest || activation.proposalDigest !== proposal.digest || activation.reviewDigest !== review.digest || activation.experimentDigest !== experiment.digest || activation.candidateBundleDigest !== experiment.candidate.digest || Date.parse(review.reviewedAt) < Date.parse(proposal.proposedAt) || Date.parse(activation.authorizedAt) < Date.parse(review.reviewedAt)) {
1764
+ throw new Error("candidate activation does not bind the measured and approved candidate");
1765
+ }
1766
+ assertAgentImprovementActivationTargets(
1767
+ proposal.changedSurfaces,
1768
+ experiment,
1769
+ activation.intent,
1770
+ activation.targets
1771
+ );
1772
+ return activation;
1773
+ }
1774
+ function verifyCandidateExecutionEvidence(input, options) {
1775
+ const experiment = verifyCandidateExperiment(options.experiment);
1776
+ const bundle = experiment[options.arm];
1777
+ const task = experiment.benchmark.tasks[options.benchmarkCell.taskIndex];
1778
+ const index = options.benchmarkCell.taskIndex * experiment.benchmark.suite.reps + options.benchmarkCell.repetition;
1779
+ if (!task || options.benchmarkCell.suiteDigest !== experiment.benchmark.suite.digest || options.seed !== experiment.benchmark.suite.seeds[index]) {
1780
+ throw new Error("candidate execution evidence points outside its signed experiment");
1781
+ }
1782
+ const evidence = verifyCanonicalCandidateDocument(
1783
+ candidateExecutionEvidenceSchema.parse(input),
1784
+ "candidate execution evidence"
1785
+ );
1786
+ const materialization = verifyCanonicalCandidateDocument(
1787
+ agentCandidateMaterializationReceiptSchema.parse(evidence.materializationReceipt),
1788
+ "candidate materialization receipt"
1789
+ );
1790
+ const receipt = verifyCanonicalCandidateDocument(
1791
+ agentCandidateRunReceiptSchema.parse(evidence.receipt),
1792
+ "candidate run receipt"
1793
+ );
1794
+ const plan = materialization.executionPlan;
1795
+ const cell = plan.material.runCell;
1796
+ const attempt = options.attempt ?? 1;
1797
+ if (cell.experimentDigest !== experiment.digest || cell.arm !== options.arm || cell.bundleDigest !== bundle.digest || cell.suiteDigest !== experiment.benchmark.suite.digest || cell.taskDigest !== task.digest || cell.taskIndex !== options.benchmarkCell.taskIndex || cell.repetition !== options.benchmarkCell.repetition || cell.seed !== options.seed || cell.attempt !== attempt || canonicalCandidateDigest(omitTopLevelDigest(cell)) !== cell.digest) {
1798
+ throw new Error("candidate execution receipt substituted its signed experiment cell");
1799
+ }
1800
+ assertCapturedInput(
1801
+ materialization.benchmark.suite,
1802
+ experiment.benchmark.suite,
1803
+ "benchmark suite"
1804
+ );
1805
+ assertCapturedInput(materialization.benchmark.task, task, "benchmark task");
1806
+ assertEvidenceMaterialDigest(plan, "candidate execution plan");
1807
+ assertEvidenceMaterialDigest(
1808
+ materialization.profileActivation.profilePlan,
1809
+ "candidate profile plan"
1810
+ );
1811
+ const expectedProfilePlan = materializeCandidateProfile(
1812
+ bundle.profile,
1813
+ candidateMaterializerHarness(materialization.harness),
1814
+ { resolvedResources: options.resolvedResources }
1815
+ );
1816
+ const activation = parseAgentCandidateProfileActivation(
1817
+ materialization.profileActivation,
1818
+ materialization.profileActivation.profilePlan.digest
1819
+ );
1820
+ const regeneratedActivation = createAgentCandidateProfileActivation(
1821
+ expectedProfilePlan,
1822
+ materialization.profileActivation.profilePlan
1823
+ );
1824
+ if (activation.digest !== regeneratedActivation.digest) {
1825
+ throw new Error("candidate profile activation does not match the experiment bundle");
1826
+ }
1827
+ if (materialization.bundleDigest !== bundle.digest || receipt.bundleDigest !== bundle.digest || receipt.runCellDigest !== cell.digest || receipt.materializationReceiptDigest !== materialization.digest || receipt.executionPlanDigest !== plan.digest) {
1828
+ throw new Error("candidate execution evidence does not bind one exact Runtime run");
1829
+ }
1830
+ assertEvidenceMaterialDigest(receipt.modelSettlement, "candidate model settlement");
1831
+ assertEvidenceMaterialDigest(receipt.taskOutcome, "candidate task outcome");
1832
+ assertEvidenceMaterialDigest(receipt.benchmarkResult, "candidate benchmark result");
1833
+ return immutableCandidateValue(evidence);
1834
+ }
1835
+ function assertExactExperimentInput(input, experiment, bundle) {
1836
+ const task = experiment.benchmark.tasks[input.benchmarkCell.taskIndex];
1837
+ const index = input.benchmarkCell.taskIndex * experiment.benchmark.suite.reps + input.benchmarkCell.repetition;
1838
+ if (input.experiment.digest !== experiment.digest || input.bundle.digest !== bundle.digest || !task || input.task.digest !== task.digest || input.benchmarkCell.suiteDigest !== experiment.benchmark.suite.digest || input.seed !== experiment.benchmark.suite.seeds[index]) {
1839
+ throw new Error("Runtime received a substituted candidate experiment cell");
1840
+ }
1841
+ }
1842
+ function assertCapturedInput(captured, expected, label) {
1843
+ const bytes = canonicalCandidateBytes(omitTopLevelDigest(expected));
1844
+ if (captured.digest !== expected.digest || captured.material.sha256 !== expected.digest || captured.material.byteLength !== bytes.byteLength) {
1845
+ throw new Error(`candidate materialization substituted its ${label}`);
1846
+ }
1847
+ }
1848
+ function assertEvidenceMaterialDigest(evidence, label) {
1849
+ const bytes = canonicalCandidateBytes(evidence.material);
1850
+ if (canonicalCandidateDigest(evidence.material) !== evidence.digest || evidence.artifact.sha256 !== evidence.digest || evidence.artifact.byteLength !== bytes.byteLength) {
1851
+ throw new Error(`${label} digest does not match its canonical material`);
1852
+ }
1853
+ }
1854
+ function sameOrderedValues(left, right) {
1855
+ return left.length === right.length && left.every((value, index) => value === right[index]);
1856
+ }
1857
+ function assertNoJudgeDerivedProposalFindings(findings) {
1858
+ const leaked = findings.filter((finding) => finding.derived_from_judge === true);
1859
+ if (leaked.length === 0) return;
1860
+ const identifiers = leaked.map(
1861
+ (finding) => typeof finding.finding_id === "string" ? finding.finding_id : "<unknown>"
1862
+ );
1863
+ throw new Error(
1864
+ `agent improvement proposal findings: judge-derived findings cannot steer an improvement: [${identifiers.join(", ")}]`
1865
+ );
1866
+ }
1867
+
1868
+ // src/intelligence/activation.ts
1869
+ import {
1870
+ agentImprovementActivationResultSchema,
1871
+ agentImprovementActivationSchema as agentImprovementActivationSchema2
1872
+ } from "@tangle-network/agent-interface";
1873
+ function createAgentImprovementActivationResult(transition, options) {
1874
+ const activation = verifyCanonicalCandidateDocument(
1875
+ agentImprovementActivationSchema2.parse(transition.activation),
1876
+ "agent improvement activation"
1877
+ );
1878
+ assertTransitionInput(activation, transition);
1879
+ const result = agentImprovementActivationResultSchema.parse(
1880
+ canonicalCandidateDocument({
1881
+ kind: "agent-improvement-activation-result",
1882
+ idempotencyKey: activation.digest,
1883
+ attemptedAt: transition.attemptedAt,
1884
+ completedAt: options.completedAt,
1885
+ outcome: options.outcome
1886
+ }).value
1887
+ );
1888
+ assertResultAgainstActivation(activation, result);
1889
+ assertOutcomeDesiredState(
1890
+ activation,
1891
+ result,
1892
+ new Map(transition.targets.map((target) => [targetIdentity(target), target.desiredDigest]))
1893
+ );
1894
+ return immutableCandidateValue(result);
1895
+ }
1896
+ function verifyAgentImprovementActivationResult(input) {
1897
+ const proposal = verifyAgentImprovementProposal(input.proposal);
1898
+ const activation = verifyAgentImprovementActivation(input);
1899
+ const result = verifyCanonicalCandidateDocument(
1900
+ agentImprovementActivationResultSchema.parse(input.result),
1901
+ "agent improvement activation result"
1902
+ );
1903
+ assertResultAgainstActivation(activation, result);
1904
+ assertResultDesiredState(proposal, activation, result);
1905
+ return result;
1906
+ }
1907
+ async function executeAgentImprovementActivation(input, options) {
1908
+ const proposal = verifyAgentImprovementProposal(input.proposal);
1909
+ const activation = verifyAgentImprovementActivation(input);
1910
+ const experiment = proposal.evaluation.experiment;
1911
+ const targetArm = activation.intent === "activate-candidate" ? "candidate" : "baseline";
1912
+ const observedAt = (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
1913
+ const attemptedAt = Date.parse(observedAt) < Date.parse(activation.authorizedAt) ? activation.authorizedAt : observedAt;
1914
+ const transition = immutableCandidateValue({
1915
+ activation,
1916
+ candidateBundle: experiment.candidate,
1917
+ bundle: experiment[targetArm],
1918
+ targets: activation.targets.map((target) => ({
1919
+ ...target,
1920
+ desiredDigest: agentImprovementTargetDigest(experiment, targetArm, target.surface)
1921
+ })),
1922
+ attemptedAt,
1923
+ expired: Date.parse(attemptedAt) >= Date.parse(activation.expiresAt)
1924
+ });
1925
+ if (transition.expired) {
1926
+ if (!options.reconcile) {
1927
+ return uncertainActivationResult(transition, "RECONCILIATION_UNAVAILABLE");
1928
+ }
1929
+ let reconciled;
1930
+ try {
1931
+ reconciled = await options.reconcile(transition);
1932
+ } catch {
1933
+ return uncertainActivationResult(transition, "RECONCILIATION_THROW");
1934
+ }
1935
+ if (reconciled === void 0) {
1936
+ return createAgentImprovementActivationResult(transition, {
1937
+ completedAt: transition.attemptedAt,
1938
+ outcome: { status: "expired" }
1939
+ });
1940
+ }
1941
+ try {
1942
+ return verifyAgentImprovementActivationResult({ ...input, result: reconciled });
1943
+ } catch {
1944
+ return uncertainActivationResult(transition, "INVALID_RECONCILIATION");
1945
+ }
1946
+ }
1947
+ let rawResult;
1948
+ try {
1949
+ rawResult = await options.transition(transition);
1950
+ } catch {
1951
+ return uncertainActivationResult(transition, "TRANSITION_THROW");
1952
+ }
1953
+ try {
1954
+ return verifyAgentImprovementActivationResult({ ...input, result: rawResult });
1955
+ } catch {
1956
+ return uncertainActivationResult(transition, "INVALID_RESULT");
1957
+ }
1958
+ }
1959
+ function uncertainActivationResult(transition, code) {
1960
+ return createAgentImprovementActivationResult(transition, {
1961
+ completedAt: transition.attemptedAt,
1962
+ outcome: {
1963
+ status: "indeterminate",
1964
+ code,
1965
+ message: "The product transition did not return a trustworthy commit result."
1966
+ }
1967
+ });
1968
+ }
1969
+ function assertTransitionInput(activation, transition) {
1970
+ const authorized = targetMap(activation.targets);
1971
+ const planned = targetMap(transition.targets);
1972
+ if (authorized.size !== planned.size || [...authorized.entries()].some(
1973
+ ([identity, target]) => planned.get(identity)?.expectedBaseDigest !== target.expectedBaseDigest
1974
+ ) || transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) || transition.candidateBundle.digest !== activation.candidateBundleDigest || activation.intent === "activate-candidate" && transition.bundle.digest !== transition.candidateBundle.digest) {
1975
+ throw new Error("activation transition does not match its authorization");
1976
+ }
1977
+ }
1978
+ function assertResultAgainstActivation(activation, result) {
1979
+ const attemptedAt = Date.parse(result.attemptedAt);
1980
+ const completedAt = Date.parse(result.completedAt);
1981
+ const expiresAt = Date.parse(activation.expiresAt);
1982
+ if (result.idempotencyKey !== activation.digest || attemptedAt < Date.parse(activation.authorizedAt) || completedAt < attemptedAt) {
1983
+ throw new Error("activation result does not bind its authorization");
1984
+ }
1985
+ const expired = attemptedAt >= expiresAt;
1986
+ if (result.outcome.status === "expired" && !expired || expired && !["expired", "indeterminate", "already-applied"].includes(result.outcome.status)) {
1987
+ throw new Error("activation result does not honor its authorization expiry");
1988
+ }
1989
+ if (!("targets" in result.outcome)) return;
1990
+ const authorized = targetMap(activation.targets);
1991
+ const observed = new Set(result.outcome.targets.map(targetIdentity));
1992
+ if (authorized.size !== observed.size || [...authorized.keys()].some((identity) => !observed.has(identity))) {
1993
+ throw new Error("activation result must cover every authorized target exactly once");
1994
+ }
1995
+ if (result.outcome.status === "applied" && result.outcome.targets.some(
1996
+ (target) => target.beforeDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest
1997
+ )) {
1998
+ throw new Error("applied activation did not start from its authorized base state");
1999
+ }
2000
+ }
2001
+ function assertResultDesiredState(proposal, activation, result) {
2002
+ if (!("targets" in result.outcome)) return;
2003
+ const experiment = proposal.evaluation.experiment;
2004
+ const targetArm = activation.intent === "activate-candidate" ? "candidate" : "baseline";
2005
+ const desired = new Map(
2006
+ activation.targets.map((target) => [
2007
+ targetIdentity(target),
2008
+ agentImprovementTargetDigest(experiment, targetArm, target.surface)
2009
+ ])
2010
+ );
2011
+ assertOutcomeDesiredState(activation, result, desired);
2012
+ }
2013
+ function assertOutcomeDesiredState(activation, result, desired) {
2014
+ if (!("targets" in result.outcome)) return;
2015
+ if (result.outcome.status === "applied") {
2016
+ if (result.outcome.targets.some(
2017
+ (target) => target.afterDigest !== desired.get(targetIdentity(target))
2018
+ )) {
2019
+ throw new Error("applied activation does not match the requested bundle");
2020
+ }
2021
+ return;
2022
+ }
2023
+ const allDesired = result.outcome.targets.every(
2024
+ (target) => target.currentDigest === desired.get(targetIdentity(target))
2025
+ );
2026
+ if (result.outcome.status === "already-applied") {
2027
+ if (!allDesired) throw new Error("already-applied activation is not at the requested state");
2028
+ return;
2029
+ }
2030
+ const authorized = targetMap(activation.targets);
2031
+ const hasStaleTarget = result.outcome.targets.some(
2032
+ (target) => target.currentDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest
2033
+ );
2034
+ if (allDesired || !hasStaleTarget) {
2035
+ throw new Error("activation conflict does not identify stale target state");
2036
+ }
2037
+ }
2038
+ function targetMap(targets) {
2039
+ return new Map(targets.map((target) => [targetIdentity(target), target]));
2040
+ }
2041
+ function targetIdentity(target) {
2042
+ return `${target.surface}\0${target.identity}`;
2043
+ }
2044
+
2045
+ export {
2046
+ AGENTIC_PROFILE_RESOURCE_ROOT,
2047
+ agenticGenerator,
2048
+ commandVerifier,
2049
+ improvementDriver,
2050
+ rawTraceDistiller,
2051
+ improve,
2052
+ buildAgentImprovementActivationTargets,
2053
+ AgentCandidateExperimentCellExecutionError,
2054
+ runAgentCandidateExperiment,
2055
+ executeAgentCandidateExperimentCell,
2056
+ createAgentImprovementMeasuredComparison,
2057
+ proposeAgentImprovement,
2058
+ createAgentImprovementProposal,
2059
+ reviewAgentImprovementProposal,
2060
+ createAgentImprovementActivation,
2061
+ verifyAgentImprovementProposal,
2062
+ verifyAgentImprovementReview,
2063
+ verifyAgentImprovementActivation,
2064
+ verifyCandidateExecutionEvidence,
2065
+ createAgentImprovementActivationResult,
2066
+ verifyAgentImprovementActivationResult,
2067
+ executeAgentImprovementActivation
2068
+ };
2069
+ //# sourceMappingURL=chunk-PSOCBNM3.js.map