@tangle-network/agent-runtime 0.337.2 → 0.338.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 (112) hide show
  1. package/dist/{activation-DRHM55Oo.d.ts → activation-CsbNax2X.d.ts} +92 -4
  2. package/dist/activation-kbkAuSmY.js +889 -0
  3. package/dist/activation-kbkAuSmY.js.map +1 -0
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +3 -6
  6. package/dist/agent.js.map +1 -1
  7. package/dist/{bundle-BPGjESee.js → bundle-DM60AI2B.js} +2 -2
  8. package/dist/{bundle-BPGjESee.js.map → bundle-DM60AI2B.js.map} +1 -1
  9. package/dist/candidate-execution/index.d.ts +2 -2
  10. package/dist/candidate-execution/index.js +4 -5
  11. package/dist/candidate-execution/index.js.map +1 -1
  12. package/dist/content-digest-sBTLujlK.js +9 -0
  13. package/dist/content-digest-sBTLujlK.js.map +1 -0
  14. package/dist/{delegate-B-T_ZB50.js → delegate-Se1YZKMb.js} +2 -2
  15. package/dist/{delegate-B-T_ZB50.js.map → delegate-Se1YZKMb.js.map} +1 -1
  16. package/dist/{coordination-driver-BHkFVqIq.js → driver-control-acknowledgers-T2a1Ouay.js} +4514 -4440
  17. package/dist/driver-control-acknowledgers-T2a1Ouay.js.map +1 -0
  18. package/dist/durable.d.ts +1 -1
  19. package/dist/durable.js +223 -227
  20. package/dist/durable.js.map +1 -1
  21. package/dist/{graph-C4RFlWAJ.js → graph-CY0wH838.js} +65 -18
  22. package/dist/graph-CY0wH838.js.map +1 -0
  23. package/dist/{graph-registry-DAI6KNXB.js → graph-registry-By0tUj4S.js} +16 -15
  24. package/dist/graph-registry-By0tUj4S.js.map +1 -0
  25. package/dist/{improvement-cycle-D1I4hQvf.js → improve-CWGBT13K.js} +75 -1220
  26. package/dist/improve-CWGBT13K.js.map +1 -0
  27. package/dist/index.d.ts +6 -6
  28. package/dist/index.js +10 -13
  29. package/dist/index.js.map +1 -1
  30. package/dist/{integrations-DopfCC2a.d.ts → integrations-6xttbPi9.d.ts} +3 -3
  31. package/dist/integrations-dFi-ALk7.js.map +1 -1
  32. package/dist/intelligence.d.ts +7 -94
  33. package/dist/intelligence.js +505 -13
  34. package/dist/intelligence.js.map +1 -1
  35. package/dist/kernel.d.ts +2 -2
  36. package/dist/kernel.js +13 -12
  37. package/dist/{loop-runner-bin-DOuBIJ2O.d.ts → loop-runner-bin-CFnrAHpl.d.ts} +2 -2
  38. package/dist/{loop-runner-bin-Dv5QvYDH.js → loop-runner-bin-CdPlhy9g.js} +3 -3
  39. package/dist/{loop-runner-bin-Dv5QvYDH.js.map → loop-runner-bin-CdPlhy9g.js.map} +1 -1
  40. package/dist/loop-runner-bin.d.ts +1 -1
  41. package/dist/loop-runner-bin.js +1 -1
  42. package/dist/mcp/bin.js +3 -3
  43. package/dist/mcp/bin.js.map +1 -1
  44. package/dist/mcp/index.d.ts +7 -3
  45. package/dist/mcp/index.js +6 -8
  46. package/dist/mcp/index.js.map +1 -1
  47. package/dist/{openai-tools-Oxk4KQrY.d.ts → openai-tools-zh2I_uD7.d.ts} +2 -2
  48. package/dist/platform.d.ts +7 -2
  49. package/dist/platform.js +16 -8
  50. package/dist/platform.js.map +1 -1
  51. package/dist/{prepare-CER-ZkPp.js → prepare-Bt0IouPq.js} +1241 -586
  52. package/dist/prepare-Bt0IouPq.js.map +1 -0
  53. package/dist/{profile-gNUsHNIJ.js → profile-Do-5xO_D.js} +89 -3
  54. package/dist/profile-Do-5xO_D.js.map +1 -0
  55. package/dist/profiles.d.ts +1 -1
  56. package/dist/profiles.js +1 -3
  57. package/dist/profiles.js.map +1 -1
  58. package/dist/{protected-model-port-BhpQRTw-.d.ts → protected-model-port-DGxQ8_YM.d.ts} +3 -3
  59. package/dist/{provision-supervisor-DGegCUH4.js → provision-supervisor-0jMufp4h.js} +12 -9
  60. package/dist/provision-supervisor-0jMufp4h.js.map +1 -0
  61. package/dist/record-value-B6bwJxLa.js +12 -0
  62. package/dist/record-value-B6bwJxLa.js.map +1 -0
  63. package/dist/{run-layout-Cu8H7aeh.js → run-cancellation-BoW5Sg9Y.js} +174 -95
  64. package/dist/run-cancellation-BoW5Sg9Y.js.map +1 -0
  65. package/dist/{runtime-BOGpotnH.js → runtime-D37zRSs7.js} +431 -621
  66. package/dist/runtime-D37zRSs7.js.map +1 -0
  67. package/dist/{sandbox-profile-compat-QTkLe1Z6.js → sandbox-profile-compat-xSoVtdWw.js} +690 -697
  68. package/dist/sandbox-profile-compat-xSoVtdWw.js.map +1 -0
  69. package/dist/search-executor-DmgUm5p7.js +1916 -0
  70. package/dist/search-executor-DmgUm5p7.js.map +1 -0
  71. package/dist/{server-hZWM-G8w.js → server-DQHJszfk.js} +4 -4
  72. package/dist/server-DQHJszfk.js.map +1 -0
  73. package/dist/{search-executor-Cm1WZmL-.js → structural-rollout-DAvIE8mw.js} +2261 -3984
  74. package/dist/structural-rollout-DAvIE8mw.js.map +1 -0
  75. package/dist/{supervise-CvAKVfue.js → supervise-WuPAwfPh.js} +7793 -5338
  76. package/dist/supervise-WuPAwfPh.js.map +1 -0
  77. package/dist/{supervisor-Rz8AGpYb.js → supervisor-CPG1I9UN.js} +26590 -27196
  78. package/dist/supervisor-CPG1I9UN.js.map +1 -0
  79. package/dist/testing.d.ts +226 -1
  80. package/dist/testing.js +13 -14
  81. package/dist/testing.js.map +1 -1
  82. package/dist/{top-app-BaMw1W2z.js → top-app-C55Wa7uy.js} +339 -337
  83. package/dist/top-app-C55Wa7uy.js.map +1 -0
  84. package/dist/tui/bin.js +1 -1
  85. package/dist/tui/index.d.ts +17 -15
  86. package/dist/tui/index.js +2 -2
  87. package/dist/{types-Dl5L4r8Z.d.ts → types-CrNWif8-.d.ts} +17410 -17173
  88. package/dist/{workspace-streams-JLjh5DC6.d.ts → workspace-streams-BZZds1Fw.d.ts} +18 -16
  89. package/package.json +2 -2
  90. package/skills/agent-graphs/SKILL.md +10 -3
  91. package/skills/agent-graphs/references/authoring.md +17 -0
  92. package/skills/profile-authoring/SKILL.md +3 -3
  93. package/skills/supervise/SKILL.md +2 -2
  94. package/dist/activation-BDP6Eivv.js +0 -234
  95. package/dist/activation-BDP6Eivv.js.map +0 -1
  96. package/dist/coordination-driver-BHkFVqIq.js.map +0 -1
  97. package/dist/graph-C4RFlWAJ.js.map +0 -1
  98. package/dist/graph-registry-DAI6KNXB.js.map +0 -1
  99. package/dist/improvement-cycle-D1I4hQvf.js.map +0 -1
  100. package/dist/prepare-CER-ZkPp.js.map +0 -1
  101. package/dist/profile-gNUsHNIJ.js.map +0 -1
  102. package/dist/protected-model-port-BuRsviSL.js +0 -766
  103. package/dist/protected-model-port-BuRsviSL.js.map +0 -1
  104. package/dist/provision-supervisor-DGegCUH4.js.map +0 -1
  105. package/dist/run-layout-Cu8H7aeh.js.map +0 -1
  106. package/dist/runtime-BOGpotnH.js.map +0 -1
  107. package/dist/sandbox-profile-compat-QTkLe1Z6.js.map +0 -1
  108. package/dist/search-executor-Cm1WZmL-.js.map +0 -1
  109. package/dist/server-hZWM-G8w.js.map +0 -1
  110. package/dist/supervise-CvAKVfue.js.map +0 -1
  111. package/dist/supervisor-Rz8AGpYb.js.map +0 -1
  112. package/dist/top-app-BaMw1W2z.js.map +0 -1
@@ -1,14 +1,14 @@
1
1
  import { a as syncDurableDirectory, i as publishExclusiveDurableFile } from "./durable-file-B_eJr6Mb.js";
2
- import { Qn as runAbortable, Ur as terminateProcessTreeAndConfirm, Zn as linkAbort, ga as detachedSnapshot, jr as runSettledCommand, pt as createExecutor } from "./supervisor-Rz8AGpYb.js";
2
+ import { Jr as runSettledCommand, Ur as linkAbort, Wr as runAbortable, bt as createExecutor, oi as terminateProcessTreeAndConfirm, sa as detachedSnapshot } from "./supervisor-CPG1I9UN.js";
3
3
  import { i as ConfigError } from "./errors-DodWX-cb.js";
4
- import { E as defaultStructuralRolloutPolicy, Q as streamAgentTurn, Y as optimizerMethod, Z as collectAgentTurn, a as reconcileInterruptedSearchCalls, b as improveSearchCost, c as searchExecutor, d as taggedLedger, i as isSearchEnvironmentFault, n as assertSearchLanes, s as searchCallTags, v as decideClosedSearch } from "./search-executor-Cm1WZmL-.js";
5
- import { B as omitTopLevelDigest, Ct as armDeadlineTimer, F as canonicalCandidateDigest$1, H as verifyCanonicalCandidateDocument, I as canonicalCandidateDocument, P as canonicalCandidateBytes$1, V as sha256Bytes$1, z as immutableCandidateValue } from "./sandbox-profile-compat-QTkLe1Z6.js";
4
+ import { I as collectAgentTurn, L as streamAgentTurn, P as optimizerMethod } from "./structural-rollout-DAvIE8mw.js";
5
+ import { F as canonicalCandidateDigest$1, Tt as armDeadlineTimer, V as sha256Bytes$1, z as immutableCandidateValue } from "./sandbox-profile-compat-xSoVtdWw.js";
6
6
  import { a as concreteProfileModel, t as assertExecutableAgentProfile } from "./model-policy-CyCUwHed.js";
7
- import { t as runAnalystLoop } from "./analyst-loop-DZw5QWT9.js";
8
- import { c as executePreparedAgentCandidate, o as verifiedResourceTextByDigest, s as verifyAgentCandidateBundle, t as prepareAgentCandidateExecution } from "./prepare-CER-ZkPp.js";
9
- import { a as assertCandidateProfileBinding, c as createAgentCandidateProfileActivation, d as omitUndefinedObjectFields, f as parseAgentCandidateProfileActivation, i as applyExactAgentProfileDiff, p as parseExactAgentProfile, r as agentCandidateProfileAsAgentProfile, u as materializeAgentCandidateProfilePlan } from "./profile-gNUsHNIJ.js";
10
- import { AGENT_IMPROVEMENT_SOURCE_METADATA_KEY, agentCandidateMaterializationReceiptSchema, agentCandidateRunReceiptSchema, agentImprovementActivationSchema, agentImprovementProposalSchema, agentImprovementReviewSchema, agentImprovementSourceMetadata, agentImprovementSourceSchema, agentProfileDiffSchema, agentProfileEnvironmentSchema, agentProfileImprovementArmSchema, agentProfileImprovementExecutionRefSchema, agentProfileModelHintsSchema, agentProfileSchema, agentProfileTrainingSchema, agentTrainingDatasetIdentitySchema, agentTrainingParametersSchema, agentTrainingReceiptSchema, agentTrainingTaskKey, agentTrainingTaskSchema, applyAgentProfileDiff, candidateExecutionEvidenceSchema, canonicalAgentProfileDigest, canonicalCandidateBytes, changedProfileImprovementSurfaces, defineAgentProfileDiff, diffAgentProfiles, numbersApproximatelyEqual, sha256DigestSchema, snapshotAgentProfile, trainedModelIdForArtifact } from "@tangle-network/agent-interface";
11
- import { CostLedger, canonicalJson, makeProposalFinding } from "@tangle-network/agent-eval";
7
+ import { t as sha256 } from "./content-digest-sBTLujlK.js";
8
+ import { E as normalizeRolloutPolicy, O as serializeRolloutPolicy, T as applyRolloutPolicyToProfile, k as structuralRolloutPolicyFromProfile } from "./activation-kbkAuSmY.js";
9
+ import { a as reconcileInterruptedSearchCalls, b as improveSearchCost, c as searchExecutor, d as taggedLedger, i as isSearchEnvironmentFault, n as assertSearchLanes, s as searchCallTags, v as decideClosedSearch } from "./search-executor-DmgUm5p7.js";
10
+ import { agentProfileEnvironmentSchema, agentProfileSchema, agentProfileTrainingSchema, agentTrainingDatasetIdentitySchema, agentTrainingParametersSchema, agentTrainingReceiptSchema, agentTrainingTaskKey, agentTrainingTaskSchema, applyAgentProfileDiff, canonicalAgentProfileDigest, canonicalCandidateBytes, diffAgentProfiles, sha256DigestSchema, snapshotAgentProfile, trainedModelIdForArtifact } from "@tangle-network/agent-interface";
11
+ import { canonicalJson, makeProposalFinding } from "@tangle-network/agent-eval";
12
12
  import { redact } from "@tangle-network/agent-eval/traces";
13
13
  import { createHash, randomUUID } from "node:crypto";
14
14
  import { constants, existsSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
@@ -18,8 +18,38 @@ import { chmod, mkdir, mkdtemp, open, realpath, rm, writeFile } from "node:fs/pr
18
18
  import { tmpdir } from "node:os";
19
19
  import { assertProposalFindings } from "@tangle-network/agent-eval/analyst";
20
20
  import { SearchRecorder, aide, asha, campaignCellSearchResult, campaignScenarioIdentity, campaignSplitDigestFromIdentities, compareOptimizationMethods, createRunCostLedger, fsCampaignStorage, gitWorktreeAdapter, isProposedCandidate, openSearchLedger, renderSearchSummary, resolveRunDir, runCampaign, runSearch, searchClaimReserveUsd, searchNodeId, searchProposalExecution, searchProposerView, searchReceiptAccounting, verifyCodeSurface, verifySearchHistoryArtifact } from "@tangle-network/agent-eval/campaign";
21
- import { measuredComparisonFromAgentProfileImprovementExperiment, measuredComparisonFromCandidateExperiment, runAgentProfileImprovementExperiment, runCandidateExperiment, sealAgentProfileImprovementExperiment, sealAgentProfileImprovementSuite, sealAgentProfileImprovementTask, sealCandidateExperiment, selfImprove, verifyAgentProfileImprovementExperimentComparison, verifyCandidateExperiment, verifyCandidateExperimentComparison } from "@tangle-network/agent-eval/contract";
21
+ import { selfImprove } from "@tangle-network/agent-eval/contract";
22
22
  import { defineEvaluationClaim, summarizeEvaluationUnits } from "@tangle-network/agent-eval/experiment";
23
+ //#region src/runtime-usage.ts
24
+ function createRuntimeUsageTotals() {
25
+ return {
26
+ tokensIn: 0,
27
+ tokensOut: 0,
28
+ costUsd: 0,
29
+ llmCalls: 0
30
+ };
31
+ }
32
+ function isUsageAmount(value) {
33
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
34
+ }
35
+ /** Fold normalized per-call events. Backend adapters own cumulative receipt reconciliation. */
36
+ function addRuntimeUsage(totals, event) {
37
+ totals.llmCalls += 1;
38
+ for (const key of [
39
+ "tokensIn",
40
+ "tokensOut",
41
+ "costUsd"
42
+ ]) {
43
+ const value = event[key];
44
+ if (isUsageAmount(value)) totals[key] += value;
45
+ else if (key === "costUsd") totals.usdKnown = false;
46
+ else totals.tokensKnown = false;
47
+ }
48
+ if (event.tokensKnown === false) totals.tokensKnown = false;
49
+ if (event.usdKnown === false) totals.usdKnown = false;
50
+ if (isUsageAmount(event.estimatedCostUsd)) totals.estimatedCostUsd = (totals.estimatedCostUsd ?? 0) + event.estimatedCostUsd;
51
+ }
52
+ //#endregion
23
53
  //#region src/improvement/worktree-tree.ts
24
54
  /**
25
55
  * The exact content of a candidate worktree, as a Git tree object.
@@ -85,6 +115,32 @@ function git(cwd, args, indexFile) {
85
115
  if (result.status !== 0) throw new Error(`agenticGenerator: git ${args[0]} exited ${result.status} in ${cwd}: ${result.stderr.trim()}`);
86
116
  return result.stdout.trim();
87
117
  }
118
+ function worktreeChangedPaths(worktreePath) {
119
+ const result = spawnSync("git", [
120
+ "status",
121
+ "--porcelain=v1",
122
+ "-z",
123
+ "--untracked-files=all"
124
+ ], {
125
+ cwd: worktreePath,
126
+ encoding: "utf-8"
127
+ });
128
+ if (result.error) throw new Error(`agenticGenerator: git status failed to spawn in ${worktreePath}: ${result.error.message}`);
129
+ if (result.status !== 0) throw new Error(`agenticGenerator: git status exited ${result.status} in ${worktreePath}: ${result.stderr.trim()}`);
130
+ const records = result.stdout.split("\0");
131
+ const paths = [];
132
+ for (let i = 0; i < records.length; i += 1) {
133
+ const record = records[i];
134
+ if (!record) continue;
135
+ paths.push(record.slice(3));
136
+ if (record[0] === "R" || record[1] === "R" || record[0] === "C" || record[1] === "C") {
137
+ const source = records[++i];
138
+ if (!source) throw new Error(`agenticGenerator: git status omitted a rename/copy path in ${worktreePath}`);
139
+ paths.push(source);
140
+ }
141
+ }
142
+ return paths;
143
+ }
88
144
  //#endregion
89
145
  //#region src/improvement/agentic-generator.ts
90
146
  /**
@@ -415,7 +471,7 @@ function shotReceipt(input) {
415
471
  provider: input.provider,
416
472
  model: input.model,
417
473
  reasoningEffort: input.profile.model?.reasoningEffort ?? null,
418
- promptSha256: sha256(input.prompt),
474
+ promptSha256: `sha256:${sha256(input.prompt)}`,
419
475
  startedAt: input.startedAt.toISOString(),
420
476
  completedAt: input.completedAt.toISOString(),
421
477
  durationMs: input.completedAt.getTime() - input.startedAt.getTime(),
@@ -468,9 +524,6 @@ function promptCacheReadTokens(usage) {
468
524
  if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
469
525
  }
470
526
  }
471
- function sha256(value) {
472
- return `sha256:${createHash("sha256").update(value).digest("hex")}`;
473
- }
474
527
  /** Turn proposal findings into a concrete coder task —
475
528
  * the senior scientific-method framing shared with the tool/MCP build prompts. */
476
529
  function defaultBuildPrompt(args) {
@@ -619,11 +672,6 @@ function boundedRationale(summary, findings) {
619
672
  function truncate$1(s, n) {
620
673
  return s.length <= n ? s : `${s.slice(0, n - 1)}…`;
621
674
  }
622
- /** Non-empty `git status --porcelain` ⇒ the harness changed the worktree.
623
- * Fails loud: the worktree is a fresh checkout, so a git error here means
624
- * something is genuinely broken (git missing, corrupt index, killed mid-run).
625
- * Folding that into `false` would silently discard a candidate and mask the
626
- * real failure — forbidden by the no-silent-fallbacks doctrine. */
627
675
  /** Do two names address the same directory? An in-place placement is only in-place if it names the
628
676
  * worktree the driver created, and a byte comparison answers that wrongly on a platform whose
629
677
  * temporary directory is a symlink: macOS reports `/var/folders/...` where the resolved path is
@@ -642,35 +690,14 @@ function canonicalPath(path) {
642
690
  return resolve(path);
643
691
  }
644
692
  }
693
+ /** Non-empty `git status --porcelain` ⇒ the harness changed the worktree.
694
+ * Fails loud: the worktree is a fresh checkout, so a git error here means
695
+ * something is genuinely broken (git missing, corrupt index, killed mid-run).
696
+ * Folding that into `false` would silently discard a candidate and mask the
697
+ * real failure — forbidden by the no-silent-fallbacks doctrine. */
645
698
  function worktreeDirty(worktreePath) {
646
699
  return worktreeChangedPaths(worktreePath).length > 0;
647
700
  }
648
- function worktreeChangedPaths(worktreePath) {
649
- const result = spawnSync("git", [
650
- "status",
651
- "--porcelain=v1",
652
- "-z",
653
- "--untracked-files=all"
654
- ], {
655
- cwd: worktreePath,
656
- encoding: "utf-8"
657
- });
658
- if (result.error) throw new Error(`agenticGenerator: git status failed to spawn in ${worktreePath}: ${result.error.message}`);
659
- if (result.status !== 0) throw new Error(`agenticGenerator: git status exited ${result.status} in ${worktreePath}: ${result.stderr.trim()}`);
660
- const records = result.stdout.split("\0");
661
- const paths = [];
662
- for (let i = 0; i < records.length; i += 1) {
663
- const record = records[i];
664
- if (!record) continue;
665
- paths.push(record.slice(3));
666
- if (record[0] === "R" || record[1] === "R" || record[0] === "C" || record[1] === "C") {
667
- const source = records[++i];
668
- if (!source) throw new Error(`agenticGenerator: git status omitted a rename/copy path in ${worktreePath}`);
669
- paths.push(source);
670
- }
671
- }
672
- return paths;
673
- }
674
701
  //#endregion
675
702
  //#region src/improvement/cleanup.ts
676
703
  async function rethrowAfterCleanup(cause, cleanup, context) {
@@ -809,76 +836,6 @@ function advanceToIncumbent(worktree, incumbent) {
809
836
  if (head.error || head.status !== 0 || head.stdout.trim() !== incumbent.candidateCommit) throw new Error("improvementDriver: candidate worktree did not reach the incumbent commit");
810
837
  }
811
838
  //#endregion
812
- //#region src/improvement/rollout-policy.ts
813
- /** The profile extensions namespace the policy persists under. */
814
- const ROLLOUT_POLICY_EXTENSION = "structural-rollout";
815
- const isBoundedInt = (v, min) => typeof v === "number" && Number.isInteger(v) && v >= min;
816
- /** Parse a serialized policy surface. Returns `undefined` for non-strings,
817
- * malformed JSON, or values outside the policy invariants. Unknown fields are
818
- * dropped; supported optional fields are preserved. */
819
- function parseRolloutPolicy(surface) {
820
- if (typeof surface !== "string" || surface.trim().length === 0) return void 0;
821
- let raw;
822
- try {
823
- raw = JSON.parse(surface);
824
- } catch {
825
- return;
826
- }
827
- return normalizeRolloutPolicy(raw);
828
- }
829
- /** Normalize an untyped policy bag (a parsed surface or a profile extension) into
830
- * a full `StructuralRolloutPolicy`, defaults merged. Returns `undefined` when any
831
- * present dial violates the policy invariants (mirrors `resolvePolicy`: integer
832
- * k ≥ 1, repairRounds ≥ 0, testgen ≥ 0) — a corrupt config must read as "not
833
- * configured", never as a fabricated recipe. */
834
- function normalizeRolloutPolicy(raw) {
835
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return void 0;
836
- const bag = raw;
837
- const k = bag.k ?? defaultStructuralRolloutPolicy.k;
838
- const repairRounds = bag.repairRounds ?? defaultStructuralRolloutPolicy.repairRounds;
839
- const testgen = bag.testgen ?? defaultStructuralRolloutPolicy.testgen;
840
- if (!isBoundedInt(k, 1) || !isBoundedInt(repairRounds, 0) || !isBoundedInt(testgen, 0)) return;
841
- return {
842
- k,
843
- repairRounds,
844
- testgen,
845
- ...typeof bag.diverse === "boolean" ? { diverse: bag.diverse } : {}
846
- };
847
- }
848
- /** Stable serialization with fixed field order. */
849
- function serializeRolloutPolicy(policy) {
850
- return JSON.stringify({
851
- k: policy.k,
852
- repairRounds: policy.repairRounds,
853
- testgen: policy.testgen,
854
- ...policy.diverse !== void 0 ? { diverse: policy.diverse } : {}
855
- });
856
- }
857
- /** Read the persisted policy off the profile. `undefined` when the profile does
858
- * not opt into structural rollout. */
859
- function structuralRolloutPolicyFromProfile(profile) {
860
- const bag = profile.extensions?.[ROLLOUT_POLICY_EXTENSION];
861
- if (bag === void 0) return void 0;
862
- return normalizeRolloutPolicy(bag);
863
- }
864
- /** Persist a detached policy under the profile extension without mutating the input. */
865
- function applyRolloutPolicyToProfile(profile, policy) {
866
- const candidate = structuredClone(profile);
867
- const bag = {
868
- k: policy.k,
869
- repairRounds: policy.repairRounds,
870
- testgen: policy.testgen,
871
- ...policy.diverse !== void 0 ? { diverse: policy.diverse } : {}
872
- };
873
- return {
874
- ...candidate,
875
- extensions: {
876
- ...candidate.extensions,
877
- [ROLLOUT_POLICY_EXTENSION]: bag
878
- }
879
- };
880
- }
881
- //#endregion
882
839
  //#region src/improvement/profile-surface.ts
883
840
  /** Extract the baseline optimized by a method and retain its structured value
884
841
  * so external optimizers can inspect it for private fields before serialization. */
@@ -1625,7 +1582,7 @@ function assertMethodCostRecorded(methodName, result, compatibleLedger, invocati
1625
1582
  if (costCeiling !== void 0 && !cost.accountingComplete) throw new ConfigError(`improve(): method '${methodName}' returned incomplete cost accounting under costCeiling; refusing final scoring`);
1626
1583
  if (costCeiling !== void 0 && exceeds(cost.totalCostUsd, costCeiling)) throw new ConfigError(`improve(): method '${methodName}' reported cost $${cost.totalCostUsd} above costCeiling $${costCeiling}; refusing final scoring`);
1627
1584
  if (cost.accountingComplete && !observed.accountingComplete) throw new ConfigError(`improve(): method '${methodName}' reported complete cost accounting but its shared cost receipts are incomplete`);
1628
- if (cost.accountingComplete && !approximatelyEqual$1(cost.totalCostUsd, observed.totalCostUsd)) throw new ConfigError(`improve(): method '${methodName}' reported $${cost.totalCostUsd} but recorded $${observed.totalCostUsd} through input.costLedger`);
1585
+ if (cost.accountingComplete && !approximatelyEqual(cost.totalCostUsd, observed.totalCostUsd)) throw new ConfigError(`improve(): method '${methodName}' reported $${cost.totalCostUsd} but recorded $${observed.totalCostUsd} through input.costLedger`);
1629
1586
  }
1630
1587
  function scopedCostLedger(parent, scope, costAttribution) {
1631
1588
  const evaluationTags = { [EVALUATION_TAG]: scope.evaluationRef };
@@ -1668,7 +1625,7 @@ function withTags(filter, tags) {
1668
1625
  }
1669
1626
  };
1670
1627
  }
1671
- function approximatelyEqual$1(left, right) {
1628
+ function approximatelyEqual(left, right) {
1672
1629
  const tolerance = Number.EPSILON * Math.max(1, Math.abs(left), Math.abs(right)) * 8;
1673
1630
  return Math.abs(left - right) <= tolerance;
1674
1631
  }
@@ -2986,1108 +2943,6 @@ async function improve(profileOrCode, opts) {
2986
2943
  return runMethodImprovement(exact, opts);
2987
2944
  }
2988
2945
  //#endregion
2989
- //#region src/intelligence/improvement-surfaces.ts
2990
- const changedSurfaceOrder = [
2991
- "prompt",
2992
- "skills",
2993
- "tools",
2994
- "mcp",
2995
- "hooks",
2996
- "subagents",
2997
- "agent-profile",
2998
- "memory",
2999
- "code",
3000
- "knowledge",
3001
- "rollout-policy"
3002
- ];
3003
- /** Agent improvement surfaces delivered as exact `AgentProfileDiff` replacements. */
3004
- const AGENT_IMPROVEMENT_PROFILE_SURFACES = [
3005
- "prompt",
3006
- "skills",
3007
- "tools",
3008
- "mcp",
3009
- "hooks",
3010
- "subagents"
3011
- ];
3012
- /**
3013
- * Profile changes eligible for the product-owned measured comparison path.
3014
- * The six directly deliverable profile surfaces retain their granular labels;
3015
- * any residual profile axis also adds the complete `agent-profile` surface.
3016
- */
3017
- const AGENT_PROFILE_MEASURED_SURFACES = [...AGENT_IMPROVEMENT_PROFILE_SURFACES, "agent-profile"];
3018
- function deriveChangedSurfaces(baselineBundle, candidateBundle) {
3019
- if (baselineBundle.knowledge || candidateBundle.knowledge) assertKnowledgeCandidatePair(baselineBundle, candidateBundle);
3020
- assertCodeCandidatePair(baselineBundle, candidateBundle);
3021
- const baseline = improvementSurfaceValues(baselineBundle);
3022
- const candidate = improvementSurfaceValues(candidateBundle);
3023
- const changed = changedSurfaceOrder.filter((surface) => canonicalCandidateDigest$1(baseline[surface]) !== canonicalCandidateDigest$1(candidate[surface]));
3024
- if (changed.length === 0) throw new Error("candidate experiment does not change an agent surface");
3025
- return changed;
3026
- }
3027
- function assertAgentImprovementActivationTargets(surfaces, experiment, intent, targets) {
3028
- if (isProfileImprovementExperiment(experiment)) assertProfileImprovementTargetsShareIdentity(targets);
3029
- const expected = new Set(surfaces);
3030
- const actual = new Set(targets.map((target) => target.surface));
3031
- const sourceArm = intent === "activate-candidate" ? "baseline" : "candidate";
3032
- if (!(isProfileImprovementExperiment(experiment) ? sameAgentImprovementSurfaceSet(surfaces, activationExperimentChangedSurfaces(experiment)) : sameOrderedSurfaces(surfaces, activationExperimentChangedSurfaces(experiment))) || targets.some((target) => !target.identity.trim()) || targets.some((target) => target.expectedBaseDigest !== activationTargetDigest(experiment, sourceArm, target.surface)) || targets.length !== surfaces.length || expected.size !== actual.size || [...expected].some((surface) => !actual.has(surface))) throw new Error("agent improvement activation targets must cover exactly the changed surfaces");
3033
- }
3034
- /** One opaque profile-state transition can change only one complete profile record. */
3035
- function assertProfileImprovementTargetsShareIdentity(targets) {
3036
- if (new Set(targets.map((target) => target.identity)).size !== 1) throw new Error("profile improvement activation targets must name one profile identity");
3037
- }
3038
- /** Bind caller-owned target identities to the exact source state Runtime measured. */
3039
- function buildAgentImprovementActivationTargets(surfaces, experiment, intent, identities) {
3040
- const sourceArm = intent === "activate-candidate" ? "baseline" : "candidate";
3041
- const targets = identities.map((target) => ({
3042
- ...target,
3043
- expectedBaseDigest: activationTargetDigest(experiment, sourceArm, target.surface)
3044
- }));
3045
- assertAgentImprovementActivationTargets(surfaces, experiment, intent, targets);
3046
- return targets;
3047
- }
3048
- /** Exact host-owned profile state for every changed profile surface. */
3049
- function agentProfileImprovementStateDigest(experiment, arm) {
3050
- return experiment[arm].stateDigest;
3051
- }
3052
- /** Map Interface's current profile-improvement contract to Runtime-deliverable surfaces. */
3053
- function profileImprovementChangedSurfaces(change) {
3054
- const surfaces = changedProfileImprovementSurfaces(change);
3055
- if (surfaces.length === 0 || !surfaces.every((surface) => isAgentProfileMeasuredSurface(surface))) throw new Error("profile improvement experiment does not change a supported surface");
3056
- return surfaces;
3057
- }
3058
- function agentImprovementTargetDigest(experiment, arm, surface) {
3059
- if (surface === "knowledge") {
3060
- const knowledge = assertKnowledgeCandidatePair(experiment.baseline, experiment.candidate);
3061
- return arm === "baseline" ? knowledge.candidate.baseHash : knowledge.candidate.candidateHash;
3062
- }
3063
- if (surface === "code") assertCodeCandidatePair(experiment.baseline, experiment.candidate);
3064
- return canonicalCandidateDigest$1(improvementSurfaceValues(experiment[arm])[surface]);
3065
- }
3066
- function agentImprovementTargetInput(bundle, surface) {
3067
- return improvementSurfaceValues(bundle)[surface];
3068
- }
3069
- function activationTargetDigest(experiment, arm, surface) {
3070
- if (isProfileImprovementExperiment(experiment)) {
3071
- if (!activationExperimentChangedSurfaces(experiment).includes(surface)) throw new Error("profile improvement activation targets an unchanged surface");
3072
- return agentProfileImprovementStateDigest(experiment, arm);
3073
- }
3074
- return agentImprovementTargetDigest(experiment, arm, surface);
3075
- }
3076
- function activationExperimentChangedSurfaces(experiment) {
3077
- if (!isProfileImprovementExperiment(experiment)) return deriveChangedSurfaces(experiment.baseline, experiment.candidate);
3078
- return profileImprovementChangedSurfaces(experiment.change);
3079
- }
3080
- function isProfileImprovementExperiment(experiment) {
3081
- return experiment.kind === "agent-profile-improvement-experiment";
3082
- }
3083
- function sameOrderedSurfaces(left, right) {
3084
- return left.length === right.length && left.every((surface, index) => surface === right[index]);
3085
- }
3086
- /** Profile-change surface order is presentation only; its measured contract is set-based. */
3087
- function sameAgentImprovementSurfaceSet(left, right) {
3088
- return left.length === right.length && left.every((surface) => right.includes(surface));
3089
- }
3090
- /** Return whether a measured surface can be delivered through an agent profile. */
3091
- function isAgentImprovementProfileSurface(surface) {
3092
- return AGENT_IMPROVEMENT_PROFILE_SURFACES.includes(surface);
3093
- }
3094
- /** Return whether a surface is eligible for shared profile measurement. */
3095
- function isAgentProfileMeasuredSurface(surface) {
3096
- return AGENT_PROFILE_MEASURED_SURFACES.includes(surface);
3097
- }
3098
- /**
3099
- * Return the canonical current-state input for one profile-deliverable improvement target.
3100
- * Missing slots become `null`; tools and subagents include both their direct and resource slots.
3101
- * Unrelated profile fields are excluded. The result matches `agentImprovementTargetInput` for the
3102
- * same profile inside a candidate bundle.
3103
- */
3104
- function agentImprovementProfileSurfaceInput(profile, surface) {
3105
- return immutableCandidateValue(profileSurfaceInput(parseExactAgentProfile(omitUndefinedObjectFields(profile, "agent improvement profile"), "agent improvement profile"), surface));
3106
- }
3107
- function profileSurfaceInput(profile, surface) {
3108
- switch (surface) {
3109
- case "prompt": return { prompt: profile.prompt ?? null };
3110
- case "skills": return profile.resources?.skills ?? null;
3111
- case "tools": return {
3112
- tools: profile.tools ?? null,
3113
- resources: profile.resources?.tools ?? null
3114
- };
3115
- case "mcp": return profile.mcp ?? null;
3116
- case "hooks": return profile.hooks ?? null;
3117
- case "subagents": return {
3118
- subagents: profile.subagents ?? null,
3119
- resources: profile.resources?.agents ?? null
3120
- };
3121
- }
3122
- }
3123
- /** Return the `Sha256Digest` of one profile surface using Runtime's canonical candidate digest. */
3124
- function agentImprovementProfileSurfaceDigest(profile, surface) {
3125
- return canonicalCandidateDigest$1(agentImprovementProfileSurfaceInput(profile, surface));
3126
- }
3127
- /**
3128
- * Replace one measured profile surface exactly, including array-valued resources.
3129
- * Apply the returned diffs in order: a diff applies its set before its removal,
3130
- * so exact replacement requires a reset record followed by a set record.
3131
- */
3132
- function agentImprovementTargetProfileDiffs(target, options) {
3133
- const { remove, set } = improvementSurfaceReplacement(target);
3134
- const common = {
3135
- kind: "agent-profile-diff",
3136
- ...options.source ? { source: options.source } : {},
3137
- metadata: {
3138
- ...options.metadata ?? {},
3139
- surface: target.surface
3140
- }
3141
- };
3142
- const reset = agentProfileDiffSchema.parse(defineAgentProfileDiff({
3143
- ...common,
3144
- id: `${options.id}:${target.surface}:reset`,
3145
- title: `Replace active ${target.surface}`,
3146
- remove
3147
- }));
3148
- if (!set) return [reset];
3149
- return [reset, agentProfileDiffSchema.parse(defineAgentProfileDiff({
3150
- ...common,
3151
- id: `${options.id}:${target.surface}:set`,
3152
- title: `Activate measured ${target.surface}`,
3153
- set
3154
- }))];
3155
- }
3156
- /**
3157
- * Derive the ordered profile patch that changes one executable profile into
3158
- * another, then prove the patch preserves the complete candidate state.
3159
- */
3160
- function agentImprovementProfileDiffs(baselineInput, candidateInput, options) {
3161
- const baseline = parseExactAgentProfile(omitUndefinedObjectFields(baselineInput, "profile improvement baseline"), "profile improvement baseline");
3162
- const candidate = parseExactAgentProfile(omitUndefinedObjectFields(candidateInput, "profile improvement candidate"), "profile improvement candidate");
3163
- if (canonicalAgentProfileDigest(baseline) === canonicalAgentProfileDigest(candidate)) throw new Error("profile improvement candidate does not change the profile");
3164
- const completeChanges = completeAgentProfileReplacementDiffs(baseline, candidate, options);
3165
- if (canonicalAgentProfileDigest(completeChanges.reduce((profile, change) => applyExactAgentProfileDiff(profile, change, "complete profile improvement candidate change"), baseline)) !== canonicalAgentProfileDigest(candidate)) throw new Error("complete profile improvement change did not reproduce the candidate");
3166
- return completeChanges;
3167
- }
3168
- function completeAgentProfileReplacementDiffs(baseline, candidate, options) {
3169
- const [first, ...rest] = diffAgentProfiles(baseline, candidate).map((change) => {
3170
- const reset = change.remove !== void 0;
3171
- return agentProfileDiffSchema.parse({
3172
- ...change,
3173
- ...options.source ? { source: options.source } : {},
3174
- metadata: {
3175
- ...options.metadata ?? {},
3176
- surface: "agent-profile"
3177
- },
3178
- id: `${options.id}:agent-profile:${reset ? "reset" : "set"}`,
3179
- title: reset ? "Reset changed agent profile fields" : "Set changed agent profile fields"
3180
- });
3181
- });
3182
- if (!first) throw new Error("complete profile differ found no changed fields");
3183
- return [first, ...rest];
3184
- }
3185
- function improvementSurfaceReplacement(target) {
3186
- const value = target.desiredInput;
3187
- switch (target.surface) {
3188
- case "prompt": {
3189
- const prompt = exactObject(value, ["prompt"], "prompt activation input").prompt;
3190
- assertDefined(prompt, "prompt activation input.prompt");
3191
- return {
3192
- remove: { prompt: true },
3193
- ...prompt === null ? {} : { set: parseProfileSet({ prompt }) }
3194
- };
3195
- }
3196
- case "skills":
3197
- assertDefined(value, "skills activation input");
3198
- return {
3199
- remove: { resources: { skills: true } },
3200
- ...value === null ? {} : { set: parseProfileSet({ resources: { skills: value } }) }
3201
- };
3202
- case "tools": {
3203
- const parsed = exactObject(value, ["tools", "resources"], "tools activation input");
3204
- assertDefined(parsed.tools, "tools activation input.tools");
3205
- assertDefined(parsed.resources, "tools activation input.resources");
3206
- const set = {
3207
- ...parsed.tools === null ? {} : { tools: parsed.tools },
3208
- ...parsed.resources === null ? {} : { resources: { tools: parsed.resources } }
3209
- };
3210
- return {
3211
- remove: {
3212
- tools: true,
3213
- resources: { tools: true }
3214
- },
3215
- ...Object.keys(set).length === 0 ? {} : { set: parseProfileSet(set) }
3216
- };
3217
- }
3218
- case "mcp":
3219
- assertDefined(value, "mcp activation input");
3220
- return {
3221
- remove: { mcp: true },
3222
- ...value === null ? {} : { set: parseProfileSet({ mcp: value }) }
3223
- };
3224
- case "hooks":
3225
- assertDefined(value, "hooks activation input");
3226
- return {
3227
- remove: { hooks: true },
3228
- ...value === null ? {} : { set: parseProfileSet({ hooks: value }) }
3229
- };
3230
- case "subagents": {
3231
- const parsed = exactObject(value, ["subagents", "resources"], "subagents activation input");
3232
- assertDefined(parsed.subagents, "subagents activation input.subagents");
3233
- assertDefined(parsed.resources, "subagents activation input.resources");
3234
- const set = {
3235
- ...parsed.subagents === null ? {} : { subagents: parsed.subagents },
3236
- ...parsed.resources === null ? {} : { resources: { agents: parsed.resources } }
3237
- };
3238
- return {
3239
- remove: {
3240
- subagents: true,
3241
- resources: { agents: true }
3242
- },
3243
- ...Object.keys(set).length === 0 ? {} : { set: parseProfileSet(set) }
3244
- };
3245
- }
3246
- }
3247
- }
3248
- function assertDefined(value, label) {
3249
- if (value === void 0) throw new Error(`${label} must not be undefined`);
3250
- }
3251
- function exactObject(value, keys, label) {
3252
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object`);
3253
- const record = value;
3254
- const actual = Object.keys(record).sort();
3255
- const expected = [...keys].sort();
3256
- if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) throw new Error(`${label} must contain exactly: ${expected.join(", ")}`);
3257
- return record;
3258
- }
3259
- function parseProfileSet(value) {
3260
- return agentProfileSchema.parse(value);
3261
- }
3262
- function assertKnowledgeCandidatePair(baselineBundle, candidateBundle) {
3263
- const baseline = baselineBundle.knowledge;
3264
- const candidate = candidateBundle.knowledge;
3265
- if (!baseline && !candidate) throw new Error("knowledge candidate pair is not present");
3266
- if (!baseline || !candidate || canonicalCandidateDigest$1({
3267
- candidate: baseline.candidate,
3268
- evaluation: baseline.evaluation
3269
- }) !== canonicalCandidateDigest$1({
3270
- candidate: candidate.candidate,
3271
- evaluation: candidate.evaluation
3272
- })) throw new Error("knowledge experiment arms must share one measured candidate and evaluation identity");
3273
- return candidate;
3274
- }
3275
- function assertCodeCandidatePair(baselineBundle, candidateBundle) {
3276
- const baseline = baselineBundle.code;
3277
- const candidate = candidateBundle.code;
3278
- if (canonicalCandidateDigest$1(baseline) === canonicalCandidateDigest$1(candidate) || candidate.kind !== "git-patch") return;
3279
- const baselineTree = baseline.kind === "no-op" ? baseline.baseTree : baseline.kind === "git-patch" ? baseline.candidateTree : void 0;
3280
- const baselineRepository = baseline.kind === "disabled" ? void 0 : baseline.repository;
3281
- if (baselineTree !== candidate.baseTree || !baselineRepository || canonicalCandidateDigest$1(baselineRepository) !== canonicalCandidateDigest$1(candidate.repository)) throw new Error("code candidate must be based on the exact repository tree measured by the baseline arm");
3282
- }
3283
- function improvementSurfaceValues(bundle) {
3284
- const profile = agentCandidateProfileAsAgentProfile(bundle.profile);
3285
- return {
3286
- prompt: agentImprovementProfileSurfaceInput(profile, "prompt"),
3287
- skills: agentImprovementProfileSurfaceInput(profile, "skills"),
3288
- tools: agentImprovementProfileSurfaceInput(profile, "tools"),
3289
- mcp: agentImprovementProfileSurfaceInput(profile, "mcp"),
3290
- hooks: agentImprovementProfileSurfaceInput(profile, "hooks"),
3291
- subagents: agentImprovementProfileSurfaceInput(profile, "subagents"),
3292
- "agent-profile": {
3293
- profile: opaqueProfileSlice(profile),
3294
- execution: bundle.execution
3295
- },
3296
- memory: {
3297
- instructions: profile.resources?.instructions ?? null,
3298
- executionPolicy: bundle.memory
3299
- },
3300
- code: bundle.code,
3301
- knowledge: bundle.knowledge ?? null,
3302
- "rollout-policy": structuralRolloutPolicyFromProfile(profile) ?? null
3303
- };
3304
- }
3305
- function opaqueProfileSlice(profile) {
3306
- const { prompt: _prompt, tools: _tools, mcp: _mcp, hooks: _hooks, subagents: _subagents, extensions, resources, ...opaqueProfile } = profile;
3307
- const { [ROLLOUT_POLICY_EXTENSION]: _rolloutPolicy, ...opaqueExtensions } = extensions ?? {};
3308
- const { instructions: _instructions, skills: _skills, tools: _resourceTools, agents: _agents, ...opaqueResources } = resources ?? {};
3309
- return {
3310
- ...opaqueProfile,
3311
- ...Object.keys(opaqueExtensions).length > 0 ? { extensions: opaqueExtensions } : {},
3312
- ...Object.keys(opaqueResources).length > 0 ? { resources: opaqueResources } : {}
3313
- };
3314
- }
3315
- //#endregion
3316
- //#region src/intelligence/optimization-receipt.ts
3317
- const optimizationReceiptMetadataKey = "optimizationReceipt";
3318
- /** Build a detached receipt only for methods backed by an identified external optimizer. */
3319
- function createOptimizationActivationReceipt(improvement) {
3320
- const provenance = improvement.provenance;
3321
- if (!provenance) return void 0;
3322
- const finalTestDataDigest = improvement.lineage.finalTestSplitDigest;
3323
- if (!finalTestDataDigest) throw new Error("method improvement does not retain its final-test split digest");
3324
- const optimizerModel = provenance.optimizerModel;
3325
- const candidateModel = improvement.candidate.profile.model;
3326
- return canonicalCandidateDocument({
3327
- kind: "optimization-activation-receipt",
3328
- method: improvement.method,
3329
- source: provenance.source,
3330
- ...provenance.bridge ? { bridge: provenance.bridge } : {},
3331
- ...provenance.modules ? { modules: provenance.modules } : {},
3332
- ...provenance.python ? { python: provenance.python } : {},
3333
- ...candidateModel || optimizerModel ? { models: {
3334
- ...candidateModel ? { candidate: candidateModel } : {},
3335
- ...optimizerModel ? { optimizer: optimizerModel } : {}
3336
- } } : {},
3337
- usage: {
3338
- optimizerEvaluations: provenance.evaluationCount,
3339
- ...provenance.tokenUsage ? { optimizerTokens: provenance.tokenUsage } : {}
3340
- },
3341
- cost: {
3342
- optimization: receiptCost(improvement.raw.optimizationCost),
3343
- finalTest: receiptCost(improvement.raw.testCost),
3344
- total: receiptCost(improvement.raw.totalCost)
3345
- },
3346
- invocation: {
3347
- runtimeInvocationId: improvement.lineage.invocationId,
3348
- optimizerRunId: provenance.runId,
3349
- ...provenance.compatibleRunId ? { compatibleOptimizerRunId: provenance.compatibleRunId } : {},
3350
- resumed: provenance.resumed,
3351
- artifactDir: provenance.artifactDir
3352
- },
3353
- developmentDataDigest: improvement.lineage.developmentSplitDigest,
3354
- finalTestDataDigest,
3355
- scenarioPartitions: improvement.lineage.scenarioPartitions
3356
- }).value;
3357
- }
3358
- /** Add Runtime-owned optimizer evidence without aliasing caller metadata. */
3359
- function attachOptimizationActivationReceipt(metadata, receipt) {
3360
- assertNoCallerOptimizationReceipt(metadata);
3361
- return immutableCandidateValue({
3362
- ...metadata ?? {},
3363
- [optimizationReceiptMetadataKey]: receipt
3364
- });
3365
- }
3366
- function assertNoCallerOptimizationReceipt(metadata) {
3367
- if (metadata && Object.hasOwn(metadata, "optimizationReceipt")) throw new Error(`candidate metadata reserves '${optimizationReceiptMetadataKey}' for Runtime`);
3368
- }
3369
- /** Read and verify the optimizer evidence carried by a measured proposal. */
3370
- function optimizationActivationReceiptFromMetadata(metadata) {
3371
- const value = metadata?.[optimizationReceiptMetadataKey];
3372
- if (value === void 0) return void 0;
3373
- return immutableCandidateValue(parseOptimizationActivationReceipt(value));
3374
- }
3375
- function parseOptimizationActivationReceipt(value) {
3376
- if (!isRecord(value) || value.kind !== "optimization-activation-receipt") throw new Error("optimization receipt must be an optimization-activation-receipt");
3377
- if (!isNonEmptyString(value.method) || !isPackageSource(value.source) || value.bridge !== void 0 && !isPackageSource(value.bridge) || !isModules(value.modules) || !isPythonRuntime(value.python) || !isModels(value.models) || !isUsage(value.usage) || !isCost(value.cost) || !isInvocation(value.invocation) || !isSha256Digest(value.developmentDataDigest) || !isSha256Digest(value.finalTestDataDigest) || !isScenarioPartitions(value.scenarioPartitions) || !isSha256Digest(value.digest)) throw new Error("optimization receipt contains invalid evidence");
3378
- const receipt = value;
3379
- if (!hasMatchingScenarioPartitionDigests(receipt)) throw new Error("optimization receipt task identities do not match its split digests");
3380
- if (canonicalCandidateDigest$1(omitTopLevelDigest(receipt)) !== receipt.digest) throw new Error("optimization receipt digest does not match its evidence");
3381
- return receipt;
3382
- }
3383
- function isScenarioPartitions(value) {
3384
- if (!isRecord(value)) return false;
3385
- return isScenarioIdentityList(value.train) && isScenarioIdentityList(value.selection) && isScenarioIdentityList(value.finalTest) && isPositiveSafeInteger(value.optimizationReps) && isPositiveSafeInteger(value.finalTestReps);
3386
- }
3387
- function isScenarioIdentityList(value) {
3388
- return Array.isArray(value) && value.every((scenario) => isRecord(scenario) && isNonEmptyString(scenario.id) && isNonEmptyString(scenario.kind) && isSha256Digest(scenario.scenarioDigest));
3389
- }
3390
- function hasMatchingScenarioPartitionDigests(receipt) {
3391
- try {
3392
- const { scenarioPartitions } = receipt;
3393
- const developmentDataDigest = canonicalCandidateDigest$1({
3394
- train: campaignSplitDigestFromIdentities(scenarioPartitions.train, scenarioPartitions.optimizationReps),
3395
- selection: campaignSplitDigestFromIdentities(scenarioPartitions.selection, scenarioPartitions.optimizationReps)
3396
- });
3397
- const finalTestDataDigest = campaignSplitDigestFromIdentities(scenarioPartitions.finalTest, scenarioPartitions.finalTestReps);
3398
- return receipt.developmentDataDigest === developmentDataDigest && receipt.finalTestDataDigest === finalTestDataDigest;
3399
- } catch {
3400
- return false;
3401
- }
3402
- }
3403
- function isPackageSource(value) {
3404
- if (!isRecord(value) || value.kind !== "package" || value.evidence !== "observed" && value.evidence !== "declared" || !isNonEmptyString(value.package) || !isNonEmptyString(value.version)) return false;
3405
- return isOptionalNonEmptyString(value.sourceUrl) && isOptionalNonEmptyString(value.revision) && (value.sourceSha256 === void 0 || typeof value.sourceSha256 === "string" && /^[0-9a-f]{64}$/.test(value.sourceSha256));
3406
- }
3407
- function isModules(value) {
3408
- return value === void 0 || Array.isArray(value) && value.every((module) => isRecord(module) && isNonEmptyString(module.module) && typeof module.sourceSha256 === "string" && /^[0-9a-f]{64}$/.test(module.sourceSha256));
3409
- }
3410
- function isPythonRuntime(value) {
3411
- return value === void 0 || isRecord(value) && isNonEmptyString(value.implementation) && isNonEmptyString(value.version);
3412
- }
3413
- function isModels(value) {
3414
- return value === void 0 || isRecord(value) && (value.candidate === void 0 || agentProfileModelHintsSchema.safeParse(value.candidate).success) && isOptionalNonEmptyString(value.optimizer) && (value.candidate !== void 0 || value.optimizer !== void 0);
3415
- }
3416
- function isUsage(value) {
3417
- if (!isRecord(value) || !isNonNegativeInteger(value.optimizerEvaluations)) return false;
3418
- if (value.optimizerTokens === void 0) return true;
3419
- const tokens = value.optimizerTokens;
3420
- if (!isRecord(tokens)) return false;
3421
- const inputTokens = tokens.inputTokens;
3422
- const outputTokens = tokens.outputTokens;
3423
- const totalTokens = tokens.totalTokens;
3424
- const calls = tokens.calls;
3425
- if (!isNonNegativeInteger(inputTokens) || !isNonNegativeInteger(outputTokens) || !isNonNegativeInteger(totalTokens) || !isNonNegativeInteger(calls)) return false;
3426
- if (!isOptionalNonNegativeInteger(tokens.cachedInputTokens) || !isOptionalNonNegativeInteger(tokens.cacheWriteInputTokens) || !isOptionalNonNegativeInteger(tokens.reasoningTokens)) return false;
3427
- const cachedInputTokens = typeof tokens.cachedInputTokens === "number" ? tokens.cachedInputTokens : 0;
3428
- const cacheWriteInputTokens = typeof tokens.cacheWriteInputTokens === "number" ? tokens.cacheWriteInputTokens : 0;
3429
- const reasoningTokens = typeof tokens.reasoningTokens === "number" ? tokens.reasoningTokens : 0;
3430
- return totalTokens === inputTokens + outputTokens && cachedInputTokens + cacheWriteInputTokens <= inputTokens && reasoningTokens <= outputTokens && (totalTokens === 0 || calls > 0);
3431
- }
3432
- function isCost(value) {
3433
- if (!isRecord(value) || !isCostPart(value.optimization) || !isCostPart(value.finalTest) || !isCostPart(value.total)) return false;
3434
- const optimization = value.optimization;
3435
- const finalTest = value.finalTest;
3436
- const total = value.total;
3437
- return approximatelyEqual(total.totalUsd, optimization.totalUsd + finalTest.totalUsd) && total.accountingComplete === (optimization.accountingComplete && finalTest.accountingComplete);
3438
- }
3439
- function isCostPart(value) {
3440
- return isRecord(value) && typeof value.totalUsd === "number" && Number.isFinite(value.totalUsd) && value.totalUsd >= 0 && typeof value.accountingComplete === "boolean" && Array.isArray(value.incompleteReasons) && value.incompleteReasons.every((reason) => typeof reason === "string");
3441
- }
3442
- function receiptCost(value) {
3443
- return {
3444
- totalUsd: value.totalCostUsd,
3445
- accountingComplete: value.accountingComplete,
3446
- incompleteReasons: [...value.incompleteReasons]
3447
- };
3448
- }
3449
- function approximatelyEqual(left, right) {
3450
- const tolerance = Number.EPSILON * Math.max(1, Math.abs(left), Math.abs(right)) * 8;
3451
- return Math.abs(left - right) <= tolerance;
3452
- }
3453
- function isInvocation(value) {
3454
- return isRecord(value) && isNonEmptyString(value.runtimeInvocationId) && isNonEmptyString(value.optimizerRunId) && isOptionalNonEmptyString(value.compatibleOptimizerRunId) && typeof value.resumed === "boolean" && isNonEmptyString(value.artifactDir);
3455
- }
3456
- function isRecord(value) {
3457
- return value !== null && typeof value === "object" && !Array.isArray(value);
3458
- }
3459
- function isNonEmptyString(value) {
3460
- return typeof value === "string" && value.trim().length > 0;
3461
- }
3462
- function isOptionalNonEmptyString(value) {
3463
- return value === void 0 || isNonEmptyString(value);
3464
- }
3465
- function isNonNegativeInteger(value) {
3466
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
3467
- }
3468
- function isPositiveSafeInteger(value) {
3469
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
3470
- }
3471
- function isOptionalNonNegativeInteger(value) {
3472
- return value === void 0 || isNonNegativeInteger(value);
3473
- }
3474
- function isSha256Digest(value) {
3475
- return typeof value === "string" && /^sha256:[0-9a-f]{64}$/.test(value);
3476
- }
3477
- //#endregion
3478
- //#region src/intelligence/profile-improvement-experiment.ts
3479
- function createProfileImprovementCostLedger(budgetUsd, context = "profile improvement") {
3480
- if (!Number.isFinite(budgetUsd) || budgetUsd < 0) throw new Error(`${context} budgetUsd must be a non-negative finite number`);
3481
- return new CostLedger({ costCeilingUsd: budgetUsd });
3482
- }
3483
- function profilePolicyWithBudget(policy, budgetUsd, context = "profile improvement") {
3484
- if (policy.budgetUsd !== void 0 && !numbersApproximatelyEqual(policy.budgetUsd, budgetUsd)) throw new Error(`${context} policy budgetUsd must equal the run budgetUsd`);
3485
- return {
3486
- ...policy,
3487
- budgetUsd
3488
- };
3489
- }
3490
- function profilePreparationAccounting(costLedger, startedAt) {
3491
- const summary = costLedger.summary();
3492
- if (!summary.accountingComplete || summary.costProvenance.kind === "uncaptured") throw new Error("profile improvement preparation cost is incomplete");
3493
- return {
3494
- wallDurationMs: Math.max(0, performance.now() - startedAt),
3495
- cost: {
3496
- usd: summary.costProvenance.usd,
3497
- provenance: summary.costProvenance.kind
3498
- }
3499
- };
3500
- }
3501
- function profileStateDigest(stateDigest, identity, profile) {
3502
- return agentProfileImprovementArmSchema.parse({ stateDigest: stateDigest({
3503
- identity,
3504
- profile
3505
- }) }).stateDigest;
3506
- }
3507
- function sealProfileImprovementBenchmark(input) {
3508
- const tasks = input.tasks.map((task) => sealAgentProfileImprovementTask(task));
3509
- return sealAgentProfileImprovementSuite({
3510
- splitDigest: campaignSplitDigestFromIdentities(tasks.map(profileTaskScenarioIdentity), input.reps),
3511
- tasks,
3512
- reps: input.reps,
3513
- seeds: input.seeds
3514
- });
3515
- }
3516
- function profileTaskScenarioIdentity(task) {
3517
- return {
3518
- id: task.scenario.id,
3519
- kind: task.scenario.kind,
3520
- scenarioDigest: task.scenario.digest
3521
- };
3522
- }
3523
- function profileImprovementMetadata(metadata, source, optimizationReceipt) {
3524
- assertNoCallerOptimizationReceipt(metadata);
3525
- if (metadata && Object.hasOwn(metadata, AGENT_IMPROVEMENT_SOURCE_METADATA_KEY)) throw new Error(`candidate metadata reserves '${AGENT_IMPROVEMENT_SOURCE_METADATA_KEY}' for Runtime`);
3526
- const merged = {
3527
- ...metadata ?? {},
3528
- ...agentImprovementSourceMetadata(source)
3529
- };
3530
- return optimizationReceipt ? attachOptimizationActivationReceipt(merged, optimizationReceipt) : immutableCandidateValue(merged);
3531
- }
3532
- //#endregion
3533
- //#region src/intelligence/improvement-cycle.ts
3534
- /** A failed baseline or candidate cell with its complete Runtime failure result. */
3535
- var AgentCandidateExperimentCellExecutionError = class extends Error {
3536
- finalization;
3537
- constructor(finalization) {
3538
- super(`candidate experiment cell failed: ${finalization.reason}`);
3539
- this.name = "AgentCandidateExperimentCellExecutionError";
3540
- this.finalization = finalization;
3541
- }
3542
- };
3543
- function sealAgentImprovementExperiment(material, improvement) {
3544
- assertRuntimeOwnedExperimentFieldsAbsent(material);
3545
- const candidateLineage = {
3546
- source: "optimizer",
3547
- parentDigests: [material.baseline.digest],
3548
- runIds: [improvement.lineage.runId],
3549
- developmentSplitDigest: improvement.lineage.developmentSplitDigest
3550
- };
3551
- const experiment = sealCandidateExperiment({
3552
- ...material,
3553
- candidateLineage
3554
- });
3555
- assertCandidateReleaseWorkIsFresh(experiment, improvement);
3556
- return experiment;
3557
- }
3558
- function assertRuntimeOwnedExperimentFieldsAbsent(material) {
3559
- if (material === null || typeof material !== "object" || Array.isArray(material)) throw new Error("agent improvement experiment material must be an object");
3560
- const supplied = ["candidateLineage", "digest"].filter((field) => Object.hasOwn(material, field));
3561
- if (supplied.length > 0) throw new Error(`agent improvement experiment material must not supply Runtime-owned fields: ${supplied.join(", ")}`);
3562
- }
3563
- /** Execute both arms of one immutable experiment and derive its paired result. */
3564
- async function runAgentCandidateExperiment(options) {
3565
- const experiment = verifyCandidateExperiment(options.experiment);
3566
- const preparation = options.preparation ?? {
3567
- wallDurationMs: 0,
3568
- cost: {
3569
- usd: 0,
3570
- provenance: "observed"
3571
- }
3572
- };
3573
- const costLedger = options.costLedger ?? (experiment.policy.budgetUsd === void 0 ? void 0 : new CostLedger({ costCeilingUsd: experiment.policy.budgetUsd }));
3574
- const run = await runCandidateExperiment({
3575
- experiment,
3576
- ...options.maxConcurrency === void 0 ? {} : { maxConcurrency: options.maxConcurrency },
3577
- ...costLedger ? { costLedger } : {},
3578
- ...options.signal ? { signal: options.signal } : {},
3579
- execute: async (input) => {
3580
- const placement = await options.placeCell(input);
3581
- return await executeAgentCandidateExperimentCell({
3582
- ...input,
3583
- ...placement
3584
- });
3585
- }
3586
- });
3587
- const evaluation = createAgentImprovementMeasuredComparison({
3588
- experiment,
3589
- measurements: run.measurements,
3590
- preparation,
3591
- measurement: run.measurement,
3592
- runId: options.runId,
3593
- ...options.candidate ? { candidate: options.candidate } : {},
3594
- ...options.generationsExplored === void 0 ? {} : { generationsExplored: options.generationsExplored },
3595
- ...options.metadata ? { metadata: options.metadata } : {}
3596
- });
3597
- return {
3598
- experiment,
3599
- measurements: run.measurements,
3600
- evaluation
3601
- };
3602
- }
3603
- /** Execute one exact arm, task, repetition, seed, and attempt through Runtime. */
3604
- async function executeAgentCandidateExperimentCell(options) {
3605
- const experiment = verifyCandidateExperiment(options.experiment);
3606
- const bundle = experiment[options.arm];
3607
- assertExactExperimentInput(options, experiment, bundle);
3608
- const attempt = options.attempt ?? 1;
3609
- if (attempt > options.task.attempt.maxAttempts) throw new Error("candidate experiment attempt exceeds the signed task policy");
3610
- const runCell = canonicalCandidateDocument({
3611
- kind: "agent-candidate-run-cell",
3612
- experimentDigest: experiment.digest,
3613
- arm: options.arm,
3614
- bundleDigest: bundle.digest,
3615
- suiteDigest: options.benchmarkCell.suiteDigest,
3616
- taskDigest: options.task.digest,
3617
- taskIndex: options.benchmarkCell.taskIndex,
3618
- repetition: options.benchmarkCell.repetition,
3619
- seed: options.seed,
3620
- attempt
3621
- }).value;
3622
- const verified = await verifyAgentCandidateBundle(bundle, options.ports);
3623
- const prepared = await prepareAgentCandidateExecution(verified, {
3624
- executionId: options.executionId,
3625
- runCell,
3626
- benchmarkSuite: experiment.benchmark.suite,
3627
- task: options.task,
3628
- executionRoots: options.executionRoots,
3629
- stagingRoots: options.stagingRoots
3630
- }, options.ports, options.preparation);
3631
- const finalization = await executePreparedAgentCandidate(prepared, options.execution);
3632
- if (!finalization.succeeded) throw new AgentCandidateExperimentCellExecutionError(finalization);
3633
- const evidence = canonicalCandidateDocument({
3634
- kind: "agent-candidate-execution-evidence",
3635
- materializationReceipt: prepared.materializationReceipt.value,
3636
- receipt: finalization.receipt.value
3637
- }).value;
3638
- return verifyCandidateExecutionEvidence(evidence, {
3639
- experiment,
3640
- arm: options.arm,
3641
- benchmarkCell: options.benchmarkCell,
3642
- seed: options.seed,
3643
- attempt,
3644
- resolvedResources: verifiedResourceTextByDigest(verified)
3645
- });
3646
- }
3647
- /** Delegate all statistics and promotion checks to agent-eval's receipt-based comparison. */
3648
- function createAgentImprovementMeasuredComparison(options) {
3649
- return verifyCandidateExperimentComparison(measuredComparisonFromCandidateExperiment(options));
3650
- }
3651
- async function analyzeAgentImprovement(runId, options, costLedger, signal) {
3652
- assertMeasuredAnalysisOptions(options);
3653
- const analysis = await runAnalystLoop({
3654
- ...options,
3655
- runId,
3656
- ...costLedger ? {
3657
- costLedger,
3658
- costPhase: "profile-improvement-analysis"
3659
- } : {},
3660
- ...signal ? { signal } : {}
3661
- });
3662
- if (costLedger) assertAnalysisCostRecorded(analysis, costLedger);
3663
- const judgeDerived = analysis.analystResult.findings.filter((finding) => finding.derived_from_judge === true);
3664
- if (judgeDerived.length > 0) throw new Error(`agent improvement analysis must not produce judge-derived findings: [${judgeDerived.map((finding) => finding.finding_id).join(", ")}]`);
3665
- return {
3666
- analysis,
3667
- findings: [...assertProposalFindings(analysis.analystResult.findings.map((finding) => ({
3668
- ...finding,
3669
- proposal_origin: "production"
3670
- })), "agent improvement findings")]
3671
- };
3672
- }
3673
- function assertMeasuredAnalysisOptions(options) {
3674
- const rawOptions = options;
3675
- if (rawOptions.knowledgeProposalSource !== void 0 || rawOptions.improvementProposalSource !== void 0) throw new Error("measured agent improvement analysis must not run proposal sources");
3676
- if (rawOptions.onEvent !== void 0 || rawOptions.log !== void 0) throw new Error("measured agent improvement analysis must not run callbacks");
3677
- if (rawOptions.inputs.judgeInput !== void 0) throw new Error("measured agent improvement analysis must not receive judge input");
3678
- }
3679
- function completeAnalysisAccounting(analysis) {
3680
- const analysisCost = analysis.analystResult.total_cost_provenance;
3681
- if (!analysisCost || analysisCost.kind === "uncaptured") throw new Error("agent improvement analysis cost is uncaptured");
3682
- if (!Number.isFinite(analysis.analystResult.total_cost_usd) || analysis.analystResult.total_cost_usd < 0) throw new Error("agent improvement analysis cost must be finite and non-negative");
3683
- if (analysisCost.usd !== analysis.analystResult.total_cost_usd) throw new Error("agent improvement analysis cost does not match its provenance");
3684
- if (!Number.isFinite(analysis.durationMs) || analysis.durationMs < 0) throw new Error("agent improvement analysis duration must be finite and non-negative");
3685
- return {
3686
- costUsd: analysis.analystResult.total_cost_usd,
3687
- durationMs: analysis.durationMs
3688
- };
3689
- }
3690
- function assertAnalysisCostRecorded(analysis, costLedger) {
3691
- const reported = completeAnalysisAccounting(analysis);
3692
- const summary = costLedger.summary();
3693
- if (!summary.accountingComplete || summary.costProvenance.kind === "uncaptured") throw new Error("agent improvement analysis cost is incomplete in the shared account");
3694
- const analysisCost = analysis.analystResult.total_cost_provenance;
3695
- if (!analysisCost || analysisCost.kind === "uncaptured") throw new Error("agent improvement analysis cost is uncaptured");
3696
- if (!numbersApproximatelyEqual(summary.totalCostUsd, reported.costUsd) || summary.costProvenance.kind !== analysisCost.kind) throw new Error("agent improvement analysis cost does not match the shared account");
3697
- }
3698
- function completeImprovementSearchAccounting(analysis, improvement) {
3699
- if (!improvement.cost.accountingComplete) throw new Error(`agent improvement optimization cost is incomplete: ${improvement.cost.incompleteReasons.join(", ") || "unspecified"}`);
3700
- if (!Number.isFinite(improvement.cost.totalCostUsd) || improvement.cost.totalCostUsd < 0) throw new Error("agent improvement optimization cost must be finite and non-negative");
3701
- if (!Number.isFinite(improvement.durationMs) || improvement.durationMs < 0) throw new Error("agent improvement optimization duration must be finite and non-negative");
3702
- return {
3703
- searchCostUsd: analysis.costUsd + improvement.cost.totalCostUsd,
3704
- searchDurationMs: analysis.durationMs + improvement.durationMs
3705
- };
3706
- }
3707
- function assertReleaseSplitIsFresh(heldOutSplitDigest, improvement) {
3708
- const consumedSplits = [improvement.lineage.developmentSplitDigest];
3709
- if (improvement.mode === "method") {
3710
- const finalTestSplitDigest = improvement.lineage.finalTestSplitDigest;
3711
- if (!finalTestSplitDigest) throw new Error("method improvement does not retain its final-test split digest");
3712
- consumedSplits.push(finalTestSplitDigest);
3713
- }
3714
- if (consumedSplits.includes(heldOutSplitDigest)) throw new Error("release benchmark reuses an optimizer development or final-test split");
3715
- }
3716
- function assertReleaseScenariosAreFresh(improvement, heldOutScenarios) {
3717
- const optimizerScenarios = /* @__PURE__ */ new Map();
3718
- for (const [partition, scenarios] of [
3719
- ["train", improvement.lineage.scenarioPartitions.train],
3720
- ["selection", improvement.lineage.scenarioPartitions.selection],
3721
- ["final-test", improvement.lineage.scenarioPartitions.finalTest]
3722
- ]) for (const scenario of scenarios) optimizerScenarios.set(canonicalCandidateDigest$1(scenario), partition);
3723
- const reused = heldOutScenarios.filter((scenario) => optimizerScenarios.has(canonicalCandidateDigest$1(scenario))).map((scenario) => `${scenario.id} (${optimizerScenarios.get(canonicalCandidateDigest$1(scenario))})`);
3724
- if (reused.length > 0) throw new Error(`release benchmark reuses optimizer scenario(s): [${reused.join(", ")}]`);
3725
- }
3726
- function assertCandidateReleaseWorkIsFresh(experiment, improvement) {
3727
- for (const splitDigest of new Set(experiment.benchmark.tasks.map((task) => task.benchmark.splitDigest))) assertReleaseSplitIsFresh(splitDigest, improvement);
3728
- if (improvement.mode !== "method") return;
3729
- assertReleaseScenariosAreFresh(improvement, experiment.benchmark.tasks.map((task) => task.scenario));
3730
- }
3731
- function assertProfileReleaseWorkIsFresh(benchmark, improvement) {
3732
- assertReleaseSplitIsFresh(benchmark.suite.splitDigest, improvement);
3733
- assertReleaseScenariosAreFresh(improvement, benchmark.tasks.map(profileTaskScenarioIdentity));
3734
- }
3735
- /**
3736
- * Analyze a product-owned profile, search one profile surface, then run the
3737
- * exact baseline and candidate through the product executor before proposing.
3738
- */
3739
- async function proposeAgentProfileImprovement(options) {
3740
- const source = agentImprovementSourceSchema.parse(options.source);
3741
- if (!isAgentProfileMeasuredSurface(options.improvement.surface ?? "prompt")) throw new Error("measured profile improvement supports profile surfaces or a complete agent profile; use the sealed-candidate path for this surface");
3742
- assertMeasuredAnalysisOptions(options.analysis);
3743
- const inputFindings = assertProposalFindings(options.improvement.findings ?? [], "profile improvement input findings");
3744
- const costLedger = createProfileImprovementCostLedger(options.budgetUsd);
3745
- const preparationStartedAt = performance.now();
3746
- const profile = parseExactAgentProfile(options.profile, "profile improvement source");
3747
- const baselineStateDigest = profileStateDigest(options.stateDigest, source.sourceIdentity, profile);
3748
- if (baselineStateDigest !== source.sourceDigest) throw new Error("profile improvement source digest does not match the measured profile state");
3749
- const policy = profilePolicyWithBudget(options.benchmark.policy, options.budgetUsd);
3750
- const benchmark = sealProfileImprovementBenchmark({
3751
- ...options.benchmark,
3752
- policy
3753
- });
3754
- const heldOutDigests = new Set(benchmark.tasks.map((task) => task.scenario.digest));
3755
- assertProfileTrainingIsHeldOut(profile, heldOutDigests);
3756
- if (options.improvement.costCeiling !== void 0 && !numbersApproximatelyEqual(options.improvement.costCeiling, options.budgetUsd)) throw new Error("profile improvement costCeiling must equal the run budgetUsd");
3757
- const { analysis, findings } = await analyzeAgentImprovement(options.runId, options.analysis, costLedger, options.signal);
3758
- const proposalFindings = immutableCandidateValue([...inputFindings, ...findings]);
3759
- const improvement = await improve(profile, {
3760
- ...options.improvement,
3761
- executionRef: options.executor.executionRef.digest,
3762
- agent: options.executor.optimize,
3763
- costLedger,
3764
- costCeiling: options.budgetUsd,
3765
- findings: proposalFindings
3766
- });
3767
- try {
3768
- if (improvement.decision !== "ship") throw new Error("agent profile improvement search did not produce a promotable candidate");
3769
- const candidateProfile = parseExactAgentProfile(improvement.candidate.profile, "profile improvement candidate");
3770
- const candidateStateDigest = profileStateDigest(options.stateDigest, source.sourceIdentity, candidateProfile);
3771
- if (candidateStateDigest === baselineStateDigest) throw new Error("profile improvement candidate state digest matches the baseline");
3772
- const change = agentImprovementProfileDiffs(profile, candidateProfile, {
3773
- id: `profile-improvement:${candidateStateDigest}`,
3774
- metadata: {
3775
- sourceIdentity: source.sourceIdentity,
3776
- sourceRevision: source.sourceRevision
3777
- }
3778
- });
3779
- const profileDiffIds = change.map((step) => {
3780
- if (!step.id) throw new Error("profile improvement change requires an exact diff id");
3781
- return step.id;
3782
- });
3783
- assertProfileTrainingIsHeldOut(candidateProfile, heldOutDigests);
3784
- assertProfileReleaseWorkIsFresh(benchmark, improvement);
3785
- const experiment = sealAgentProfileImprovementExperiment({
3786
- kind: "agent-profile-improvement-experiment",
3787
- digestAlgorithm: "rfc8785-sha256",
3788
- source,
3789
- executionRef: options.executor.executionRef,
3790
- baseline: { stateDigest: baselineStateDigest },
3791
- candidate: { stateDigest: candidateStateDigest },
3792
- change,
3793
- candidateLineage: {
3794
- source: "optimizer",
3795
- parentDigests: [source.sourceDigest],
3796
- runIds: [improvement.lineage.runId],
3797
- profileDiffIds,
3798
- developmentSplitDigest: improvement.lineage.developmentSplitDigest
3799
- },
3800
- benchmark,
3801
- policy
3802
- });
3803
- const profilesByStateDigest = /* @__PURE__ */ new Map([[baselineStateDigest, profile], [candidateStateDigest, candidateProfile]]);
3804
- const preparation = profilePreparationAccounting(costLedger, preparationStartedAt);
3805
- const run = await runAgentProfileImprovementExperiment({
3806
- experiment,
3807
- ...options.maxConcurrency === void 0 ? {} : { maxConcurrency: options.maxConcurrency },
3808
- costLedger,
3809
- ...options.signal ? { signal: options.signal } : {},
3810
- execute: async (input) => {
3811
- const measuredProfile = profilesByStateDigest.get(input.stateDigest);
3812
- if (!measuredProfile) throw new Error("profile improvement execution requested an unknown profile state");
3813
- return options.executor.measure({
3814
- ...input,
3815
- profile: measuredProfile
3816
- });
3817
- }
3818
- });
3819
- const optimizationReceipt = createOptimizationActivationReceipt(improvement);
3820
- const evaluation = verifyAgentProfileImprovementExperimentComparison(measuredComparisonFromAgentProfileImprovementExperiment({
3821
- experiment,
3822
- measurements: run.measurements,
3823
- runId: options.runId,
3824
- ...options.candidate ? { candidate: options.candidate } : {},
3825
- generationsExplored: improvement.generationsExplored ?? 0,
3826
- preparation,
3827
- measurement: run.measurement,
3828
- metadata: profileImprovementMetadata(options.metadata, source, optimizationReceipt)
3829
- }));
3830
- const proposal = createAgentImprovementProposal({
3831
- runId: options.runId,
3832
- findings: proposalFindings,
3833
- evaluation,
3834
- ...options.now ? { now: options.now } : {}
3835
- });
3836
- return {
3837
- analysis,
3838
- improvement,
3839
- experiment,
3840
- measurements: run.measurements,
3841
- proposal
3842
- };
3843
- } catch (cause) {
3844
- return rethrowAfterCleanup(cause, () => improvement.dispose(), "proposeAgentProfileImprovement failed");
3845
- }
3846
- }
3847
- /** Analyze, search, then remeasure the resulting exact candidate before proposing it. */
3848
- async function proposeAgentImprovement(options) {
3849
- assertNoCallerOptimizationReceipt(options.metadata);
3850
- assertMeasuredAnalysisOptions(options.analysis);
3851
- const inputFindings = assertProposalFindings(options.improvement.findings ?? [], "agent improvement input findings");
3852
- const { analysis, findings } = await analyzeAgentImprovement(options.runId, options.analysis);
3853
- const analysisAccounting = completeAnalysisAccounting(analysis);
3854
- const proposalFindings = immutableCandidateValue([...inputFindings, ...findings]);
3855
- const improvementInput = {
3856
- ...options.improvement,
3857
- findings: proposalFindings
3858
- };
3859
- const improvement = improvementInput.surface === "code" ? await improve(improvementInput) : await improve(options.profile, improvementInput);
3860
- try {
3861
- if (improvement.decision !== "ship") throw new Error("agent improvement search did not produce a promotable candidate");
3862
- const searchAccounting = completeImprovementSearchAccounting(analysisAccounting, improvement);
3863
- const preparation = {
3864
- wallDurationMs: searchAccounting.searchDurationMs,
3865
- cost: {
3866
- usd: searchAccounting.searchCostUsd,
3867
- provenance: "estimated"
3868
- }
3869
- };
3870
- const optimizationReceipt = improvement.mode === "method" ? createOptimizationActivationReceipt(improvement) : void 0;
3871
- const experiment = sealAgentImprovementExperiment(await options.buildExperiment({
3872
- analysis,
3873
- improvement
3874
- }), improvement);
3875
- assertCandidateProfileBinding(options.profile, experiment.baseline.profile);
3876
- assertImprovementCandidateBinding(improvement, experiment);
3877
- const measured = await runAgentCandidateExperiment({
3878
- experiment,
3879
- runId: options.runId,
3880
- placeCell: options.placeCell,
3881
- ...options.maxConcurrency === void 0 ? {} : { maxConcurrency: options.maxConcurrency },
3882
- ...options.signal ? { signal: options.signal } : {},
3883
- ...options.candidate ? { candidate: options.candidate } : {},
3884
- ...optimizationReceipt ? { metadata: attachOptimizationActivationReceipt(options.metadata, optimizationReceipt) } : options.metadata ? { metadata: options.metadata } : {},
3885
- ...improvement.generationsExplored === void 0 ? {} : { generationsExplored: improvement.generationsExplored },
3886
- preparation
3887
- });
3888
- const proposal = createAgentImprovementProposal({
3889
- runId: options.runId,
3890
- findings: proposalFindings,
3891
- evaluation: measured.evaluation,
3892
- ...options.now ? { now: options.now } : {}
3893
- });
3894
- return {
3895
- analysis,
3896
- improvement,
3897
- experiment,
3898
- measurements: measured.measurements,
3899
- proposal
3900
- };
3901
- } catch (cause) {
3902
- return rethrowAfterCleanup(cause, () => improvement.dispose(), "proposeAgentImprovement failed");
3903
- }
3904
- }
3905
- function assertImprovementCandidateBinding(improvement, experiment) {
3906
- const candidate = improvement.candidate;
3907
- if (candidate.surface !== "code") {
3908
- try {
3909
- assertCandidateProfileBinding(candidate.profile, experiment.candidate.profile);
3910
- } catch (cause) {
3911
- throw new Error("candidate experiment does not contain the improvement winner", { cause });
3912
- }
3913
- return;
3914
- }
3915
- const surface = candidate.value;
3916
- const code = experiment.candidate.code;
3917
- 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) throw new Error("candidate experiment does not contain the improvement winner");
3918
- if (canonicalCandidateDigest$1(experiment.baseline.profile) !== canonicalCandidateDigest$1(experiment.candidate.profile)) throw new Error("code improvement candidate changed the agent profile");
3919
- }
3920
- /** Create the reviewable record only from a complete, recomputable experiment result. */
3921
- function createAgentImprovementProposal(options) {
3922
- const findings = assertProposalFindings(options.findings, "createAgentImprovementProposal findings");
3923
- const { evaluation, changedSurfaces } = validateShippableAgentImprovementEvaluation(options.evaluation, options.runId, "agent improvement proposal");
3924
- return agentImprovementProposalSchema.parse(canonicalCandidateDocument({
3925
- kind: "agent-improvement-proposal",
3926
- runId: options.runId,
3927
- changedSurfaces,
3928
- proposedAt: (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
3929
- findings: [...findings],
3930
- evaluation
3931
- }).value);
3932
- }
3933
- /** Persist a human or tenant-policy decision bound to one exact proposal. */
3934
- function reviewAgentImprovementProposal(inputProposal, input) {
3935
- const proposal = verifyAgentImprovementProposal(inputProposal);
3936
- if (!input.reviewedBy.trim()) throw new Error("candidate review requires reviewedBy");
3937
- if (!input.reason.trim()) throw new Error("candidate review requires a reason");
3938
- if (input.decision === "approve" && proposal.evaluation.decision.outcome !== "ship") throw new Error("candidate cannot be approved without a passing experiment");
3939
- const reviewedAt = (input.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
3940
- if (Date.parse(reviewedAt) < Date.parse(proposal.proposedAt)) throw new Error("candidate review cannot predate its proposal");
3941
- return agentImprovementReviewSchema.parse(canonicalCandidateDocument({
3942
- kind: "agent-improvement-review",
3943
- proposalDigest: proposal.digest,
3944
- decision: input.decision,
3945
- reviewedBy: input.reviewedBy,
3946
- reviewedAt,
3947
- reason: input.reason,
3948
- ...input.feedback === void 0 ? {} : { feedback: input.feedback }
3949
- }).value);
3950
- }
3951
- /** Authorize product-owned writes only after the exact candidate was measured and approved. */
3952
- function createAgentImprovementActivation(inputProposal, inputReview, options) {
3953
- const proposal = verifyAgentImprovementProposal(inputProposal);
3954
- const review = verifyAgentImprovementReview(inputReview);
3955
- if (review.decision !== "approve" || review.proposalDigest !== proposal.digest) throw new Error("candidate activation requires an approval for the exact proposal");
3956
- if (!options.fundingOwner.trim() || !options.authorizedBy.trim()) throw new Error("candidate activation authority must be non-empty");
3957
- const experiment = proposal.evaluation.experiment;
3958
- const authorizedAt = (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
3959
- if (Date.parse(authorizedAt) < Date.parse(review.reviewedAt)) throw new Error("candidate activation cannot predate its approval");
3960
- const targets = buildAgentImprovementActivationTargets(proposal.changedSurfaces, experiment, options.intent, options.targets);
3961
- const executionRef = profileActivationExecutionRef(experiment, targets, options.executionRef);
3962
- return agentImprovementActivationSchema.parse(canonicalCandidateDocument({
3963
- kind: "agent-improvement-activation",
3964
- proposalDigest: proposal.digest,
3965
- reviewDigest: review.digest,
3966
- experimentDigest: experiment.digest,
3967
- candidateDigest: measuredCandidateDigest(proposal),
3968
- ...executionRef ? { executionRef } : {},
3969
- intent: options.intent,
3970
- targets,
3971
- fundingOwner: options.fundingOwner,
3972
- authorizedBy: options.authorizedBy,
3973
- authorizedAt,
3974
- expiresAt: options.expiresAt
3975
- }).value);
3976
- }
3977
- /** Validate a proposal and recompute every binding to its measured experiment. */
3978
- function verifyAgentImprovementProposal(input) {
3979
- const proposal = verifyCanonicalCandidateDocument(agentImprovementProposalSchema.parse(input), "agent improvement proposal");
3980
- const { changedSurfaces } = validateShippableAgentImprovementEvaluation(proposal.evaluation, proposal.runId, "agent improvement proposal");
3981
- if (!(proposal.evaluation.kind === "agent-profile-improvement-measured-comparison" ? sameAgentImprovementSurfaceSet(proposal.changedSurfaces, changedSurfaces) : sameOrderedValues(proposal.changedSurfaces, changedSurfaces))) throw new Error("proposal changed surfaces do not match its exact experiment");
3982
- assertProposalFindings(proposal.findings, "agent improvement proposal findings");
3983
- return proposal;
3984
- }
3985
- /** Return a sealed bundle experiment; ordinary profile changes need a product-owned executor. */
3986
- function requireSealedCandidateExperiment(proposal) {
3987
- if (proposal.evaluation.kind !== "agent-improvement-measured-comparison") throw new Error("agent profile improvement activation requires a product profile-diff executor, not a sealed candidate bundle");
3988
- return proposal.evaluation.experiment;
3989
- }
3990
- function measuredCandidateDigest(proposal) {
3991
- return proposal.evaluation.kind === "agent-profile-improvement-measured-comparison" ? proposal.evaluation.experiment.candidate.stateDigest : proposal.evaluation.experiment.candidate.digest;
3992
- }
3993
- function profileActivationExecutionRef(experiment, targets, executionRef) {
3994
- if (!targets.some((target) => target.surface === "agent-profile")) {
3995
- if (executionRef !== void 0) throw new Error("profile activation executionRef is valid only for agent-profile targets");
3996
- return;
3997
- }
3998
- if (experiment.kind !== "agent-profile-improvement-experiment") throw new Error("agent-profile activation requires a measured profile experiment");
3999
- if (executionRef === void 0) throw new Error("profile improvement activation requires the measured executor");
4000
- const parsed = agentProfileImprovementExecutionRefSchema.parse(executionRef);
4001
- if (canonicalCandidateDigest$1(parsed) !== canonicalCandidateDigest$1(experiment.executionRef)) throw new Error("profile improvement activation executor does not match the measurement");
4002
- return parsed;
4003
- }
4004
- function validateShippableAgentImprovementEvaluation(input, runId, subject) {
4005
- const evaluation = verifyAgentImprovementEvaluation(input);
4006
- if (evaluation.decision.outcome !== "ship") throw new Error(`${subject} requires a passing experiment`);
4007
- if (runId !== evaluation.provenance.runId) throw new Error("proposal runId does not match its measured experiment");
4008
- return {
4009
- evaluation,
4010
- changedSurfaces: evaluation.kind === "agent-profile-improvement-measured-comparison" ? profileImprovementChangedSurfaces(evaluation.experiment.change) : deriveChangedSurfaces(evaluation.experiment.baseline, evaluation.experiment.candidate)
4011
- };
4012
- }
4013
- /** Use each owning package's complete measurement validator before a proposal is persisted. */
4014
- function verifyAgentImprovementEvaluation(input) {
4015
- if (typeof input === "object" && input !== null && "kind" in input && input.kind === "agent-profile-improvement-measured-comparison") {
4016
- const evaluation = verifyAgentProfileImprovementExperimentComparison(input);
4017
- optimizationActivationReceiptFromMetadata(evaluation.metadata);
4018
- return evaluation;
4019
- }
4020
- const evaluation = verifyCandidateExperimentComparison(input);
4021
- optimizationActivationReceiptFromMetadata(evaluation.metadata);
4022
- return evaluation;
4023
- }
4024
- /** Validate the canonical identity and wire shape of an improvement review. */
4025
- function verifyAgentImprovementReview(input) {
4026
- return verifyCanonicalCandidateDocument(agentImprovementReviewSchema.parse(input), "agent improvement review");
4027
- }
4028
- /** Validate activation authority against the exact proposal, review, experiment, and base state. */
4029
- function verifyAgentImprovementActivation(input) {
4030
- const proposal = verifyAgentImprovementProposal(input.proposal);
4031
- const review = verifyAgentImprovementReview(input.review);
4032
- const activation = verifyCanonicalCandidateDocument(agentImprovementActivationSchema.parse(input.activation), "agent improvement activation");
4033
- const experiment = proposal.evaluation.experiment;
4034
- if (review.decision !== "approve" || review.proposalDigest !== proposal.digest || activation.proposalDigest !== proposal.digest || activation.reviewDigest !== review.digest || activation.experimentDigest !== experiment.digest || activation.candidateDigest !== measuredCandidateDigest(proposal) || Date.parse(review.reviewedAt) < Date.parse(proposal.proposedAt) || Date.parse(activation.authorizedAt) < Date.parse(review.reviewedAt)) throw new Error("candidate activation does not bind the measured and approved candidate");
4035
- if (activation.targets.some((target) => target.surface === "agent-profile") && (proposal.evaluation.kind !== "agent-profile-improvement-measured-comparison" || activation.executionRef === void 0 || canonicalCandidateDigest$1(activation.executionRef) !== canonicalCandidateDigest$1(proposal.evaluation.experiment.executionRef))) throw new Error("profile activation does not bind the measured executor");
4036
- assertAgentImprovementActivationTargets(proposal.changedSurfaces, experiment, activation.intent, activation.targets);
4037
- return activation;
4038
- }
4039
- /** Recheck one Runtime receipt against its exact signed experiment cell. */
4040
- function verifyCandidateExecutionEvidence(input, options) {
4041
- const experiment = verifyCandidateExperiment(options.experiment);
4042
- const bundle = experiment[options.arm];
4043
- const task = experiment.benchmark.tasks[options.benchmarkCell.taskIndex];
4044
- const index = options.benchmarkCell.taskIndex * experiment.benchmark.suite.reps + options.benchmarkCell.repetition;
4045
- if (!task || options.benchmarkCell.suiteDigest !== experiment.benchmark.suite.digest || options.seed !== experiment.benchmark.suite.seeds[index]) throw new Error("candidate execution evidence points outside its signed experiment");
4046
- const evidence = verifyCanonicalCandidateDocument(candidateExecutionEvidenceSchema.parse(input), "candidate execution evidence");
4047
- const materialization = verifyCanonicalCandidateDocument(agentCandidateMaterializationReceiptSchema.parse(evidence.materializationReceipt), "candidate materialization receipt");
4048
- const receipt = verifyCanonicalCandidateDocument(agentCandidateRunReceiptSchema.parse(evidence.receipt), "candidate run receipt");
4049
- const plan = materialization.executionPlan;
4050
- const cell = plan.material.runCell;
4051
- const attempt = options.attempt ?? 1;
4052
- 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$1(omitTopLevelDigest(cell)) !== cell.digest) throw new Error("candidate execution receipt substituted its signed experiment cell");
4053
- assertCapturedInput(materialization.benchmark.suite, experiment.benchmark.suite, "benchmark suite");
4054
- assertCapturedInput(materialization.benchmark.task, task, "benchmark task");
4055
- assertEvidenceMaterialDigest(plan, "candidate execution plan");
4056
- assertEvidenceMaterialDigest(materialization.profileActivation.profilePlan, "candidate profile plan");
4057
- const expectedProfilePlan = materializeAgentCandidateProfilePlan({
4058
- profile: bundle.profile,
4059
- harness: bundle.execution.harness,
4060
- launch: bundle.execution.launch,
4061
- workspace: bundle.execution.cwd.workspace,
4062
- workspaces: plan.material.workspaces,
4063
- resolvedResources: options.resolvedResources
4064
- });
4065
- const activation = parseAgentCandidateProfileActivation(materialization.profileActivation, materialization.profileActivation.profilePlan.digest);
4066
- const regeneratedActivation = createAgentCandidateProfileActivation(expectedProfilePlan, materialization.profileActivation.profilePlan);
4067
- if (activation.digest !== regeneratedActivation.digest) throw new Error("candidate profile activation does not match the experiment bundle");
4068
- if (materialization.bundleDigest !== bundle.digest || receipt.bundleDigest !== bundle.digest || receipt.runCellDigest !== cell.digest || receipt.materializationReceiptDigest !== materialization.digest || receipt.executionPlanDigest !== plan.digest) throw new Error("candidate execution evidence does not bind one exact Runtime run");
4069
- assertEvidenceMaterialDigest(receipt.modelSettlement, "candidate model settlement");
4070
- assertEvidenceMaterialDigest(receipt.taskOutcome, "candidate task outcome");
4071
- assertEvidenceMaterialDigest(receipt.benchmarkResult, "candidate benchmark result");
4072
- return immutableCandidateValue(evidence);
4073
- }
4074
- function assertExactExperimentInput(input, experiment, bundle) {
4075
- const task = experiment.benchmark.tasks[input.benchmarkCell.taskIndex];
4076
- const index = input.benchmarkCell.taskIndex * experiment.benchmark.suite.reps + input.benchmarkCell.repetition;
4077
- 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]) throw new Error("Runtime received a substituted candidate experiment cell");
4078
- }
4079
- function assertCapturedInput(captured, expected, label) {
4080
- const bytes = canonicalCandidateBytes$1(omitTopLevelDigest(expected));
4081
- if (captured.digest !== expected.digest || captured.material.sha256 !== expected.digest || captured.material.byteLength !== bytes.byteLength) throw new Error(`candidate materialization substituted its ${label}`);
4082
- }
4083
- function assertEvidenceMaterialDigest(evidence, label) {
4084
- const bytes = canonicalCandidateBytes$1(evidence.material);
4085
- if (canonicalCandidateDigest$1(evidence.material) !== evidence.digest || evidence.artifact.sha256 !== evidence.digest || evidence.artifact.byteLength !== bytes.byteLength) throw new Error(`${label} digest does not match its canonical material`);
4086
- }
4087
- function sameOrderedValues(left, right) {
4088
- return left.length === right.length && left.every((value, index) => value === right[index]);
4089
- }
4090
- //#endregion
4091
- export { commandVerifier as $, agentImprovementTargetInput as A, assertCandidateValidator as B, optimizationActivationReceiptFromMetadata as C, agentImprovementProfileSurfaceDigest as D, agentImprovementProfileDiffs as E, isAgentImprovementProfileSurface as F, rawTraceDistiller as G, parseExecutionRef as H, isAgentProfileMeasuredSurface as I, normalizeRolloutPolicy as J, ROLLOUT_POLICY_EXTENSION as K, improve as L, agentProfileImprovementStateDigest as M, assertProfileImprovementTargetsShareIdentity as N, agentImprovementProfileSurfaceInput as O, buildAgentImprovementActivationTargets as P, agenticGenerator as Q, createCommandProfileTrainer as R, createOptimizationActivationReceipt as S, AGENT_PROFILE_MEASURED_SURFACES as T, privateValuePaths as U, assertProfileTrainingIsHeldOut as V, withMethodRuntimeControls as W, serializeRolloutPolicy as X, parseRolloutPolicy as Y, structuralRolloutPolicyFromProfile as Z, profilePolicyWithBudget as _, executeAgentCandidateExperimentCell as a, profileTaskScenarioIdentity as b, requireSealedCandidateExperiment as c, verifyAgentImprovementActivation as d, defaultBuildPrompt as et, verifyAgentImprovementProposal as f, profileImprovementMetadata as g, createProfileImprovementCostLedger as h, createAgentImprovementProposal as i, agentImprovementTargetProfileDiffs as j, agentImprovementTargetDigest as k, reviewAgentImprovementProposal as l, verifyCandidateExecutionEvidence as m, createAgentImprovementActivation as n, proposeAgentImprovement as o, verifyAgentImprovementReview as p, applyRolloutPolicyToProfile as q, createAgentImprovementMeasuredComparison as r, proposeAgentProfileImprovement as s, AgentCandidateExperimentCellExecutionError as t, runAgentCandidateExperiment as u, profilePreparationAccounting as v, AGENT_IMPROVEMENT_PROFILE_SURFACES as w, sealProfileImprovementBenchmark as x, profileStateDigest as y, searchMethod as z };
2946
+ export { assertProfileTrainingIsHeldOut as a, withMethodRuntimeControls as c, agenticGenerator as d, commandVerifier as f, isUsageAmount as g, createRuntimeUsageTotals as h, assertCandidateValidator as i, rawTraceDistiller as l, addRuntimeUsage as m, createCommandProfileTrainer as n, parseExecutionRef as o, defaultBuildPrompt as p, searchMethod as r, privateValuePaths as s, improve as t, rethrowAfterCleanup as u };
4092
2947
 
4093
- //# sourceMappingURL=improvement-cycle-D1I4hQvf.js.map
2948
+ //# sourceMappingURL=improve-CWGBT13K.js.map