@tangle-network/agent-runtime 0.279.0 → 0.281.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 (58) hide show
  1. package/dist/{activation-B5NExoOz.d.ts → activation-BcTWDNOD.d.ts} +151 -25
  2. package/dist/{activation-BkUdrvqh.js → activation-C1ZAyQrQ.js} +2 -2
  3. package/dist/{activation-BkUdrvqh.js.map → activation-C1ZAyQrQ.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-BBL_OgRw.js → coordination-driver-B-HOpGN4.js} +2 -2
  7. package/dist/{coordination-driver-BBL_OgRw.js.map → coordination-driver-B-HOpGN4.js.map} +1 -1
  8. package/dist/{delegate-CZc7B-Tl.js → delegate-C1eIBN70.js} +2 -2
  9. package/dist/{delegate-CZc7B-Tl.js.map → delegate-C1eIBN70.js.map} +1 -1
  10. package/dist/durable.d.ts +2 -2
  11. package/dist/durable.js +768 -499
  12. package/dist/durable.js.map +1 -1
  13. package/dist/{graph-Ci8Ufs_f.js → graph-KjJaTmbO.js} +4 -4
  14. package/dist/{graph-Ci8Ufs_f.js.map → graph-KjJaTmbO.js.map} +1 -1
  15. package/dist/{improvement-cycle-Bi43xCVa.js → improvement-cycle-DCTCTmNl.js} +763 -43
  16. package/dist/improvement-cycle-DCTCTmNl.js.map +1 -0
  17. package/dist/{index-Dm8SHDGW.d.ts → index-BSSGMvUd.d.ts} +97 -144
  18. package/dist/index.d.ts +4 -4
  19. package/dist/index.js +8 -8
  20. package/dist/intelligence.d.ts +1 -1
  21. package/dist/intelligence.js +3 -3
  22. package/dist/kernel.d.ts +1 -1
  23. package/dist/kernel.js +8 -8
  24. package/dist/{loop-runner-bin-C9FJshTP.js → loop-runner-bin-Co2eBFbb.js} +3 -3
  25. package/dist/{loop-runner-bin-C9FJshTP.js.map → loop-runner-bin-Co2eBFbb.js.map} +1 -1
  26. package/dist/{loop-runner-bin-D6khQtoC.d.ts → loop-runner-bin-DgeZHpWJ.d.ts} +2 -2
  27. package/dist/loop-runner-bin.d.ts +1 -1
  28. package/dist/loop-runner-bin.js +1 -1
  29. package/dist/mcp/bin.js +3 -3
  30. package/dist/mcp/index.d.ts +1 -1
  31. package/dist/mcp/index.js +4 -4
  32. package/dist/platform.d.ts +34 -36
  33. package/dist/platform.js +122 -29
  34. package/dist/platform.js.map +1 -1
  35. package/dist/{provision-supervisor-BvnihiyB.js → provision-supervisor-CkN8RRjv.js} +3 -3
  36. package/dist/{provision-supervisor-BvnihiyB.js.map → provision-supervisor-CkN8RRjv.js.map} +1 -1
  37. package/dist/{runtime-DsAHXig2.js → runtime-B_yRPBjj.js} +16 -966
  38. package/dist/runtime-B_yRPBjj.js.map +1 -0
  39. package/dist/{server-Dyc1zvug.js → server-dOyG5Tw6.js} +3 -3
  40. package/dist/{server-Dyc1zvug.js.map → server-dOyG5Tw6.js.map} +1 -1
  41. package/dist/{structural-rollout-D-0X6lsU.js → shared-box-CZFdugL1.js} +959 -9
  42. package/dist/shared-box-CZFdugL1.js.map +1 -0
  43. package/dist/{supervise-DBQdrp7H.js → supervise-zt91I62x.js} +3 -3
  44. package/dist/{supervise-DBQdrp7H.js.map → supervise-zt91I62x.js.map} +1 -1
  45. package/dist/{supervisor-DtlPj9me.js → supervisor-UXgaPisu.js} +49 -58
  46. package/dist/supervisor-UXgaPisu.js.map +1 -0
  47. package/dist/testing.d.ts +1 -1
  48. package/dist/testing.js +12 -12
  49. package/dist/tui/index.d.ts +1 -1
  50. package/dist/tui/index.js +1 -1
  51. package/package.json +4 -4
  52. package/skills/profile-authoring/SKILL.md +210 -0
  53. package/skills/supervise/SKILL.md +2 -2
  54. package/dist/improvement-cycle-Bi43xCVa.js.map +0 -1
  55. package/dist/runtime-DsAHXig2.js.map +0 -1
  56. package/dist/structural-rollout-D-0X6lsU.js.map +0 -1
  57. package/dist/supervisor-DtlPj9me.js.map +0 -1
  58. package/skills/supervise/references/profile-authoring.md +0 -19
package/dist/durable.js CHANGED
@@ -1,16 +1,18 @@
1
- import { $i as detachedSnapshot, Ai as readCommittedJsonLines, Di as isNoEntError, E as failedItems, Kt as loadSpawnForest, Oa as zeroSpend, Oi as parseCommittedJsonLines, Pi as authoredProfileDigest, ga as cloneSpend, ji as writeAllBytes, jr as contentAddress, ki as prepareJsonlAppend, ma as addSpend, zt as FileSpawnJournal } from "./supervisor-DtlPj9me.js";
1
+ import { $i as detachedSnapshot, Ai as readCommittedJsonLines, Bt as FileSpawnJournal, E as failedItems, Oa as zeroSpend, Oi as isNoEntError, Pi as authoredProfileDigest, ga as cloneSpend, ji as writeAllBytes, ki as prepareJsonlAppend, kr as contentAddress, ma as addSpend, qt as loadSpawnForest } from "./supervisor-UXgaPisu.js";
2
2
  import { f as RuntimeRunStateError, m as ValidationError } from "./errors-DodWX-cb.js";
3
3
  import { a as withPursuitContext, t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
4
4
  import { a as writeAtomicDurableFile, r as publishExclusiveDurableFile } from "./durable-file-DWQA4ooo.js";
5
5
  import { i as applyExactAgentProfileDiff } from "./profile-D3eXNBQV.js";
6
- import { _ as readRootStream, g as ROOT_STREAM_FILE, i as superviseRootProfile, r as supervise, v as readRootStreamReceipt } from "./supervise-DBQdrp7H.js";
6
+ import { _ as readRootStream, g as ROOT_STREAM_FILE, i as superviseRootProfile, r as supervise, v as readRootStreamReceipt } from "./supervise-zt91I62x.js";
7
7
  import { h as supervisorRunDir } from "./run-layout-vwd4SwX_.js";
8
- import { canonicalCandidateDigest, canonicalCandidateJson, sha256Bytes } from "@tangle-network/agent-interface";
8
+ import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, canonicalCandidateJson, sha256Bytes } from "@tangle-network/agent-interface";
9
9
  import { createHash } from "node:crypto";
10
10
  import { execFile } from "node:child_process";
11
11
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
12
- import { mkdir, open, readFile, realpath, rmdir, unlink } from "node:fs/promises";
12
+ import { access, mkdir, readFile, realpath, rmdir, unlink } from "node:fs/promises";
13
13
  import { promisify } from "node:util";
14
+ import { SearchRecorder, developmentClaim, incumbent, openSearchLedger, parseSearchLedgerLine, runSearch, uniform } from "@tangle-network/agent-eval/campaign";
15
+ import { pathToFileURL } from "node:url";
14
16
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
15
17
  //#region src/durable/chat-engine.ts
16
18
  const encoder = new TextEncoder();
@@ -959,6 +961,767 @@ async function readFailureRecord(runDir) {
959
961
  return parsed;
960
962
  }
961
963
  //#endregion
964
+ //#region src/durable/pursuit-versions.ts
965
+ /**
966
+ * The pursuit version chain, on Eval's search kernel (`runSearch`).
967
+ *
968
+ * A version is a search node: the exact AgentProfile it executes, content-addressed by
969
+ * `canonicalAgentProfileDigest`. Every later version is an edge from the version the chain keeps,
970
+ * whose diff is the one change `next` returned, and one cell: a `supervisePursuit` run of the
971
+ * version, forked from its parent's sealed `result.json`, then scored by the outside judge. The
972
+ * policy is the kernel's hill climb, `incumbent({ patience, minImprovement })`. The search ledger
973
+ * at `<runDir>.search/ledger.jsonl` is the chain's only record and its only checkpoint: a call on
974
+ * a closed chain reads it back, and a call on an open chain continues it.
975
+ */
976
+ /** Where `'review-of-best'` mounts a review: `inputs/review/version-<n>.md`. One review lives in
977
+ * a profile at a time. */
978
+ const REVIEW_DIR = "inputs/review/";
979
+ /** The chain's directory beside the first version's: the ledger and its content blobs. */
980
+ function pursuitVersionsLedgerPath(runDir) {
981
+ return resolve(`${resolve(runDir.trim())}.search`, "ledger.jsonl");
982
+ }
983
+ /**
984
+ * Validate a `versions` option before any compute. The same check runs inside `supervisePursuit`;
985
+ * a caller that records the option as data can run it at preflight.
986
+ */
987
+ function assertPursuitVersions(versions) {
988
+ const fail = (message) => {
989
+ throw new ValidationError(`supervisePursuit versions: ${message}`);
990
+ };
991
+ if (typeof versions !== "object" || versions === null) fail("must be an object");
992
+ const option = versions;
993
+ const extra = Object.keys(option).filter((key) => ![
994
+ "judge",
995
+ "next",
996
+ "stop"
997
+ ].includes(key));
998
+ if (extra.length > 0) fail(`unknown fields: ${extra.join(", ")}`);
999
+ const { judge, next, stop } = option;
1000
+ if (typeof judge !== "object" || judge === null || typeof judge.judge !== "function") fail("judge must be a VersionJudge, such as declaredCheckJudge(check)");
1001
+ else if (!isSha256(judge.digest)) fail("judge.digest must be a sha256 digest (sha256:<64 hex>)");
1002
+ if (next !== "review-of-best" && typeof next !== "function") fail("next must be a function or 'review-of-best'");
1003
+ if (typeof stop !== "object" || stop === null) fail("stop must be an object");
1004
+ const rule = stop;
1005
+ const known = /* @__PURE__ */ new Set([
1006
+ "patience",
1007
+ "maxVersions",
1008
+ "maxUsd",
1009
+ "deadlineMs",
1010
+ "minImprovement"
1011
+ ]);
1012
+ const unknown = Object.keys(rule).filter((key) => !known.has(key));
1013
+ if (unknown.length > 0) fail(`stop has unknown fields: ${unknown.join(", ")}`);
1014
+ for (const key of ["patience", "maxVersions"]) if (!Number.isInteger(rule[key]) || rule[key] < 1) fail(`stop.${key} must be an integer of at least 1`);
1015
+ for (const key of ["maxUsd", "deadlineMs"]) if (!isFiniteNumber(rule[key]) || rule[key] <= 0) fail(`stop.${key} must be a finite number above 0`);
1016
+ if (rule.minImprovement !== void 0 && (!isFiniteNumber(rule.minImprovement) || rule.minImprovement < 0)) fail("stop.minImprovement must be a finite number of at least 0");
1017
+ }
1018
+ /** Every rule the chain adds to the kernel's. Its digest, with the stop rule, is the process
1019
+ * revision the ledger records, so a changed rule or stop rule is a different search. */
1020
+ const VERSION_CHAIN_DEFINITION = {
1021
+ name: "agent-runtime.pursuit-versions.2026-09",
1022
+ node: "the exact AgentProfile a version executes, content-addressed by canonicalAgentProfileDigest; a change that does not apply is a node addressed by its parent digest and change, and refused",
1023
+ edge: "one change from the kept version, stored as its Interface profile diff",
1024
+ cell: "one supervisePursuit run of the version on the pursuit task, forked from its parent sealed result.json, then scored by the outside judge; a settled version directory is read back after its root identity and fork seal are checked",
1025
+ outcome: "a scored winner passes; a scored no-winner fails with its reason; an unscored version is a retryable error; a run that throws fails the call and leaves its cell open",
1026
+ deadline: "the chain deadline aborts a running version; its judge still runs",
1027
+ directories: "version n runs at <runDir>.v<n> with run id <runId>.v<n>; version 1 at <runDir>"
1028
+ };
1029
+ const VERSION_CHAIN_URI = "npm:@tangle-network/agent-runtime#supervisePursuit.versions";
1030
+ /** The pursuit task's one train task. */
1031
+ const TASK_ID = "pursuit";
1032
+ const LANE = "in-process";
1033
+ /** The longest delay Node's setTimeout honors. */
1034
+ const MAX_TIMER_MS = 2147483647;
1035
+ /** Run a version chain. `supervisePursuit` calls this when `versions` is set. */
1036
+ async function runPursuitVersions(profile, task, opts, runOne) {
1037
+ const { versions, fork: firstFork, signal: callerSignal, ...base } = opts;
1038
+ assertPursuitVersions(versions);
1039
+ for (const key of [
1040
+ "journal",
1041
+ "blobs",
1042
+ "rootHandle",
1043
+ "steerDir"
1044
+ ]) if (base[key] !== void 0) throw new ValidationError(`supervisePursuit versions: ${key} names one run, and a version chain has one per version; omit it`);
1045
+ if (versions.next === "review-of-best" && base.continuation?.profile.review === void 0) throw new ValidationError("supervisePursuit versions: next 'review-of-best' needs continuation.profile.review, the words the next version reads about its review");
1046
+ const { judge, stop } = versions;
1047
+ if (base.budget.maxUsd !== void 0 && base.budget.maxUsd > stop.maxUsd) throw new ValidationError(`supervisePursuit versions: budget.maxUsd ${base.budget.maxUsd} is above stop.maxUsd ${stop.maxUsd}, so no version could start`);
1048
+ const next = versions.next === "review-of-best" ? reviewOfBest(base.runId ?? "supervise", base.continuation?.profile.review ?? "") : versions.next;
1049
+ const now = base.now ?? Date.now;
1050
+ const pursuitId = base.pursuitId.trim();
1051
+ const runDir = resolve(base.runDir.trim());
1052
+ const runId = base.runId ?? "supervise";
1053
+ const ledgerPath = pursuitVersionsLedgerPath(runDir);
1054
+ const searchId = `versions:${pursuitId}:${runId}`;
1055
+ const retired = resolve(`${runDir}.versions`, "versions.jsonl");
1056
+ if (await exists(retired)) throw new ValidationError(`supervisePursuit versions: ${retired} holds a chain in the retired versions.jsonl format; finish it on the agent-runtime release that wrote it, or start a new chain in another runDir`);
1057
+ const firstProfile = firstFork === void 0 ? profile : applyExactAgentProfileDiff(profile, firstFork.change, "supervisePursuit versions");
1058
+ const taskRevision = digestOf(task, "task");
1059
+ const identity = (nodeProfile) => ({
1060
+ model: {
1061
+ provider: "agent-runtime",
1062
+ alias: "supervisePursuit",
1063
+ unknown: "a version runs every model its tree chose; the version's settle record names them"
1064
+ },
1065
+ agent: {
1066
+ uri: `agent-profile:${pursuitId}`,
1067
+ revision: canonicalAgentProfileDigest(nodeProfile)
1068
+ },
1069
+ benchmark: {
1070
+ uri: `pursuit:${pursuitId}`,
1071
+ revision: taskRevision
1072
+ }
1073
+ });
1074
+ const ledger = openSearchLedger({
1075
+ path: ledgerPath,
1076
+ searchId
1077
+ });
1078
+ const deadline = (await ledger.state()).header?.budget.deadline ?? new Date(now() - settledElapsed(await readSettleRecord(runDir)) + stop.deadlineMs).toISOString();
1079
+ const policy = incumbent({
1080
+ patience: stop.patience,
1081
+ ...stop.minImprovement === void 0 ? {} : { minImprovement: stop.minImprovement }
1082
+ });
1083
+ const allocation = uniform();
1084
+ const recorder = await SearchRecorder.open({
1085
+ ledger,
1086
+ now
1087
+ }, {
1088
+ subject: pursuitId,
1089
+ process: {
1090
+ name: "pursuit-versions",
1091
+ executionRef: {
1092
+ uri: VERSION_CHAIN_URI,
1093
+ revision: canonicalCandidateDigest({
1094
+ ...VERSION_CHAIN_DEFINITION,
1095
+ stop: canonicalStop(stop)
1096
+ })
1097
+ }
1098
+ },
1099
+ artifactKind: "agent-profile",
1100
+ objective: {
1101
+ metric: "version-judge-score",
1102
+ direction: "maximize",
1103
+ judge: {
1104
+ uri: "agent-runtime:version-judge",
1105
+ revision: judge.digest
1106
+ },
1107
+ claim: developmentClaim(pursuitId)
1108
+ },
1109
+ splits: {
1110
+ train: [{
1111
+ taskId: TASK_ID,
1112
+ unitId: TASK_ID,
1113
+ source: {
1114
+ uri: `pursuit:${pursuitId}`,
1115
+ revision: taskRevision
1116
+ }
1117
+ }],
1118
+ selection: [],
1119
+ test: [],
1120
+ heldOutUnits: true
1121
+ },
1122
+ policy: {
1123
+ expansion: policy.name,
1124
+ allocation: allocation.name,
1125
+ seed: 0
1126
+ },
1127
+ budget: {
1128
+ maxUsd: stop.maxUsd,
1129
+ maxCells: null,
1130
+ maxNodes: stop.maxVersions,
1131
+ deadline,
1132
+ maxConcurrency: 1,
1133
+ reservedClaimUsd: 0
1134
+ },
1135
+ containment: null,
1136
+ derivedFrom: null,
1137
+ identity: identity(firstProfile)
1138
+ });
1139
+ const deadlineAt = Date.parse(deadline);
1140
+ const expired = new AbortController();
1141
+ let timer;
1142
+ const arm = () => {
1143
+ const remaining = deadlineAt - now();
1144
+ if (remaining <= 0) {
1145
+ expired.abort(/* @__PURE__ */ new Error("the version chain reached its deadline"));
1146
+ return;
1147
+ }
1148
+ timer = setTimeout(arm, Math.min(remaining, MAX_TIMER_MS));
1149
+ timer.unref?.();
1150
+ };
1151
+ arm();
1152
+ const codec = {
1153
+ node(store, node) {
1154
+ if (node.profile !== null) {
1155
+ const artifact = store.blob("agent-profile", {
1156
+ kind: "agent-profile",
1157
+ profile: node.profile
1158
+ });
1159
+ return {
1160
+ artifactDigest: canonicalAgentProfileDigest(node.profile),
1161
+ artifact,
1162
+ surfaces: [{
1163
+ surfaceId: "profile",
1164
+ kind: "agent-profile",
1165
+ artifact
1166
+ }]
1167
+ };
1168
+ }
1169
+ const refused = {
1170
+ kind: "unapplied-change",
1171
+ parentDigest: node.parentDigest ?? null,
1172
+ change: node.change ?? null
1173
+ };
1174
+ const artifact = store.blob("change", {
1175
+ ...refused,
1176
+ refusal: node.refusal
1177
+ });
1178
+ return {
1179
+ artifactDigest: canonicalCandidateDigest(refused),
1180
+ artifact,
1181
+ surfaces: [{
1182
+ surfaceId: "profile",
1183
+ kind: "agent-profile",
1184
+ artifact
1185
+ }]
1186
+ };
1187
+ },
1188
+ diff(store, parent, child) {
1189
+ if (parent.profile === null || child.profile === null || child.change === void 0) return { unknown: "a refused change has no profile to diff" };
1190
+ const from = canonicalAgentProfileDigest(parent.profile);
1191
+ if (child.parentDigest !== from) return { unknown: "the change was written against another parent" };
1192
+ return store.blob("diff", {
1193
+ kind: "agent-profile-diff",
1194
+ from,
1195
+ to: canonicalAgentProfileDigest(child.profile),
1196
+ diffs: [child.change]
1197
+ });
1198
+ },
1199
+ load(store, node) {
1200
+ return loadNode(store, node);
1201
+ }
1202
+ };
1203
+ const executor = {
1204
+ lanes: () => [{
1205
+ name: LANE,
1206
+ capacity: 1,
1207
+ costCap: "estimate",
1208
+ cellUsd: base.budget.maxUsd ?? 0
1209
+ }],
1210
+ place: () => LANE,
1211
+ adopt: async () => null,
1212
+ async run(work) {
1213
+ const chain = await versionsOf();
1214
+ const record = chain.get(work.nodeId);
1215
+ if (record?.profile == null) throw new RuntimeRunStateError(`version node ${work.nodeId} has no profile to run`);
1216
+ const parent = record.parentNodeId === null ? void 0 : chain.get(record.parentNodeId);
1217
+ if (parent !== void 0 && (parent.seal === void 0 || parent.profile === null)) throw new RuntimeRunStateError(`version ${record.version}'s parent has no sealed result`);
1218
+ if (await readSettleRecord(record.runDir) === void 0) await runVersion(record, parent, AbortSignal.any([work.signal, expired.signal]));
1219
+ const { settled, byteLength } = await readVersion(record, parent);
1220
+ const charged = !record.seals.has(settled.settleDigest);
1221
+ return cellResult(settled, byteLength, await judgeVersion(settled, work.signal), work.lane, charged);
1222
+ }
1223
+ };
1224
+ const proposerSource = {
1225
+ uri: versions.next === "review-of-best" ? `${VERSION_CHAIN_URI}.review-of-best` : `${VERSION_CHAIN_URI}.next`,
1226
+ revision: canonicalCandidateDigest({ next: versions.next === "review-of-best" ? "review-of-best" : Function.prototype.toString.call(versions.next) })
1227
+ };
1228
+ const proposer = {
1229
+ name: versions.next === "review-of-best" ? "review-of-best" : "next",
1230
+ kind: "optimizer",
1231
+ source: proposerSource,
1232
+ execution: {
1233
+ kind: "deterministic",
1234
+ source: proposerSource
1235
+ },
1236
+ childrenPerProposal: 1,
1237
+ async propose(request) {
1238
+ const parent = request.parents[0];
1239
+ const judged = await judgedVersions(await versionsOf());
1240
+ const best = judged.find((version) => version.nodeId === parent.nodeId);
1241
+ if (best === void 0 || parent.artifact.profile === null) throw new RuntimeRunStateError(`supervisePursuit versions: the kept version ${parent.nodeId} has no judged run to fork from`);
1242
+ const change = await next({
1243
+ best,
1244
+ last: judged.at(-1),
1245
+ versions: Object.freeze(judged)
1246
+ }, request.signal);
1247
+ if (typeof change?.id !== "string" || change.id.trim().length === 0) throw new ValidationError("supervisePursuit versions: next must return a change with an id");
1248
+ const parentDigest = canonicalAgentProfileDigest(parent.artifact.profile);
1249
+ let child;
1250
+ try {
1251
+ child = {
1252
+ profile: applyExactAgentProfileDiff(parent.artifact.profile, change, "supervisePursuit versions"),
1253
+ change,
1254
+ parentDigest,
1255
+ refusal: null
1256
+ };
1257
+ } catch (error) {
1258
+ child = {
1259
+ profile: null,
1260
+ change,
1261
+ parentDigest,
1262
+ refusal: errorMessage$1(error)
1263
+ };
1264
+ }
1265
+ return {
1266
+ children: [{
1267
+ artifact: child,
1268
+ label: change.title ?? change.id,
1269
+ rationale: (change.source?.notes ?? []).join("\n")
1270
+ }],
1271
+ accounting: versions.next === "review-of-best" ? FREE : {
1272
+ tokens: {
1273
+ status: "unknown",
1274
+ reason: "the caller's next reports no usage"
1275
+ },
1276
+ cost: {
1277
+ status: "unknown",
1278
+ knownLowerBoundUsd: 0,
1279
+ reason: "the caller's next reports no spend"
1280
+ }
1281
+ }
1282
+ };
1283
+ }
1284
+ };
1285
+ try {
1286
+ const closed = await runSearch({
1287
+ recorder,
1288
+ root: {
1289
+ profile: firstProfile,
1290
+ refusal: null
1291
+ },
1292
+ codec,
1293
+ policy,
1294
+ allocation,
1295
+ proposer,
1296
+ executor,
1297
+ admit: (node) => node.refusal,
1298
+ ...callerSignal === void 0 ? {} : { signal: callerSignal },
1299
+ now
1300
+ });
1301
+ const judged = await judgedVersions(await versionsOf());
1302
+ const best = judged.find((version) => version.nodeId === closed.leader);
1303
+ if (best === void 0) throw new RuntimeRunStateError(`supervisePursuit versions: the chain in ${ledgerPath} closed (${closed.reason}) without a judged version to keep`);
1304
+ const observerPath = resolve(best.runDir, "observer.jsonl");
1305
+ return Object.freeze({
1306
+ result: best.result,
1307
+ pursuit: projectPursuit(await new FileObserverJournal(observerPath, pursuitId).read()),
1308
+ observerPath,
1309
+ settlePath: resolve(best.runDir, SETTLE_RECORD_FILE),
1310
+ versions: Object.freeze({
1311
+ ledgerPath,
1312
+ searchId,
1313
+ reason: closed.reason,
1314
+ best: best.version,
1315
+ versions: Object.freeze(judged),
1316
+ spend: closed.state.audit.spend,
1317
+ receipt: recorder.receipt({
1318
+ producerId: "pursuit-versions",
1319
+ runId
1320
+ })
1321
+ })
1322
+ });
1323
+ } finally {
1324
+ if (timer !== void 0) clearTimeout(timer);
1325
+ }
1326
+ /** Run one version: the first as the call's own run, a later one as a fork of its parent. */
1327
+ async function runVersion(record, parent, signal) {
1328
+ if (parent === void 0 || record.change === void 0) {
1329
+ await runOne(profile, task, {
1330
+ ...base,
1331
+ runId: record.runId,
1332
+ runDir: record.runDir,
1333
+ ...firstFork === void 0 ? {} : { fork: firstFork },
1334
+ signal
1335
+ });
1336
+ return;
1337
+ }
1338
+ const fork = {
1339
+ runDir: parent.runDir,
1340
+ settleDigest: parent.seal.sha256,
1341
+ change: record.change,
1342
+ acceptUncertain: true
1343
+ };
1344
+ const check = parent.verdict?.check;
1345
+ await runOne(parent.profile, task, {
1346
+ ...base,
1347
+ ...base.continuation !== void 0 && check !== void 0 ? { continuation: {
1348
+ ...base.continuation,
1349
+ best: {
1350
+ label: `v${parent.version}`,
1351
+ verdict: check
1352
+ }
1353
+ } } : {},
1354
+ runId: record.runId,
1355
+ runDir: record.runDir,
1356
+ fork,
1357
+ signal
1358
+ });
1359
+ }
1360
+ /**
1361
+ * Read a settled version back and check it is this node's run: its root ran the node's profile
1362
+ * and, for a fork, recorded the parent's seal and the change. A directory that holds another
1363
+ * run is refused, never adopted.
1364
+ */
1365
+ async function readVersion(record, parent) {
1366
+ const { bytes, result } = await readSealed(record.runDir, record.version);
1367
+ if (result.tree.root !== record.runId) throw new RuntimeRunStateError(`supervisePursuit versions: ${record.runDir} holds run '${result.tree.root}', not version ${record.version}'s '${record.runId}'`);
1368
+ const root = (await new FileSpawnJournal(resolve(record.runDir, "spawn-journal.jsonl")).loadTree(record.runId))?.find((event) => event.kind === "spawned" && event.parent === void 0);
1369
+ const ran = root?.identity?.profileDigest;
1370
+ const expected = authoredProfileDigest(superviseRootProfile(record.profile, base.profileGuidance));
1371
+ const correlation = root?.identity?.correlation;
1372
+ const fork = parent !== void 0 ? {
1373
+ settleDigest: parent.seal?.sha256,
1374
+ changeId: record.change?.id
1375
+ } : firstFork === void 0 ? void 0 : {
1376
+ settleDigest: firstFork.settleDigest,
1377
+ changeId: firstFork.change.id
1378
+ };
1379
+ const mismatch = [
1380
+ ran !== expected ? `its root ran profile ${ran}, not ${expected}` : void 0,
1381
+ fork !== void 0 && correlation?.forkParentSettleDigest !== fork.settleDigest ? `its root forked from seal ${correlation?.forkParentSettleDigest}, not ${fork.settleDigest}` : void 0,
1382
+ fork !== void 0 && correlation?.forkProfileDiffId !== fork.changeId ? `its root applied change ${correlation?.forkProfileDiffId}, not ${fork.changeId}` : void 0
1383
+ ].filter((item) => item !== void 0);
1384
+ if (mismatch.length > 0) throw new RuntimeRunStateError(`supervisePursuit versions: version ${record.version} at ${record.runDir} is not this chain's run: ${mismatch.join("; ")}`);
1385
+ return {
1386
+ settled: versionOf(record, parent, bytes, result),
1387
+ byteLength: bytes.byteLength
1388
+ };
1389
+ }
1390
+ async function judgeVersion(settled, signal) {
1391
+ const verdict = await judge.judge(settled, signal);
1392
+ if (typeof verdict !== "object" || verdict === null) throw new ValidationError("supervisePursuit versions: the judge returned no verdict");
1393
+ if (verdict.judgeDigest !== judge.digest) throw new ValidationError(`supervisePursuit versions: the verdict for version ${settled.version} carries ${String(verdict.judgeDigest)}, not the pinned judge ${judge.digest}`);
1394
+ if (verdict.score !== null && !isFiniteNumber(verdict.score)) throw new ValidationError("supervisePursuit versions: a verdict score must be a finite number or null");
1395
+ return JSON.parse(JSON.stringify(verdict));
1396
+ }
1397
+ function cellResult(settled, byteLength, verdict, lane, charged) {
1398
+ const spent = settled.result.spentTotal;
1399
+ const settlePath = resolve(settled.runDir, SETTLE_RECORD_FILE);
1400
+ return {
1401
+ outcome: verdict.score === null ? {
1402
+ status: "errored",
1403
+ metrics: {},
1404
+ error: {
1405
+ code: "unscored",
1406
+ message: `the judge could not score version ${settled.version}`,
1407
+ retryable: true
1408
+ }
1409
+ } : settled.result.kind === "winner" ? {
1410
+ status: "passed",
1411
+ score: verdict.score,
1412
+ metrics: {}
1413
+ } : {
1414
+ status: "failed",
1415
+ score: verdict.score,
1416
+ metrics: {},
1417
+ failure: {
1418
+ code: settled.result.reason,
1419
+ message: `version ${settled.version} settled without a winner: ${settled.result.reason}`
1420
+ }
1421
+ },
1422
+ accounting: charged ? versionAccounting(spent) : FREE,
1423
+ identity: identity(settled.profile),
1424
+ boxMinutes: charged && isFiniteNumber(spent.boxMinutes) && spent.boxMinutesKnown !== false ? spent.boxMinutes : null,
1425
+ wallMs: charged && isFiniteNumber(spent.ms) ? Math.max(0, Math.round(spent.ms)) : null,
1426
+ placement: {
1427
+ lane,
1428
+ boxId: null
1429
+ },
1430
+ traceRef: { unknown: `version ${settled.version} is run ${settled.runId}; the chain records no trace id` },
1431
+ artifacts: [{
1432
+ role: "settle-record",
1433
+ uri: pathToFileURL(settlePath).href,
1434
+ sha256: settled.settleDigest,
1435
+ byteLength
1436
+ }, recorder.blob("verdict", {
1437
+ kind: "version-verdict",
1438
+ version: settled.version,
1439
+ runId: settled.runId,
1440
+ verdict
1441
+ })]
1442
+ };
1443
+ }
1444
+ /** A version as the judge and `next` read it. */
1445
+ function versionOf(record, parent, bytes, result) {
1446
+ return Object.freeze({
1447
+ version: record.version,
1448
+ nodeId: record.nodeId,
1449
+ runId: record.runId,
1450
+ runDir: record.runDir,
1451
+ settleDigest: sha256Bytes(bytes),
1452
+ result,
1453
+ profile: record.profile,
1454
+ ...parent?.seal === void 0 ? {} : { parent: {
1455
+ version: parent.version,
1456
+ runId: parent.runId,
1457
+ settleDigest: parent.seal.sha256
1458
+ } },
1459
+ ...record.change === void 0 ? {} : { change: record.change }
1460
+ });
1461
+ }
1462
+ /** Every version whose latest settled cell carries a verdict, first first, each read back from
1463
+ * its sealed `result.json`. */
1464
+ async function judgedVersions(chain) {
1465
+ const judged = [];
1466
+ for (const record of chain.values()) {
1467
+ if (record.seal === void 0 || record.verdict === void 0) continue;
1468
+ const { bytes, result } = await readSealed(record.runDir, record.version);
1469
+ if (sha256Bytes(bytes) !== record.seal.sha256) throw new RuntimeRunStateError(`supervisePursuit versions: version ${record.version}'s result.json changed after it was judged`);
1470
+ const parent = record.parentNodeId === null ? void 0 : chain.get(record.parentNodeId);
1471
+ judged.push(Object.freeze({
1472
+ ...versionOf(record, parent, bytes, result),
1473
+ verdict: record.verdict
1474
+ }));
1475
+ }
1476
+ return judged;
1477
+ }
1478
+ /**
1479
+ * Every node of the chain, in registration order, from the ledger. The state holds cells, not
1480
+ * their events' artifacts, so each cell's seal and verdict are read from the ledger lines the
1481
+ * state verified, through Eval's own line parser.
1482
+ */
1483
+ async function versionsOf() {
1484
+ const state = await recorder.state();
1485
+ const head = state.head?.sequence ?? -1;
1486
+ const nodes = state.nodes().map((node) => ({
1487
+ node,
1488
+ cellId: state.cells({ nodeId: node.nodeId })[0]?.cellId,
1489
+ diff: node.edgeIds[0] === void 0 ? void 0 : state.edge(node.edgeIds[0])?.diffs[0]
1490
+ }));
1491
+ const attempts = /* @__PURE__ */ new Map();
1492
+ const text = await readFile(ledgerPath, "utf8");
1493
+ for (const [index, line] of text.split("\n").entries()) {
1494
+ if (line.length === 0) continue;
1495
+ const entry = parseSearchLedgerLine(line, searchId, {
1496
+ path: ledgerPath,
1497
+ line: index + 1
1498
+ });
1499
+ if (entry.sequence > head) break;
1500
+ const { event } = entry;
1501
+ if (event.kind !== "cell-settled") continue;
1502
+ const seals = attempts.get(event.cellId)?.seals ?? /* @__PURE__ */ new Set();
1503
+ const seal = event.artifacts.find((artifact) => artifact.role === "settle-record");
1504
+ if (seal !== void 0) seals.add(seal.sha256);
1505
+ attempts.set(event.cellId, {
1506
+ latest: event,
1507
+ seals
1508
+ });
1509
+ }
1510
+ const chain = /* @__PURE__ */ new Map();
1511
+ for (const { node, cellId, diff } of nodes) {
1512
+ const settled = cellId === void 0 ? void 0 : attempts.get(cellId);
1513
+ const artifact = (role) => settled?.latest.artifacts.find((candidate) => candidate.role === role);
1514
+ const seal = artifact("settle-record");
1515
+ const verdict = artifact("verdict");
1516
+ chain.set(node.nodeId, {
1517
+ nodeId: node.nodeId,
1518
+ version: node.ordinal + 1,
1519
+ ...versionRun(runDir, runId, node.ordinal + 1),
1520
+ profile: loadNode(recorder, node).profile,
1521
+ parentNodeId: node.primaryParentId,
1522
+ ...diff === void 0 || "unknown" in diff ? {} : { change: recorder.readBlob(diff).diffs[0] },
1523
+ ...seal === void 0 ? {} : { seal },
1524
+ ...verdict === void 0 ? {} : { verdict: recorder.readBlob(verdict).verdict },
1525
+ seals: settled?.seals ?? /* @__PURE__ */ new Set()
1526
+ });
1527
+ }
1528
+ return chain;
1529
+ }
1530
+ }
1531
+ /** The bytes of a version's sealed `result.json` and the record they hold. */
1532
+ async function readSealed(runDir, version) {
1533
+ let bytes;
1534
+ try {
1535
+ bytes = await readFile(resolve(runDir, SETTLE_RECORD_FILE));
1536
+ } catch (error) {
1537
+ if (!isNoEntError(error)) throw error;
1538
+ throw new RuntimeRunStateError(`supervisePursuit versions: version ${version} has no settle record in ${runDir}`);
1539
+ }
1540
+ const result = await readSettleRecord(runDir);
1541
+ return {
1542
+ bytes,
1543
+ result
1544
+ };
1545
+ }
1546
+ function loadNode(store, node) {
1547
+ const stored = store.readBlob(node.artifact);
1548
+ if (stored.kind === "agent-profile") {
1549
+ const parsed = agentProfileSchema.safeParse(stored.profile);
1550
+ if (!parsed.success) throw new RuntimeRunStateError(`version node ${node.nodeId} holds an invalid AgentProfile`);
1551
+ return {
1552
+ profile: parsed.data,
1553
+ refusal: null
1554
+ };
1555
+ }
1556
+ if (stored.kind === "unapplied-change") return {
1557
+ profile: null,
1558
+ ...stored.change ? { change: stored.change } : {},
1559
+ ...stored.parentDigest ? { parentDigest: stored.parentDigest } : {},
1560
+ refusal: stored.refusal ?? "the change did not apply"
1561
+ };
1562
+ throw new RuntimeRunStateError(`version node ${node.nodeId} holds no version artifact`);
1563
+ }
1564
+ /** The `<runDir>.v<n>` directory and `<runId>.v<n>` id of version `n`, beside the first. */
1565
+ function versionRun(runDir, runId, version) {
1566
+ return version === 1 ? {
1567
+ runDir,
1568
+ runId
1569
+ } : {
1570
+ runDir: `${runDir}.v${version}`,
1571
+ runId: `${runId}.v${version}`
1572
+ };
1573
+ }
1574
+ /** A version's settled spend as the ledger's accounting. Unknown dollars carry the part a
1575
+ * provider is known to have billed as their floor. */
1576
+ function versionAccounting(spent) {
1577
+ const tokensKnown = spent !== void 0 && spent.tokensKnown !== false && Number.isSafeInteger(spent.tokens?.input) && Number.isSafeInteger(spent.tokens?.output);
1578
+ const usdKnown = spent !== void 0 && spent.usdKnown !== false && isFiniteNumber(spent.usd);
1579
+ return {
1580
+ tokens: tokensKnown ? {
1581
+ status: "known",
1582
+ inputTokens: spent.tokens.input,
1583
+ outputTokens: spent.tokens.output,
1584
+ cachedTokens: spent.tokens.cacheRead ?? 0
1585
+ } : {
1586
+ status: "unknown",
1587
+ reason: "the version's settled spend names unreported tokens"
1588
+ },
1589
+ cost: usdKnown ? {
1590
+ status: "known",
1591
+ usd: spent.usd,
1592
+ source: "provider"
1593
+ } : {
1594
+ status: "unknown",
1595
+ knownLowerBoundUsd: Math.max(0, isFiniteNumber(spent?.usd) ? spent.usd - (spent.usdEstimated ?? 0) : 0),
1596
+ reason: "the version's settled spend names unpriced or unreported work"
1597
+ }
1598
+ };
1599
+ }
1600
+ /** How long a version that settled before its chain opened ran, from its settle record. */
1601
+ function settledElapsed(settled) {
1602
+ const elapsed = settled?.spentTotal?.ms;
1603
+ return isFiniteNumber(elapsed) ? elapsed : 0;
1604
+ }
1605
+ const FREE = {
1606
+ tokens: {
1607
+ status: "known",
1608
+ inputTokens: 0,
1609
+ outputTokens: 0,
1610
+ cachedTokens: 0
1611
+ },
1612
+ cost: {
1613
+ status: "known",
1614
+ usd: 0,
1615
+ source: "free"
1616
+ }
1617
+ };
1618
+ function canonicalStop(stop) {
1619
+ return {
1620
+ patience: stop.patience,
1621
+ maxVersions: stop.maxVersions,
1622
+ maxUsd: stop.maxUsd,
1623
+ deadlineMs: stop.deadlineMs,
1624
+ ...stop.minImprovement === void 0 ? {} : { minImprovement: stop.minImprovement }
1625
+ };
1626
+ }
1627
+ /**
1628
+ * `'review-of-best'`: fork from the kept version with its check's verdict mounted under
1629
+ * {@link REVIEW_DIR} and the profile's review words as one instruction. The previous review's
1630
+ * mount and instruction are removed, so a profile carries one review.
1631
+ */
1632
+ function reviewOfBest(runId, words) {
1633
+ return ({ best, versions }) => {
1634
+ const n = versions.length + 1;
1635
+ const verdict = best.verdict.check;
1636
+ const path = `${REVIEW_DIR}version-${best.version}.md`;
1637
+ const instruction = words.replaceAll("{version}", String(best.version)).replaceAll("{path}", path).replaceAll("{score}", best.verdict.score === null ? "none" : String(best.verdict.score)).trim();
1638
+ const page = reviewPage(best.version, best.verdict.score, verdict);
1639
+ const earlierInstructions = best.change?.set?.prompt?.instructions ?? [];
1640
+ const earlierMounts = (best.profile.resources?.files ?? []).map((file) => file.path).filter((mounted) => mounted.startsWith("inputs/review/") && mounted !== path);
1641
+ return {
1642
+ kind: "agent-profile-diff",
1643
+ id: `${runId}-v${n}-review-of-v${best.version}`,
1644
+ title: `Version ${n}: review of version ${best.version}`,
1645
+ source: {
1646
+ kind: "optimizer",
1647
+ notes: [`review-of-best: version ${best.version}`, `judge ${best.verdict.judgeDigest}`]
1648
+ },
1649
+ set: {
1650
+ prompt: { instructions: [instruction] },
1651
+ resources: { files: [{
1652
+ path,
1653
+ resource: {
1654
+ kind: "inline",
1655
+ name: path,
1656
+ content: page
1657
+ }
1658
+ }] }
1659
+ },
1660
+ ...earlierInstructions.length > 0 || earlierMounts.length > 0 ? { remove: {
1661
+ ...earlierInstructions.length > 0 ? { prompt: { instructions: [...earlierInstructions] } } : {},
1662
+ ...earlierMounts.length > 0 ? { resources: { files: earlierMounts } } : {}
1663
+ } } : {}
1664
+ };
1665
+ };
1666
+ }
1667
+ /** The review page: facts only, in the check's own lines. */
1668
+ function reviewPage(version, score, verdict) {
1669
+ if (verdict === void 0) return [
1670
+ `# Version ${version}`,
1671
+ "",
1672
+ `Score: ${score ?? "none"}. The judge reported no per-item verdict.`,
1673
+ ""
1674
+ ].join("\n");
1675
+ const failing = failedItems(verdict);
1676
+ return [
1677
+ `# Version ${version}`,
1678
+ "",
1679
+ `Score: ${score ?? "none"}.${verdict.threshold === void 0 ? "" : ` The check passes at ${verdict.threshold}.`}`,
1680
+ "",
1681
+ "## Items",
1682
+ "",
1683
+ ...Object.entries(verdict.items ?? {}).map(([item, value]) => `- ${item}: ${value >= 1 ? "passes" : `fails (${value})`}`),
1684
+ "",
1685
+ ...failing.length === 0 ? [] : [
1686
+ "## Failures",
1687
+ "",
1688
+ ...verdict.failures ?? [],
1689
+ ""
1690
+ ],
1691
+ ...verdict.review === void 0 ? [] : [
1692
+ "## The check's review",
1693
+ "",
1694
+ verdict.review,
1695
+ ""
1696
+ ]
1697
+ ].join("\n");
1698
+ }
1699
+ function digestOf(value, name) {
1700
+ try {
1701
+ return canonicalCandidateDigest(value);
1702
+ } catch (error) {
1703
+ throw new ValidationError(`supervisePursuit versions: the ${name} must be canonical JSON to pin the chain: ${errorMessage$1(error)}`);
1704
+ }
1705
+ }
1706
+ async function exists(path) {
1707
+ try {
1708
+ await access(path);
1709
+ return true;
1710
+ } catch (error) {
1711
+ if (isNoEntError(error)) return false;
1712
+ throw error;
1713
+ }
1714
+ }
1715
+ function isSha256(value) {
1716
+ return typeof value === "string" && /^sha256:[0-9a-f]{64}$/u.test(value);
1717
+ }
1718
+ function isFiniteNumber(value) {
1719
+ return typeof value === "number" && Number.isFinite(value);
1720
+ }
1721
+ function errorMessage$1(error) {
1722
+ return error instanceof Error ? error.message : String(error);
1723
+ }
1724
+ //#endregion
962
1725
  //#region src/durable/run-fork.ts
963
1726
  /**
964
1727
  * The `execution.correlation` keys a fork records on its root. Runtime writes them; a caller that
@@ -1254,500 +2017,6 @@ async function removeIfPresent(path) {
1254
2017
  }
1255
2018
  }
1256
2019
  //#endregion
1257
- //#region src/durable/pursuit-versions.ts
1258
- /** The longest delay Node's setTimeout honors. */
1259
- const MAX_TIMER_MS = 2147483647;
1260
- /** The ledger file inside the lineage directory. */
1261
- const PURSUIT_VERSIONS_FILE = "versions.jsonl";
1262
- /** The `<runDir>.v<n>` directory and `<runId>.v<n>` id of version `n`, beside the first. */
1263
- function pursuitVersionRun(runDir, runId, version) {
1264
- return version === 1 ? {
1265
- runDir,
1266
- runId
1267
- } : {
1268
- runDir: `${runDir}.v${version}`,
1269
- runId: `${runId}.v${version}`
1270
- };
1271
- }
1272
- /**
1273
- * Validate a `versions` option before any compute. The same check runs inside `supervisePursuit`;
1274
- * a caller that records the option as data can run it at preflight.
1275
- */
1276
- function assertPursuitVersions(versions) {
1277
- const fail = (message) => {
1278
- throw new ValidationError(`supervisePursuit versions: ${message}`);
1279
- };
1280
- if (typeof versions !== "object" || versions === null) fail("must be an object");
1281
- const { judge, next, stop, run } = versions;
1282
- if (typeof judge !== "object" || judge === null || typeof judge.judge !== "function") fail("judge must be a VersionJudge, such as declaredCheckJudge(check)");
1283
- else if (!isSha256(judge.digest)) fail("judge.digest must be a sha256 digest (sha256:<64 hex>)");
1284
- if (next !== "review-of-best" && typeof next !== "function") fail("next must be a function or 'review-of-best'");
1285
- if (run !== void 0 && typeof run !== "function") fail("run must be a function when set");
1286
- const { usd } = versions;
1287
- if (usd !== void 0 && typeof usd !== "function") fail("usd must be a function when set");
1288
- if (typeof stop !== "object" || stop === null) fail("stop must be an object");
1289
- const rule = stop;
1290
- const known = /* @__PURE__ */ new Set([
1291
- "patience",
1292
- "maxVersions",
1293
- "maxUsd",
1294
- "deadlineMs",
1295
- "minImprovement"
1296
- ]);
1297
- const unknown = Object.keys(rule).filter((key) => !known.has(key));
1298
- if (unknown.length > 0) fail(`stop has unknown fields: ${unknown.join(", ")}`);
1299
- for (const key of ["patience", "maxVersions"]) if (!Number.isInteger(rule[key]) || rule[key] < 1) fail(`stop.${key} must be an integer of at least 1`);
1300
- for (const key of ["maxUsd", "deadlineMs"]) if (typeof rule[key] !== "number" || !Number.isFinite(rule[key]) || rule[key] <= 0) fail(`stop.${key} must be a finite number above 0`);
1301
- if (rule.minImprovement !== void 0 && (typeof rule.minImprovement !== "number" || !Number.isFinite(rule.minImprovement) || rule.minImprovement < 0)) fail("stop.minImprovement must be a finite number of at least 0");
1302
- }
1303
- /** Run a version chain. `supervisePursuit` calls this when `versions` is set. */
1304
- async function runPursuitVersions(profile, task, opts, runOne) {
1305
- const { versions, ...rest } = opts;
1306
- assertPursuitVersions(versions);
1307
- for (const key of [
1308
- "journal",
1309
- "blobs",
1310
- "rootHandle",
1311
- "steerDir"
1312
- ]) if (rest[key] !== void 0) throw new ValidationError(`supervisePursuit versions: ${key} names one run, and a version chain has one per version; omit it`);
1313
- const judge = versions.judge;
1314
- if (versions.next === "review-of-best" && rest.continuation?.profile.review === void 0) throw new ValidationError("supervisePursuit versions: next 'review-of-best' needs continuation.profile.review, the words the next version reads about its review");
1315
- const next = versions.next === "review-of-best" ? reviewOfBest(rest.runId ?? "supervise", rest.continuation?.profile.review ?? "") : versions.next;
1316
- const stop = versions.stop;
1317
- const minImprovement = stop.minImprovement ?? 0;
1318
- const now = rest.now ?? Date.now;
1319
- const pursuitId = rest.pursuitId.trim();
1320
- const runDir = resolve(rest.runDir.trim());
1321
- const runId = rest.runId ?? "supervise";
1322
- const { fork: firstFork, signal: callerSignal, ...base } = rest;
1323
- const lineageDir = `${runDir}.versions`;
1324
- const ledgerPath = resolve(lineageDir, PURSUIT_VERSIONS_FILE);
1325
- const firstProfile = firstFork === void 0 ? profile : applyExactAgentProfileDiff(profile, firstFork.change, "supervisePursuit versions");
1326
- await mkdir(lineageDir, { recursive: true });
1327
- const lock = await acquireRunDirectoryLock(lineageDir, `${runId}:versions`, now);
1328
- try {
1329
- const ledger = await readLedger(ledgerPath);
1330
- let chain = ledger.find((line) => line.kind === "chain");
1331
- if (chain === void 0) {
1332
- const elapsed = (await readSettleRecord(runDir))?.spentTotal?.ms;
1333
- const startedAt = new Date(now() - (typeof elapsed === "number" && Number.isFinite(elapsed) ? elapsed : 0)).toISOString();
1334
- chain = {
1335
- kind: "chain",
1336
- pursuitId,
1337
- runId,
1338
- runDir,
1339
- judgeDigest: judge.digest,
1340
- stop: canonicalStop(stop),
1341
- startedAt
1342
- };
1343
- await appendLedger(ledgerPath, chain);
1344
- } else {
1345
- const mismatch = [
1346
- chain.pursuitId !== pursuitId ? `pursuitId '${chain.pursuitId}'` : void 0,
1347
- chain.runId !== runId ? `runId '${chain.runId}'` : void 0,
1348
- chain.runDir !== runDir ? `runDir '${chain.runDir}'` : void 0,
1349
- chain.judgeDigest !== judge.digest ? `judge digest ${chain.judgeDigest}` : void 0,
1350
- contentAddress(chain.stop) !== contentAddress(canonicalStop(stop)) ? "another stop rule" : void 0
1351
- ].filter((item) => item !== void 0);
1352
- if (mismatch.length > 0) throw new ValidationError(`supervisePursuit versions: ${ledgerPath} records a chain with ${mismatch.join(", ")}; a chain keeps its identity, judge and stop rule`);
1353
- }
1354
- const startedAtMs = Date.parse(chain.startedAt);
1355
- const deadline = new AbortController();
1356
- let timer;
1357
- const arm = () => {
1358
- const remaining = startedAtMs + stop.deadlineMs - now();
1359
- if (remaining <= 0) {
1360
- deadline.abort(/* @__PURE__ */ new Error("the version chain reached its deadline"));
1361
- return;
1362
- }
1363
- timer = setTimeout(arm, Math.min(remaining, MAX_TIMER_MS));
1364
- timer.unref?.();
1365
- };
1366
- arm();
1367
- const signal = callerSignal === void 0 ? deadline.signal : AbortSignal.any([callerSignal, deadline.signal]);
1368
- try {
1369
- const judged = [];
1370
- const profiles = /* @__PURE__ */ new Map([[1, firstProfile]]);
1371
- let pending = {
1372
- version: 1,
1373
- runId,
1374
- runDir
1375
- };
1376
- let stopped;
1377
- for (const line of ledger) if (line.kind === "start") {
1378
- const parentProfile = profiles.get(line.parent.version);
1379
- if (parentProfile === void 0) throw new RuntimeRunStateError(`supervisePursuit versions: ${ledgerPath} starts version ${line.version} from unknown version ${line.parent.version}`);
1380
- profiles.set(line.version, applyExactAgentProfileDiff(parentProfile, line.change, "supervisePursuit versions"));
1381
- pending = {
1382
- version: line.version,
1383
- runId: line.runId,
1384
- runDir: line.runDir,
1385
- parent: line.parent,
1386
- change: line.change
1387
- };
1388
- } else if (line.kind === "judged") {
1389
- if (line.version !== judged.length + 1 || line.version !== pending?.version) throw new RuntimeRunStateError(`supervisePursuit versions: ${ledgerPath} judges version ${line.version} out of order`);
1390
- if (line.verdict.judgeDigest !== judge.digest) throw new ValidationError(`supervisePursuit versions: version ${line.version} was judged under ${line.verdict.judgeDigest}, not ${judge.digest}`);
1391
- const settled = await readSettled(pending, profiles);
1392
- if (settled.settleDigest !== line.settleDigest) throw new RuntimeRunStateError(`supervisePursuit versions: version ${line.version}'s result.json changed after it was judged`);
1393
- judged.push(Object.freeze({
1394
- ...settled,
1395
- verdict: line.verdict,
1396
- improved: line.improved,
1397
- usd: line.usd,
1398
- usdKnown: line.usdKnown,
1399
- usdSource: line.usdSource,
1400
- ...line.lineage === void 0 ? {} : { lineage: line.lineage }
1401
- }));
1402
- pending = void 0;
1403
- } else if (line.kind === "stopped") stopped = line;
1404
- while (stopped === void 0) {
1405
- if (pending !== void 0) {
1406
- const spec = pending;
1407
- const settled = await settle(spec);
1408
- const verdict = await judgeVersion(settled);
1409
- const bestScore = bestOf(judged)?.verdict.score;
1410
- const improved = isFiniteNumber(verdict.score) && (!isFiniteNumber(bestScore) || verdict.score > bestScore + minImprovement);
1411
- const spent = settled.result.spentTotal;
1412
- const measured = versions.usd === void 0 ? void 0 : await versions.usd(settled, signal);
1413
- const usdSource = measured === void 0 ? "runtime" : "caller";
1414
- const usd = measured === void 0 ? isFiniteNumber(spent?.usd) ? spent.usd : null : isFiniteNumber(measured) ? measured : null;
1415
- const usdKnown = usd !== null && (measured !== void 0 || spent?.usdKnown !== false);
1416
- const lineage = versionLineage(spec, firstFork);
1417
- await appendLedger(ledgerPath, {
1418
- kind: "judged",
1419
- version: spec.version,
1420
- runId: spec.runId,
1421
- runDir: spec.runDir,
1422
- settleDigest: settled.settleDigest,
1423
- ...spec.parent === void 0 ? {} : { parent: spec.parent },
1424
- ...spec.change?.id === void 0 ? {} : { changeId: spec.change.id },
1425
- verdict,
1426
- improved,
1427
- usd,
1428
- usdKnown,
1429
- usdSource,
1430
- ...lineage === void 0 ? {} : { lineage }
1431
- });
1432
- judged.push(Object.freeze({
1433
- ...settled,
1434
- verdict,
1435
- improved,
1436
- usd,
1437
- usdKnown,
1438
- usdSource,
1439
- ...lineage === void 0 ? {} : { lineage }
1440
- }));
1441
- pending = void 0;
1442
- }
1443
- const reason = stopReason(judged);
1444
- if (reason !== void 0) {
1445
- stopped = {
1446
- kind: "stopped",
1447
- reason,
1448
- at: new Date(now()).toISOString(),
1449
- best: (bestOf(judged) ?? judged[0]).version,
1450
- spentUsd: spentOf(judged)
1451
- };
1452
- await appendLedger(ledgerPath, stopped);
1453
- break;
1454
- }
1455
- const best = bestOf(judged) ?? judged[0];
1456
- const last = judged[judged.length - 1];
1457
- const change = await next({
1458
- best,
1459
- last,
1460
- versions: Object.freeze([...judged])
1461
- }, signal);
1462
- if (typeof change?.id !== "string" || change.id.trim().length === 0) throw new ValidationError("supervisePursuit versions: next must return a change with an id");
1463
- const version = judged.length + 1;
1464
- const spec = {
1465
- version,
1466
- ...pursuitVersionRun(runDir, runId, version),
1467
- parent: {
1468
- version: best.version,
1469
- runId: best.runId,
1470
- settleDigest: best.settleDigest
1471
- },
1472
- change
1473
- };
1474
- profiles.set(version, applyExactAgentProfileDiff(best.profile, change, "supervisePursuit versions"));
1475
- await appendLedger(ledgerPath, {
1476
- kind: "start",
1477
- version,
1478
- runId: spec.runId,
1479
- runDir: spec.runDir,
1480
- parent: spec.parent,
1481
- change
1482
- });
1483
- pending = spec;
1484
- }
1485
- const bestVersion = judged.find((item) => item.version === stopped.best) ?? judged[0];
1486
- const record = Object.freeze({
1487
- lineageDir,
1488
- judgeDigest: judge.digest,
1489
- stop: canonicalStop(stop),
1490
- startedAt: chain.startedAt,
1491
- versions: Object.freeze([...judged]),
1492
- best: bestVersion.version,
1493
- spentUsd: stopped.spentUsd,
1494
- stopped: Object.freeze({
1495
- reason: stopped.reason,
1496
- at: stopped.at
1497
- })
1498
- });
1499
- const observerPath = resolve(bestVersion.runDir, "observer.jsonl");
1500
- return Object.freeze({
1501
- result: bestVersion.result,
1502
- pursuit: projectPursuit(await new FileObserverJournal(observerPath, pursuitId).read()),
1503
- observerPath,
1504
- settlePath: resolve(bestVersion.runDir, SETTLE_RECORD_FILE),
1505
- versions: record
1506
- });
1507
- /** Run the version unless its directory already settled, then read it back. */
1508
- async function settle(spec) {
1509
- if (await readSettleRecord(spec.runDir) === void 0) {
1510
- if (signal.aborted) throw new RuntimeRunStateError(`supervisePursuit versions: version ${spec.version} was not started: ${abortMessage(signal)}`);
1511
- if (spec.parent === void 0 || spec.change === void 0) await runOne(profile, task, {
1512
- ...base,
1513
- ...firstFork === void 0 ? {} : { fork: firstFork },
1514
- signal
1515
- });
1516
- else {
1517
- const parent = judged.find((item) => item.version === spec.parent.version);
1518
- if (parent === void 0) throw new RuntimeRunStateError(`supervisePursuit versions: version ${spec.version}'s parent ${spec.parent.version} is not judged`);
1519
- const fork = {
1520
- runDir: parent.runDir,
1521
- settleDigest: parent.settleDigest,
1522
- change: spec.change,
1523
- acceptUncertain: true
1524
- };
1525
- const bar = base.continuation !== void 0 && parent.verdict.check !== void 0 ? { continuation: {
1526
- ...base.continuation,
1527
- best: {
1528
- label: `v${parent.version}`,
1529
- verdict: parent.verdict.check
1530
- }
1531
- } } : {};
1532
- const options = {
1533
- ...base,
1534
- ...bar,
1535
- runId: spec.runId,
1536
- runDir: spec.runDir,
1537
- fork,
1538
- signal
1539
- };
1540
- if (versions.run === void 0) await runOne(parent.profile, task, options);
1541
- else {
1542
- const prepared = await prepareRunFork(parent.profile, task, options, fork);
1543
- await versions.run(Object.freeze({
1544
- version: spec.version,
1545
- runId: spec.runId,
1546
- runDir: spec.runDir,
1547
- pursuitId,
1548
- profile: prepared.profile,
1549
- task,
1550
- budget: base.budget,
1551
- execution: prepared.execution,
1552
- fork,
1553
- parentProfile: parent.profile
1554
- }), signal);
1555
- }
1556
- }
1557
- }
1558
- const settled = await readSettled(spec, profiles);
1559
- if (settled === void 0) throw new RuntimeRunStateError(`supervisePursuit versions: version ${spec.version} returned without a settle record in ${spec.runDir}`);
1560
- return settled;
1561
- }
1562
- async function judgeVersion(settled) {
1563
- const verdict = await judge.judge(settled, signal);
1564
- if (typeof verdict !== "object" || verdict === null) throw new ValidationError("supervisePursuit versions: the judge returned no verdict");
1565
- if (verdict.judgeDigest !== judge.digest) throw new ValidationError(`supervisePursuit versions: the verdict for version ${settled.version} carries ${String(verdict.judgeDigest)}, not the pinned judge ${judge.digest}`);
1566
- if (verdict.score !== null && !isFiniteNumber(verdict.score)) throw new ValidationError("supervisePursuit versions: a verdict score must be a finite number or null");
1567
- return JSON.parse(JSON.stringify(verdict));
1568
- }
1569
- function stopReason(done) {
1570
- if (callerSignal?.aborted) return "aborted";
1571
- if (done.length >= stop.maxVersions) return "max-versions";
1572
- let stale = 0;
1573
- for (let index = done.length - 1; index >= 0 && !done[index].improved; index -= 1) stale += 1;
1574
- if (stale >= stop.patience) return "no-improvement";
1575
- if (done.some((item) => item.usd === null)) return "spend-unknown";
1576
- if (spentOf(done) >= stop.maxUsd) return "max-usd";
1577
- if (deadline.signal.aborted || now() - startedAtMs >= stop.deadlineMs) return "deadline";
1578
- }
1579
- } finally {
1580
- if (timer !== void 0) clearTimeout(timer);
1581
- }
1582
- } finally {
1583
- await lock.release();
1584
- }
1585
- }
1586
- async function readSettled(spec, profiles) {
1587
- let bytes;
1588
- try {
1589
- bytes = await readFile(resolve(spec.runDir, SETTLE_RECORD_FILE));
1590
- } catch (error) {
1591
- if (!isNoEntError(error)) throw error;
1592
- throw new RuntimeRunStateError(`supervisePursuit versions: version ${spec.version} has no settle record in ${spec.runDir}`);
1593
- }
1594
- const result = await readSettleRecord(spec.runDir);
1595
- const profile = profiles.get(spec.version);
1596
- if (profile === void 0) throw new RuntimeRunStateError(`supervisePursuit versions: version ${spec.version} has no recorded profile`);
1597
- return Object.freeze({
1598
- version: spec.version,
1599
- runId: spec.runId,
1600
- runDir: spec.runDir,
1601
- settleDigest: sha256Bytes(bytes),
1602
- result,
1603
- profile,
1604
- ...spec.parent === void 0 ? {} : { parent: spec.parent },
1605
- ...spec.change === void 0 ? {} : { change: spec.change }
1606
- });
1607
- }
1608
- function versionLineage(spec, firstFork) {
1609
- if (spec.parent !== void 0 && spec.change !== void 0) return {
1610
- source: lineageSource(spec.change),
1611
- runIds: [spec.parent.runId],
1612
- profileDiffIds: [spec.change.id]
1613
- };
1614
- if (firstFork !== void 0) return {
1615
- source: lineageSource(firstFork.change),
1616
- profileDiffIds: [firstFork.change.id]
1617
- };
1618
- }
1619
- /** The change's author, in the lineage's words. A trace-derived change is a compound of runs. */
1620
- function lineageSource(change) {
1621
- const kind = change.source?.kind;
1622
- return kind === "human" || kind === "optimizer" || kind === "frontier-author" ? kind : "compound";
1623
- }
1624
- function bestOf(done) {
1625
- let best;
1626
- for (const item of done) {
1627
- if (!isFiniteNumber(item.verdict.score)) continue;
1628
- if (best === void 0 || item.verdict.score > best.verdict.score) best = item;
1629
- }
1630
- return best;
1631
- }
1632
- function spentOf(done) {
1633
- return done.reduce((sum, item) => sum + (item.usd ?? 0), 0);
1634
- }
1635
- function canonicalStop(stop) {
1636
- return {
1637
- patience: stop.patience,
1638
- maxVersions: stop.maxVersions,
1639
- maxUsd: stop.maxUsd,
1640
- deadlineMs: stop.deadlineMs,
1641
- ...stop.minImprovement === void 0 ? {} : { minImprovement: stop.minImprovement }
1642
- };
1643
- }
1644
- /** Where `'review-of-best'` mounts a review: `inputs/review/version-<n>.md`. One review lives in
1645
- * a profile at a time. */
1646
- const REVIEW_DIR = "inputs/review/";
1647
- /**
1648
- * `'review-of-best'`: fork from the best version with its check's verdict mounted under
1649
- * {@link REVIEW_DIR} and the profile's review words as one instruction. The previous review's
1650
- * mount and instruction are removed, so a profile carries one review. This is what the Lab's
1651
- * `continue-best` changes did in Lab code, now written once from the check's own verdict.
1652
- */
1653
- function reviewOfBest(runId, words) {
1654
- return ({ best, versions }) => {
1655
- const n = versions.length + 1;
1656
- const verdict = best.verdict.check;
1657
- const path = `${REVIEW_DIR}version-${best.version}.md`;
1658
- const instruction = words.replaceAll("{version}", String(best.version)).replaceAll("{path}", path).replaceAll("{score}", best.verdict.score === null ? "none" : String(best.verdict.score)).trim();
1659
- const page = reviewPage(best.version, best.verdict.score, verdict);
1660
- const earlierInstructions = best.change?.set?.prompt?.instructions ?? [];
1661
- const earlierMounts = (best.profile.resources?.files ?? []).map((file) => file.path).filter((mounted) => mounted.startsWith("inputs/review/") && mounted !== path);
1662
- return {
1663
- kind: "agent-profile-diff",
1664
- id: `${runId}-v${n}-review-of-v${best.version}`,
1665
- title: `Version ${n}: review of version ${best.version}`,
1666
- source: {
1667
- kind: "optimizer",
1668
- notes: [`review-of-best: version ${best.version}`, `judge ${best.verdict.judgeDigest}`]
1669
- },
1670
- set: {
1671
- prompt: { instructions: [instruction] },
1672
- resources: { files: [{
1673
- path,
1674
- resource: {
1675
- kind: "inline",
1676
- name: path,
1677
- content: page
1678
- }
1679
- }] }
1680
- },
1681
- ...earlierInstructions.length > 0 || earlierMounts.length > 0 ? { remove: {
1682
- ...earlierInstructions.length > 0 ? { prompt: { instructions: [...earlierInstructions] } } : {},
1683
- ...earlierMounts.length > 0 ? { resources: { files: earlierMounts } } : {}
1684
- } } : {}
1685
- };
1686
- };
1687
- }
1688
- /** The review page: facts only, in the check's own lines. */
1689
- function reviewPage(version, score, verdict) {
1690
- if (verdict === void 0) return [
1691
- `# Version ${version}`,
1692
- "",
1693
- `Score: ${score ?? "none"}. The judge reported no per-item verdict.`,
1694
- ""
1695
- ].join("\n");
1696
- const failing = failedItems(verdict);
1697
- return [
1698
- `# Version ${version}`,
1699
- "",
1700
- `Score: ${score ?? "none"}.${verdict.threshold === void 0 ? "" : ` The check passes at ${verdict.threshold}.`}`,
1701
- "",
1702
- "## Items",
1703
- "",
1704
- ...Object.entries(verdict.items ?? {}).map(([item, value]) => `- ${item}: ${value >= 1 ? "passes" : `fails (${value})`}`),
1705
- "",
1706
- ...failing.length === 0 ? [] : [
1707
- "## Failures",
1708
- "",
1709
- ...verdict.failures ?? [],
1710
- ""
1711
- ],
1712
- ...verdict.review === void 0 ? [] : [
1713
- "## The check's review",
1714
- "",
1715
- verdict.review,
1716
- ""
1717
- ]
1718
- ].join("\n");
1719
- }
1720
- async function readLedger(path) {
1721
- let text;
1722
- try {
1723
- text = await readFile(path, "utf8");
1724
- } catch (error) {
1725
- if (isNoEntError(error)) return [];
1726
- throw error;
1727
- }
1728
- return parseCommittedJsonLines(text, path);
1729
- }
1730
- async function appendLedger(path, line) {
1731
- const endsWithRecord = await prepareJsonlAppend(path);
1732
- const handle = await open(path, "a");
1733
- try {
1734
- await writeAllBytes(handle, `${endsWithRecord ? "\n" : ""}${JSON.stringify(line)}\n`);
1735
- await handle.sync();
1736
- } finally {
1737
- await handle.close();
1738
- }
1739
- }
1740
- function isSha256(value) {
1741
- return typeof value === "string" && /^sha256:[0-9a-f]{64}$/u.test(value);
1742
- }
1743
- function isFiniteNumber(value) {
1744
- return typeof value === "number" && Number.isFinite(value);
1745
- }
1746
- function abortMessage(signal) {
1747
- const reason = signal.reason;
1748
- return reason instanceof Error ? reason.message : String(reason ?? "aborted");
1749
- }
1750
- //#endregion
1751
2020
  //#region src/durable/supervise-pursuit.ts
1752
2021
  /** A failed Runtime execution whose complete third-person projection was retained. */
1753
2022
  var SupervisePursuitError = class extends Error {
@@ -1946,6 +2215,6 @@ function compareText(left, right) {
1946
2215
  return left < right ? -1 : left > right ? 1 : 0;
1947
2216
  }
1948
2217
  //#endregion
1949
- export { FAILURE_RECORD_FILE, FORK_PARENT_UNCERTAIN_NODES_KEY, FileObserverJournal, PURSUIT_VERSIONS_FILE, REVIEW_DIR, ROOT_STREAM_FILE, RUN_DIRECTORY_LOCK_FILE, RUN_FORK_CORRELATION_KEYS, RunDirectoryLockedError, SETTLE_RECORD_FILE, SettledRunDirectoryError, SupervisePursuitError, acquireRunDirectoryLock, assertPursuitVersions, createFileObserverHooks, deriveExecutionId, discoverDurableSupervisionRun, handleChatTurn, observerRecordDigest, projectPursuit, pursuitVersionRun, readFailureRecord, readRootStream, readRootStreamReceipt, readRunDirectoryLock, readSettleRecord, runDirectoryHolderIsLive, settleRecordJson, supervisePursuit, verifyObserverRecords };
2218
+ export { FAILURE_RECORD_FILE, FORK_PARENT_UNCERTAIN_NODES_KEY, FileObserverJournal, REVIEW_DIR, ROOT_STREAM_FILE, RUN_DIRECTORY_LOCK_FILE, RUN_FORK_CORRELATION_KEYS, RunDirectoryLockedError, SETTLE_RECORD_FILE, SettledRunDirectoryError, SupervisePursuitError, acquireRunDirectoryLock, assertPursuitVersions, createFileObserverHooks, deriveExecutionId, discoverDurableSupervisionRun, handleChatTurn, observerRecordDigest, projectPursuit, pursuitVersionsLedgerPath, readFailureRecord, readRootStream, readRootStreamReceipt, readRunDirectoryLock, readSettleRecord, runDirectoryHolderIsLive, settleRecordJson, supervisePursuit, verifyObserverRecords };
1950
2219
 
1951
2220
  //# sourceMappingURL=durable.js.map