@tangle-network/agent-runtime 6.0.8 → 7.0.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 (78) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +23 -9
  3. package/dist/{activation-Cwy3_Qn_.js → activation-Ba9IAgQ3.js} +2 -2
  4. package/dist/{activation-Cwy3_Qn_.js.map → activation-Ba9IAgQ3.js.map} +1 -1
  5. package/dist/{activation-CWx7I1PU.d.ts → activation-DIkTEBWF.d.ts} +2 -2
  6. package/dist/agent.d.ts +1 -1
  7. package/dist/agent.js +3 -3
  8. package/dist/{coordination-manager-D9z7To7p.js → coordination-manager-DQZ2u6L-.js} +58 -6
  9. package/dist/coordination-manager-DQZ2u6L-.js.map +1 -0
  10. package/dist/{delegate-ws-KBA2H.js → delegate-DFLSVjFG.js} +2 -2
  11. package/dist/{delegate-ws-KBA2H.js.map → delegate-DFLSVjFG.js.map} +1 -1
  12. package/dist/durable.d.ts +71 -4
  13. package/dist/durable.js +158 -10
  14. package/dist/durable.js.map +1 -1
  15. package/dist/{failure-cause-BzjUUsRz.js → failure-cause-rJTm_Tx8.js} +6 -9
  16. package/dist/failure-cause-rJTm_Tx8.js.map +1 -0
  17. package/dist/{graph-2_nX4ib4.js → graph-BjQF2syl.js} +6 -6
  18. package/dist/{graph-2_nX4ib4.js.map → graph-BjQF2syl.js.map} +1 -1
  19. package/dist/{improve-BxfqTsZy.js → improve-BolbYegO.js} +6 -6
  20. package/dist/{improve-BxfqTsZy.js.map → improve-BolbYegO.js.map} +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +10 -10
  23. package/dist/intelligence.d.ts +2 -2
  24. package/dist/intelligence.js +4 -4
  25. package/dist/kernel.d.ts +2 -2
  26. package/dist/kernel.js +13 -13
  27. package/dist/{loop-runner-BmGZ4y1W.js → loop-runner-C9W3T_3T.js} +2 -2
  28. package/dist/{loop-runner-BmGZ4y1W.js.map → loop-runner-C9W3T_3T.js.map} +1 -1
  29. package/dist/{loop-runner-CUMypgRw.d.ts → loop-runner-Cs9IJ6Nk.d.ts} +2 -2
  30. package/dist/loop-runner-bin.d.ts +1 -1
  31. package/dist/loop-runner-bin.js +1 -1
  32. package/dist/mcp/bin.js +3 -3
  33. package/dist/mcp/index.d.ts +1 -1
  34. package/dist/mcp/index.js +6 -6
  35. package/dist/mcp/memory-bin.js +1 -1
  36. package/dist/profiles.d.ts +1 -1
  37. package/dist/{provision-supervisor-CeQTPHRr.js → provision-supervisor-BQFHjCtN.js} +5 -5
  38. package/dist/{provision-supervisor-CeQTPHRr.js.map → provision-supervisor-BQFHjCtN.js.map} +1 -1
  39. package/dist/{run-cancellation-D_4vJ522.js → run-cancellation-B84X8ZAP.js} +2 -2
  40. package/dist/{run-cancellation-D_4vJ522.js.map → run-cancellation-B84X8ZAP.js.map} +1 -1
  41. package/dist/{run-state-CTZVngI_.js → run-state-Dh1bGERI.js} +6 -6
  42. package/dist/{run-state-CTZVngI_.js.map → run-state-Dh1bGERI.js.map} +1 -1
  43. package/dist/{runtime-COm9uBBx.js → runtime-C9F1PG2A.js} +13 -13
  44. package/dist/{runtime-COm9uBBx.js.map → runtime-C9F1PG2A.js.map} +1 -1
  45. package/dist/{search-executor-DTEIl58w.js → search-executor-CKR9_6NR.js} +4 -4
  46. package/dist/{search-executor-DTEIl58w.js.map → search-executor-CKR9_6NR.js.map} +1 -1
  47. package/dist/{server-zO9Nz9Nk.js → server-Dh3SQGQT.js} +4 -4
  48. package/dist/{server-zO9Nz9Nk.js.map → server-Dh3SQGQT.js.map} +1 -1
  49. package/dist/{settle-record-U7fkQEZa.js → settle-record-C6LdVvok.js} +12 -4
  50. package/dist/settle-record-C6LdVvok.js.map +1 -0
  51. package/dist/{structural-rollout-BwTwTUXF.js → structural-rollout-Dapf2aZY.js} +25 -7
  52. package/dist/structural-rollout-Dapf2aZY.js.map +1 -0
  53. package/dist/{supervise-tmqDU6YT.js → supervise-xwl2D6q3.js} +9 -7
  54. package/dist/{supervise-tmqDU6YT.js.map → supervise-xwl2D6q3.js.map} +1 -1
  55. package/dist/{supervision-discovery-CGbXayGv.js → supervision-discovery-B47U8TH5.js} +3 -3
  56. package/dist/{supervision-discovery-CGbXayGv.js.map → supervision-discovery-B47U8TH5.js.map} +1 -1
  57. package/dist/{scope-gIYQ5ZiL.js → supervisor-accounting-DxLQ_TQe.js} +330 -44
  58. package/dist/supervisor-accounting-DxLQ_TQe.js.map +1 -0
  59. package/dist/{supervisor-1A27fE6k.js → supervisor-gC-u_PRk.js} +11 -314
  60. package/dist/supervisor-gC-u_PRk.js.map +1 -0
  61. package/dist/testing.d.ts +1 -1
  62. package/dist/testing.js +11 -11
  63. package/dist/{tool-server-B9q2dtnW.js → tool-server-Dg350Bgz.js} +2 -2
  64. package/dist/{tool-server-B9q2dtnW.js.map → tool-server-Dg350Bgz.js.map} +1 -1
  65. package/dist/{top-web-CS4PD4ck.js → top-web-BJLnFQdr.js} +6 -6
  66. package/dist/{top-web-CS4PD4ck.js.map → top-web-BJLnFQdr.js.map} +1 -1
  67. package/dist/tui/bin.js +6 -6
  68. package/dist/tui/bin.js.map +1 -1
  69. package/dist/tui/index.d.ts +1 -1
  70. package/dist/tui/index.js +2 -2
  71. package/dist/{types-w3Oo1uRJ.d.ts → types-Jg274chm.d.ts} +153 -309
  72. package/package.json +1 -1
  73. package/dist/coordination-manager-D9z7To7p.js.map +0 -1
  74. package/dist/failure-cause-BzjUUsRz.js.map +0 -1
  75. package/dist/scope-gIYQ5ZiL.js.map +0 -1
  76. package/dist/settle-record-U7fkQEZa.js.map +0 -1
  77. package/dist/structural-rollout-BwTwTUXF.js.map +0 -1
  78. package/dist/supervisor-1A27fE6k.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"durable.js","names":[],"sources":["../src/durable/pursuit-version-evidence.ts","../src/durable/pursuit-version-review.ts","../src/durable/pursuit-version-run.ts","../src/durable/pursuit-versions.ts","../src/durable/run-fork.ts","../src/durable/run-tool-spans.ts","../src/durable/pursuit-observer-delivery.ts","../src/durable/run-reopen.ts","../src/durable/supervise-pursuit.ts"],"sourcesContent":["// Sealed pursuit-version results, identity checks and settled outcome evidence.\n\nimport { access, readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport type {\n SearchArtifactRef,\n SearchAttemptAccounting,\n SearchNode,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { isFiniteNumber } from '../finite-number'\nimport type { Spend, SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport { isNoEntError } from './jsonl-file'\nimport type { JudgedPursuitVersion, VersionVerdict } from './pursuit-versions'\nimport { parseSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\n\n/** The chain's directory beside the first version's: the ledger and its content blobs. */\nexport function pursuitVersionsLedgerPath(runDir: string): string {\n return resolve(`${resolve(runDir.trim())}.search`, 'ledger.jsonl')\n}\n\n/** A search node's artifact: a version's profile, or a change that did not apply. */\nexport interface VersionNode {\n readonly profile: AgentProfile | null\n /** The change from the parent; set on a node a proposal returned in this process. */\n readonly change?: AgentProfileDiff\n readonly parentDigest?: Sha256Digest\n readonly refusal: string | null\n}\n\n/** One node of the chain, as the ledger records it. */\nexport interface VersionRecord {\n readonly nodeId: string\n readonly version: number\n readonly runId: string\n readonly runDir: string\n /** Null for a change that did not apply. */\n readonly profile: AgentProfile | null\n readonly parentNodeId: string | null\n /** The change from the parent, from the node's first edge. */\n readonly change?: AgentProfileDiff\n /** The settled attempt's seal and verdict. */\n readonly seal?: SearchArtifactRef\n readonly verdict?: VersionVerdict\n}\n\n/** The bytes of a version's sealed `result.json` and the record they hold, parsed from the same\n * bytes that are hashed. */\nexport async function readSealed(\n runDir: string,\n version: number,\n): Promise<{ bytes: Uint8Array; result: SupervisedResult<unknown> }> {\n const path = resolve(runDir, SETTLE_RECORD_FILE)\n let bytes: Uint8Array\n try {\n bytes = await readFile(path)\n } catch (error) {\n if (!isNoEntError(error)) throw error\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${version} has no settle record in ${runDir}`,\n )\n }\n return { bytes, result: parseSettleRecord(Buffer.from(bytes).toString('utf8'), path) }\n}\n\n/** A profile as the JSON the ledger stores: validated, with undefined entries absent. */\nexport function jsonProfile(profile: unknown): AgentProfile {\n canonicalAgentProfileDigest(profile as AgentProfile)\n return JSON.parse(JSON.stringify(agentProfileSchema.parse(profile))) as AgentProfile\n}\n\nexport function loadNode(\n store: { readBlob(ref: SearchArtifactRef): unknown },\n node: SearchNode,\n): VersionNode {\n const stored = store.readBlob(node.artifact) as {\n kind?: unknown\n profile?: unknown\n change?: AgentProfileDiff | null\n parentDigest?: Sha256Digest | null\n refusal?: string | null\n }\n if (stored.kind === 'agent-profile') {\n const parsed = agentProfileSchema.safeParse(stored.profile)\n if (!parsed.success) {\n throw new RuntimeRunStateError(`version node ${node.nodeId} holds an invalid AgentProfile`)\n }\n return { profile: parsed.data as AgentProfile, refusal: null }\n }\n if (stored.kind === 'unapplied-change') {\n return {\n profile: null,\n ...(stored.change ? { change: stored.change } : {}),\n ...(stored.parentDigest ? { parentDigest: stored.parentDigest } : {}),\n refusal: stored.refusal ?? 'the change did not apply',\n }\n }\n throw new RuntimeRunStateError(`version node ${node.nodeId} holds no version artifact`)\n}\n\n/** The `<runDir>.v<n>` directory and `<runId>.v<n>` id of version `n`, beside the first. */\nexport function versionRun(runDir: string, runId: string, version: number) {\n return version === 1\n ? { runDir, runId }\n : { runDir: `${runDir}.v${version}`, runId: `${runId}.v${version}` }\n}\n\n/** A version's settled spend as the ledger's accounting. Unknown dollars carry the part a\n * provider is known to have billed as their floor. */\nexport function versionAccounting(spent: Spend | undefined): SearchAttemptAccounting {\n const tokensKnown =\n spent !== undefined &&\n spent.tokensKnown !== false &&\n spent.tokens?.tokensKnown !== false &&\n Number.isSafeInteger(spent.tokens?.input) &&\n Number.isSafeInteger(spent.tokens?.output) &&\n Number.isSafeInteger(spent.tokens?.cacheRead)\n const usdKnown = spent !== undefined && spent.usdKnown !== false && isFiniteNumber(spent.usd)\n return {\n tokens: tokensKnown\n ? {\n status: 'known',\n inputTokens: spent.tokens.input,\n outputTokens: spent.tokens.output,\n cachedTokens: spent.tokens.cacheRead!,\n }\n : {\n status: 'unknown',\n reason: `the version's settled spend reports no complete token count with its cache split (input ${spent?.tokens?.input ?? 'none'}, output ${spent?.tokens?.output ?? 'none'})`,\n },\n cost: usdKnown\n ? { status: 'known', usd: spent.usd, source: 'provider' }\n : {\n status: 'unknown',\n knownLowerBoundUsd: Math.max(\n 0,\n isFiniteNumber(spent?.usd) ? spent.usd - (spent.usdEstimated ?? 0) : 0,\n ),\n reason: \"the version's settled spend names unpriced or unreported work\",\n },\n }\n}\n\n/** How long a version that settled before its chain opened ran, from its settle record. */\nexport function settledElapsed(settled: SupervisedResult<unknown> | undefined): number {\n const elapsed = settled?.spentTotal?.ms\n return isFiniteNumber(elapsed) ? elapsed : 0\n}\n\nexport const FREE: SearchAttemptAccounting = {\n tokens: { status: 'known', inputTokens: 0, outputTokens: 0, cachedTokens: 0 },\n cost: { status: 'known', usd: 0, source: 'free' },\n}\n\n/**\n * What a version that did no work failed with: a driver error, by its name and its message with\n * the parts that differ between runs (digits, hex runs, absolute paths) normalized, or an unscored\n * verdict. Null for a version that ran, won or not.\n */\nexport function versionFailure(version: JudgedPursuitVersion): string | null {\n if (version.verdict.score === null) return 'unscored by the judge'\n const { result } = version\n if (result.kind !== 'no-winner' || result.reason !== 'driver-failed') return null\n const message = result.error.message\n .replace(/(?:\\/[\\w.@~+-]+){2,}/gu, '<path>')\n .replace(/\\b[0-9a-f]{8,}\\b/giu, '<hex>')\n .replace(/\\d+/gu, '<n>')\n .slice(0, 500)\n return `driver-failed: ${result.error.name}: ${message}`\n}\n\nexport function pursuitValueDigest(value: unknown, name: string): Sha256Digest {\n try {\n return canonicalCandidateDigest(value)\n } catch (error) {\n throw new ValidationError(\n `supervisePursuit versions: the ${name} must be canonical JSON to pin the chain: ${errorMessage(error)}`,\n )\n }\n}\n\nexport async function exists(path: string): Promise<boolean> {\n try {\n await access(path)\n return true\n } catch (error) {\n if (isNoEntError(error)) return false\n throw error\n }\n}\n\nexport function isSha256(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[0-9a-f]{64}$/u.test(value)\n}\n","// Profile review instructions and their mounted verdict page.\n\nimport type { AgentProfileDiff } from '@tangle-network/agent-interface'\nimport type { CheckVerdict } from '../runtime/supervise/completion-gate'\nimport { failedItems } from '../runtime/supervise/continuation'\nimport type { NextPursuitVersion } from './pursuit-versions'\n\n/** Where `'review-of-best'` mounts a review: `inputs/review/version-<n>.md`. One review lives in\n * a profile at a time. */\nconst REVIEW_DIR = 'inputs/review/'\n\n/**\n * `'review-of-best'`: fork from the kept version with its check's verdict mounted under\n * {@link REVIEW_DIR} and the profile's review words as one instruction. The previous review's\n * mount and instruction are removed, so a profile carries one review.\n */\nexport function reviewOfBest(runId: string, words: string): NextPursuitVersion {\n return ({ best, versions }) => {\n const n = versions.length + 1\n const verdict = best.verdict.check\n const path = `${REVIEW_DIR}version-${best.version}.md`\n const instruction = words\n .replaceAll('{version}', String(best.version))\n .replaceAll('{path}', path)\n .replaceAll('{score}', best.verdict.score === null ? 'none' : String(best.verdict.score))\n .trim()\n const page = reviewPage(best.version, best.verdict.score, verdict)\n // Instructions are set and removed by value: an earlier review instruction equal to this one\n // stays as it is, and every other earlier one is removed.\n const earlier = best.change?.set?.prompt?.instructions ?? []\n const earlierInstructions = earlier.filter((text) => text !== instruction)\n const earlierMounts = (best.profile.resources?.files ?? [])\n .map((file) => file.path)\n .filter((mounted) => mounted.startsWith(REVIEW_DIR) && mounted !== path)\n return {\n kind: 'agent-profile-diff',\n id: `${runId}-v${n}-review-of-v${best.version}`,\n title: `Version ${n}: review of version ${best.version}`,\n source: {\n kind: 'optimizer',\n notes: [`review-of-best: version ${best.version}`, `judge ${best.verdict.judgeDigest}`],\n },\n set: {\n ...(earlier.includes(instruction) ? {} : { prompt: { instructions: [instruction] } }),\n resources: {\n files: [{ path, resource: { kind: 'inline', name: path, content: page } }],\n },\n },\n ...(earlierInstructions.length > 0 || earlierMounts.length > 0\n ? {\n remove: {\n ...(earlierInstructions.length > 0\n ? { prompt: { instructions: [...earlierInstructions] } }\n : {}),\n ...(earlierMounts.length > 0 ? { resources: { files: earlierMounts } } : {}),\n },\n }\n : {}),\n } as AgentProfileDiff\n }\n}\n\n/** The review page: facts only, in the check's own lines. */\nfunction reviewPage(\n version: number,\n score: number | null,\n verdict: CheckVerdict | undefined,\n): string {\n if (verdict === undefined) {\n return [\n `# Version ${version}`,\n '',\n `Score: ${score ?? 'none'}. The judge reported no per-item verdict.`,\n '',\n ].join('\\n')\n }\n const failing = failedItems(verdict)\n return [\n `# Version ${version}`,\n '',\n `Score: ${score ?? 'none'}.${verdict.threshold === undefined ? '' : ` The check passes at ${verdict.threshold}.`}`,\n '',\n '## Items',\n '',\n ...Object.entries(verdict.items ?? {}).map(\n ([item, value]) => `- ${item}: ${value >= 1 ? 'passes' : `fails (${value})`}`,\n ),\n '',\n ...(failing.length === 0 ? [] : ['## Failures', '', ...(verdict.failures ?? []), '']),\n ...(verdict.review === undefined ? [] : [\"## The check's review\", '', verdict.review, '']),\n ].join('\\n')\n}\n","/**\n * One pursuit version chain at run time: running a version in its directory, reading it back\n * and checking it is this node's run, judging it, turning it into the kernel's cell result, and\n * reading the chain back from its search ledger.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport {\n parseSearchLedgerLine,\n type SearchCellResult,\n type SearchCellSettledEvent,\n type SearchCellWork,\n type SearchExecutionIdentity,\n type SearchRecorder,\n type SearchTaskOutcome,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n canonicalAgentProfileDigest,\n type Sha256Digest,\n sha256Bytes,\n} from '@tangle-network/agent-interface'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { isFiniteNumber } from '../finite-number'\nimport { authoredProfileDigest } from '../runtime/supervise/materialization'\nimport { superviseRootProfile } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { SpawnEvent, SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport { contentAddress } from './content-address'\nimport {\n loadNode,\n readSealed,\n type VersionNode,\n type VersionRecord,\n versionAccounting,\n versionRun,\n} from './pursuit-version-evidence'\nimport type {\n JudgedPursuitVersion,\n SettledPursuitVersion,\n VersionJudge,\n VersionVerdict,\n} from './pursuit-versions'\nimport type { PursuitFork } from './run-fork'\nimport { readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\nimport type { SupervisedPursuitResult, SupervisePursuitOptions } from './supervise-pursuit'\n\nexport type RunOne = (\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions,\n) => Promise<SupervisedPursuitResult<SupervisedResult<unknown>>>\n\n/** What one chain's versions share. */\nexport interface VersionChainContext {\n readonly profile: SupervisorProfile\n readonly task: unknown\n /** The call's options without the fields each version sets for itself. */\n readonly base: Omit<SupervisePursuitOptions, 'versions' | 'fork' | 'signal'>\n readonly firstFork: PursuitFork | undefined\n readonly runOne: RunOne\n readonly judge: VersionJudge\n readonly recorder: SearchRecorder\n /** Aborts a running version when the chain reaches its deadline. */\n readonly expired: AbortSignal\n readonly pursuitId: string\n readonly runDir: string\n readonly runId: string\n readonly ledgerPath: string\n readonly searchId: string\n readonly taskRevision: string\n}\n\n/** The execution identity a version's node and cell record. */\nexport function versionExecutionIdentity(\n pursuitId: string,\n taskRevision: string,\n nodeProfile: AgentProfile,\n): SearchExecutionIdentity {\n return {\n model: {\n provider: 'agent-runtime',\n alias: 'supervisePursuit',\n unknown: \"a version runs every model its tree chose; the version's settle record names them\",\n },\n agent: {\n uri: `agent-profile:${pursuitId}`,\n revision: canonicalAgentProfileDigest(nodeProfile),\n },\n benchmark: { uri: `pursuit:${pursuitId}`, revision: taskRevision },\n }\n}\n\n/** A version as the judge and `next` read it. */\nfunction versionOf(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n settleDigest: Sha256Digest,\n result: SupervisedResult<unknown>,\n): SettledPursuitVersion {\n return Object.freeze({\n version: record.version,\n nodeId: record.nodeId,\n runId: record.runId,\n runDir: record.runDir,\n settleDigest,\n result,\n profile: record.profile!,\n ...(parent?.seal === undefined\n ? {}\n : {\n parent: {\n version: parent.version,\n runId: parent.runId,\n settleDigest: parent.seal.sha256 as Sha256Digest,\n },\n }),\n ...(record.change === undefined ? {} : { change: record.change }),\n })\n}\n\nfunction outcomeOf(settled: SettledPursuitVersion, verdict: VersionVerdict): SearchTaskOutcome {\n if (verdict.score === null) {\n return {\n status: 'errored',\n metrics: {},\n error: {\n code: 'unscored',\n message: `the judge could not score version ${settled.version}`,\n retryable: false,\n },\n }\n }\n if (settled.result.kind === 'winner') {\n return { status: 'passed', score: verdict.score, metrics: {} }\n }\n return {\n status: 'failed',\n score: verdict.score,\n metrics: {},\n failure: {\n code: settled.result.reason,\n message: `version ${settled.version} settled without a winner: ${settled.result.reason}`,\n },\n }\n}\n\nexport class VersionChainRun {\n // Each sealed result.json is read and hashed once per call.\n private readonly sealed = new Map<Sha256Digest, SupervisedResult<unknown>>()\n\n constructor(private readonly ctx: VersionChainContext) {}\n\n /** Run a version if its directory holds no settle record, read it back, and judge it. */\n async runCell(work: SearchCellWork<VersionNode>): Promise<SearchCellResult> {\n const chain = await this.versionsOf()\n const record = chain.get(work.nodeId)\n if (record?.profile == null) {\n throw new RuntimeRunStateError(`version node ${work.nodeId} has no profile to run`)\n }\n const parent = record.parentNodeId === null ? undefined : chain.get(record.parentNodeId)\n if (parent !== undefined && (parent.seal === undefined || parent.profile === null)) {\n throw new RuntimeRunStateError(`version ${record.version}'s parent has no sealed result`)\n }\n // A version whose run throws fails the call and leaves its cell open: Runtime's driver\n // retry already ran, and calling again resumes the version in its own directory.\n if ((await readSettleRecord(record.runDir)) === undefined) {\n const signal = AbortSignal.any([work.signal, this.ctx.expired])\n if (signal.aborted) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version} was not started: ${errorMessage(signal.reason)}`,\n )\n }\n await this.runVersion(record, parent, signal)\n }\n const { settled, byteLength } = await this.readVersion(record, parent)\n const verdict = await this.judgeVersion(settled, work.signal)\n return this.cellResult(settled, byteLength, verdict, work.lane)\n }\n\n /** Run one version: the first as the call's own run, a later one as a fork of its parent. */\n private async runVersion(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n signal: AbortSignal,\n ): Promise<void> {\n const { profile, task, base, firstFork, runOne } = this.ctx\n if (parent === undefined || record.change === undefined) {\n await runOne(profile, task, {\n ...base,\n runId: record.runId,\n runDir: record.runDir,\n ...(firstFork === undefined ? {} : { fork: firstFork }),\n signal,\n })\n return\n }\n // A version starts a new tree and never replays its parent's children, so a parent that\n // settled with a child still in doubt (a deadline or a driver failure leaves them) is forked,\n // and the version's root records those nodes.\n const fork: PursuitFork = {\n runDir: parent.runDir,\n settleDigest: parent.seal!.sha256 as Sha256Digest,\n change: record.change,\n acceptUncertain: true,\n }\n // The version's continuation note states the bar against the version it forks from.\n const check = parent.verdict?.check\n await runOne(parent.profile!, task, {\n ...base,\n ...(base.continuation !== undefined && check !== undefined\n ? {\n continuation: {\n ...base.continuation,\n best: { label: `v${parent.version}`, verdict: check },\n },\n }\n : {}),\n runId: record.runId,\n runDir: record.runDir,\n fork,\n signal,\n })\n }\n\n /**\n * Read a settled version back and check it is this node's run: its root ran the node's profile\n * and, for a fork, recorded the parent's seal and the change. A directory that holds another\n * run is refused, never adopted.\n */\n private async readVersion(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n ): Promise<{ settled: SettledPursuitVersion; byteLength: number }> {\n const { base, firstFork, taskRevision } = this.ctx\n const { bytes, result } = await readSealed(record.runDir, record.version)\n if (result.tree.root !== record.runId) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: ${record.runDir} holds run '${result.tree.root}', not version ${record.version}'s '${record.runId}'`,\n )\n }\n const events = await new FileSpawnJournal(\n resolve(record.runDir, 'spawn-journal.jsonl'),\n ).loadTree(record.runId)\n const root = events?.find(\n (event): event is Extract<SpawnEvent, { kind: 'spawned' }> =>\n event.kind === 'spawned' && event.parent === undefined,\n )\n const ran = root?.identity?.profileDigest\n const expected = authoredProfileDigest(\n superviseRootProfile(record.profile!, base.profileGuidance),\n )\n const ranTask = root?.identity?.taskDigest\n const correlation = root?.identity?.correlation\n const fork =\n parent !== undefined\n ? { settleDigest: parent.seal?.sha256, changeId: record.change?.id }\n : firstFork === undefined\n ? undefined\n : { settleDigest: firstFork.settleDigest, changeId: firstFork.change.id }\n const mismatch = [\n ran !== expected ? `its root ran profile ${ran}, not ${expected}` : undefined,\n ranTask !== taskRevision ? `its root ran task ${ranTask}, not ${taskRevision}` : undefined,\n contentAddress(root?.budget) !== contentAddress(base.budget)\n ? 'its root ran under another budget'\n : undefined,\n fork !== undefined && correlation?.forkParentSettleDigest !== fork.settleDigest\n ? `its root forked from seal ${correlation?.forkParentSettleDigest}, not ${fork.settleDigest}`\n : undefined,\n fork !== undefined && correlation?.forkProfileDiffId !== fork.changeId\n ? `its root applied change ${correlation?.forkProfileDiffId}, not ${fork.changeId}`\n : undefined,\n ].filter((item): item is string => item !== undefined)\n if (mismatch.length > 0) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version} at ${record.runDir} is not this chain's run: ${mismatch.join('; ')}`,\n )\n }\n const settled = versionOf(record, parent, sha256Bytes(bytes), result)\n this.sealed.set(settled.settleDigest, result)\n return { settled, byteLength: bytes.byteLength }\n }\n\n private async judgeVersion(\n settled: SettledPursuitVersion,\n signal: AbortSignal,\n ): Promise<VersionVerdict> {\n const { judge } = this.ctx\n const verdict = await judge.judge(settled, signal)\n if (typeof verdict !== 'object' || verdict === null) {\n throw new ValidationError('supervisePursuit versions: the judge returned no verdict')\n }\n if (verdict.judgeDigest !== judge.digest) {\n throw new ValidationError(\n `supervisePursuit versions: the verdict for version ${settled.version} carries ${String(verdict.judgeDigest)}, not the pinned judge ${judge.digest}`,\n )\n }\n if (verdict.score !== null && !isFiniteNumber(verdict.score)) {\n throw new ValidationError(\n 'supervisePursuit versions: a verdict score must be a finite number or null',\n )\n }\n // The ledger keeps the verdict as JSON; a value JSON cannot hold is refused here.\n return JSON.parse(JSON.stringify(verdict)) as VersionVerdict\n }\n\n private cellResult(\n settled: SettledPursuitVersion,\n byteLength: number,\n verdict: VersionVerdict,\n lane: string,\n ): SearchCellResult {\n const spent = settled.result.spentTotal\n const settlePath = resolve(settled.runDir, SETTLE_RECORD_FILE)\n return {\n outcome: outcomeOf(settled, verdict),\n accounting: versionAccounting(spent),\n identity: versionExecutionIdentity(\n this.ctx.pursuitId,\n this.ctx.taskRevision,\n settled.profile,\n ),\n boxMinutes:\n isFiniteNumber(spent.boxMinutes) && spent.boxMinutesKnown !== false\n ? spent.boxMinutes\n : null,\n wallMs: isFiniteNumber(spent.ms) ? Math.max(0, Math.round(spent.ms)) : null,\n placement: { lane, boxId: null },\n traceRef: {\n unknown: `version ${settled.version} is run ${settled.runId}; the chain records no trace id`,\n },\n artifacts: [\n {\n role: 'settle-record',\n uri: pathToFileURL(settlePath).href,\n sha256: settled.settleDigest,\n byteLength,\n },\n this.ctx.recorder.blob('verdict', {\n kind: 'version-verdict',\n version: settled.version,\n runId: settled.runId,\n verdict,\n }),\n ],\n }\n }\n\n /** Every version whose latest settled cell carries a verdict, first first, each read back from\n * its sealed `result.json`. */\n async judgedVersions(chain: ReadonlyMap<string, VersionRecord>): Promise<JudgedPursuitVersion[]> {\n const judged: JudgedPursuitVersion[] = []\n for (const record of chain.values()) {\n if (record.seal === undefined || record.verdict === undefined) continue\n const seal = record.seal.sha256 as Sha256Digest\n let result = this.sealed.get(seal)\n if (result === undefined) {\n const read = await readSealed(record.runDir, record.version)\n if (sha256Bytes(read.bytes) !== seal) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version}'s result.json changed after it was judged`,\n )\n }\n result = read.result\n this.sealed.set(seal, result)\n }\n const parent = record.parentNodeId === null ? undefined : chain.get(record.parentNodeId)\n judged.push(\n Object.freeze({ ...versionOf(record, parent, seal, result), verdict: record.verdict }),\n )\n }\n return judged\n }\n\n /**\n * Every node of the chain, in registration order, from the ledger. The state holds cells, not\n * their events' artifacts, so each cell's seal and verdict are read from the ledger lines the\n * state verified, through Eval's own line parser.\n */\n async versionsOf(): Promise<Map<string, VersionRecord>> {\n const { recorder, ledgerPath, searchId, runDir, runId } = this.ctx\n // Take what the state holds before any await: an append retires the view.\n const state = await recorder.state()\n const head = state.head?.sequence ?? -1\n const nodes = state.nodes().map((node) => ({\n node,\n cellId: state.cells({ nodeId: node.nodeId })[0]?.cellId,\n diff: node.edgeIds[0] === undefined ? undefined : state.edge(node.edgeIds[0])?.diffs[0],\n }))\n const settledCells = new Map<string, SearchCellSettledEvent>()\n const text = await readFile(ledgerPath, 'utf8')\n for (const [index, line] of text.split('\\n').entries()) {\n if (line.length === 0) continue\n const entry = parseSearchLedgerLine(line, searchId, { path: ledgerPath, line: index + 1 })\n if (entry.sequence > head) break\n if (entry.event.kind === 'cell-settled') settledCells.set(entry.event.cellId, entry.event)\n }\n const chain = new Map<string, VersionRecord>()\n for (const { node, cellId, diff } of nodes) {\n const settled = cellId === undefined ? undefined : settledCells.get(cellId)\n const artifact = (role: string) =>\n settled?.artifacts.find((candidate) => candidate.role === role)\n const seal = artifact('settle-record')\n const verdict = artifact('verdict')\n chain.set(node.nodeId, {\n nodeId: node.nodeId,\n version: node.ordinal + 1,\n ...versionRun(runDir, runId, node.ordinal + 1),\n profile: loadNode(recorder, node).profile,\n parentNodeId: node.primaryParentId,\n ...(diff === undefined || 'unknown' in diff\n ? {}\n : { change: (recorder.readBlob(diff) as { diffs: AgentProfileDiff[] }).diffs[0]! }),\n ...(seal === undefined ? {} : { seal }),\n ...(verdict === undefined\n ? {}\n : { verdict: (recorder.readBlob(verdict) as { verdict: VersionVerdict }).verdict }),\n })\n }\n return chain\n }\n}\n","/**\n * The pursuit version chain, on Eval's search kernel (`runSearch`).\n *\n * A version is a search node: the exact AgentProfile it executes, content-addressed by\n * `canonicalAgentProfileDigest`. Every later version is an edge from the version the chain keeps,\n * whose diff is the one change `next` returned, and one cell: a `supervisePursuit` run of the\n * version, forked from its parent's sealed `result.json`, then scored by the outside judge. The\n * policy is the kernel's hill climb, `incumbent({ patience, minImprovement })`. The search ledger\n * at `<runDir>.search/ledger.jsonl` is the chain's only record and its only checkpoint: a call on\n * a closed chain reads it back, and a call on an open chain continues it.\n */\n\nimport { resolve } from 'node:path'\nimport {\n developmentClaim,\n incumbent,\n openSearchLedger,\n runSearch,\n type SearchArtifactCodec,\n type SearchAudit,\n type SearchCloseReason,\n type SearchExecutor,\n type SearchHistoryReceipt,\n type SearchProposerPort,\n SearchRecorder,\n type SearchSourceRef,\n uniform,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { applyExactAgentProfileDiff } from '../candidate-execution/profile'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { isFiniteNumber } from '../finite-number'\nimport type { CheckVerdict } from '../runtime/supervise/completion-gate'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport { FileObserverJournal } from './observer-journal'\nimport { projectPursuit } from './observer-projection'\nimport {\n exists,\n FREE,\n isSha256,\n jsonProfile,\n loadNode,\n pursuitValueDigest,\n pursuitVersionsLedgerPath,\n settledElapsed,\n type VersionNode,\n versionFailure,\n} from './pursuit-version-evidence'\nimport { reviewOfBest } from './pursuit-version-review'\nimport { type RunOne, VersionChainRun, versionExecutionIdentity } from './pursuit-version-run'\nimport { readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport type { SupervisedPursuitResult, SupervisePursuitOptions } from './supervise-pursuit'\n\n/**\n * Continue a pursuit across versions: after each version settles, an outside judge scores it, and\n * the next version forks from the version the chain keeps with one change, until the stop rule\n * ends the chain.\n */\nexport interface PursuitVersions {\n /** Scores each settled version from outside its tree: the run's declared check\n * (`declaredCheckJudge`), or any judge with a digest. */\n readonly judge: VersionJudge\n /** The change the next version applies to the kept version's profile. `'review-of-best'`\n * mounts the kept version's verdict under `inputs/review/`, replaces any earlier review, and\n * gives the next version's continuation note the kept version's per-item verdict as its bar. */\n readonly next: NextPursuitVersion | 'review-of-best'\n /** When the chain stops. Every cap is required: a chain without one is refused. */\n readonly stop: PursuitVersionStop\n}\n\n/** The chain's stop rule. The chain starts no version its caps do not admit. */\nexport interface PursuitVersionStop {\n /** Stop after this many proposed versions in a row that did not take the lead. */\n readonly patience: number\n /** At most this many versions, the first included. A change the chain refuses counts as one. */\n readonly maxVersions: number\n /**\n * The chain's dollars: a version starts only while settled spend plus a hold for it stays\n * within this. A version's unknown spend counts as its proven floor. The hold is the version's\n * own `budget.maxUsd`, which bounds it in flight; without one it is 0 until 20 versions\n * settled, then 1.5 times the p99 of their spend.\n */\n readonly maxUsd: number\n /** The chain's wall clock, from its first version's start. A running version is aborted at it. */\n readonly deadlineMs: number\n /** A version takes the lead when its score beats the kept version's by more than this.\n * Default 0. */\n readonly minImprovement?: number\n /**\n * Stop after this many versions in a row failed identically: each run ended `driver-failed`\n * with the same error, or the judge could not score it. Such a failure repeats whatever the\n * next change is (a refused workspace file, a broken credential), so neither patience nor a\n * version cap should be what stops it. Default 3.\n */\n readonly identicalFailures?: number\n}\n\n/** An outside judge. Runtime calls it after a version's settle record exists, never inside the\n * version's tree, and gives it no handle into that tree. Place it where you like, such as its own\n * sandbox through `runIsolatedCheck({ box })`. */\nexport interface VersionJudge {\n /** The sha256 of the judge's code and configuration. Every verdict must carry it, and a chain\n * whose ledger was opened under another digest is refused. */\n readonly digest: Sha256Digest\n judge(version: SettledPursuitVersion, signal: AbortSignal): Promise<VersionVerdict>\n}\n\nexport interface VersionVerdict {\n /** Higher is better. `null` when the judge could not score the version: the cell is recorded\n * unscored, and an unscored version never takes the lead. */\n readonly score: number | null\n /** Must equal `VersionJudge.digest`. */\n readonly judgeDigest: Sha256Digest\n /** What the judge measured, retained verbatim in the ledger. JSON values only. */\n readonly detail?: unknown\n /** The check's per-item verdict, when the judge is a check: what `'review-of-best'` mounts and\n * what the next version's bar compares against. */\n readonly check?: CheckVerdict\n}\n\n/** A settled version, as the judge and `next` read it. */\nexport interface SettledPursuitVersion {\n /** 1 for the first version: the node's registration ordinal plus 1. */\n readonly version: number\n /** The version's node in the chain's search ledger. */\n readonly nodeId: string\n readonly runId: string\n readonly runDir: string\n /** The sha256 of the version's `result.json` bytes: its seal. */\n readonly settleDigest: Sha256Digest\n readonly result: SupervisedResult<unknown>\n /** The profile the version executed: the first version's, or its parent's plus its change. */\n readonly profile: AgentProfile\n /** The version it forked from. Absent for the first version. */\n readonly parent?: {\n readonly version: number\n readonly runId: string\n readonly settleDigest: Sha256Digest\n }\n readonly change?: AgentProfileDiff\n}\n\nexport interface JudgedPursuitVersion extends SettledPursuitVersion {\n readonly verdict: VersionVerdict\n}\n\nexport interface NextPursuitVersionInput {\n /** The version the next one forks from: the version the chain keeps. */\n readonly best: JudgedPursuitVersion\n /** The most recently judged version. */\n readonly last: JudgedPursuitVersion\n /** Every judged version, first first. */\n readonly versions: readonly JudgedPursuitVersion[]\n}\n\n/** Build the one change the next version applies to `best.profile`. Its `id` must be non-empty. */\nexport type NextPursuitVersion = (\n input: NextPursuitVersionInput,\n signal: AbortSignal,\n) => AgentProfileDiff | Promise<AgentProfileDiff>\n\n/** The chain as its search ledger records it, returned beside the kept version's result. */\nexport interface PursuitVersionChain {\n /** `<runDir>.search/ledger.jsonl`: the chain's only record and checkpoint. */\n readonly ledgerPath: string\n readonly searchId: string\n /** Why the chain stopped: the kernel's close reason (`patience`, `max-nodes`, `budget`,\n * `deadline` or `converged`). */\n readonly reason: SearchCloseReason\n /** Present when the chain stopped because its last `versions` versions failed identically\n * (`stop.identicalFailures`); `reason` is then `converged`. */\n readonly identicalFailures?: { readonly versions: number; readonly failure: string }\n /** The kept version's number: the kernel's leader when the chain closed. */\n readonly best: number\n /** Every judged version, first first. */\n readonly versions: readonly JudgedPursuitVersion[]\n /** Known dollars, proven floors of unknown ones, and the counts of each. */\n readonly spend: SearchAudit['spend']\n /** A bounded receipt over the exact ledger bytes. */\n readonly receipt: SearchHistoryReceipt\n}\n\n/**\n * Validate a `versions` option before any compute. The same check runs inside `supervisePursuit`;\n * a caller that records the option as data can run it at preflight.\n */\nexport function assertPursuitVersions(versions: unknown): asserts versions is PursuitVersions {\n const fail = (message: string): never => {\n throw new ValidationError(`supervisePursuit versions: ${message}`)\n }\n if (typeof versions !== 'object' || versions === null) fail('must be an object')\n const option = versions as Record<string, unknown>\n const extra = Object.keys(option).filter((key) => !['judge', 'next', 'stop'].includes(key))\n if (extra.length > 0) fail(`unknown fields: ${extra.join(', ')}`)\n const { judge, next, stop } = option\n if (\n typeof judge !== 'object' ||\n judge === null ||\n typeof (judge as VersionJudge).judge !== 'function'\n ) {\n fail('judge must be a VersionJudge, such as declaredCheckJudge(check)')\n } else if (!isSha256((judge as VersionJudge).digest)) {\n fail('judge.digest must be a sha256 digest (sha256:<64 hex>)')\n }\n if (next !== 'review-of-best' && typeof next !== 'function') {\n fail(\"next must be a function or 'review-of-best'\")\n }\n if (typeof stop !== 'object' || stop === null) fail('stop must be an object')\n const rule = stop as Record<string, unknown>\n const known = new Set([\n 'patience',\n 'maxVersions',\n 'maxUsd',\n 'deadlineMs',\n 'minImprovement',\n 'identicalFailures',\n ])\n const unknown = Object.keys(rule).filter((key) => !known.has(key))\n if (unknown.length > 0) fail(`stop has unknown fields: ${unknown.join(', ')}`)\n for (const key of ['patience', 'maxVersions'] as const) {\n if (!Number.isInteger(rule[key]) || (rule[key] as number) < 1) {\n fail(`stop.${key} must be an integer of at least 1`)\n }\n }\n if (\n rule.identicalFailures !== undefined &&\n (!Number.isInteger(rule.identicalFailures) || (rule.identicalFailures as number) < 1)\n ) {\n fail('stop.identicalFailures must be an integer of at least 1')\n }\n for (const key of ['maxUsd', 'deadlineMs'] as const) {\n if (!isFiniteNumber(rule[key]) || (rule[key] as number) <= 0) {\n fail(`stop.${key} must be a finite number above 0`)\n }\n }\n if (\n rule.minImprovement !== undefined &&\n (!isFiniteNumber(rule.minImprovement) || rule.minImprovement < 0)\n ) {\n fail('stop.minImprovement must be a finite number of at least 0')\n }\n}\n\n/** Every rule the chain adds to the kernel's. Its digest, with the stop rule, is the process\n * revision the ledger records, so a changed rule or stop rule is a different search. */\nconst VERSION_CHAIN_DEFINITION = {\n name: 'agent-runtime.pursuit-versions.2026-09',\n 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',\n edge: 'one change from the kept version, stored as its Interface profile diff',\n 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',\n outcome:\n 'a scored winner passes; a scored no-winner fails with its reason; an unscored version is a final error; a run that throws fails the call and leaves its cell open',\n deadline: 'the chain deadline aborts a running version; its judge still runs',\n failures:\n 'before proposing, the chain closes converged when its last stop.identicalFailures judged versions failed identically: driver-failed with the same error name and message, digits, hex runs and absolute paths normalized, or unscored by the judge',\n directories: 'version n runs at <runDir>.v<n> with run id <runId>.v<n>; version 1 at <runDir>',\n} as const\n\nconst VERSION_CHAIN_URI = 'npm:@tangle-network/agent-runtime#supervisePursuit.versions'\n/** The pursuit task's one train task. */\nconst TASK_ID = 'pursuit'\nconst LANE = 'in-process'\n/** The longest delay Node's setTimeout honors. */\nconst MAX_TIMER_MS = 2_147_483_647\n/** 9999-12-31T23:59:59.999Z: the latest instant the ledger's four-digit-year timestamps hold, so\n * a deadline such as `Number.MAX_SAFE_INTEGER` means no deadline rather than an invalid date. */\nconst LATEST_DEADLINE_MS = 253_402_300_799_999\n\ntype ChainBase = Omit<SupervisePursuitOptions, 'versions' | 'fork' | 'signal'>\n\n/** Refuse a chain call that no version could satisfy, before any compute. */\nfunction assertChainCall(versions: PursuitVersions, base: ChainBase): void {\n assertPursuitVersions(versions)\n for (const key of ['journal', 'blobs', 'rootHandle', 'steerDir'] as const) {\n if (base[key] !== undefined) {\n throw new ValidationError(\n `supervisePursuit versions: ${key} names one run, and a version chain has one per version; omit it`,\n )\n }\n }\n if (versions.next === 'review-of-best' && base.continuation?.profile.review === undefined) {\n throw new ValidationError(\n \"supervisePursuit versions: next 'review-of-best' needs continuation.profile.review, the words the next version reads about its review\",\n )\n }\n const { stop } = versions\n if (base.budget.maxUsd !== undefined && base.budget.maxUsd > stop.maxUsd) {\n throw new ValidationError(\n `supervisePursuit versions: budget.maxUsd ${base.budget.maxUsd} is above stop.maxUsd ${stop.maxUsd}, so no version could start`,\n )\n }\n}\n\n/** Run a version chain. `supervisePursuit` calls this when `versions` is set. */\nexport async function runPursuitVersions(\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions & { readonly versions: PursuitVersions },\n runOne: RunOne,\n): Promise<SupervisedPursuitResult<SupervisedResult<unknown>> & { versions: PursuitVersionChain }> {\n const { versions, fork: firstFork, signal: callerSignal, ...base } = opts\n assertChainCall(versions, base)\n const { judge, stop } = versions\n const next: NextPursuitVersion =\n versions.next === 'review-of-best'\n ? reviewOfBest(base.runId ?? 'supervise', base.continuation?.profile.review ?? '')\n : versions.next\n const now = base.now ?? Date.now\n const pursuitId = base.pursuitId.trim()\n const runDir = resolve(base.runDir.trim())\n const runId = base.runId ?? 'supervise'\n const ledgerPath = pursuitVersionsLedgerPath(runDir)\n const searchId = `versions:${pursuitId}:${runId}`\n const retired = resolve(`${runDir}.versions`, 'versions.jsonl')\n if (await exists(retired)) {\n throw new ValidationError(\n `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`,\n )\n }\n\n // The first version's executed profile; later versions derive theirs from their parent's.\n const firstProfile = jsonProfile(\n firstFork === undefined\n ? profile\n : applyExactAgentProfileDiff(profile, firstFork.change, 'supervisePursuit versions'),\n )\n const taskRevision = pursuitValueDigest(task, 'task')\n const ledger = openSearchLedger({ path: ledgerPath, searchId })\n const deadline = await chainDeadline((await ledger.state()).header, now, runDir, stop)\n const policy = incumbent({\n patience: stop.patience,\n ...(stop.minImprovement === undefined ? {} : { minImprovement: stop.minImprovement }),\n })\n const allocation = uniform()\n const recorder = await openVersionRecorder({\n ledger,\n now,\n pursuitId,\n taskRevision,\n judge,\n stop,\n policy,\n allocation,\n deadline,\n firstProfile,\n })\n\n const clock = armChainDeadline(deadline, now)\n const chain = new VersionChainRun({\n profile,\n task,\n base,\n firstFork,\n runOne,\n judge,\n recorder,\n expired: clock.signal,\n pursuitId,\n runDir,\n runId,\n ledgerPath,\n searchId,\n taskRevision,\n })\n const failureLimit = stop.identicalFailures ?? DEFAULT_IDENTICAL_FAILURES\n try {\n const closed = await runSearch({\n recorder,\n root: { profile: firstProfile, refusal: null },\n codec: versionCodec,\n policy,\n allocation,\n proposer: versionProposer(versions.next, next, chain, failureLimit),\n executor: versionExecutor(chain, base.budget.maxUsd),\n admit: (node) => node.refusal,\n ...(callerSignal === undefined ? {} : { signal: callerSignal }),\n now,\n })\n const judged = await chain.judgedVersions(await chain.versionsOf())\n // A converged chain whose last versions share a failure stopped by the identical-failure rule.\n const failed =\n closed.reason === 'converged' ? identicalFailureStreak(judged, failureLimit) : null\n const stopped = failed === null ? null : { versions: failureLimit, failure: failed }\n const best = judged.find((version) => version.nodeId === closed.leader)\n if (best === undefined) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: the chain in ${ledgerPath} closed (${closed.reason}) without a judged version to keep`,\n )\n }\n const observerPath = resolve(best.runDir, 'observer.jsonl')\n return Object.freeze({\n result: best.result,\n pursuit: projectPursuit(await new FileObserverJournal(observerPath, pursuitId).read()),\n observerPath,\n settlePath: resolve(best.runDir, SETTLE_RECORD_FILE),\n versions: Object.freeze({\n ledgerPath,\n searchId,\n reason: closed.reason,\n ...(stopped === null ? {} : { identicalFailures: stopped }),\n best: best.version,\n versions: Object.freeze(judged),\n spend: closed.state.audit.spend,\n receipt: recorder.receipt({ producerId: 'pursuit-versions', runId }),\n }),\n })\n } finally {\n clock.cancel()\n }\n}\n\ninterface VersionRecorderInput {\n ledger: ReturnType<typeof openSearchLedger>\n now: () => number\n pursuitId: string\n taskRevision: string\n judge: VersionJudge\n stop: PursuitVersionStop\n policy: { name: string }\n allocation: { name: string }\n deadline: string\n firstProfile: AgentProfile\n}\n\n/** Open the chain's search recorder: its subject, process revision, splits, policy and budget. */\nfunction openVersionRecorder(input: VersionRecorderInput): Promise<SearchRecorder> {\n const { ledger, now, pursuitId, taskRevision, judge, stop, policy, allocation, deadline } = input\n return SearchRecorder.open(\n { ledger, now },\n {\n subject: pursuitId,\n process: {\n name: 'pursuit-versions',\n executionRef: {\n uri: VERSION_CHAIN_URI,\n revision: canonicalCandidateDigest({\n ...VERSION_CHAIN_DEFINITION,\n stop: canonicalStop(stop),\n }),\n },\n },\n artifactKind: 'agent-profile',\n objective: {\n metric: 'version-judge-score',\n direction: 'maximize',\n judge: { uri: 'agent-runtime:version-judge', revision: judge.digest },\n claim: developmentClaim(pursuitId),\n },\n splits: {\n train: [\n {\n taskId: TASK_ID,\n unitId: TASK_ID,\n source: { uri: `pursuit:${pursuitId}`, revision: taskRevision },\n },\n ],\n selection: [],\n test: [],\n heldOutUnits: true,\n },\n policy: { expansion: policy.name, allocation: allocation.name, seed: 0 },\n budget: {\n maxUsd: stop.maxUsd,\n maxCells: null,\n maxNodes: stop.maxVersions,\n deadline,\n maxConcurrency: 1,\n reservedClaimUsd: 0,\n },\n containment: null,\n derivedFrom: null,\n identity: versionExecutionIdentity(pursuitId, taskRevision, input.firstProfile),\n },\n )\n}\n\n/**\n * The chain's clock starts with its first version, or when the chain opened on a first version\n * that had already settled. A resumed chain keeps the deadline its ledger recorded.\n */\nasync function chainDeadline(\n opened: { budget: { deadline: string | null } } | null | undefined,\n now: () => number,\n runDir: string,\n stop: PursuitVersionStop,\n): Promise<string> {\n return (\n opened?.budget.deadline ??\n new Date(\n Math.min(\n now() - settledElapsed(await readSettleRecord(runDir)) + stop.deadlineMs,\n LATEST_DEADLINE_MS,\n ),\n ).toISOString()\n )\n}\n\n/**\n * The chain's deadline aborts a running version. A timer longer than 2^31 - 1 ms fires at once\n * in Node, so a long chain re-arms in steps.\n */\nfunction armChainDeadline(\n deadline: string,\n now: () => number,\n): { signal: AbortSignal; cancel(): void } {\n const deadlineAt = Date.parse(deadline)\n const expired = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const arm = () => {\n const remaining = deadlineAt - now()\n if (remaining <= 0) {\n expired.abort(new Error('the version chain reached its deadline'))\n return\n }\n timer = setTimeout(arm, Math.min(remaining, MAX_TIMER_MS))\n timer.unref?.()\n }\n arm()\n return {\n signal: expired.signal,\n cancel() {\n if (timer !== undefined) clearTimeout(timer)\n },\n }\n}\n\nconst versionCodec: SearchArtifactCodec<VersionNode> = {\n node(store, node) {\n if (node.profile !== null) {\n const artifact = store.blob('agent-profile', {\n kind: 'agent-profile',\n profile: node.profile,\n })\n return {\n artifactDigest: canonicalAgentProfileDigest(node.profile),\n artifact,\n surfaces: [{ surfaceId: 'profile', kind: 'agent-profile', artifact }],\n }\n }\n const refused = {\n kind: 'unapplied-change',\n parentDigest: node.parentDigest ?? null,\n change: node.change ?? null,\n }\n const artifact = store.blob('change', { ...refused, refusal: node.refusal })\n return {\n artifactDigest: canonicalCandidateDigest(refused),\n artifact,\n surfaces: [{ surfaceId: 'profile', kind: 'agent-profile', artifact }],\n }\n },\n diff(store, parent, child) {\n if (parent.profile === null || child.profile === null || child.change === undefined) {\n return { unknown: 'a refused change has no profile to diff' }\n }\n const from = canonicalAgentProfileDigest(parent.profile)\n if (child.parentDigest !== from) {\n return { unknown: 'the change was written against another parent' }\n }\n return store.blob('diff', {\n kind: 'agent-profile-diff',\n from,\n to: canonicalAgentProfileDigest(child.profile),\n diffs: [child.change],\n })\n },\n load(store, node) {\n return loadNode(store, node)\n },\n}\n\nfunction versionExecutor(\n chain: VersionChainRun,\n maxUsd: number | undefined,\n): SearchExecutor<VersionNode> {\n return {\n // A version's budget.maxUsd bounds it in flight, so it is the hard hold. Without one the\n // hold is the kernel's estimate: 0 until 20 versions settled, then 1.5 times their p99.\n lanes: () => [\n maxUsd === undefined\n ? { name: LANE, capacity: 1, costCap: 'estimate', cellUsd: 0 }\n : { name: LANE, capacity: 1, costCap: 'hard', cellUsd: maxUsd },\n ],\n place: () => LANE,\n // A version that settled is read back from its directory by `run`, so nothing is adopted.\n adopt: async () => null,\n run: (work) => chain.runCell(work),\n }\n}\n\n/** The proposer: the caller's `next` (or the review of the kept version) as the one edge. */\nfunction versionProposer(\n nextOption: PursuitVersions['next'],\n next: NextPursuitVersion,\n chain: VersionChainRun,\n failureLimit: number,\n): SearchProposerPort<VersionNode> {\n const reviewing = nextOption === 'review-of-best'\n const proposerSource: SearchSourceRef = {\n uri: reviewing ? `${VERSION_CHAIN_URI}.review-of-best` : `${VERSION_CHAIN_URI}.next`,\n revision: canonicalCandidateDigest({\n next: reviewing ? 'review-of-best' : Function.prototype.toString.call(nextOption),\n }),\n }\n return {\n name: reviewing ? 'review-of-best' : 'next',\n kind: 'optimizer',\n source: proposerSource,\n execution: { kind: 'deterministic', source: proposerSource },\n childrenPerProposal: 1,\n async propose(request) {\n const parent = request.parents[0]!\n const judged = await chain.judgedVersions(await chain.versionsOf())\n const failure = identicalFailureStreak(judged, failureLimit)\n if (failure !== null) {\n return {\n children: [],\n stop: `the last ${failureLimit} versions failed identically: ${failure}`,\n accounting: FREE,\n }\n }\n const best = judged.find((version) => version.nodeId === parent.nodeId)\n if (best === undefined || parent.artifact.profile === null) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: the kept version ${parent.nodeId} has no judged run to fork from`,\n )\n }\n const returned = await next(\n { best, last: judged.at(-1)!, versions: Object.freeze(judged) },\n request.signal,\n )\n if (typeof returned?.id !== 'string' || returned.id.trim().length === 0) {\n throw new ValidationError('supervisePursuit versions: next must return a change with an id')\n }\n // The ledger stores the change as JSON, so it is taken as JSON: an undefined entry is absent.\n const change = JSON.parse(JSON.stringify(returned)) as AgentProfileDiff\n const child = childNode(parent.artifact.profile, change)\n return {\n children: [\n {\n artifact: child,\n label: change.title ?? returned.id,\n rationale: (change.source?.notes ?? []).join('\\n'),\n },\n ],\n accounting: reviewing\n ? FREE\n : {\n tokens: { status: 'unknown', reason: \"the caller's next reports no usage\" },\n cost: {\n status: 'unknown',\n knownLowerBoundUsd: 0,\n reason: \"the caller's next reports no spend\",\n },\n },\n }\n },\n }\n}\n\n/** The node a change makes, or the refused node when it does not apply to the parent. */\nfunction childNode(parentProfile: AgentProfile, change: AgentProfileDiff): VersionNode {\n const parentDigest = canonicalAgentProfileDigest(parentProfile)\n try {\n return {\n profile: applyExactAgentProfileDiff(parentProfile, change, 'supervisePursuit versions'),\n change,\n parentDigest,\n refusal: null,\n }\n } catch (error) {\n return { profile: null, change, parentDigest, refusal: errorMessage(error) }\n }\n}\n\nfunction canonicalStop(stop: PursuitVersionStop): PursuitVersionStop {\n return {\n patience: stop.patience,\n maxVersions: stop.maxVersions,\n maxUsd: stop.maxUsd,\n deadlineMs: stop.deadlineMs,\n ...(stop.minImprovement === undefined ? {} : { minImprovement: stop.minImprovement }),\n identicalFailures: stop.identicalFailures ?? DEFAULT_IDENTICAL_FAILURES,\n }\n}\n\nconst DEFAULT_IDENTICAL_FAILURES = 3\n\n/** The failure the last `count` judged versions share, or null when they do not all share one. */\nexport function identicalFailureStreak(\n versions: readonly JudgedPursuitVersion[],\n count: number,\n): string | null {\n if (versions.length < count) return null\n const failures = versions.slice(-count).map(versionFailure)\n const [first] = failures\n return first !== null && first !== undefined && failures.every((failure) => failure === first)\n ? first\n : null\n}\n","import { readFile, realpath } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n canonicalCandidateDigest,\n type Sha256Digest,\n sha256Bytes,\n} from '@tangle-network/agent-interface'\nimport { applyExactAgentProfileDiff } from '../candidate-execution/profile'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { authoredProfileDigest } from '../runtime/supervise/materialization'\nimport { type SuperviseOptions, superviseRootProfile } from '../runtime/supervise/supervise'\nimport type { AgentExecutionRef, SpawnEvent } from '../runtime/supervise/types'\nimport { contentAddress } from './content-address'\nimport { isNoEntError } from './jsonl-file'\nimport { readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\nimport { loadSpawnForest } from './spawn-journal/spawn-forest'\n\n/**\n * Start a run as a version of a settled run: the parent's recorded root inputs plus one change.\n *\n * The call's `profile`, `task` and `budget` must be the parent's, byte for byte, as its sealed\n * journal records them. Runtime applies `change` to that profile and runs the result in a new\n * run directory. The parent directory is read and never written.\n */\nexport interface PursuitFork {\n /** The settled parent's run directory. */\n readonly runDir: string\n /** The sha256 of the parent's `result.json` bytes: the sealed point the fork starts from. */\n readonly settleDigest: Sha256Digest\n /** The one change, applied to the parent's root profile. Its `id` is recorded. */\n readonly change: AgentProfileDiff\n /**\n * Fork a parent whose journal holds a node without a terminal record, an unbegun owned tree, an\n * unconfirmed teardown, or work in flight. Such a node may still act, and a fork never replays\n * the parent's children, so it can only duplicate work outside the fork's tree. The root then\n * records those node ids as `forkParentUncertainNodes`. Omit it to refuse such a parent.\n */\n readonly acceptUncertain?: boolean\n}\n\n/**\n * The `execution.correlation` keys a fork records on its root. Runtime writes them; a caller that\n * supplies one is refused. `lineageRootRunId` is the first run of the chain of parents, so the\n * spend of every version of one lineage groups under one id.\n */\nexport const RUN_FORK_CORRELATION_KEYS = Object.freeze([\n 'forkParentRunId',\n 'forkParentSettleDigest',\n 'forkProfileDiffId',\n 'lineageRootRunId',\n] as const)\n\n/** The correlation key an accepted uncertain parent adds: its uncertain node ids, comma-joined. */\nconst FORK_PARENT_UNCERTAIN_NODES_KEY = 'forkParentUncertainNodes'\n\n/** What `supervisePursuit` executes for a fork: the changed profile and the attributed execution. */\ninterface PreparedRunFork {\n readonly profile: AgentProfile\n readonly execution: AgentExecutionRef\n}\n\ntype SpawnedEvent = Extract<SpawnEvent, { kind: 'spawned' }>\n\n/**\n * Verify the parent and derive the fork's profile and attribution. It reads only the parent, so\n * a refused fork spends nothing and writes nothing.\n */\nexport async function prepareRunFork(\n profile: AgentProfile,\n task: unknown,\n opts: SuperviseOptions & { readonly runId?: string; readonly runDir: string },\n fork: PursuitFork,\n): Promise<PreparedRunFork> {\n const change = fork.change\n if (typeof change?.id !== 'string' || change.id.trim().length === 0) {\n throw new ValidationError('supervisePursuit fork: change.id must be a non-empty string')\n }\n const parentDir = await realDirectory(fork.runDir, 'fork.runDir')\n const forkDir = await realDirectory(opts.runDir, 'runDir', true)\n // A fork at, inside or around the parent's directory would write into the parent.\n if (contains(parentDir, forkDir) || contains(forkDir, parentDir)) {\n throw new ValidationError(\n `supervisePursuit fork: runDir ${forkDir} overlaps the parent's runDir ${parentDir}; a fork needs its own directory outside the parent's`,\n )\n }\n\n // The seal: the exact bytes Runtime wrote once at the parent's settle.\n let bytes: Uint8Array\n try {\n bytes = await readFile(resolve(parentDir, SETTLE_RECORD_FILE))\n } catch (error) {\n if (!isNoEntError(error)) throw error\n throw new RuntimeRunStateError(\n `supervisePursuit fork: ${parentDir} holds no ${SETTLE_RECORD_FILE}; only a settled run is forked`,\n )\n }\n const observed = sha256Bytes(bytes)\n if (observed !== fork.settleDigest) {\n throw new RuntimeRunStateError(\n `supervisePursuit fork: ${SETTLE_RECORD_FILE} hashes to ${observed}, not the requested ${fork.settleDigest}`,\n )\n }\n const settled = await readSettleRecord(parentDir)\n if (settled === undefined) {\n throw new RuntimeRunStateError(`supervisePursuit fork: ${parentDir} lost its settle record`)\n }\n const parentRunId = settled.tree.root\n if ((opts.runId ?? 'supervise') === parentRunId) {\n throw new ValidationError(\n `supervisePursuit fork: runId '${parentRunId}' is the parent's; a fork needs its own runId`,\n )\n }\n\n // Certainty: a node the parent never settled may still act, so a fork could duplicate it.\n const forest = await loadSpawnForest(\n new FileSpawnJournal(resolve(parentDir, 'spawn-journal.jsonl')),\n parentRunId,\n )\n const uncertain = [\n ...forest.inDoubt.map((node) => `${node.nodeId} (no terminal record)`),\n ...forest.missingTrees.map((tree) => `${tree.ownerNodeId} (tree ${tree.root} never begun)`),\n ...(settled.teardownUnconfirmed ?? []).map((node) => `${node.id} (teardown unconfirmed)`),\n ]\n if (settled.tree.inFlight > 0 && uncertain.length === 0) {\n uncertain.push(`${settled.tree.inFlight} in flight`)\n }\n if (uncertain.length > 0 && fork.acceptUncertain !== true) {\n throw new RuntimeRunStateError(\n `supervisePursuit fork: run '${parentRunId}' has uncertain nodes: ${uncertain.join(', ')}; set fork.acceptUncertain to fork it anyway`,\n )\n }\n\n // Inputs: the fork differs from its parent by the change alone.\n const root = forest.trees[0]?.events.find(\n (event): event is SpawnedEvent => event.kind === 'spawned' && event.parent === undefined,\n )\n const recorded = root?.identity\n if (recorded?.profileDigest === undefined || recorded.taskDigest === undefined) {\n throw new RuntimeRunStateError(\n `supervisePursuit fork: run '${parentRunId}' records no root profile and task digest`,\n )\n }\n const mismatches = [\n authoredProfileDigest(superviseRootProfile(profile, opts.profileGuidance)) !==\n recorded.profileDigest\n ? `profile is not the parent's ${recorded.profileDigest}`\n : undefined,\n digestOrUndefined(task) !== recorded.taskDigest\n ? `task is not the parent's ${recorded.taskDigest}`\n : undefined,\n contentAddress(root?.budget) !== contentAddress(opts.budget)\n ? \"budget is not the parent's\"\n : undefined,\n ].filter((mismatch): mismatch is string => mismatch !== undefined)\n if (mismatches.length > 0) {\n throw new ValidationError(`supervisePursuit fork: ${mismatches.join('; ')}`)\n }\n\n const forked = applyExactAgentProfileDiff(profile, change, 'supervisePursuit fork')\n if (\n authoredProfileDigest(superviseRootProfile(forked, opts.profileGuidance)) ===\n recorded.profileDigest\n ) {\n throw new ValidationError(\n `supervisePursuit fork: change '${change.id}' leaves the parent's profile unchanged`,\n )\n }\n\n const supplied = opts.execution?.correlation ?? {}\n const owned = [...RUN_FORK_CORRELATION_KEYS, FORK_PARENT_UNCERTAIN_NODES_KEY].filter((key) =>\n Object.hasOwn(supplied, key),\n )\n if (owned.length > 0) {\n throw new ValidationError(\n `supervisePursuit fork: execution.correlation cannot set ${owned.join(', ')}; Runtime records them`,\n )\n }\n return Object.freeze({\n profile: forked,\n execution: Object.freeze({\n ...opts.execution,\n correlation: Object.freeze({\n ...supplied,\n forkParentRunId: parentRunId,\n forkParentSettleDigest: fork.settleDigest,\n forkProfileDiffId: change.id,\n lineageRootRunId: recorded.correlation?.lineageRootRunId ?? parentRunId,\n ...(uncertain.length === 0\n ? {}\n : { [FORK_PARENT_UNCERTAIN_NODES_KEY]: uncertain.join(', ') }),\n }),\n }),\n })\n}\n\nfunction digestOrUndefined(value: unknown): Sha256Digest | undefined {\n try {\n return canonicalCandidateDigest(value)\n } catch {\n return undefined\n }\n}\n\n/**\n * Resolve a directory through symlinks. The fork's own directory may not exist yet; it resolves\n * through its nearest existing ancestor, so a symlinked ancestor cannot hide an overlap.\n */\nasync function realDirectory(path: string, name: string, mayBeAbsent = false): Promise<string> {\n if (typeof path !== 'string' || path.trim().length === 0) {\n throw new ValidationError(`supervisePursuit fork: ${name} must be a non-empty string`)\n }\n const absolute = resolve(path.trim())\n try {\n return await realpath(absolute)\n } catch (error) {\n const ancestor = dirname(absolute)\n if (!mayBeAbsent || !isNoEntError(error) || ancestor === absolute) throw error\n return join(await realDirectory(ancestor, name, true), basename(absolute))\n }\n}\n\n/** Whether `inner` is `outer` or lies beneath it. */\nfunction contains(outer: string, inner: string): boolean {\n const path = relative(outer, inner)\n return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`))\n}\n","import { join } from 'node:path'\nimport type { ToolSpan } from '@tangle-network/agent-eval'\nimport { ValidationError } from '../errors'\nimport { readRootStream } from '../runtime/supervise/root-stream'\nimport { runToolSpans } from '../runtime/supervise/run-traces'\nimport { FileObserverJournal } from './observer-journal'\nimport { projectPursuit } from './observer-projection'\nimport { FileResultBlobStore } from './spawn-journal/result-blob-store'\nimport { discoverDurableSupervisionRun } from './supervision-discovery'\n\n/**\n * Every tool span a finished `supervise({ runDir })` run recorded, read from its directory alone:\n * the root's `root-stream.jsonl` as one trace named by the root node id, and each settled node's\n * persisted trace (the observer projection's `trace`) from `<runDir>/blobs`, re-keyed to the node\n * id. The same builder feeds the continuation panel's trace store.\n *\n * A node whose trace blob is missing throws `ValidationError`; a node with no captured trace adds\n * nothing.\n */\nexport async function durableRunToolSpans(runDir: string): Promise<readonly ToolSpan[]> {\n const run = await discoverDurableSupervisionRun(runDir)\n if (run.roots.length > 1) {\n throw new ValidationError(\n `${run.runDir} holds ${run.roots.length} supervision roots; a run directory has one`,\n )\n }\n const rootId = run.roots[0]\n const journal = run.observer && (await FileObserverJournal.open(run.observer.path))\n const nodes = journal === undefined ? [] : projectPursuit(await journal.read()).nodes\n const workers = nodes.flatMap((node) =>\n node.trace === undefined || node.id === rootId ? [] : [{ id: node.id, trace: node.trace }],\n )\n return Object.freeze(\n await runToolSpans({\n ...(rootId === undefined\n ? {}\n : { root: { id: rootId, read: () => readRootStream(run.runDir) } }),\n workers,\n blobs: new FileResultBlobStore(join(run.runDir, 'blobs')),\n }),\n )\n}\n","import type { PursuitProjection } from './observer-projection'\n\n/**\n * Where a pursuit's observer projection is delivered while it runs, so a run started anywhere is\n * findable in one place by its pursuit id.\n *\n * Intelligence persists the projection on its run spine (`runtime-observer:pursuit:<pursuitId>`)\n * and records the id of the API key that delivered it, which joins the run to that key's spend.\n * Delivery is an observation, never a dependency: a refused, slow or unreachable endpoint is\n * reported once and the run continues exactly as it would without it.\n */\nexport interface PursuitObserverDelivery {\n /** Intelligence base URL, e.g. `https://intelligence.tangle.tools`. */\n readonly baseUrl: string\n /** Platform API key presented as the Bearer; Intelligence resolves the tenant from it. */\n readonly apiKey: string\n /** The Intelligence subject (project) the pursuit belongs to. */\n readonly subjectKey: string\n readonly subjectName?: string\n /**\n * Flat facts the caller owns about the run, recorded on the pursuit row unchanged, such as the\n * program and idea a registration names. Runtime neither reads nor validates their meaning.\n */\n readonly attributes?: Readonly<Record<string, string>>\n /** How often a live run re-delivers its projection. Default 60 s; the last delivery is liveness. */\n readonly intervalMs?: number\n /** Per-request bound. Default 10 s. */\n readonly timeoutMs?: number\n readonly fetch?: typeof fetch\n}\n\n/** The execution state Runtime reports. It never claims the pursuit's semantic success. */\nexport type PursuitObserverState = 'running' | 'done' | 'failed'\n\nexport type PursuitObserverDeliveryOutcome =\n | { readonly succeeded: true; readonly status: number }\n | { readonly succeeded: false; readonly reason: string }\n\n/** The Intelligence route that persists a delivered projection on its run spine. */\nexport const PURSUIT_OBSERVER_DELIVERY_PATH = '/v1/ingest/pursuit-observer'\n\nconst DEFAULT_INTERVAL_MS = 60_000\nconst DEFAULT_TIMEOUT_MS = 10_000\n\n/** POST one projection. Never throws; the outcome says whether Intelligence accepted it. */\nasync function deliverPursuitObserver(\n delivery: PursuitObserverDelivery,\n state: PursuitObserverState,\n projection: PursuitProjection,\n): Promise<PursuitObserverDeliveryOutcome> {\n const send = delivery.fetch ?? globalThis.fetch\n const url = `${delivery.baseUrl.replace(/\\/+$/u, '')}${PURSUIT_OBSERVER_DELIVERY_PATH}`\n try {\n const response = await send(url, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${delivery.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n subjectKey: delivery.subjectKey,\n ...(delivery.subjectName === undefined ? {} : { subjectName: delivery.subjectName }),\n state,\n ...(delivery.attributes === undefined ? {} : { attributes: delivery.attributes }),\n projection,\n }),\n signal: AbortSignal.timeout(delivery.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n })\n if (response.ok) return { succeeded: true, status: response.status }\n const detail = (await response.text().catch(() => '')).slice(0, 300)\n return { succeeded: false, reason: `HTTP ${response.status}${detail ? `: ${detail}` : ''}` }\n } catch (error) {\n return { succeeded: false, reason: error instanceof Error ? error.message : String(error) }\n }\n}\n\nexport interface PursuitObserverDeliverer {\n /** Queue a delivery of the current projection. Deliveries never overlap; a burst collapses to one. */\n push(state: PursuitObserverState): void\n /** Stop liveness delivery and deliver the final snapshot. A parked run remains nonterminal. */\n close(state: PursuitObserverState): Promise<PursuitObserverDeliveryOutcome>\n}\n\n/**\n * Deliver a live run's projection at start, on an interval, and at settlement. `read` projects\n * the run's own journal at the moment of each delivery, so every delivery is the whole record.\n */\nexport function startPursuitObserverDelivery(\n delivery: PursuitObserverDelivery,\n read: () => Promise<PursuitProjection>,\n warn: (message: string) => void = (message) => console.warn(message),\n): PursuitObserverDeliverer {\n let chain: Promise<PursuitObserverDeliveryOutcome | undefined> = Promise.resolve(undefined)\n let pending: PursuitObserverState | undefined\n let warned = false\n let closed = false\n\n const deliver = async (state: PursuitObserverState) => {\n let projection: PursuitProjection\n try {\n projection = await read()\n } catch (error) {\n return report({\n succeeded: false,\n reason: `observer projection unreadable: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n return report(await deliverPursuitObserver(delivery, state, projection))\n }\n const report = (outcome: PursuitObserverDeliveryOutcome) => {\n if (!outcome.succeeded && !warned) {\n warned = true\n warn(\n `supervisePursuit: pursuit observer delivery to ${delivery.baseUrl} failed (${outcome.reason}); the run continues and later deliveries retry`,\n )\n }\n return outcome\n }\n const push = (state: PursuitObserverState) => {\n if (closed) return\n if (pending !== undefined) return\n pending = state\n chain = chain.then(() => {\n const next = pending as PursuitObserverState\n pending = undefined\n return deliver(next)\n })\n }\n\n const timer = setInterval(() => push('running'), delivery.intervalMs ?? DEFAULT_INTERVAL_MS)\n timer.unref?.()\n push('running')\n\n return {\n push,\n async close(state) {\n closed = true\n clearInterval(timer)\n const terminal = chain.then(() => deliver(state))\n chain = terminal\n const bound = delivery.timeoutMs ?? DEFAULT_TIMEOUT_MS\n let timeout: ReturnType<typeof setTimeout> | undefined\n const expired = new Promise<PursuitObserverDeliveryOutcome>((resolve) => {\n timeout = setTimeout(\n () => resolve({ succeeded: false, reason: `terminal delivery exceeded ${bound} ms` }),\n bound * 2,\n )\n timeout.unref?.()\n })\n try {\n return await Promise.race([terminal, expired])\n } finally {\n clearTimeout(timeout)\n }\n },\n }\n}\n","import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport {\n publishExclusiveDurableFile,\n syncDurableDirectory,\n} from '../runtime/supervise/durable-file'\nimport { runCancellationFile, runCancelRequestFile } from '../runtime/supervise/run-cancellation'\nimport { workerCancellationsDir } from '../runtime/supervise/run-layout'\nimport { assertValidBudget } from '../runtime/supervise/spend-validation'\nimport { assertResumeLimits } from '../runtime/supervise/supervisor-root-contract'\nimport type { Budget, SpawnEvent, SpawnJournal, SupervisorOpts } from '../runtime/supervise/types'\nimport type { FileObserverJournal } from './observer-journal'\nimport { fenceRunWrite } from './run-fence'\nimport { SETTLE_RECORD_FILE, settleRecordDigest } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\n\n/*\n * Reopening a settled run under its own run id.\n *\n * A wrong settle used to be final: `supervisePursuit` refuses a directory that holds `result.json`,\n * and `fork` and `versions` each start a new run id in a new directory. Magnetar used 21 run ids\n * from 2026-10-16 to 10-21 for one solve; 16 of those runs settled, 11 of them in under 5 hours.\n *\n * A reopen archives the settled segment and resumes the same journal. Before it writes anything it\n * checks the resume limits (`assertResumeLimits`): a reopen refused for its budget or reservation\n * policy leaves `result.json`, the cancel files and the journal as they were. The profile's identity\n * and materialization are checked by `supervise` itself, after these steps. Every step is\n * idempotent, so a later call with the same `operationId` finishes a reopen that crashed partway:\n * 1. copy `result.json` byte for byte to `settles/<n>.json`;\n * 2. append one `reopened` spawn-journal row naming the operator, the reason and the archive;\n * 3. append one observer event, so the pursuit projection shows one lineage;\n * 4. move the run's cancel request and acknowledgement aside under this reopen's and that\n * request's operation ids, so a new `cancelRun` is accepted (one run carries one run-scoped\n * cancel operation) and no later reopen overwrites an earlier segment's cancel;\n * 5. last, remove `result.json`.\n * The caller then runs `supervise` with `resume: true`: settled children replay by key, the pool\n * is restored from the journal, and the next settle writes `result.json` again.\n */\n\n/** `supervisePursuit`'s `reopen` option: reopen this settled run under its own run id. */\nexport interface RunReopen {\n /** Who reopens the run. Required and non-empty. */\n readonly operator: string\n /** Why. Required and non-empty. */\n readonly reason: string\n /** Idempotency key: calling again with it finishes a reopen that crashed partway. */\n readonly operationId: string\n /**\n * The budget the reopened run is held to, recorded on its `reopened` row, which a later resume\n * must then match. Omit and the call's `budget` must equal the recorded one: the root's, or the\n * last budget a reopen recorded. A run that settled `budget-exhausted` and reopens without a\n * larger budget pauses at once (with `driverRetry.pauseRootStops`) or settles\n * `budget-exhausted` again. A deadline is measured from the original root instant, so a run\n * whose recorded deadline has passed settles `deadline` at once unless this budget drops the\n * deadline or moves it.\n */\n readonly budget?: Budget\n}\n\n/** The directory that holds a run's archived settle records. */\nexport const SETTLE_ARCHIVE_DIR = 'settles'\n\n/** Refuse a reopen that names no operator or reason, or that is combined with a fork or versions. */\nexport function assertRunReopen(\n reopen: RunReopen,\n opts: { readonly fork?: unknown; readonly versions?: unknown },\n): void {\n if (reopen.operator.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.operator must be non-empty')\n }\n if (reopen.reason.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.reason must be non-empty')\n }\n if (reopen.operationId.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.operationId must be non-empty')\n }\n if (reopen.budget !== undefined) assertValidBudget(reopen.budget, 'reopen.budget')\n if (opts.fork !== undefined || opts.versions !== undefined) {\n throw new TypeError(\n 'supervisePursuit: reopen continues this run under its own id; fork and versions start new runs',\n )\n }\n}\n\n/**\n * Archive the settled segment of the run at `runDir` and clear it for a resume. Runs under the\n * directory lock. Throws when there is nothing to reopen, or when `operationId` already reopened a\n * segment that has since settled again.\n */\nexport async function reopenSettledRun(input: {\n readonly runDir: string\n readonly runId: string\n readonly reopen: RunReopen\n readonly journal: SpawnJournal | undefined\n /** The call's budget and reservation policy, checked against the recorded ones before any write. */\n readonly limits: Pick<SupervisorOpts, 'budget' | 'reservationPolicy'>\n readonly observer: FileObserverJournal\n readonly pursuitId: string\n readonly now: () => number\n}): Promise<void> {\n const { runDir, runId, reopen, observer, pursuitId, now } = input\n const operationId = reopen.operationId.trim()\n const settlePath = resolve(runDir, SETTLE_RECORD_FILE)\n const journal = input.journal ?? new FileSpawnJournal(resolve(runDir, 'spawn-journal.jsonl'))\n const events = (await journal.loadTree(runId)) ?? []\n const reopened = events.filter(\n (event): event is Extract<SpawnEvent, { kind: 'reopened' }> =>\n event.kind === 'reopened' && event.id === runId,\n )\n const mine = reopened.find((event) => event.operationId === operationId)\n const settled = await readBytes(settlePath)\n if (settled === undefined) {\n // Removing result.json is the last step, so a recorded reopen without it is complete.\n if (mine !== undefined) return\n throw new Error(\n `supervisePursuit: ${runDir} holds no ${SETTLE_RECORD_FILE}; nothing to reopen; resume it`,\n )\n }\n assertResumeLimits(\n events,\n {\n runId,\n budget: reopen.budget ?? input.limits.budget,\n ...(input.limits.reservationPolicy === undefined\n ? {}\n : { reservationPolicy: input.limits.reservationPolicy }),\n },\n mine === undefined ? reopen.budget : undefined,\n )\n const result = JSON.parse(settled) as { readonly kind?: unknown; readonly reason?: unknown }\n const digest = settleRecordDigest(result)\n if (mine !== undefined && mine.prior.digest !== digest) {\n throw new Error(\n `supervisePursuit: reopen '${operationId}' already reopened run '${runId}', which has settled again; reopen it under a new operationId`,\n )\n }\n const archivedAs = mine?.prior.archivedAs ?? (await archiveName(runDir, settled))\n const archivePath = resolve(runDir, archivedAs)\n if (\n !publishExclusiveDurableFile(archivePath, settled) &&\n (await readBytes(archivePath)) !== settled\n ) {\n throw new Error(\n `supervisePursuit: ${archivePath} already holds a different settle record; reopen refused`,\n )\n }\n const at = new Date(now()).toISOString()\n if (mine === undefined) {\n await journal.appendEvent(runId, {\n kind: 'reopened',\n id: runId,\n operator: reopen.operator,\n reason: reopen.reason,\n operationId,\n prior: {\n kind: String(result.kind),\n ...(typeof result.reason === 'string' ? { reason: result.reason } : {}),\n digest,\n archivedAs,\n },\n ...(reopen.budget === undefined ? {} : { budget: reopen.budget }),\n seq: reopened.length,\n at,\n })\n }\n const eventId = `${runId}:pursuit:reopened:${operationId}`\n if (!(await observer.read()).some((record) => record.event?.id === eventId)) {\n await observer.appendEvent({\n id: eventId,\n pursuitId,\n runId,\n target: 'agent.run',\n phase: 'event',\n timestamp: now(),\n payload: { reopened: { operator: reopen.operator, reason: reopen.reason, archivedAs } },\n })\n }\n fenceRunWrite(() => {\n setCancellationAside(runDir, operationId)\n unlinkSync(settlePath)\n syncDurableDirectory(runDir)\n })\n}\n\n/** The next free `settles/<n>.json`, or the archive that already holds these bytes (a reopen that\n * crashed after archiving and before its journal row). */\nasync function archiveName(runDir: string, settled: string): Promise<string> {\n const dir = resolve(runDir, SETTLE_ARCHIVE_DIR)\n fenceRunWrite(() => mkdirSync(dir, { recursive: true }))\n const numbers = readdirSync(dir)\n .map((name) => /^(\\d+)\\.json$/u.exec(name)?.[1])\n .filter((n): n is string => n !== undefined)\n .map(Number)\n .sort((a, b) => a - b)\n for (const n of numbers) {\n if ((await readBytes(join(dir, `${n}.json`))) === settled)\n return `${SETTLE_ARCHIVE_DIR}/${n}.json`\n }\n return `${SETTLE_ARCHIVE_DIR}/${(numbers.at(-1) ?? 0) + 1}.json`\n}\n\n/** Move the settled run's cancel request and acknowledgement aside under the reopen's and the\n * request's operation ids, so the reopened run accepts a new `cancelRun`. Idempotent: an absent\n * file is skipped. A reopen's operation id names one segment, so a later segment cancelled under\n * the same cancel operation id lands beside this one instead of over it. */\nfunction setCancellationAside(runDir: string, reopenOperationId: string): void {\n const requestFile = runCancelRequestFile(runDir)\n const ackFile = runCancellationFile(runDir)\n if (!existsSync(requestFile) && !existsSync(ackFile)) return\n const source = existsSync(requestFile) ? requestFile : ackFile\n const { operationId } = JSON.parse(readFileSync(source, 'utf8')) as {\n readonly operationId: string\n }\n const reopenedDir = join(workerCancellationsDir(runDir), 'reopened')\n const aside = join(\n reopenedDir,\n encodeURIComponent(reopenOperationId),\n encodeURIComponent(operationId),\n )\n mkdirSync(aside, { recursive: true })\n if (existsSync(ackFile)) renameSync(ackFile, join(aside, 'run.json'))\n if (existsSync(requestFile)) renameSync(requestFile, join(aside, 'run.request.json'))\n syncDurableDirectory(aside)\n syncDurableDirectory(join(reopenedDir, encodeURIComponent(reopenOperationId)))\n syncDurableDirectory(reopenedDir)\n syncDurableDirectory(workerCancellationsDir(runDir))\n}\n\nasync function readBytes(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n","import { resolve } from 'node:path'\nimport { runtimeFailureCause } from '../runtime/failure-cause'\nimport { FileCoordinationLog } from '../runtime/supervise/coordination-log'\nimport {\n type AgentGraph,\n type GraphResult,\n type RunGraphOptions,\n superviseAgentGraph,\n} from '../runtime/supervise/graph'\nimport { graphExecutionOptions } from '../runtime/supervise/graph-backend'\nimport { readRootStreamReceipt } from '../runtime/supervise/root-stream'\nimport { supervisorRunDir } from '../runtime/supervise/run-layout'\nimport { RunParkedError } from '../runtime/supervise/run-parking'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport { rootCoordinationOwner } from '../runtime/supervise/supervise-identity'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport {\n composeRuntimeHooks,\n type RuntimeHookEvent,\n type RuntimeHooks,\n withPursuitContext,\n} from '../runtime-hooks'\nimport { createFileObserverHooks } from './observer-journal'\nimport { type PursuitProjection, projectPursuit } from './observer-projection'\nimport {\n type PursuitObserverDeliverer,\n type PursuitObserverDelivery,\n startPursuitObserverDelivery,\n} from './pursuit-observer-delivery'\nimport {\n type PursuitVersionChain,\n type PursuitVersions,\n runPursuitVersions,\n} from './pursuit-versions'\nimport { type PursuitFork, prepareRunFork } from './run-fork'\nimport { acquireRunDirectoryLock } from './run-lock'\nimport { assertRunReopen, type RunReopen, reopenSettledRun } from './run-reopen'\nimport {\n FAILURE_RECORD_FILE,\n readSettleRecord,\n SETTLE_RECORD_FILE,\n SettledRunDirectoryError,\n writeFailureRecord,\n writeSettleRecord,\n} from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\n\nexport interface SupervisePursuitOptions extends SuperviseOptions {\n /** Stable objective identity spanning concrete Runtime runs. */\n readonly pursuitId: string\n /**\n * One concrete Runtime execution owns one durable directory and observer journal.\n * A pursuit spanning several runs reuses `pursuitId` across distinct `runDir`s;\n * Intelligence joins those isolated projections without a shared write head.\n */\n readonly runDir: string\n /** Always `'release'`: settlement seals the segment, so retained environments are released.\n * `'keep'` is refused. A reopen replays the journal rather than retaining environments. */\n readonly retainedAtSettlement?: 'release'\n /**\n * Run this pursuit as a version of a settled run: `profile`, `task` and `budget` must equal the\n * parent's recorded root, and Runtime executes the parent's profile with `fork.change` applied.\n * The root's `execution.correlation` records the parent, its sealed digest, the change and the\n * lineage (`RUN_FORK_CORRELATION_KEYS`). The fork's `runDir` must lie outside the parent's, and\n * the parent's outside it. The parent's directory is never written, and a refused fork, such as\n * one whose parent has an uncertain node, writes nothing.\n */\n readonly fork?: PursuitFork\n /**\n * Continue this pursuit across versions, on Eval's search kernel. The first version runs at\n * `runDir` as usual, or is read back when that directory already settled. After each version\n * settles, `versions.judge` scores it from outside its tree; unless `versions.stop` ends the\n * chain, the next version forks from the version the chain keeps with the change\n * `versions.next` returns, at `<runDir>.v<n>` with run id `<runId>.v<n>`. The search ledger at\n * `<runDir>.search/ledger.jsonl` records every version as a node, every change as an edge, and\n * every run and verdict as a cell; it is the chain's only record and checkpoint. A call on a\n * closed chain reads it back; a call on an open chain continues it without re-running or\n * re-judging a settled version. Aborting `signal` pauses the chain: the call rejects and a later\n * call continues it. The call returns the kept version's result with the chain.\n */\n readonly versions?: PursuitVersions\n /**\n * Deliver this run's observer projection to Intelligence at start, every `intervalMs` while it\n * runs, and at settlement or failure, so the run is findable by its pursuit id from wherever it\n * was started. Optional and fail-open: a delivery that fails is reported once and never changes\n * the run. Each version of a `versions` chain delivers its own run under the same pursuit.\n */\n readonly observerDelivery?: PursuitObserverDelivery\n /**\n * Reopen this settled run under its own run id instead of refusing it (`./run-reopen.ts`).\n * Under the directory lock, `result.json` is archived byte for byte to `settles/<n>.json`, one\n * `reopened` journal row names the operator and reason, the run's settled cancel operation is\n * moved aside, and the run resumes from its journal (`resume: true`): settled children replay by\n * key and spend from before the reopen is debited once. `reopen.budget`, when set, replaces the\n * call's `budget` and is recorded for later resumes. Refused with `fork` or `versions`, and on a\n * directory with no `result.json` (\"nothing to reopen; resume it\"); a reopen whose budget or\n * reservation policy the recorded run refuses (\"resume budget mismatch\") writes nothing.\n */\n readonly reopen?: RunReopen\n}\n\nexport interface SupervisedPursuitResult<Result> {\n readonly result: Result\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n /** `result.json` in the run directory: `result` as canonical JSON, written once at settle. */\n readonly settlePath: string\n /** The version chain, when the call set `versions`. */\n readonly versions?: PursuitVersionChain\n}\n\n/** A failed Runtime execution whose complete third-person projection was retained. */\nexport class SupervisePursuitError extends Error {\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n /** `failure.json` in the run directory: the record of this throw. */\n readonly failurePath: string\n\n constructor(\n cause: unknown,\n pursuit: PursuitProjection,\n observerPath: string,\n failurePath: string,\n ) {\n super(`supervisePursuit: ${errorMessage(cause)}`, { cause })\n this.name = 'SupervisePursuitError'\n this.pursuit = pursuit\n this.observerPath = observerPath\n this.failurePath = failurePath\n }\n}\n\n/**\n * Execute `supervise()` with a durable observer and return its verified pursuit projection.\n * Each `runDir` owns its lock and journals; Intelligence joins directories by `pursuitId`.\n * Agents never receive the observer path or projection.\n *\n * `result.json` seals a segment and refuses re-entry before compute; `failure.json` records\n * the latest throw and permits a corrected retry. Both pursuit entrypoints use the same\n * directory lifecycle below. A competing process is refused with the lock holder's identity;\n * an abandoned `supervise.lock.guard` requires confirmation of inactivity before removal.\n */\nexport async function supervisePursuit(\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions,\n): Promise<SupervisedPursuitResult<Awaited<ReturnType<typeof supervise>>>> {\n assertPursuitDirectory(opts, 'supervisePursuit')\n if (opts.reopen !== undefined) assertRunReopen(opts.reopen, opts)\n\n if (opts.versions !== undefined) {\n return runPursuitVersions(\n profile,\n task,\n opts as SupervisePursuitOptions & { readonly versions: PursuitVersions },\n supervisePursuit,\n ) as Promise<SupervisedPursuitResult<Awaited<ReturnType<typeof supervise>>>>\n }\n\n const {\n pursuitId: _pursuitId,\n hooks: _hooks,\n fork,\n versions: _versions,\n observerDelivery: _observerDelivery,\n reopen,\n ...superviseOptions\n } = opts\n\n // A fork is verified on every entry, a resume included, so the recorded root identity it\n // derives is the one the Supervisor's resume contract compares against. It reads only the\n // settled parent, and runs before the lock so a refused fork writes nothing, not even runDir.\n const forked =\n fork === undefined ? undefined : await prepareRunFork(profile, task, superviseOptions, fork)\n\n return runDurablePursuit(\n opts,\n ({ hooks, steerDir }) =>\n supervise(forked?.profile ?? profile, task, {\n ...superviseOptions,\n ...(forked === undefined ? {} : { execution: forked.execution }),\n ...(reopen === undefined\n ? {}\n : { resume: true, ...(reopen.budget === undefined ? {} : { budget: reopen.budget }) }),\n steerDir,\n // Settlement seals this segment; a later reopen replays its journal.\n retainedAtSettlement: 'release',\n hooks,\n }),\n (result) => result,\n opts.budget,\n )\n}\n\n/** Options for {@link superviseGraphPursuit}: every `runGraph` option, plus the pursuit identity,\n * the run directory this execution owns, and optional observer delivery. */\nexport interface SuperviseGraphPursuitOptions extends RunGraphOptions {\n /** Stable objective identity spanning concrete Runtime runs. */\n readonly pursuitId: string\n /** The directory this execution owns: journal, blobs, observer journal, lock and terminal\n * records. Re-running the same `runDir` and `runId` resumes an unsettled graph; a settled\n * graph requires an explicit `reopen`. */\n readonly runDir: string\n /** Always `'release'`: a reopened segment reuses its journal, not retired environments. */\n readonly retainedAtSettlement?: 'release'\n /** As for {@link supervisePursuit}. */\n readonly observerDelivery?: PursuitObserverDelivery\n /** Explicitly reopen a settled segment under this graph's existing run id and journal. */\n readonly reopen?: RunReopen\n}\n\n/**\n * Graph twin of `supervisePursuit`, using its directory lifecycle and `runGraph` execution.\n * The directory run id binds the supervised root; spawn-journal edge events own the ledger.\n * Explicit `reopen` archives the result and resumes this id; ordinary settled re-entry refuses.\n * Forks and version chains are offered by `supervisePursuit` only.\n */\nexport async function superviseGraphPursuit(\n graph: AgentGraph,\n opts: SuperviseGraphPursuitOptions,\n): Promise<SupervisedPursuitResult<GraphResult>> {\n assertPursuitDirectory(opts, 'superviseGraphPursuit')\n if (opts.reopen !== undefined) assertRunReopen(opts.reopen, {})\n const {\n pursuitId: _pursuitId,\n hooks: _hooks,\n observerDelivery: _observerDelivery,\n brain,\n reopen,\n ...graphOptions\n } = opts\n return runDurablePursuit(\n opts,\n ({ hooks, steerDir }) =>\n superviseAgentGraph(\n reopen?.budget === undefined ? graph : { ...graph, budget: reopen.budget },\n graphExecutionOptions({\n ...graphOptions,\n // The lock, the settle record and the journal name one run, so the graph takes the\n // directory's run id rather than its own digest-derived default.\n runId: graphOptions.runId ?? 'supervise',\n ...(reopen === undefined ? {} : { resume: true }),\n steerDir,\n retainedAtSettlement: 'release',\n hooks,\n }),\n brain,\n ),\n (result) => result.result,\n graph.budget,\n )\n}\n\n/** The pursuit identity and run directory both durable entries require. */\nfunction assertPursuitDirectory(\n opts: {\n readonly pursuitId: string\n readonly runDir: string\n readonly retainedAtSettlement?: string\n },\n entry: string,\n): void {\n for (const field of ['pursuitId', 'runDir'] as const) {\n if (opts[field].trim().length === 0) throw new TypeError(`${entry}: ${field} must be non-empty`)\n }\n if (opts.retainedAtSettlement === 'keep') {\n throw new TypeError(\n `${entry}: retainedAtSettlement 'keep' cannot hold, because a settled pursuit is never re-entered`,\n )\n }\n}\n\n/** Own the directory lock, terminal records and observer lifecycle for both pursuit entries. */\nasync function runDurablePursuit<Result>(\n opts: SupervisePursuitOptions | SuperviseGraphPursuitOptions,\n execute: (seams: { readonly hooks: RuntimeHooks; readonly steerDir: string }) => Promise<Result>,\n settled: (result: Result) => SupervisedResult<unknown>,\n budget: Budget,\n): Promise<SupervisedPursuitResult<Result>> {\n const pursuitId = opts.pursuitId.trim()\n const runDir = opts.runDir.trim()\n const observerPath = resolve(runDir, 'observer.jsonl')\n const settlePath = resolve(runDir, SETTLE_RECORD_FILE)\n const failurePath = resolve(runDir, FAILURE_RECORD_FILE)\n const runId = opts.runId ?? 'supervise'\n const now = opts.now ?? Date.now\n\n // The lock is taken before the settle record is read so a run that settles between the read\n // and the lock cannot be re-entered; both refusals happen before the observer journal is touched.\n const lock = await acquireRunDirectoryLock(runDir, runId, now)\n return lock.run(async () => {\n let delivery: PursuitObserverDeliverer | undefined\n let terminalState: 'done' | 'failed' | 'running' = 'failed'\n try {\n const observer = createFileObserverHooks(observerPath, pursuitId)\n if (opts.reopen !== undefined)\n await reopenSettledRun({\n runDir,\n runId,\n reopen: opts.reopen,\n journal: opts.journal,\n limits: {\n budget,\n ...(opts.reservationPolicy === undefined\n ? {}\n : { reservationPolicy: opts.reservationPolicy }),\n },\n observer: observer.journal,\n pursuitId,\n now,\n })\n else {\n const prior = await readSettleRecord(runDir)\n if (prior !== undefined) {\n throw new SettledRunDirectoryError(settlePath, prior.tree.root, runId)\n }\n }\n\n // Bind this attempt to existing journal boundaries while its directory lock is held.\n const events =\n (await (\n opts.journal ?? new FileSpawnJournal(resolve(runDir, 'spawn-journal.jsonl'))\n ).loadTree(runId)) ?? []\n const root = events.find((event) => event.kind === 'spawned' && event.id === runId)\n const prior =\n root?.kind === 'spawned' && root.identity\n ? await new FileCoordinationLog(resolve(runDir, 'coordination-log.jsonl')).load(\n runId,\n rootCoordinationOwner(root.identity),\n )\n : undefined\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'before', now(), {\n coordinationOffset: prior?.records.length ?? 0,\n }),\n )\n delivery =\n opts.observerDelivery === undefined\n ? undefined\n : startPursuitObserverDelivery(opts.observerDelivery, async () =>\n projectPursuit(await observer.journal.read()),\n )\n\n let result: Result\n try {\n result = await execute({\n // The observer runs first so a caller hook that throws cannot prevent the\n // canonical lifecycle fact from entering the durable journal.\n hooks: withPursuitContext(pursuitId, composeRuntimeHooks(observer.hooks, opts.hooks)),\n // `runDir` owns the pursuit journal and terminal records. The public steer writer\n // addresses the canonical per-run event directory beneath that root, so keep its control\n // plane there without moving the durable pursuit records.\n steerDir: opts.steerDir ?? supervisorRunDir(runDir, runId),\n })\n } catch (error) {\n if (error instanceof RunParkedError && error.runId === runId) {\n terminalState = 'running'\n throw error\n }\n let pursuit: PursuitProjection\n try {\n // The journal fact is raw evidence and lands first; the failure record summarizes it.\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'error', now(), {\n status: 'failed',\n error: errorMessage(error),\n failure: runtimeFailureCause(error),\n }),\n )\n pursuit = projectPursuit(await observer.journal.read())\n } catch (observerError) {\n throw new Error(\n 'supervisePursuit: Runtime failed and durable observer completeness could not be proven',\n { cause: new AggregateError([error, observerError]) },\n )\n }\n // A failure record that cannot be written must not hide the journal fact above; it is\n // reported as its own cause beside the run's error.\n try {\n // The root's stream is already on disk whether or not the run settled; the record names\n // it so a root that died mid-turn keeps what it had streamed.\n const rootStream = await readRootStreamReceipt(runDir)\n await writeFailureRecord(runDir, {\n runId,\n pursuitId,\n at: new Date(now()).toISOString(),\n error: {\n name: error instanceof Error ? error.name : 'NonError',\n message: errorMessage(error),\n },\n ...(rootStream === undefined ? {} : { rootStream }),\n })\n } catch (recordError) {\n throw new Error(\n `supervisePursuit: Runtime failed and the failure record ${failurePath} could not be written`,\n { cause: new AggregateError([error, recordError]) },\n )\n }\n throw new SupervisePursuitError(error, pursuit, observerPath, failurePath)\n }\n\n // The settle record is the re-entry guard, so it is durable before the journal says `done`.\n // A record that cannot be written leaves the attempt open in the journal and the run\n // re-enterable, which replays the settled children and settles again.\n const terminal = settled(result)\n try {\n await writeSettleRecord(runDir, terminal)\n } catch (cause) {\n throw new Error(\n `supervisePursuit: Runtime settled but the settle record ${settlePath} could not be written`,\n { cause },\n )\n }\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'after', now(), {\n status: 'done',\n ...(terminal.kind === 'no-winner' &&\n terminal.reason === 'driver-failed' &&\n terminal.error.failure\n ? { error: terminal.error.message, failure: terminal.error.failure }\n : {}),\n }),\n )\n terminalState = 'done'\n return Object.freeze({\n result,\n pursuit: projectPursuit(await observer.journal.read()),\n observerPath,\n settlePath,\n })\n } finally {\n // The terminal delivery reads the journal after its last fact, and is bounded so an\n // unreachable Intelligence delays the return by at most twice its timeout.\n await delivery?.close(terminalState)\n await lock.release()\n }\n })\n}\n\nfunction rootEvent(\n pursuitId: string,\n runId: string,\n phase: 'before' | 'after' | 'error',\n timestamp: number,\n payload?: Record<string, unknown>,\n): RuntimeHookEvent {\n return Object.freeze({\n id: `${runId}:pursuit:${phase}:${timestamp}`,\n pursuitId,\n runId,\n target: 'agent.run',\n phase,\n timestamp,\n ...(payload ? { payload: Object.freeze({ ...payload }) } : {}),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,0BAA0B,QAAwB;CAChE,OAAO,QAA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AC/B,IAAI;IACF,MAAM,kBAAkB,QAAQ,QAAQ;GAC1C,SAAS,OAAO;IACd,MAAM,IAAI,MACR,2DAA2D,WAAW,wBACtE,EAAE,MAAM,CACV;GACF;GACA,MAAM,SAAS,QAAQ,YACrB,UAAU,WAAW,OAAO,SAAS,IAAI,GAAG;IAC1C,QAAQ;IACR,GAAI,SAAS,SAAS,eACtB,SAAS,WAAW,mBACpB,SAAS,MAAM,UACX;KAAE,OAAO,SAAS,MAAM;KAAS,SAAS,SAAS,MAAM;IAAQ,IACjE,CAAC;GACP,CAAC,CACH;GACA,gBAAgB;GAChB,OAAO,OAAO,OAAO;IACnB;IACA,SAAS,eAAe,MAAM,SAAS,QAAQ,KAAK,CAAC;IACrD;IACA;GACF,CAAC;EACH,UAAU;GAGR,MAAM,UAAU,MAAM,aAAa;GACnC,MAAM,KAAK,QAAQ;EACrB;CACF,CAAC;AACH;AAEA,SAAS,UACP,WACA,OACA,OACA,WACA,SACkB;CAClB,OAAO,OAAO,OAAO;EACnB,IAAI,GAAG,MAAM,WAAW,MAAM,GAAG;EACjC;EACA;EACA,QAAQ;EACR;EACA;EACA,GAAI,UAAU,EAAE,SAAS,OAAO,OAAO,EAAE,GAAG,QAAQ,CAAC,EAAE,IAAI,CAAC;CAC9D,CAAC;AACH"}
1
+ {"version":3,"file":"durable.js","names":[],"sources":["../src/durable/pursuit-version-evidence.ts","../src/durable/pursuit-version-review.ts","../src/durable/pursuit-version-run.ts","../src/durable/pursuit-versions.ts","../src/durable/reconcile-unconfirmed-teardowns.ts","../src/durable/run-fork.ts","../src/durable/run-tool-spans.ts","../src/durable/pursuit-observer-delivery.ts","../src/durable/run-reopen.ts","../src/durable/supervise-pursuit.ts"],"sourcesContent":["// Sealed pursuit-version results, identity checks and settled outcome evidence.\n\nimport { access, readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport type {\n SearchArtifactRef,\n SearchAttemptAccounting,\n SearchNode,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { isFiniteNumber } from '../finite-number'\nimport type { Spend, SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport { isNoEntError } from './jsonl-file'\nimport type { JudgedPursuitVersion, VersionVerdict } from './pursuit-versions'\nimport { parseSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\n\n/** The chain's directory beside the first version's: the ledger and its content blobs. */\nexport function pursuitVersionsLedgerPath(runDir: string): string {\n return resolve(`${resolve(runDir.trim())}.search`, 'ledger.jsonl')\n}\n\n/** A search node's artifact: a version's profile, or a change that did not apply. */\nexport interface VersionNode {\n readonly profile: AgentProfile | null\n /** The change from the parent; set on a node a proposal returned in this process. */\n readonly change?: AgentProfileDiff\n readonly parentDigest?: Sha256Digest\n readonly refusal: string | null\n}\n\n/** One node of the chain, as the ledger records it. */\nexport interface VersionRecord {\n readonly nodeId: string\n readonly version: number\n readonly runId: string\n readonly runDir: string\n /** Null for a change that did not apply. */\n readonly profile: AgentProfile | null\n readonly parentNodeId: string | null\n /** The change from the parent, from the node's first edge. */\n readonly change?: AgentProfileDiff\n /** The settled attempt's seal and verdict. */\n readonly seal?: SearchArtifactRef\n readonly verdict?: VersionVerdict\n}\n\n/** The bytes of a version's sealed `result.json` and the record they hold, parsed from the same\n * bytes that are hashed. */\nexport async function readSealed(\n runDir: string,\n version: number,\n): Promise<{ bytes: Uint8Array; result: SupervisedResult<unknown> }> {\n const path = resolve(runDir, SETTLE_RECORD_FILE)\n let bytes: Uint8Array\n try {\n bytes = await readFile(path)\n } catch (error) {\n if (!isNoEntError(error)) throw error\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${version} has no settle record in ${runDir}`,\n )\n }\n return { bytes, result: parseSettleRecord(Buffer.from(bytes).toString('utf8'), path) }\n}\n\n/** A profile as the JSON the ledger stores: validated, with undefined entries absent. */\nexport function jsonProfile(profile: unknown): AgentProfile {\n canonicalAgentProfileDigest(profile as AgentProfile)\n return JSON.parse(JSON.stringify(agentProfileSchema.parse(profile))) as AgentProfile\n}\n\nexport function loadNode(\n store: { readBlob(ref: SearchArtifactRef): unknown },\n node: SearchNode,\n): VersionNode {\n const stored = store.readBlob(node.artifact) as {\n kind?: unknown\n profile?: unknown\n change?: AgentProfileDiff | null\n parentDigest?: Sha256Digest | null\n refusal?: string | null\n }\n if (stored.kind === 'agent-profile') {\n const parsed = agentProfileSchema.safeParse(stored.profile)\n if (!parsed.success) {\n throw new RuntimeRunStateError(`version node ${node.nodeId} holds an invalid AgentProfile`)\n }\n return { profile: parsed.data as AgentProfile, refusal: null }\n }\n if (stored.kind === 'unapplied-change') {\n return {\n profile: null,\n ...(stored.change ? { change: stored.change } : {}),\n ...(stored.parentDigest ? { parentDigest: stored.parentDigest } : {}),\n refusal: stored.refusal ?? 'the change did not apply',\n }\n }\n throw new RuntimeRunStateError(`version node ${node.nodeId} holds no version artifact`)\n}\n\n/** The `<runDir>.v<n>` directory and `<runId>.v<n>` id of version `n`, beside the first. */\nexport function versionRun(runDir: string, runId: string, version: number) {\n return version === 1\n ? { runDir, runId }\n : { runDir: `${runDir}.v${version}`, runId: `${runId}.v${version}` }\n}\n\n/** A version's settled spend as the ledger's accounting. Unknown dollars carry the part a\n * provider is known to have billed as their floor. */\nexport function versionAccounting(spent: Spend | undefined): SearchAttemptAccounting {\n const tokensKnown =\n spent !== undefined &&\n spent.tokensKnown !== false &&\n spent.tokens?.tokensKnown !== false &&\n Number.isSafeInteger(spent.tokens?.input) &&\n Number.isSafeInteger(spent.tokens?.output) &&\n Number.isSafeInteger(spent.tokens?.cacheRead)\n const usdKnown = spent !== undefined && spent.usdKnown !== false && isFiniteNumber(spent.usd)\n return {\n tokens: tokensKnown\n ? {\n status: 'known',\n inputTokens: spent.tokens.input,\n outputTokens: spent.tokens.output,\n cachedTokens: spent.tokens.cacheRead!,\n }\n : {\n status: 'unknown',\n reason: `the version's settled spend reports no complete token count with its cache split (input ${spent?.tokens?.input ?? 'none'}, output ${spent?.tokens?.output ?? 'none'})`,\n },\n cost: usdKnown\n ? { status: 'known', usd: spent.usd, source: 'provider' }\n : {\n status: 'unknown',\n knownLowerBoundUsd: Math.max(\n 0,\n isFiniteNumber(spent?.usd) ? spent.usd - (spent.usdEstimated ?? 0) : 0,\n ),\n reason: \"the version's settled spend names unpriced or unreported work\",\n },\n }\n}\n\n/** How long a version that settled before its chain opened ran, from its settle record. */\nexport function settledElapsed(settled: SupervisedResult<unknown> | undefined): number {\n const elapsed = settled?.spentTotal?.ms\n return isFiniteNumber(elapsed) ? elapsed : 0\n}\n\nexport const FREE: SearchAttemptAccounting = {\n tokens: { status: 'known', inputTokens: 0, outputTokens: 0, cachedTokens: 0 },\n cost: { status: 'known', usd: 0, source: 'free' },\n}\n\n/**\n * What a version that did no work failed with: a driver error, by its name and its message with\n * the parts that differ between runs (digits, hex runs, absolute paths) normalized, or an unscored\n * verdict. Null for a version that ran, won or not.\n */\nexport function versionFailure(version: JudgedPursuitVersion): string | null {\n if (version.verdict.score === null) return 'unscored by the judge'\n const { result } = version\n if (result.kind !== 'no-winner' || result.reason !== 'driver-failed') return null\n const message = result.error.message\n .replace(/(?:\\/[\\w.@~+-]+){2,}/gu, '<path>')\n .replace(/\\b[0-9a-f]{8,}\\b/giu, '<hex>')\n .replace(/\\d+/gu, '<n>')\n .slice(0, 500)\n return `driver-failed: ${result.error.name}: ${message}`\n}\n\nexport function pursuitValueDigest(value: unknown, name: string): Sha256Digest {\n try {\n return canonicalCandidateDigest(value)\n } catch (error) {\n throw new ValidationError(\n `supervisePursuit versions: the ${name} must be canonical JSON to pin the chain: ${errorMessage(error)}`,\n )\n }\n}\n\nexport async function exists(path: string): Promise<boolean> {\n try {\n await access(path)\n return true\n } catch (error) {\n if (isNoEntError(error)) return false\n throw error\n }\n}\n\nexport function isSha256(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[0-9a-f]{64}$/u.test(value)\n}\n","// Profile review instructions and their mounted verdict page.\n\nimport type { AgentProfileDiff } from '@tangle-network/agent-interface'\nimport type { CheckVerdict } from '../runtime/supervise/completion-gate'\nimport { failedItems } from '../runtime/supervise/continuation'\nimport type { NextPursuitVersion } from './pursuit-versions'\n\n/** Where `'review-of-best'` mounts a review: `inputs/review/version-<n>.md`. One review lives in\n * a profile at a time. */\nconst REVIEW_DIR = 'inputs/review/'\n\n/**\n * `'review-of-best'`: fork from the kept version with its check's verdict mounted under\n * {@link REVIEW_DIR} and the profile's review words as one instruction. The previous review's\n * mount and instruction are removed, so a profile carries one review.\n */\nexport function reviewOfBest(runId: string, words: string): NextPursuitVersion {\n return ({ best, versions }) => {\n const n = versions.length + 1\n const verdict = best.verdict.check\n const path = `${REVIEW_DIR}version-${best.version}.md`\n const instruction = words\n .replaceAll('{version}', String(best.version))\n .replaceAll('{path}', path)\n .replaceAll('{score}', best.verdict.score === null ? 'none' : String(best.verdict.score))\n .trim()\n const page = reviewPage(best.version, best.verdict.score, verdict)\n // Instructions are set and removed by value: an earlier review instruction equal to this one\n // stays as it is, and every other earlier one is removed.\n const earlier = best.change?.set?.prompt?.instructions ?? []\n const earlierInstructions = earlier.filter((text) => text !== instruction)\n const earlierMounts = (best.profile.resources?.files ?? [])\n .map((file) => file.path)\n .filter((mounted) => mounted.startsWith(REVIEW_DIR) && mounted !== path)\n return {\n kind: 'agent-profile-diff',\n id: `${runId}-v${n}-review-of-v${best.version}`,\n title: `Version ${n}: review of version ${best.version}`,\n source: {\n kind: 'optimizer',\n notes: [`review-of-best: version ${best.version}`, `judge ${best.verdict.judgeDigest}`],\n },\n set: {\n ...(earlier.includes(instruction) ? {} : { prompt: { instructions: [instruction] } }),\n resources: {\n files: [{ path, resource: { kind: 'inline', name: path, content: page } }],\n },\n },\n ...(earlierInstructions.length > 0 || earlierMounts.length > 0\n ? {\n remove: {\n ...(earlierInstructions.length > 0\n ? { prompt: { instructions: [...earlierInstructions] } }\n : {}),\n ...(earlierMounts.length > 0 ? { resources: { files: earlierMounts } } : {}),\n },\n }\n : {}),\n } as AgentProfileDiff\n }\n}\n\n/** The review page: facts only, in the check's own lines. */\nfunction reviewPage(\n version: number,\n score: number | null,\n verdict: CheckVerdict | undefined,\n): string {\n if (verdict === undefined) {\n return [\n `# Version ${version}`,\n '',\n `Score: ${score ?? 'none'}. The judge reported no per-item verdict.`,\n '',\n ].join('\\n')\n }\n const failing = failedItems(verdict)\n return [\n `# Version ${version}`,\n '',\n `Score: ${score ?? 'none'}.${verdict.threshold === undefined ? '' : ` The check passes at ${verdict.threshold}.`}`,\n '',\n '## Items',\n '',\n ...Object.entries(verdict.items ?? {}).map(\n ([item, value]) => `- ${item}: ${value >= 1 ? 'passes' : `fails (${value})`}`,\n ),\n '',\n ...(failing.length === 0 ? [] : ['## Failures', '', ...(verdict.failures ?? []), '']),\n ...(verdict.review === undefined ? [] : [\"## The check's review\", '', verdict.review, '']),\n ].join('\\n')\n}\n","/**\n * One pursuit version chain at run time: running a version in its directory, reading it back\n * and checking it is this node's run, judging it, turning it into the kernel's cell result, and\n * reading the chain back from its search ledger.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport {\n parseSearchLedgerLine,\n type SearchCellResult,\n type SearchCellSettledEvent,\n type SearchCellWork,\n type SearchExecutionIdentity,\n type SearchRecorder,\n type SearchTaskOutcome,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n canonicalAgentProfileDigest,\n type Sha256Digest,\n sha256Bytes,\n} from '@tangle-network/agent-interface'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { isFiniteNumber } from '../finite-number'\nimport { authoredProfileDigest } from '../runtime/supervise/materialization'\nimport { superviseRootProfile } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { SpawnEvent, SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport { contentAddress } from './content-address'\nimport {\n loadNode,\n readSealed,\n type VersionNode,\n type VersionRecord,\n versionAccounting,\n versionRun,\n} from './pursuit-version-evidence'\nimport type {\n JudgedPursuitVersion,\n SettledPursuitVersion,\n VersionJudge,\n VersionVerdict,\n} from './pursuit-versions'\nimport type { PursuitFork } from './run-fork'\nimport { readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\nimport type { SupervisedPursuitResult, SupervisePursuitOptions } from './supervise-pursuit'\n\nexport type RunOne = (\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions,\n) => Promise<SupervisedPursuitResult<SupervisedResult<unknown>>>\n\n/** What one chain's versions share. */\nexport interface VersionChainContext {\n readonly profile: SupervisorProfile\n readonly task: unknown\n /** The call's options without the fields each version sets for itself. */\n readonly base: Omit<SupervisePursuitOptions, 'versions' | 'fork' | 'signal'>\n readonly firstFork: PursuitFork | undefined\n readonly runOne: RunOne\n readonly judge: VersionJudge\n readonly recorder: SearchRecorder\n /** Aborts a running version when the chain reaches its deadline. */\n readonly expired: AbortSignal\n readonly pursuitId: string\n readonly runDir: string\n readonly runId: string\n readonly ledgerPath: string\n readonly searchId: string\n readonly taskRevision: string\n}\n\n/** The execution identity a version's node and cell record. */\nexport function versionExecutionIdentity(\n pursuitId: string,\n taskRevision: string,\n nodeProfile: AgentProfile,\n): SearchExecutionIdentity {\n return {\n model: {\n provider: 'agent-runtime',\n alias: 'supervisePursuit',\n unknown: \"a version runs every model its tree chose; the version's settle record names them\",\n },\n agent: {\n uri: `agent-profile:${pursuitId}`,\n revision: canonicalAgentProfileDigest(nodeProfile),\n },\n benchmark: { uri: `pursuit:${pursuitId}`, revision: taskRevision },\n }\n}\n\n/** A version as the judge and `next` read it. */\nfunction versionOf(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n settleDigest: Sha256Digest,\n result: SupervisedResult<unknown>,\n): SettledPursuitVersion {\n return Object.freeze({\n version: record.version,\n nodeId: record.nodeId,\n runId: record.runId,\n runDir: record.runDir,\n settleDigest,\n result,\n profile: record.profile!,\n ...(parent?.seal === undefined\n ? {}\n : {\n parent: {\n version: parent.version,\n runId: parent.runId,\n settleDigest: parent.seal.sha256 as Sha256Digest,\n },\n }),\n ...(record.change === undefined ? {} : { change: record.change }),\n })\n}\n\nfunction outcomeOf(settled: SettledPursuitVersion, verdict: VersionVerdict): SearchTaskOutcome {\n if (verdict.score === null) {\n return {\n status: 'errored',\n metrics: {},\n error: {\n code: 'unscored',\n message: `the judge could not score version ${settled.version}`,\n retryable: false,\n },\n }\n }\n if (settled.result.kind === 'winner') {\n return { status: 'passed', score: verdict.score, metrics: {} }\n }\n return {\n status: 'failed',\n score: verdict.score,\n metrics: {},\n failure: {\n code: settled.result.reason,\n message: `version ${settled.version} settled without a winner: ${settled.result.reason}`,\n },\n }\n}\n\nexport class VersionChainRun {\n // Each sealed result.json is read and hashed once per call.\n private readonly sealed = new Map<Sha256Digest, SupervisedResult<unknown>>()\n\n constructor(private readonly ctx: VersionChainContext) {}\n\n /** Run a version if its directory holds no settle record, read it back, and judge it. */\n async runCell(work: SearchCellWork<VersionNode>): Promise<SearchCellResult> {\n const chain = await this.versionsOf()\n const record = chain.get(work.nodeId)\n if (record?.profile == null) {\n throw new RuntimeRunStateError(`version node ${work.nodeId} has no profile to run`)\n }\n const parent = record.parentNodeId === null ? undefined : chain.get(record.parentNodeId)\n if (parent !== undefined && (parent.seal === undefined || parent.profile === null)) {\n throw new RuntimeRunStateError(`version ${record.version}'s parent has no sealed result`)\n }\n // A version whose run throws fails the call and leaves its cell open: Runtime's driver\n // retry already ran, and calling again resumes the version in its own directory.\n if ((await readSettleRecord(record.runDir)) === undefined) {\n const signal = AbortSignal.any([work.signal, this.ctx.expired])\n if (signal.aborted) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version} was not started: ${errorMessage(signal.reason)}`,\n )\n }\n await this.runVersion(record, parent, signal)\n }\n const { settled, byteLength } = await this.readVersion(record, parent)\n const verdict = await this.judgeVersion(settled, work.signal)\n return this.cellResult(settled, byteLength, verdict, work.lane)\n }\n\n /** Run one version: the first as the call's own run, a later one as a fork of its parent. */\n private async runVersion(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n signal: AbortSignal,\n ): Promise<void> {\n const { profile, task, base, firstFork, runOne } = this.ctx\n if (parent === undefined || record.change === undefined) {\n await runOne(profile, task, {\n ...base,\n runId: record.runId,\n runDir: record.runDir,\n ...(firstFork === undefined ? {} : { fork: firstFork }),\n signal,\n })\n return\n }\n // A version starts a new tree and never replays its parent's children, so a parent that\n // settled with a child still in doubt (a deadline or a driver failure leaves them) is forked,\n // and the version's root records those nodes.\n const fork: PursuitFork = {\n runDir: parent.runDir,\n settleDigest: parent.seal!.sha256 as Sha256Digest,\n change: record.change,\n acceptUncertain: true,\n }\n // The version's continuation note states the bar against the version it forks from.\n const check = parent.verdict?.check\n await runOne(parent.profile!, task, {\n ...base,\n ...(base.continuation !== undefined && check !== undefined\n ? {\n continuation: {\n ...base.continuation,\n best: { label: `v${parent.version}`, verdict: check },\n },\n }\n : {}),\n runId: record.runId,\n runDir: record.runDir,\n fork,\n signal,\n })\n }\n\n /**\n * Read a settled version back and check it is this node's run: its root ran the node's profile\n * and, for a fork, recorded the parent's seal and the change. A directory that holds another\n * run is refused, never adopted.\n */\n private async readVersion(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n ): Promise<{ settled: SettledPursuitVersion; byteLength: number }> {\n const { base, firstFork, taskRevision } = this.ctx\n const { bytes, result } = await readSealed(record.runDir, record.version)\n if (result.tree.root !== record.runId) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: ${record.runDir} holds run '${result.tree.root}', not version ${record.version}'s '${record.runId}'`,\n )\n }\n const events = await new FileSpawnJournal(\n resolve(record.runDir, 'spawn-journal.jsonl'),\n ).loadTree(record.runId)\n const root = events?.find(\n (event): event is Extract<SpawnEvent, { kind: 'spawned' }> =>\n event.kind === 'spawned' && event.parent === undefined,\n )\n const ran = root?.identity?.profileDigest\n const expected = authoredProfileDigest(\n superviseRootProfile(record.profile!, base.profileGuidance),\n )\n const ranTask = root?.identity?.taskDigest\n const correlation = root?.identity?.correlation\n const fork =\n parent !== undefined\n ? { settleDigest: parent.seal?.sha256, changeId: record.change?.id }\n : firstFork === undefined\n ? undefined\n : { settleDigest: firstFork.settleDigest, changeId: firstFork.change.id }\n const mismatch = [\n ran !== expected ? `its root ran profile ${ran}, not ${expected}` : undefined,\n ranTask !== taskRevision ? `its root ran task ${ranTask}, not ${taskRevision}` : undefined,\n contentAddress(root?.budget) !== contentAddress(base.budget)\n ? 'its root ran under another budget'\n : undefined,\n fork !== undefined && correlation?.forkParentSettleDigest !== fork.settleDigest\n ? `its root forked from seal ${correlation?.forkParentSettleDigest}, not ${fork.settleDigest}`\n : undefined,\n fork !== undefined && correlation?.forkProfileDiffId !== fork.changeId\n ? `its root applied change ${correlation?.forkProfileDiffId}, not ${fork.changeId}`\n : undefined,\n ].filter((item): item is string => item !== undefined)\n if (mismatch.length > 0) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version} at ${record.runDir} is not this chain's run: ${mismatch.join('; ')}`,\n )\n }\n const settled = versionOf(record, parent, sha256Bytes(bytes), result)\n this.sealed.set(settled.settleDigest, result)\n return { settled, byteLength: bytes.byteLength }\n }\n\n private async judgeVersion(\n settled: SettledPursuitVersion,\n signal: AbortSignal,\n ): Promise<VersionVerdict> {\n const { judge } = this.ctx\n const verdict = await judge.judge(settled, signal)\n if (typeof verdict !== 'object' || verdict === null) {\n throw new ValidationError('supervisePursuit versions: the judge returned no verdict')\n }\n if (verdict.judgeDigest !== judge.digest) {\n throw new ValidationError(\n `supervisePursuit versions: the verdict for version ${settled.version} carries ${String(verdict.judgeDigest)}, not the pinned judge ${judge.digest}`,\n )\n }\n if (verdict.score !== null && !isFiniteNumber(verdict.score)) {\n throw new ValidationError(\n 'supervisePursuit versions: a verdict score must be a finite number or null',\n )\n }\n // The ledger keeps the verdict as JSON; a value JSON cannot hold is refused here.\n return JSON.parse(JSON.stringify(verdict)) as VersionVerdict\n }\n\n private cellResult(\n settled: SettledPursuitVersion,\n byteLength: number,\n verdict: VersionVerdict,\n lane: string,\n ): SearchCellResult {\n const spent = settled.result.spentTotal\n const settlePath = resolve(settled.runDir, SETTLE_RECORD_FILE)\n return {\n outcome: outcomeOf(settled, verdict),\n accounting: versionAccounting(spent),\n identity: versionExecutionIdentity(\n this.ctx.pursuitId,\n this.ctx.taskRevision,\n settled.profile,\n ),\n boxMinutes:\n isFiniteNumber(spent.boxMinutes) && spent.boxMinutesKnown !== false\n ? spent.boxMinutes\n : null,\n wallMs: isFiniteNumber(spent.ms) ? Math.max(0, Math.round(spent.ms)) : null,\n placement: { lane, boxId: null },\n traceRef: {\n unknown: `version ${settled.version} is run ${settled.runId}; the chain records no trace id`,\n },\n artifacts: [\n {\n role: 'settle-record',\n uri: pathToFileURL(settlePath).href,\n sha256: settled.settleDigest,\n byteLength,\n },\n this.ctx.recorder.blob('verdict', {\n kind: 'version-verdict',\n version: settled.version,\n runId: settled.runId,\n verdict,\n }),\n ],\n }\n }\n\n /** Every version whose latest settled cell carries a verdict, first first, each read back from\n * its sealed `result.json`. */\n async judgedVersions(chain: ReadonlyMap<string, VersionRecord>): Promise<JudgedPursuitVersion[]> {\n const judged: JudgedPursuitVersion[] = []\n for (const record of chain.values()) {\n if (record.seal === undefined || record.verdict === undefined) continue\n const seal = record.seal.sha256 as Sha256Digest\n let result = this.sealed.get(seal)\n if (result === undefined) {\n const read = await readSealed(record.runDir, record.version)\n if (sha256Bytes(read.bytes) !== seal) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version}'s result.json changed after it was judged`,\n )\n }\n result = read.result\n this.sealed.set(seal, result)\n }\n const parent = record.parentNodeId === null ? undefined : chain.get(record.parentNodeId)\n judged.push(\n Object.freeze({ ...versionOf(record, parent, seal, result), verdict: record.verdict }),\n )\n }\n return judged\n }\n\n /**\n * Every node of the chain, in registration order, from the ledger. The state holds cells, not\n * their events' artifacts, so each cell's seal and verdict are read from the ledger lines the\n * state verified, through Eval's own line parser.\n */\n async versionsOf(): Promise<Map<string, VersionRecord>> {\n const { recorder, ledgerPath, searchId, runDir, runId } = this.ctx\n // Take what the state holds before any await: an append retires the view.\n const state = await recorder.state()\n const head = state.head?.sequence ?? -1\n const nodes = state.nodes().map((node) => ({\n node,\n cellId: state.cells({ nodeId: node.nodeId })[0]?.cellId,\n diff: node.edgeIds[0] === undefined ? undefined : state.edge(node.edgeIds[0])?.diffs[0],\n }))\n const settledCells = new Map<string, SearchCellSettledEvent>()\n const text = await readFile(ledgerPath, 'utf8')\n for (const [index, line] of text.split('\\n').entries()) {\n if (line.length === 0) continue\n const entry = parseSearchLedgerLine(line, searchId, { path: ledgerPath, line: index + 1 })\n if (entry.sequence > head) break\n if (entry.event.kind === 'cell-settled') settledCells.set(entry.event.cellId, entry.event)\n }\n const chain = new Map<string, VersionRecord>()\n for (const { node, cellId, diff } of nodes) {\n const settled = cellId === undefined ? undefined : settledCells.get(cellId)\n const artifact = (role: string) =>\n settled?.artifacts.find((candidate) => candidate.role === role)\n const seal = artifact('settle-record')\n const verdict = artifact('verdict')\n chain.set(node.nodeId, {\n nodeId: node.nodeId,\n version: node.ordinal + 1,\n ...versionRun(runDir, runId, node.ordinal + 1),\n profile: loadNode(recorder, node).profile,\n parentNodeId: node.primaryParentId,\n ...(diff === undefined || 'unknown' in diff\n ? {}\n : { change: (recorder.readBlob(diff) as { diffs: AgentProfileDiff[] }).diffs[0]! }),\n ...(seal === undefined ? {} : { seal }),\n ...(verdict === undefined\n ? {}\n : { verdict: (recorder.readBlob(verdict) as { verdict: VersionVerdict }).verdict }),\n })\n }\n return chain\n }\n}\n","/**\n * The pursuit version chain, on Eval's search kernel (`runSearch`).\n *\n * A version is a search node: the exact AgentProfile it executes, content-addressed by\n * `canonicalAgentProfileDigest`. Every later version is an edge from the version the chain keeps,\n * whose diff is the one change `next` returned, and one cell: a `supervisePursuit` run of the\n * version, forked from its parent's sealed `result.json`, then scored by the outside judge. The\n * policy is the kernel's hill climb, `incumbent({ patience, minImprovement })`. The search ledger\n * at `<runDir>.search/ledger.jsonl` is the chain's only record and its only checkpoint: a call on\n * a closed chain reads it back, and a call on an open chain continues it.\n */\n\nimport { resolve } from 'node:path'\nimport {\n developmentClaim,\n incumbent,\n openSearchLedger,\n runSearch,\n type SearchArtifactCodec,\n type SearchAudit,\n type SearchCloseReason,\n type SearchExecutor,\n type SearchHistoryReceipt,\n type SearchProposerPort,\n SearchRecorder,\n type SearchSourceRef,\n uniform,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { applyExactAgentProfileDiff } from '../candidate-execution/profile'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { isFiniteNumber } from '../finite-number'\nimport type { CheckVerdict } from '../runtime/supervise/completion-gate'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport { FileObserverJournal } from './observer-journal'\nimport { projectPursuit } from './observer-projection'\nimport {\n exists,\n FREE,\n isSha256,\n jsonProfile,\n loadNode,\n pursuitValueDigest,\n pursuitVersionsLedgerPath,\n settledElapsed,\n type VersionNode,\n versionFailure,\n} from './pursuit-version-evidence'\nimport { reviewOfBest } from './pursuit-version-review'\nimport { type RunOne, VersionChainRun, versionExecutionIdentity } from './pursuit-version-run'\nimport { readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport type { SupervisedPursuitResult, SupervisePursuitOptions } from './supervise-pursuit'\n\n/**\n * Continue a pursuit across versions: after each version settles, an outside judge scores it, and\n * the next version forks from the version the chain keeps with one change, until the stop rule\n * ends the chain.\n */\nexport interface PursuitVersions {\n /** Scores each settled version from outside its tree: the run's declared check\n * (`declaredCheckJudge`), or any judge with a digest. */\n readonly judge: VersionJudge\n /** The change the next version applies to the kept version's profile. `'review-of-best'`\n * mounts the kept version's verdict under `inputs/review/`, replaces any earlier review, and\n * gives the next version's continuation note the kept version's per-item verdict as its bar. */\n readonly next: NextPursuitVersion | 'review-of-best'\n /** When the chain stops. Every cap is required: a chain without one is refused. */\n readonly stop: PursuitVersionStop\n}\n\n/** The chain's stop rule. The chain starts no version its caps do not admit. */\nexport interface PursuitVersionStop {\n /** Stop after this many proposed versions in a row that did not take the lead. */\n readonly patience: number\n /** At most this many versions, the first included. A change the chain refuses counts as one. */\n readonly maxVersions: number\n /**\n * The chain's dollars: a version starts only while settled spend plus a hold for it stays\n * within this. A version's unknown spend counts as its proven floor. The hold is the version's\n * own `budget.maxUsd`, which bounds it in flight; without one it is 0 until 20 versions\n * settled, then 1.5 times the p99 of their spend.\n */\n readonly maxUsd: number\n /** The chain's wall clock, from its first version's start. A running version is aborted at it. */\n readonly deadlineMs: number\n /** A version takes the lead when its score beats the kept version's by more than this.\n * Default 0. */\n readonly minImprovement?: number\n /**\n * Stop after this many versions in a row failed identically: each run ended `driver-failed`\n * with the same error, or the judge could not score it. Such a failure repeats whatever the\n * next change is (a refused workspace file, a broken credential), so neither patience nor a\n * version cap should be what stops it. Default 3.\n */\n readonly identicalFailures?: number\n}\n\n/** An outside judge. Runtime calls it after a version's settle record exists, never inside the\n * version's tree, and gives it no handle into that tree. Place it where you like, such as its own\n * sandbox through `runIsolatedCheck({ box })`. */\nexport interface VersionJudge {\n /** The sha256 of the judge's code and configuration. Every verdict must carry it, and a chain\n * whose ledger was opened under another digest is refused. */\n readonly digest: Sha256Digest\n judge(version: SettledPursuitVersion, signal: AbortSignal): Promise<VersionVerdict>\n}\n\nexport interface VersionVerdict {\n /** Higher is better. `null` when the judge could not score the version: the cell is recorded\n * unscored, and an unscored version never takes the lead. */\n readonly score: number | null\n /** Must equal `VersionJudge.digest`. */\n readonly judgeDigest: Sha256Digest\n /** What the judge measured, retained verbatim in the ledger. JSON values only. */\n readonly detail?: unknown\n /** The check's per-item verdict, when the judge is a check: what `'review-of-best'` mounts and\n * what the next version's bar compares against. */\n readonly check?: CheckVerdict\n}\n\n/** A settled version, as the judge and `next` read it. */\nexport interface SettledPursuitVersion {\n /** 1 for the first version: the node's registration ordinal plus 1. */\n readonly version: number\n /** The version's node in the chain's search ledger. */\n readonly nodeId: string\n readonly runId: string\n readonly runDir: string\n /** The sha256 of the version's `result.json` bytes: its seal. */\n readonly settleDigest: Sha256Digest\n readonly result: SupervisedResult<unknown>\n /** The profile the version executed: the first version's, or its parent's plus its change. */\n readonly profile: AgentProfile\n /** The version it forked from. Absent for the first version. */\n readonly parent?: {\n readonly version: number\n readonly runId: string\n readonly settleDigest: Sha256Digest\n }\n readonly change?: AgentProfileDiff\n}\n\nexport interface JudgedPursuitVersion extends SettledPursuitVersion {\n readonly verdict: VersionVerdict\n}\n\nexport interface NextPursuitVersionInput {\n /** The version the next one forks from: the version the chain keeps. */\n readonly best: JudgedPursuitVersion\n /** The most recently judged version. */\n readonly last: JudgedPursuitVersion\n /** Every judged version, first first. */\n readonly versions: readonly JudgedPursuitVersion[]\n}\n\n/** Build the one change the next version applies to `best.profile`. Its `id` must be non-empty. */\nexport type NextPursuitVersion = (\n input: NextPursuitVersionInput,\n signal: AbortSignal,\n) => AgentProfileDiff | Promise<AgentProfileDiff>\n\n/** The chain as its search ledger records it, returned beside the kept version's result. */\nexport interface PursuitVersionChain {\n /** `<runDir>.search/ledger.jsonl`: the chain's only record and checkpoint. */\n readonly ledgerPath: string\n readonly searchId: string\n /** Why the chain stopped: the kernel's close reason (`patience`, `max-nodes`, `budget`,\n * `deadline` or `converged`). */\n readonly reason: SearchCloseReason\n /** Present when the chain stopped because its last `versions` versions failed identically\n * (`stop.identicalFailures`); `reason` is then `converged`. */\n readonly identicalFailures?: { readonly versions: number; readonly failure: string }\n /** The kept version's number: the kernel's leader when the chain closed. */\n readonly best: number\n /** Every judged version, first first. */\n readonly versions: readonly JudgedPursuitVersion[]\n /** Known dollars, proven floors of unknown ones, and the counts of each. */\n readonly spend: SearchAudit['spend']\n /** A bounded receipt over the exact ledger bytes. */\n readonly receipt: SearchHistoryReceipt\n}\n\n/**\n * Validate a `versions` option before any compute. The same check runs inside `supervisePursuit`;\n * a caller that records the option as data can run it at preflight.\n */\nexport function assertPursuitVersions(versions: unknown): asserts versions is PursuitVersions {\n const fail = (message: string): never => {\n throw new ValidationError(`supervisePursuit versions: ${message}`)\n }\n if (typeof versions !== 'object' || versions === null) fail('must be an object')\n const option = versions as Record<string, unknown>\n const extra = Object.keys(option).filter((key) => !['judge', 'next', 'stop'].includes(key))\n if (extra.length > 0) fail(`unknown fields: ${extra.join(', ')}`)\n const { judge, next, stop } = option\n if (\n typeof judge !== 'object' ||\n judge === null ||\n typeof (judge as VersionJudge).judge !== 'function'\n ) {\n fail('judge must be a VersionJudge, such as declaredCheckJudge(check)')\n } else if (!isSha256((judge as VersionJudge).digest)) {\n fail('judge.digest must be a sha256 digest (sha256:<64 hex>)')\n }\n if (next !== 'review-of-best' && typeof next !== 'function') {\n fail(\"next must be a function or 'review-of-best'\")\n }\n if (typeof stop !== 'object' || stop === null) fail('stop must be an object')\n const rule = stop as Record<string, unknown>\n const known = new Set([\n 'patience',\n 'maxVersions',\n 'maxUsd',\n 'deadlineMs',\n 'minImprovement',\n 'identicalFailures',\n ])\n const unknown = Object.keys(rule).filter((key) => !known.has(key))\n if (unknown.length > 0) fail(`stop has unknown fields: ${unknown.join(', ')}`)\n for (const key of ['patience', 'maxVersions'] as const) {\n if (!Number.isInteger(rule[key]) || (rule[key] as number) < 1) {\n fail(`stop.${key} must be an integer of at least 1`)\n }\n }\n if (\n rule.identicalFailures !== undefined &&\n (!Number.isInteger(rule.identicalFailures) || (rule.identicalFailures as number) < 1)\n ) {\n fail('stop.identicalFailures must be an integer of at least 1')\n }\n for (const key of ['maxUsd', 'deadlineMs'] as const) {\n if (!isFiniteNumber(rule[key]) || (rule[key] as number) <= 0) {\n fail(`stop.${key} must be a finite number above 0`)\n }\n }\n if (\n rule.minImprovement !== undefined &&\n (!isFiniteNumber(rule.minImprovement) || rule.minImprovement < 0)\n ) {\n fail('stop.minImprovement must be a finite number of at least 0')\n }\n}\n\n/** Every rule the chain adds to the kernel's. Its digest, with the stop rule, is the process\n * revision the ledger records, so a changed rule or stop rule is a different search. */\nconst VERSION_CHAIN_DEFINITION = {\n name: 'agent-runtime.pursuit-versions.2026-09',\n 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',\n edge: 'one change from the kept version, stored as its Interface profile diff',\n 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',\n outcome:\n 'a scored winner passes; a scored no-winner fails with its reason; an unscored version is a final error; a run that throws fails the call and leaves its cell open',\n deadline: 'the chain deadline aborts a running version; its judge still runs',\n failures:\n 'before proposing, the chain closes converged when its last stop.identicalFailures judged versions failed identically: driver-failed with the same error name and message, digits, hex runs and absolute paths normalized, or unscored by the judge',\n directories: 'version n runs at <runDir>.v<n> with run id <runId>.v<n>; version 1 at <runDir>',\n} as const\n\nconst VERSION_CHAIN_URI = 'npm:@tangle-network/agent-runtime#supervisePursuit.versions'\n/** The pursuit task's one train task. */\nconst TASK_ID = 'pursuit'\nconst LANE = 'in-process'\n/** The longest delay Node's setTimeout honors. */\nconst MAX_TIMER_MS = 2_147_483_647\n/** 9999-12-31T23:59:59.999Z: the latest instant the ledger's four-digit-year timestamps hold, so\n * a deadline such as `Number.MAX_SAFE_INTEGER` means no deadline rather than an invalid date. */\nconst LATEST_DEADLINE_MS = 253_402_300_799_999\n\ntype ChainBase = Omit<SupervisePursuitOptions, 'versions' | 'fork' | 'signal'>\n\n/** Refuse a chain call that no version could satisfy, before any compute. */\nfunction assertChainCall(versions: PursuitVersions, base: ChainBase): void {\n assertPursuitVersions(versions)\n for (const key of ['journal', 'blobs', 'rootHandle', 'steerDir'] as const) {\n if (base[key] !== undefined) {\n throw new ValidationError(\n `supervisePursuit versions: ${key} names one run, and a version chain has one per version; omit it`,\n )\n }\n }\n if (versions.next === 'review-of-best' && base.continuation?.profile.review === undefined) {\n throw new ValidationError(\n \"supervisePursuit versions: next 'review-of-best' needs continuation.profile.review, the words the next version reads about its review\",\n )\n }\n const { stop } = versions\n if (base.budget.maxUsd !== undefined && base.budget.maxUsd > stop.maxUsd) {\n throw new ValidationError(\n `supervisePursuit versions: budget.maxUsd ${base.budget.maxUsd} is above stop.maxUsd ${stop.maxUsd}, so no version could start`,\n )\n }\n}\n\n/** Run a version chain. `supervisePursuit` calls this when `versions` is set. */\nexport async function runPursuitVersions(\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions & { readonly versions: PursuitVersions },\n runOne: RunOne,\n): Promise<SupervisedPursuitResult<SupervisedResult<unknown>> & { versions: PursuitVersionChain }> {\n const { versions, fork: firstFork, signal: callerSignal, ...base } = opts\n assertChainCall(versions, base)\n const { judge, stop } = versions\n const next: NextPursuitVersion =\n versions.next === 'review-of-best'\n ? reviewOfBest(base.runId ?? 'supervise', base.continuation?.profile.review ?? '')\n : versions.next\n const now = base.now ?? Date.now\n const pursuitId = base.pursuitId.trim()\n const runDir = resolve(base.runDir.trim())\n const runId = base.runId ?? 'supervise'\n const ledgerPath = pursuitVersionsLedgerPath(runDir)\n const searchId = `versions:${pursuitId}:${runId}`\n const retired = resolve(`${runDir}.versions`, 'versions.jsonl')\n if (await exists(retired)) {\n throw new ValidationError(\n `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`,\n )\n }\n\n // The first version's executed profile; later versions derive theirs from their parent's.\n const firstProfile = jsonProfile(\n firstFork === undefined\n ? profile\n : applyExactAgentProfileDiff(profile, firstFork.change, 'supervisePursuit versions'),\n )\n const taskRevision = pursuitValueDigest(task, 'task')\n const ledger = openSearchLedger({ path: ledgerPath, searchId })\n const deadline = await chainDeadline((await ledger.state()).header, now, runDir, stop)\n const policy = incumbent({\n patience: stop.patience,\n ...(stop.minImprovement === undefined ? {} : { minImprovement: stop.minImprovement }),\n })\n const allocation = uniform()\n const recorder = await openVersionRecorder({\n ledger,\n now,\n pursuitId,\n taskRevision,\n judge,\n stop,\n policy,\n allocation,\n deadline,\n firstProfile,\n })\n\n const clock = armChainDeadline(deadline, now)\n const chain = new VersionChainRun({\n profile,\n task,\n base,\n firstFork,\n runOne,\n judge,\n recorder,\n expired: clock.signal,\n pursuitId,\n runDir,\n runId,\n ledgerPath,\n searchId,\n taskRevision,\n })\n const failureLimit = stop.identicalFailures ?? DEFAULT_IDENTICAL_FAILURES\n try {\n const closed = await runSearch({\n recorder,\n root: { profile: firstProfile, refusal: null },\n codec: versionCodec,\n policy,\n allocation,\n proposer: versionProposer(versions.next, next, chain, failureLimit),\n executor: versionExecutor(chain, base.budget.maxUsd),\n admit: (node) => node.refusal,\n ...(callerSignal === undefined ? {} : { signal: callerSignal }),\n now,\n })\n const judged = await chain.judgedVersions(await chain.versionsOf())\n // A converged chain whose last versions share a failure stopped by the identical-failure rule.\n const failed =\n closed.reason === 'converged' ? identicalFailureStreak(judged, failureLimit) : null\n const stopped = failed === null ? null : { versions: failureLimit, failure: failed }\n const best = judged.find((version) => version.nodeId === closed.leader)\n if (best === undefined) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: the chain in ${ledgerPath} closed (${closed.reason}) without a judged version to keep`,\n )\n }\n const observerPath = resolve(best.runDir, 'observer.jsonl')\n return Object.freeze({\n result: best.result,\n pursuit: projectPursuit(await new FileObserverJournal(observerPath, pursuitId).read()),\n observerPath,\n settlePath: resolve(best.runDir, SETTLE_RECORD_FILE),\n versions: Object.freeze({\n ledgerPath,\n searchId,\n reason: closed.reason,\n ...(stopped === null ? {} : { identicalFailures: stopped }),\n best: best.version,\n versions: Object.freeze(judged),\n spend: closed.state.audit.spend,\n receipt: recorder.receipt({ producerId: 'pursuit-versions', runId }),\n }),\n })\n } finally {\n clock.cancel()\n }\n}\n\ninterface VersionRecorderInput {\n ledger: ReturnType<typeof openSearchLedger>\n now: () => number\n pursuitId: string\n taskRevision: string\n judge: VersionJudge\n stop: PursuitVersionStop\n policy: { name: string }\n allocation: { name: string }\n deadline: string\n firstProfile: AgentProfile\n}\n\n/** Open the chain's search recorder: its subject, process revision, splits, policy and budget. */\nfunction openVersionRecorder(input: VersionRecorderInput): Promise<SearchRecorder> {\n const { ledger, now, pursuitId, taskRevision, judge, stop, policy, allocation, deadline } = input\n return SearchRecorder.open(\n { ledger, now },\n {\n subject: pursuitId,\n process: {\n name: 'pursuit-versions',\n executionRef: {\n uri: VERSION_CHAIN_URI,\n revision: canonicalCandidateDigest({\n ...VERSION_CHAIN_DEFINITION,\n stop: canonicalStop(stop),\n }),\n },\n },\n artifactKind: 'agent-profile',\n objective: {\n metric: 'version-judge-score',\n direction: 'maximize',\n judge: { uri: 'agent-runtime:version-judge', revision: judge.digest },\n claim: developmentClaim(pursuitId),\n },\n splits: {\n train: [\n {\n taskId: TASK_ID,\n unitId: TASK_ID,\n source: { uri: `pursuit:${pursuitId}`, revision: taskRevision },\n },\n ],\n selection: [],\n test: [],\n heldOutUnits: true,\n },\n policy: { expansion: policy.name, allocation: allocation.name, seed: 0 },\n budget: {\n maxUsd: stop.maxUsd,\n maxCells: null,\n maxNodes: stop.maxVersions,\n deadline,\n maxConcurrency: 1,\n reservedClaimUsd: 0,\n },\n containment: null,\n derivedFrom: null,\n identity: versionExecutionIdentity(pursuitId, taskRevision, input.firstProfile),\n },\n )\n}\n\n/**\n * The chain's clock starts with its first version, or when the chain opened on a first version\n * that had already settled. A resumed chain keeps the deadline its ledger recorded.\n */\nasync function chainDeadline(\n opened: { budget: { deadline: string | null } } | null | undefined,\n now: () => number,\n runDir: string,\n stop: PursuitVersionStop,\n): Promise<string> {\n return (\n opened?.budget.deadline ??\n new Date(\n Math.min(\n now() - settledElapsed(await readSettleRecord(runDir)) + stop.deadlineMs,\n LATEST_DEADLINE_MS,\n ),\n ).toISOString()\n )\n}\n\n/**\n * The chain's deadline aborts a running version. A timer longer than 2^31 - 1 ms fires at once\n * in Node, so a long chain re-arms in steps.\n */\nfunction armChainDeadline(\n deadline: string,\n now: () => number,\n): { signal: AbortSignal; cancel(): void } {\n const deadlineAt = Date.parse(deadline)\n const expired = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const arm = () => {\n const remaining = deadlineAt - now()\n if (remaining <= 0) {\n expired.abort(new Error('the version chain reached its deadline'))\n return\n }\n timer = setTimeout(arm, Math.min(remaining, MAX_TIMER_MS))\n timer.unref?.()\n }\n arm()\n return {\n signal: expired.signal,\n cancel() {\n if (timer !== undefined) clearTimeout(timer)\n },\n }\n}\n\nconst versionCodec: SearchArtifactCodec<VersionNode> = {\n node(store, node) {\n if (node.profile !== null) {\n const artifact = store.blob('agent-profile', {\n kind: 'agent-profile',\n profile: node.profile,\n })\n return {\n artifactDigest: canonicalAgentProfileDigest(node.profile),\n artifact,\n surfaces: [{ surfaceId: 'profile', kind: 'agent-profile', artifact }],\n }\n }\n const refused = {\n kind: 'unapplied-change',\n parentDigest: node.parentDigest ?? null,\n change: node.change ?? null,\n }\n const artifact = store.blob('change', { ...refused, refusal: node.refusal })\n return {\n artifactDigest: canonicalCandidateDigest(refused),\n artifact,\n surfaces: [{ surfaceId: 'profile', kind: 'agent-profile', artifact }],\n }\n },\n diff(store, parent, child) {\n if (parent.profile === null || child.profile === null || child.change === undefined) {\n return { unknown: 'a refused change has no profile to diff' }\n }\n const from = canonicalAgentProfileDigest(parent.profile)\n if (child.parentDigest !== from) {\n return { unknown: 'the change was written against another parent' }\n }\n return store.blob('diff', {\n kind: 'agent-profile-diff',\n from,\n to: canonicalAgentProfileDigest(child.profile),\n diffs: [child.change],\n })\n },\n load(store, node) {\n return loadNode(store, node)\n },\n}\n\nfunction versionExecutor(\n chain: VersionChainRun,\n maxUsd: number | undefined,\n): SearchExecutor<VersionNode> {\n return {\n // A version's budget.maxUsd bounds it in flight, so it is the hard hold. Without one the\n // hold is the kernel's estimate: 0 until 20 versions settled, then 1.5 times their p99.\n lanes: () => [\n maxUsd === undefined\n ? { name: LANE, capacity: 1, costCap: 'estimate', cellUsd: 0 }\n : { name: LANE, capacity: 1, costCap: 'hard', cellUsd: maxUsd },\n ],\n place: () => LANE,\n // A version that settled is read back from its directory by `run`, so nothing is adopted.\n adopt: async () => null,\n run: (work) => chain.runCell(work),\n }\n}\n\n/** The proposer: the caller's `next` (or the review of the kept version) as the one edge. */\nfunction versionProposer(\n nextOption: PursuitVersions['next'],\n next: NextPursuitVersion,\n chain: VersionChainRun,\n failureLimit: number,\n): SearchProposerPort<VersionNode> {\n const reviewing = nextOption === 'review-of-best'\n const proposerSource: SearchSourceRef = {\n uri: reviewing ? `${VERSION_CHAIN_URI}.review-of-best` : `${VERSION_CHAIN_URI}.next`,\n revision: canonicalCandidateDigest({\n next: reviewing ? 'review-of-best' : Function.prototype.toString.call(nextOption),\n }),\n }\n return {\n name: reviewing ? 'review-of-best' : 'next',\n kind: 'optimizer',\n source: proposerSource,\n execution: { kind: 'deterministic', source: proposerSource },\n childrenPerProposal: 1,\n async propose(request) {\n const parent = request.parents[0]!\n const judged = await chain.judgedVersions(await chain.versionsOf())\n const failure = identicalFailureStreak(judged, failureLimit)\n if (failure !== null) {\n return {\n children: [],\n stop: `the last ${failureLimit} versions failed identically: ${failure}`,\n accounting: FREE,\n }\n }\n const best = judged.find((version) => version.nodeId === parent.nodeId)\n if (best === undefined || parent.artifact.profile === null) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: the kept version ${parent.nodeId} has no judged run to fork from`,\n )\n }\n const returned = await next(\n { best, last: judged.at(-1)!, versions: Object.freeze(judged) },\n request.signal,\n )\n if (typeof returned?.id !== 'string' || returned.id.trim().length === 0) {\n throw new ValidationError('supervisePursuit versions: next must return a change with an id')\n }\n // The ledger stores the change as JSON, so it is taken as JSON: an undefined entry is absent.\n const change = JSON.parse(JSON.stringify(returned)) as AgentProfileDiff\n const child = childNode(parent.artifact.profile, change)\n return {\n children: [\n {\n artifact: child,\n label: change.title ?? returned.id,\n rationale: (change.source?.notes ?? []).join('\\n'),\n },\n ],\n accounting: reviewing\n ? FREE\n : {\n tokens: { status: 'unknown', reason: \"the caller's next reports no usage\" },\n cost: {\n status: 'unknown',\n knownLowerBoundUsd: 0,\n reason: \"the caller's next reports no spend\",\n },\n },\n }\n },\n }\n}\n\n/** The node a change makes, or the refused node when it does not apply to the parent. */\nfunction childNode(parentProfile: AgentProfile, change: AgentProfileDiff): VersionNode {\n const parentDigest = canonicalAgentProfileDigest(parentProfile)\n try {\n return {\n profile: applyExactAgentProfileDiff(parentProfile, change, 'supervisePursuit versions'),\n change,\n parentDigest,\n refusal: null,\n }\n } catch (error) {\n return { profile: null, change, parentDigest, refusal: errorMessage(error) }\n }\n}\n\nfunction canonicalStop(stop: PursuitVersionStop): PursuitVersionStop {\n return {\n patience: stop.patience,\n maxVersions: stop.maxVersions,\n maxUsd: stop.maxUsd,\n deadlineMs: stop.deadlineMs,\n ...(stop.minImprovement === undefined ? {} : { minImprovement: stop.minImprovement }),\n identicalFailures: stop.identicalFailures ?? DEFAULT_IDENTICAL_FAILURES,\n }\n}\n\nconst DEFAULT_IDENTICAL_FAILURES = 3\n\n/** The failure the last `count` judged versions share, or null when they do not all share one. */\nexport function identicalFailureStreak(\n versions: readonly JudgedPursuitVersion[],\n count: number,\n): string | null {\n if (versions.length < count) return null\n const failures = versions.slice(-count).map(versionFailure)\n const [first] = failures\n return first !== null && first !== undefined && failures.every((failure) => failure === first)\n ? first\n : null\n}\n","import { resolve } from 'node:path'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport {\n acquireRunDirectoryLock,\n RUN_DIRECTORY_LOCK_FILE,\n RunDirectoryLockedError,\n runDirectoryHolderIsLive,\n} from './run-lock'\nimport { readSettleRecord } from './settle-record'\n\n/**\n * Read each unconfirmed environment of a settled run by the provider's own id, delete only\n * the ones the provider still holds, and report which were already gone, which this call\n * deleted, and which could not be decided. A kept environment is never read or deleted.\n * The port reads and deletes one id at a time; a fleet listing cannot hide a named worker.\n */\n\n/** One environment named by the provider that issued it. */\nexport interface EnvironmentTarget {\n readonly provider: string\n readonly environmentId: string\n}\n\n/** What a direct read of one environment proved. `unknown` means the read did not decide. */\nexport type EnvironmentPresence =\n | { readonly state: 'absent' }\n | { readonly state: 'present' }\n | { readonly state: 'unknown'; readonly detail: string }\n\n/** What a delete of one environment the read found present proved. */\nexport type EnvironmentDeletion =\n | { readonly state: 'deleted' }\n | { readonly state: 'absent' }\n | { readonly state: 'unknown'; readonly detail: string }\n\n/**\n * The caller's provider adapter. `read` and `delete` take the provider's own id.\n * A delete that finds the environment already gone reports `absent`.\n */\nexport interface UnconfirmedEnvironmentPort {\n read(target: EnvironmentTarget): Promise<EnvironmentPresence>\n delete(target: EnvironmentTarget): Promise<EnvironmentDeletion>\n}\n\n/** An environment this call proved gone. `nodeId` is the teardown record that named it. */\nexport interface ReconciledEnvironment extends EnvironmentTarget {\n readonly nodeId?: string\n}\n\n/** An environment, or a node with no id, this call could not decide. */\nexport interface UnreconciledEnvironment {\n readonly nodeId?: string\n readonly provider?: string\n readonly environmentId?: string\n readonly detail: string\n}\n\n/** The three sets one reconcile call returns. A repeated id is acted on once and reported\n * on every node that names it. */\nexport interface UnconfirmedTeardownReconcile {\n readonly confirmed: readonly ReconciledEnvironment[]\n readonly deleted: readonly ReconciledEnvironment[]\n readonly unknown: readonly UnreconciledEnvironment[]\n}\n\n/** The directory has no settle record, so there is no settled run to reconcile. */\nexport class NoSettleRecordError extends Error {\n readonly runDir: string\n\n constructor(runDir: string) {\n super(`reconcileUnconfirmedTeardowns: ${runDir} has no settle record`)\n this.name = 'NoSettleRecordError'\n this.runDir = runDir\n }\n}\n\nconst DETAIL_LIMIT = 240\n\ntype Decision =\n | { readonly kind: 'confirmed' }\n | { readonly kind: 'deleted' }\n | { readonly kind: 'unknown'; readonly detail: string }\n\n/** Finish unconfirmed teardowns named by a settled run's `result.json`. */\nexport async function reconcileUnconfirmedTeardowns(\n runDir: string,\n port: UnconfirmedEnvironmentPort,\n): Promise<UnconfirmedTeardownReconcile> {\n const directory = resolve(runDir)\n const holder = await runDirectoryHolderIsLive(directory)\n if (holder.live) {\n if (holder.holder === undefined) {\n throw new Error(\n `reconcileUnconfirmedTeardowns: ${directory} is held by a lock this host cannot read`,\n )\n }\n throw new RunDirectoryLockedError(resolve(directory, RUN_DIRECTORY_LOCK_FILE), holder.holder)\n }\n const settled = await readSettleRecord(directory)\n if (settled === undefined) throw new NoSettleRecordError(directory)\n const lock = await acquireRunDirectoryLock(directory, settled.tree.root)\n try {\n const current = await readSettleRecord(directory)\n if (current === undefined) throw new NoSettleRecordError(directory)\n return await sweep(current, port)\n } finally {\n await lock.release()\n }\n}\n\nasync function sweep(\n settled: SupervisedResult<unknown>,\n port: UnconfirmedEnvironmentPort,\n): Promise<UnconfirmedTeardownReconcile> {\n const listed = settled.teardownUnconfirmed\n if (listed === undefined) return { confirmed: [], deleted: [], unknown: [] }\n if (!Array.isArray(listed)) {\n throw new Error(\n 'reconcileUnconfirmedTeardowns: settle record teardownUnconfirmed is not an array',\n )\n }\n const confirmed: ReconciledEnvironment[] = []\n const deleted: ReconciledEnvironment[] = []\n const unknown: UnreconciledEnvironment[] = []\n const decided = new Map<string, Promise<Decision>>()\n for (const entry of listed) await oneNode(entry, port, decided, confirmed, deleted, unknown)\n return { confirmed, deleted, unknown }\n}\n\nasync function oneNode(\n entry: unknown,\n port: UnconfirmedEnvironmentPort,\n decided: Map<string, Promise<Decision>>,\n confirmed: ReconciledEnvironment[],\n deleted: ReconciledEnvironment[],\n unknown: UnreconciledEnvironment[],\n): Promise<void> {\n if (typeof entry !== 'object' || entry === null) {\n unknown.push({ detail: 'unreadable teardown record' })\n return\n }\n const record = entry as {\n id?: unknown\n environments?: unknown\n kept?: unknown\n }\n const nodeId = typeof record.id === 'string' && record.id.length > 0 ? record.id : undefined\n const environments = Array.isArray(record.environments) ? record.environments : []\n const keptIds = keptKeys(record.kept)\n const sweepable: EnvironmentTarget[] = []\n let unnamed = 0\n for (const item of environments) {\n const named = sweepableEnvironment(item)\n if (named === 'kept') continue\n if (named !== undefined && keptIds.has(`${named.provider}\\0${named.environmentId}`)) continue\n if (named === undefined) unnamed += 1\n else sweepable.push(named)\n }\n if (sweepable.length === 0 && unnamed === 0 && environments.length === 0 && keptIds.size === 0) {\n unknown.push({ ...(nodeId === undefined ? {} : { nodeId }), detail: 'no environment id' })\n return\n }\n for (let index = 0; index < unnamed; index += 1) {\n unknown.push({\n ...(nodeId === undefined ? {} : { nodeId }),\n detail: 'environment record has no provider id',\n })\n }\n for (const target of sweepable) {\n const outcome = await decisionFor(port, decided, target)\n const row = { ...(nodeId === undefined ? {} : { nodeId }), ...target }\n if (outcome.kind === 'confirmed') confirmed.push(row)\n else if (outcome.kind === 'deleted') deleted.push(row)\n else unknown.push({ ...row, detail: outcome.detail })\n }\n}\n\nfunction keptKeys(value: unknown): Set<string> {\n const keys = new Set<string>()\n if (!Array.isArray(value)) return keys\n for (const item of value) {\n if (typeof item !== 'object' || item === null) continue\n const record = item as { provider?: unknown; environmentId?: unknown }\n if (typeof record.provider !== 'string' || typeof record.environmentId !== 'string') continue\n keys.add(`${record.provider}\\0${record.environmentId}`)\n }\n return keys\n}\n\nfunction sweepableEnvironment(value: unknown): EnvironmentTarget | 'kept' | undefined {\n if (typeof value !== 'object' || value === null) return undefined\n const record = value as { provider?: unknown; environmentId?: unknown; keptFor?: unknown }\n if (record.keptFor !== undefined) return 'kept'\n if (typeof record.provider !== 'string' || record.provider.length === 0) return undefined\n if (typeof record.environmentId !== 'string' || record.environmentId.length === 0) {\n return undefined\n }\n return { provider: record.provider, environmentId: record.environmentId }\n}\n\nfunction decisionFor(\n port: UnconfirmedEnvironmentPort,\n decided: Map<string, Promise<Decision>>,\n target: EnvironmentTarget,\n): Promise<Decision> {\n const key = `${target.provider}\\0${target.environmentId}`\n const cached = decided.get(key)\n if (cached !== undefined) return cached\n const pending = decide(port, target)\n decided.set(key, pending)\n return pending\n}\n\nasync function decide(\n port: UnconfirmedEnvironmentPort,\n target: EnvironmentTarget,\n): Promise<Decision> {\n try {\n const read = await port.read(target)\n if (read?.state === 'absent') return { kind: 'confirmed' }\n if (read?.state !== 'present') {\n return {\n kind: 'unknown',\n detail: detailOf(read?.state === 'unknown' ? read.detail : undefined),\n }\n }\n const removed = await port.delete(target)\n if (removed?.state === 'deleted' || removed?.state === 'absent') return { kind: 'deleted' }\n return {\n kind: 'unknown',\n detail: detailOf(removed?.state === 'unknown' ? removed.detail : undefined),\n }\n } catch (error) {\n return { kind: 'unknown', detail: detailOf(error) }\n }\n}\n\nfunction detailOf(value: unknown): string {\n const text =\n value instanceof Error\n ? value.message\n : typeof value === 'string'\n ? value\n : 'unreadable provider answer'\n const oneLine = text.replace(/\\s+/g, ' ').trim()\n const bounded = oneLine.length > DETAIL_LIMIT ? `${oneLine.slice(0, DETAIL_LIMIT - 1)}…` : oneLine\n return bounded.length > 0 ? bounded : 'unreadable provider answer'\n}\n","import { readFile, realpath } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n canonicalCandidateDigest,\n type Sha256Digest,\n sha256Bytes,\n} from '@tangle-network/agent-interface'\nimport { applyExactAgentProfileDiff } from '../candidate-execution/profile'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { authoredProfileDigest } from '../runtime/supervise/materialization'\nimport { type SuperviseOptions, superviseRootProfile } from '../runtime/supervise/supervise'\nimport type { AgentExecutionRef, SpawnEvent } from '../runtime/supervise/types'\nimport { contentAddress } from './content-address'\nimport { isNoEntError } from './jsonl-file'\nimport { readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\nimport { loadSpawnForest } from './spawn-journal/spawn-forest'\n\n/**\n * Start a run as a version of a settled run: the parent's recorded root inputs plus one change.\n *\n * The call's `profile`, `task` and `budget` must be the parent's, byte for byte, as its sealed\n * journal records them. Runtime applies `change` to that profile and runs the result in a new\n * run directory. The parent directory is read and never written.\n */\nexport interface PursuitFork {\n /** The settled parent's run directory. */\n readonly runDir: string\n /** The sha256 of the parent's `result.json` bytes: the sealed point the fork starts from. */\n readonly settleDigest: Sha256Digest\n /** The one change, applied to the parent's root profile. Its `id` is recorded. */\n readonly change: AgentProfileDiff\n /**\n * Fork a parent whose journal holds a node without a terminal record, an unbegun owned tree, an\n * unconfirmed teardown, or work in flight. Such a node may still act, and a fork never replays\n * the parent's children, so it can only duplicate work outside the fork's tree. The root then\n * records those node ids as `forkParentUncertainNodes`. Omit it to refuse such a parent.\n */\n readonly acceptUncertain?: boolean\n}\n\n/**\n * The `execution.correlation` keys a fork records on its root. Runtime writes them; a caller that\n * supplies one is refused. `lineageRootRunId` is the first run of the chain of parents, so the\n * spend of every version of one lineage groups under one id.\n */\nexport const RUN_FORK_CORRELATION_KEYS = Object.freeze([\n 'forkParentRunId',\n 'forkParentSettleDigest',\n 'forkProfileDiffId',\n 'lineageRootRunId',\n] as const)\n\n/** The correlation key an accepted uncertain parent adds: its uncertain node ids, comma-joined. */\nconst FORK_PARENT_UNCERTAIN_NODES_KEY = 'forkParentUncertainNodes'\n\n/** What `supervisePursuit` executes for a fork: the changed profile and the attributed execution. */\ninterface PreparedRunFork {\n readonly profile: AgentProfile\n readonly execution: AgentExecutionRef\n}\n\ntype SpawnedEvent = Extract<SpawnEvent, { kind: 'spawned' }>\n\n/**\n * Verify the parent and derive the fork's profile and attribution. It reads only the parent, so\n * a refused fork spends nothing and writes nothing.\n */\nexport async function prepareRunFork(\n profile: AgentProfile,\n task: unknown,\n opts: SuperviseOptions & { readonly runId?: string; readonly runDir: string },\n fork: PursuitFork,\n): Promise<PreparedRunFork> {\n const change = fork.change\n if (typeof change?.id !== 'string' || change.id.trim().length === 0) {\n throw new ValidationError('supervisePursuit fork: change.id must be a non-empty string')\n }\n const parentDir = await realDirectory(fork.runDir, 'fork.runDir')\n const forkDir = await realDirectory(opts.runDir, 'runDir', true)\n // A fork at, inside or around the parent's directory would write into the parent.\n if (contains(parentDir, forkDir) || contains(forkDir, parentDir)) {\n throw new ValidationError(\n `supervisePursuit fork: runDir ${forkDir} overlaps the parent's runDir ${parentDir}; a fork needs its own directory outside the parent's`,\n )\n }\n\n // The seal: the exact bytes Runtime wrote once at the parent's settle.\n let bytes: Uint8Array\n try {\n bytes = await readFile(resolve(parentDir, SETTLE_RECORD_FILE))\n } catch (error) {\n if (!isNoEntError(error)) throw error\n throw new RuntimeRunStateError(\n `supervisePursuit fork: ${parentDir} holds no ${SETTLE_RECORD_FILE}; only a settled run is forked`,\n )\n }\n const observed = sha256Bytes(bytes)\n if (observed !== fork.settleDigest) {\n throw new RuntimeRunStateError(\n `supervisePursuit fork: ${SETTLE_RECORD_FILE} hashes to ${observed}, not the requested ${fork.settleDigest}`,\n )\n }\n const settled = await readSettleRecord(parentDir)\n if (settled === undefined) {\n throw new RuntimeRunStateError(`supervisePursuit fork: ${parentDir} lost its settle record`)\n }\n const parentRunId = settled.tree.root\n if ((opts.runId ?? 'supervise') === parentRunId) {\n throw new ValidationError(\n `supervisePursuit fork: runId '${parentRunId}' is the parent's; a fork needs its own runId`,\n )\n }\n\n // Certainty: a node the parent never settled may still act, so a fork could duplicate it.\n const forest = await loadSpawnForest(\n new FileSpawnJournal(resolve(parentDir, 'spawn-journal.jsonl')),\n parentRunId,\n )\n const uncertain = [\n ...forest.inDoubt.map((node) => `${node.nodeId} (no terminal record)`),\n ...forest.missingTrees.map((tree) => `${tree.ownerNodeId} (tree ${tree.root} never begun)`),\n ...(settled.teardownUnconfirmed ?? []).map((node) => `${node.id} (teardown unconfirmed)`),\n ]\n if (settled.tree.inFlight > 0 && uncertain.length === 0) {\n uncertain.push(`${settled.tree.inFlight} in flight`)\n }\n if (uncertain.length > 0 && fork.acceptUncertain !== true) {\n throw new RuntimeRunStateError(\n `supervisePursuit fork: run '${parentRunId}' has uncertain nodes: ${uncertain.join(', ')}; set fork.acceptUncertain to fork it anyway`,\n )\n }\n\n // Inputs: the fork differs from its parent by the change alone.\n const root = forest.trees[0]?.events.find(\n (event): event is SpawnedEvent => event.kind === 'spawned' && event.parent === undefined,\n )\n const recorded = root?.identity\n if (recorded?.profileDigest === undefined || recorded.taskDigest === undefined) {\n throw new RuntimeRunStateError(\n `supervisePursuit fork: run '${parentRunId}' records no root profile and task digest`,\n )\n }\n const mismatches = [\n authoredProfileDigest(superviseRootProfile(profile, opts.profileGuidance)) !==\n recorded.profileDigest\n ? `profile is not the parent's ${recorded.profileDigest}`\n : undefined,\n digestOrUndefined(task) !== recorded.taskDigest\n ? `task is not the parent's ${recorded.taskDigest}`\n : undefined,\n contentAddress(root?.budget) !== contentAddress(opts.budget)\n ? \"budget is not the parent's\"\n : undefined,\n ].filter((mismatch): mismatch is string => mismatch !== undefined)\n if (mismatches.length > 0) {\n throw new ValidationError(`supervisePursuit fork: ${mismatches.join('; ')}`)\n }\n\n const forked = applyExactAgentProfileDiff(profile, change, 'supervisePursuit fork')\n if (\n authoredProfileDigest(superviseRootProfile(forked, opts.profileGuidance)) ===\n recorded.profileDigest\n ) {\n throw new ValidationError(\n `supervisePursuit fork: change '${change.id}' leaves the parent's profile unchanged`,\n )\n }\n\n const supplied = opts.execution?.correlation ?? {}\n const owned = [...RUN_FORK_CORRELATION_KEYS, FORK_PARENT_UNCERTAIN_NODES_KEY].filter((key) =>\n Object.hasOwn(supplied, key),\n )\n if (owned.length > 0) {\n throw new ValidationError(\n `supervisePursuit fork: execution.correlation cannot set ${owned.join(', ')}; Runtime records them`,\n )\n }\n return Object.freeze({\n profile: forked,\n execution: Object.freeze({\n ...opts.execution,\n correlation: Object.freeze({\n ...supplied,\n forkParentRunId: parentRunId,\n forkParentSettleDigest: fork.settleDigest,\n forkProfileDiffId: change.id,\n lineageRootRunId: recorded.correlation?.lineageRootRunId ?? parentRunId,\n ...(uncertain.length === 0\n ? {}\n : { [FORK_PARENT_UNCERTAIN_NODES_KEY]: uncertain.join(', ') }),\n }),\n }),\n })\n}\n\nfunction digestOrUndefined(value: unknown): Sha256Digest | undefined {\n try {\n return canonicalCandidateDigest(value)\n } catch {\n return undefined\n }\n}\n\n/**\n * Resolve a directory through symlinks. The fork's own directory may not exist yet; it resolves\n * through its nearest existing ancestor, so a symlinked ancestor cannot hide an overlap.\n */\nasync function realDirectory(path: string, name: string, mayBeAbsent = false): Promise<string> {\n if (typeof path !== 'string' || path.trim().length === 0) {\n throw new ValidationError(`supervisePursuit fork: ${name} must be a non-empty string`)\n }\n const absolute = resolve(path.trim())\n try {\n return await realpath(absolute)\n } catch (error) {\n const ancestor = dirname(absolute)\n if (!mayBeAbsent || !isNoEntError(error) || ancestor === absolute) throw error\n return join(await realDirectory(ancestor, name, true), basename(absolute))\n }\n}\n\n/** Whether `inner` is `outer` or lies beneath it. */\nfunction contains(outer: string, inner: string): boolean {\n const path = relative(outer, inner)\n return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`))\n}\n","import { join } from 'node:path'\nimport type { ToolSpan } from '@tangle-network/agent-eval'\nimport { ValidationError } from '../errors'\nimport { readRootStream } from '../runtime/supervise/root-stream'\nimport { runToolSpans } from '../runtime/supervise/run-traces'\nimport { FileObserverJournal } from './observer-journal'\nimport { projectPursuit } from './observer-projection'\nimport { FileResultBlobStore } from './spawn-journal/result-blob-store'\nimport { discoverDurableSupervisionRun } from './supervision-discovery'\n\n/**\n * Every tool span a finished `supervise({ runDir })` run recorded, read from its directory alone:\n * the root's `root-stream.jsonl` as one trace named by the root node id, and each settled node's\n * persisted trace (the observer projection's `trace`) from `<runDir>/blobs`, re-keyed to the node\n * id. The same builder feeds the continuation panel's trace store.\n *\n * A node whose trace blob is missing throws `ValidationError`; a node with no captured trace adds\n * nothing.\n */\nexport async function durableRunToolSpans(runDir: string): Promise<readonly ToolSpan[]> {\n const run = await discoverDurableSupervisionRun(runDir)\n if (run.roots.length > 1) {\n throw new ValidationError(\n `${run.runDir} holds ${run.roots.length} supervision roots; a run directory has one`,\n )\n }\n const rootId = run.roots[0]\n const journal = run.observer && (await FileObserverJournal.open(run.observer.path))\n const nodes = journal === undefined ? [] : projectPursuit(await journal.read()).nodes\n const workers = nodes.flatMap((node) =>\n node.trace === undefined || node.id === rootId ? [] : [{ id: node.id, trace: node.trace }],\n )\n return Object.freeze(\n await runToolSpans({\n ...(rootId === undefined\n ? {}\n : { root: { id: rootId, read: () => readRootStream(run.runDir) } }),\n workers,\n blobs: new FileResultBlobStore(join(run.runDir, 'blobs')),\n }),\n )\n}\n","import type { PursuitProjection } from './observer-projection'\n\n/**\n * Where a pursuit's observer projection is delivered while it runs, so a run started anywhere is\n * findable in one place by its pursuit id.\n *\n * Intelligence persists the projection on its run spine (`runtime-observer:pursuit:<pursuitId>`)\n * and records the id of the API key that delivered it, which joins the run to that key's spend.\n * Delivery is an observation, never a dependency: a refused, slow or unreachable endpoint is\n * reported once and the run continues exactly as it would without it.\n */\nexport interface PursuitObserverDelivery {\n /** Intelligence base URL, e.g. `https://intelligence.tangle.tools`. */\n readonly baseUrl: string\n /** Platform API key presented as the Bearer; Intelligence resolves the tenant from it. */\n readonly apiKey: string\n /** The Intelligence subject (project) the pursuit belongs to. */\n readonly subjectKey: string\n readonly subjectName?: string\n /**\n * Flat facts the caller owns about the run, recorded on the pursuit row unchanged, such as the\n * program and idea a registration names. Runtime neither reads nor validates their meaning.\n */\n readonly attributes?: Readonly<Record<string, string>>\n /** How often a live run re-delivers its projection. Default 60 s; the last delivery is liveness. */\n readonly intervalMs?: number\n /** Per-request bound. Default 10 s. */\n readonly timeoutMs?: number\n readonly fetch?: typeof fetch\n}\n\n/** The execution state Runtime reports. It never claims the pursuit's semantic success. */\nexport type PursuitObserverState = 'running' | 'done' | 'failed'\n\nexport type PursuitObserverDeliveryOutcome =\n | { readonly succeeded: true; readonly status: number }\n | { readonly succeeded: false; readonly reason: string }\n\n/** The Intelligence route that persists a delivered projection on its run spine. */\nexport const PURSUIT_OBSERVER_DELIVERY_PATH = '/v1/ingest/pursuit-observer'\n\nconst DEFAULT_INTERVAL_MS = 60_000\nconst DEFAULT_TIMEOUT_MS = 10_000\n\n/** POST one projection. Never throws; the outcome says whether Intelligence accepted it. */\nasync function deliverPursuitObserver(\n delivery: PursuitObserverDelivery,\n state: PursuitObserverState,\n projection: PursuitProjection,\n): Promise<PursuitObserverDeliveryOutcome> {\n const send = delivery.fetch ?? globalThis.fetch\n const url = `${delivery.baseUrl.replace(/\\/+$/u, '')}${PURSUIT_OBSERVER_DELIVERY_PATH}`\n try {\n const response = await send(url, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${delivery.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n subjectKey: delivery.subjectKey,\n ...(delivery.subjectName === undefined ? {} : { subjectName: delivery.subjectName }),\n state,\n ...(delivery.attributes === undefined ? {} : { attributes: delivery.attributes }),\n projection,\n }),\n signal: AbortSignal.timeout(delivery.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n })\n if (response.ok) return { succeeded: true, status: response.status }\n const detail = (await response.text().catch(() => '')).slice(0, 300)\n return { succeeded: false, reason: `HTTP ${response.status}${detail ? `: ${detail}` : ''}` }\n } catch (error) {\n return { succeeded: false, reason: error instanceof Error ? error.message : String(error) }\n }\n}\n\nexport interface PursuitObserverDeliverer {\n /** Queue a delivery of the current projection. Deliveries never overlap; a burst collapses to one. */\n push(state: PursuitObserverState): void\n /** Stop liveness delivery and deliver the final snapshot. A parked run remains nonterminal. */\n close(state: PursuitObserverState): Promise<PursuitObserverDeliveryOutcome>\n}\n\n/**\n * Deliver a live run's projection at start, on an interval, and at settlement. `read` projects\n * the run's own journal at the moment of each delivery, so every delivery is the whole record.\n */\nexport function startPursuitObserverDelivery(\n delivery: PursuitObserverDelivery,\n read: () => Promise<PursuitProjection>,\n warn: (message: string) => void = (message) => console.warn(message),\n): PursuitObserverDeliverer {\n let chain: Promise<PursuitObserverDeliveryOutcome | undefined> = Promise.resolve(undefined)\n let pending: PursuitObserverState | undefined\n let warned = false\n let closed = false\n\n const deliver = async (state: PursuitObserverState) => {\n let projection: PursuitProjection\n try {\n projection = await read()\n } catch (error) {\n return report({\n succeeded: false,\n reason: `observer projection unreadable: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n return report(await deliverPursuitObserver(delivery, state, projection))\n }\n const report = (outcome: PursuitObserverDeliveryOutcome) => {\n if (!outcome.succeeded && !warned) {\n warned = true\n warn(\n `supervisePursuit: pursuit observer delivery to ${delivery.baseUrl} failed (${outcome.reason}); the run continues and later deliveries retry`,\n )\n }\n return outcome\n }\n const push = (state: PursuitObserverState) => {\n if (closed) return\n if (pending !== undefined) return\n pending = state\n chain = chain.then(() => {\n const next = pending as PursuitObserverState\n pending = undefined\n return deliver(next)\n })\n }\n\n const timer = setInterval(() => push('running'), delivery.intervalMs ?? DEFAULT_INTERVAL_MS)\n timer.unref?.()\n push('running')\n\n return {\n push,\n async close(state) {\n closed = true\n clearInterval(timer)\n const terminal = chain.then(() => deliver(state))\n chain = terminal\n const bound = delivery.timeoutMs ?? DEFAULT_TIMEOUT_MS\n let timeout: ReturnType<typeof setTimeout> | undefined\n const expired = new Promise<PursuitObserverDeliveryOutcome>((resolve) => {\n timeout = setTimeout(\n () => resolve({ succeeded: false, reason: `terminal delivery exceeded ${bound} ms` }),\n bound * 2,\n )\n timeout.unref?.()\n })\n try {\n return await Promise.race([terminal, expired])\n } finally {\n clearTimeout(timeout)\n }\n },\n }\n}\n","import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport {\n publishExclusiveDurableFile,\n syncDurableDirectory,\n} from '../runtime/supervise/durable-file'\nimport { runCancellationFile, runCancelRequestFile } from '../runtime/supervise/run-cancellation'\nimport { workerCancellationsDir } from '../runtime/supervise/run-layout'\nimport { assertValidBudget } from '../runtime/supervise/spend-validation'\nimport { assertResumeLimits } from '../runtime/supervise/supervisor-root-contract'\nimport type { Budget, SpawnEvent, SpawnJournal, SupervisorOpts } from '../runtime/supervise/types'\nimport type { FileObserverJournal } from './observer-journal'\nimport { fenceRunWrite } from './run-fence'\nimport { SETTLE_RECORD_FILE, settleRecordDigest } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\n\n/*\n * Reopening a settled run under its own run id.\n *\n * A wrong settle used to be final: `supervisePursuit` refuses a directory that holds `result.json`,\n * and `fork` and `versions` each start a new run id in a new directory. Magnetar used 21 run ids\n * from 2026-10-16 to 10-21 for one solve; 16 of those runs settled, 11 of them in under 5 hours.\n *\n * A reopen archives the settled segment and resumes the same journal. Before it writes anything it\n * checks the resume limits (`assertResumeLimits`): a reopen refused for its budget or reservation\n * policy leaves `result.json`, the cancel files and the journal as they were. The profile's identity\n * and materialization are checked by `supervise` itself, after these steps. Every step is\n * idempotent, so a later call with the same `operationId` finishes a reopen that crashed partway:\n * 1. copy `result.json` byte for byte to `settles/<n>.json`;\n * 2. append one `reopened` spawn-journal row naming the operator, the reason and the archive;\n * 3. append one observer event, so the pursuit projection shows one lineage;\n * 4. move the run's cancel request and acknowledgement aside under this reopen's and that\n * request's operation ids, so a new `cancelRun` is accepted (one run carries one run-scoped\n * cancel operation) and no later reopen overwrites an earlier segment's cancel;\n * 5. last, remove `result.json`.\n * The caller then runs `supervise` with `resume: true`: settled children replay by key, the pool\n * is restored from the journal, and the next settle writes `result.json` again.\n */\n\n/** `supervisePursuit`'s `reopen` option: reopen this settled run under its own run id. */\nexport interface RunReopen {\n /** Who reopens the run. Required and non-empty. */\n readonly operator: string\n /** Why. Required and non-empty. */\n readonly reason: string\n /** Idempotency key: calling again with it finishes a reopen that crashed partway. */\n readonly operationId: string\n /**\n * The budget the reopened run is held to, recorded on its `reopened` row, which a later resume\n * must then match. Omit and the call's `budget` must equal the recorded one: the root's, or the\n * last budget a reopen recorded. A run that settled `budget-exhausted` and reopens without a\n * larger budget pauses at once (with `driverRetry.pauseRootStops`) or settles\n * `budget-exhausted` again. A deadline is measured from the original root instant, so a run\n * whose recorded deadline has passed settles `deadline` at once unless this budget drops the\n * deadline or moves it.\n */\n readonly budget?: Budget\n}\n\n/** The directory that holds a run's archived settle records. */\nexport const SETTLE_ARCHIVE_DIR = 'settles'\n\n/** Refuse a reopen that names no operator or reason, or that is combined with a fork or versions. */\nexport function assertRunReopen(\n reopen: RunReopen,\n opts: { readonly fork?: unknown; readonly versions?: unknown },\n): void {\n if (reopen.operator.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.operator must be non-empty')\n }\n if (reopen.reason.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.reason must be non-empty')\n }\n if (reopen.operationId.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.operationId must be non-empty')\n }\n if (reopen.budget !== undefined) assertValidBudget(reopen.budget, 'reopen.budget')\n if (opts.fork !== undefined || opts.versions !== undefined) {\n throw new TypeError(\n 'supervisePursuit: reopen continues this run under its own id; fork and versions start new runs',\n )\n }\n}\n\n/**\n * Archive the settled segment of the run at `runDir` and clear it for a resume. Runs under the\n * directory lock. Throws when there is nothing to reopen, or when `operationId` already reopened a\n * segment that has since settled again.\n */\nexport async function reopenSettledRun(input: {\n readonly runDir: string\n readonly runId: string\n readonly reopen: RunReopen\n readonly journal: SpawnJournal | undefined\n /** The call's budget and reservation policy, checked against the recorded ones before any write. */\n readonly limits: Pick<SupervisorOpts, 'budget' | 'reservationPolicy'>\n readonly observer: FileObserverJournal\n readonly pursuitId: string\n readonly now: () => number\n}): Promise<void> {\n const { runDir, runId, reopen, observer, pursuitId, now } = input\n const operationId = reopen.operationId.trim()\n const settlePath = resolve(runDir, SETTLE_RECORD_FILE)\n const journal = input.journal ?? new FileSpawnJournal(resolve(runDir, 'spawn-journal.jsonl'))\n const events = (await journal.loadTree(runId)) ?? []\n const reopened = events.filter(\n (event): event is Extract<SpawnEvent, { kind: 'reopened' }> =>\n event.kind === 'reopened' && event.id === runId,\n )\n const mine = reopened.find((event) => event.operationId === operationId)\n const settled = await readBytes(settlePath)\n if (settled === undefined) {\n // Removing result.json is the last step, so a recorded reopen without it is complete.\n if (mine !== undefined) return\n throw new Error(\n `supervisePursuit: ${runDir} holds no ${SETTLE_RECORD_FILE}; nothing to reopen; resume it`,\n )\n }\n assertResumeLimits(\n events,\n {\n runId,\n budget: reopen.budget ?? input.limits.budget,\n ...(input.limits.reservationPolicy === undefined\n ? {}\n : { reservationPolicy: input.limits.reservationPolicy }),\n },\n mine === undefined ? reopen.budget : undefined,\n )\n const result = JSON.parse(settled) as { readonly kind?: unknown; readonly reason?: unknown }\n const digest = settleRecordDigest(result)\n if (mine !== undefined && mine.prior.digest !== digest) {\n throw new Error(\n `supervisePursuit: reopen '${operationId}' already reopened run '${runId}', which has settled again; reopen it under a new operationId`,\n )\n }\n const archivedAs = mine?.prior.archivedAs ?? (await archiveName(runDir, settled))\n const archivePath = resolve(runDir, archivedAs)\n if (\n !publishExclusiveDurableFile(archivePath, settled) &&\n (await readBytes(archivePath)) !== settled\n ) {\n throw new Error(\n `supervisePursuit: ${archivePath} already holds a different settle record; reopen refused`,\n )\n }\n const at = new Date(now()).toISOString()\n if (mine === undefined) {\n await journal.appendEvent(runId, {\n kind: 'reopened',\n id: runId,\n operator: reopen.operator,\n reason: reopen.reason,\n operationId,\n prior: {\n kind: String(result.kind),\n ...(typeof result.reason === 'string' ? { reason: result.reason } : {}),\n digest,\n archivedAs,\n },\n ...(reopen.budget === undefined ? {} : { budget: reopen.budget }),\n seq: reopened.length,\n at,\n })\n }\n const eventId = `${runId}:pursuit:reopened:${operationId}`\n if (!(await observer.read()).some((record) => record.event?.id === eventId)) {\n await observer.appendEvent({\n id: eventId,\n pursuitId,\n runId,\n target: 'agent.run',\n phase: 'event',\n timestamp: now(),\n payload: { reopened: { operator: reopen.operator, reason: reopen.reason, archivedAs } },\n })\n }\n fenceRunWrite(() => {\n setCancellationAside(runDir, operationId)\n unlinkSync(settlePath)\n syncDurableDirectory(runDir)\n })\n}\n\n/** The next free `settles/<n>.json`, or the archive that already holds these bytes (a reopen that\n * crashed after archiving and before its journal row). */\nasync function archiveName(runDir: string, settled: string): Promise<string> {\n const dir = resolve(runDir, SETTLE_ARCHIVE_DIR)\n fenceRunWrite(() => mkdirSync(dir, { recursive: true }))\n const numbers = readdirSync(dir)\n .map((name) => /^(\\d+)\\.json$/u.exec(name)?.[1])\n .filter((n): n is string => n !== undefined)\n .map(Number)\n .sort((a, b) => a - b)\n for (const n of numbers) {\n if ((await readBytes(join(dir, `${n}.json`))) === settled)\n return `${SETTLE_ARCHIVE_DIR}/${n}.json`\n }\n return `${SETTLE_ARCHIVE_DIR}/${(numbers.at(-1) ?? 0) + 1}.json`\n}\n\n/** Move the settled run's cancel request and acknowledgement aside under the reopen's and the\n * request's operation ids, so the reopened run accepts a new `cancelRun`. Idempotent: an absent\n * file is skipped. A reopen's operation id names one segment, so a later segment cancelled under\n * the same cancel operation id lands beside this one instead of over it. */\nfunction setCancellationAside(runDir: string, reopenOperationId: string): void {\n const requestFile = runCancelRequestFile(runDir)\n const ackFile = runCancellationFile(runDir)\n if (!existsSync(requestFile) && !existsSync(ackFile)) return\n const source = existsSync(requestFile) ? requestFile : ackFile\n const { operationId } = JSON.parse(readFileSync(source, 'utf8')) as {\n readonly operationId: string\n }\n const reopenedDir = join(workerCancellationsDir(runDir), 'reopened')\n const aside = join(\n reopenedDir,\n encodeURIComponent(reopenOperationId),\n encodeURIComponent(operationId),\n )\n mkdirSync(aside, { recursive: true })\n if (existsSync(ackFile)) renameSync(ackFile, join(aside, 'run.json'))\n if (existsSync(requestFile)) renameSync(requestFile, join(aside, 'run.request.json'))\n syncDurableDirectory(aside)\n syncDurableDirectory(join(reopenedDir, encodeURIComponent(reopenOperationId)))\n syncDurableDirectory(reopenedDir)\n syncDurableDirectory(workerCancellationsDir(runDir))\n}\n\nasync function readBytes(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n","import { resolve } from 'node:path'\nimport { runtimeFailureCause } from '../runtime/failure-cause'\nimport { FileCoordinationLog } from '../runtime/supervise/coordination-log'\nimport {\n type AgentGraph,\n type GraphResult,\n type RunGraphOptions,\n superviseAgentGraph,\n} from '../runtime/supervise/graph'\nimport { graphExecutionOptions } from '../runtime/supervise/graph-backend'\nimport { readRootStreamReceipt } from '../runtime/supervise/root-stream'\nimport { supervisorRunDir } from '../runtime/supervise/run-layout'\nimport { RunParkedError } from '../runtime/supervise/run-parking'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport { rootCoordinationOwner } from '../runtime/supervise/supervise-identity'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport {\n composeRuntimeHooks,\n type RuntimeHookEvent,\n type RuntimeHooks,\n withPursuitContext,\n} from '../runtime-hooks'\nimport { createFileObserverHooks } from './observer-journal'\nimport { type PursuitProjection, projectPursuit } from './observer-projection'\nimport {\n type PursuitObserverDeliverer,\n type PursuitObserverDelivery,\n startPursuitObserverDelivery,\n} from './pursuit-observer-delivery'\nimport {\n type PursuitVersionChain,\n type PursuitVersions,\n runPursuitVersions,\n} from './pursuit-versions'\nimport { type PursuitFork, prepareRunFork } from './run-fork'\nimport { acquireRunDirectoryLock } from './run-lock'\nimport { assertRunReopen, type RunReopen, reopenSettledRun } from './run-reopen'\nimport {\n FAILURE_RECORD_FILE,\n readSettleRecord,\n SETTLE_RECORD_FILE,\n SettledRunDirectoryError,\n writeFailureRecord,\n writeSettleRecord,\n} from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\n\nexport interface SupervisePursuitOptions extends SuperviseOptions {\n /** Stable objective identity spanning concrete Runtime runs. */\n readonly pursuitId: string\n /**\n * One concrete Runtime execution owns one durable directory and observer journal.\n * A pursuit spanning several runs reuses `pursuitId` across distinct `runDir`s;\n * Intelligence joins those isolated projections without a shared write head.\n */\n readonly runDir: string\n /** Always `'release'`: settlement seals the segment, so retained environments are released.\n * `'keep'` is refused. A reopen replays the journal rather than retaining environments. */\n readonly retainedAtSettlement?: 'release'\n /**\n * Run this pursuit as a version of a settled run: `profile`, `task` and `budget` must equal the\n * parent's recorded root, and Runtime executes the parent's profile with `fork.change` applied.\n * The root's `execution.correlation` records the parent, its sealed digest, the change and the\n * lineage (`RUN_FORK_CORRELATION_KEYS`). The fork's `runDir` must lie outside the parent's, and\n * the parent's outside it. The parent's directory is never written, and a refused fork, such as\n * one whose parent has an uncertain node, writes nothing.\n */\n readonly fork?: PursuitFork\n /**\n * Continue this pursuit across versions, on Eval's search kernel. The first version runs at\n * `runDir` as usual, or is read back when that directory already settled. After each version\n * settles, `versions.judge` scores it from outside its tree; unless `versions.stop` ends the\n * chain, the next version forks from the version the chain keeps with the change\n * `versions.next` returns, at `<runDir>.v<n>` with run id `<runId>.v<n>`. The search ledger at\n * `<runDir>.search/ledger.jsonl` records every version as a node, every change as an edge, and\n * every run and verdict as a cell; it is the chain's only record and checkpoint. A call on a\n * closed chain reads it back; a call on an open chain continues it without re-running or\n * re-judging a settled version. Aborting `signal` pauses the chain: the call rejects and a later\n * call continues it. The call returns the kept version's result with the chain.\n */\n readonly versions?: PursuitVersions\n /**\n * Deliver this run's observer projection to Intelligence at start, every `intervalMs` while it\n * runs, and at settlement or failure, so the run is findable by its pursuit id from wherever it\n * was started. Optional and fail-open: a delivery that fails is reported once and never changes\n * the run. Each version of a `versions` chain delivers its own run under the same pursuit.\n */\n readonly observerDelivery?: PursuitObserverDelivery\n /**\n * Reopen this settled run under its own run id instead of refusing it (`./run-reopen.ts`).\n * Under the directory lock, `result.json` is archived byte for byte to `settles/<n>.json`, one\n * `reopened` journal row names the operator and reason, the run's settled cancel operation is\n * moved aside, and the run resumes from its journal (`resume: true`): settled children replay by\n * key and spend from before the reopen is debited once. `reopen.budget`, when set, replaces the\n * call's `budget` and is recorded for later resumes. Refused with `fork` or `versions`, and on a\n * directory with no `result.json` (\"nothing to reopen; resume it\"); a reopen whose budget or\n * reservation policy the recorded run refuses (\"resume budget mismatch\") writes nothing.\n */\n readonly reopen?: RunReopen\n}\n\nexport interface SupervisedPursuitResult<Result> {\n readonly result: Result\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n /** `result.json` in the run directory: `result` as canonical JSON, written once at settle. */\n readonly settlePath: string\n /** The version chain, when the call set `versions`. */\n readonly versions?: PursuitVersionChain\n}\n\n/** A failed Runtime execution whose complete third-person projection was retained. */\nexport class SupervisePursuitError extends Error {\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n /** `failure.json` in the run directory: the record of this throw. */\n readonly failurePath: string\n\n constructor(\n cause: unknown,\n pursuit: PursuitProjection,\n observerPath: string,\n failurePath: string,\n ) {\n super(`supervisePursuit: ${errorMessage(cause)}`, { cause })\n this.name = 'SupervisePursuitError'\n this.pursuit = pursuit\n this.observerPath = observerPath\n this.failurePath = failurePath\n }\n}\n\n/**\n * Execute `supervise()` with a durable observer and return its verified pursuit projection.\n * Each `runDir` owns its lock and journals; Intelligence joins directories by `pursuitId`.\n * Agents never receive the observer path or projection.\n *\n * `result.json` seals a segment and refuses re-entry before compute; `failure.json` records\n * the latest throw and permits a corrected retry. Both pursuit entrypoints use the same\n * directory lifecycle below. A competing process is refused with the lock holder's identity;\n * an abandoned `supervise.lock.guard` requires confirmation of inactivity before removal.\n */\nexport async function supervisePursuit(\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions,\n): Promise<SupervisedPursuitResult<Awaited<ReturnType<typeof supervise>>>> {\n assertPursuitDirectory(opts, 'supervisePursuit')\n if (opts.reopen !== undefined) assertRunReopen(opts.reopen, opts)\n\n if (opts.versions !== undefined) {\n return runPursuitVersions(\n profile,\n task,\n opts as SupervisePursuitOptions & { readonly versions: PursuitVersions },\n supervisePursuit,\n ) as Promise<SupervisedPursuitResult<Awaited<ReturnType<typeof supervise>>>>\n }\n\n const {\n pursuitId: _pursuitId,\n hooks: _hooks,\n fork,\n versions: _versions,\n observerDelivery: _observerDelivery,\n reopen,\n ...superviseOptions\n } = opts\n\n // A fork is verified on every entry, a resume included, so the recorded root identity it\n // derives is the one the Supervisor's resume contract compares against. It reads only the\n // settled parent, and runs before the lock so a refused fork writes nothing, not even runDir.\n const forked =\n fork === undefined ? undefined : await prepareRunFork(profile, task, superviseOptions, fork)\n\n return runDurablePursuit(\n opts,\n ({ hooks, steerDir }) =>\n supervise(forked?.profile ?? profile, task, {\n ...superviseOptions,\n ...(forked === undefined ? {} : { execution: forked.execution }),\n ...(reopen === undefined\n ? {}\n : { resume: true, ...(reopen.budget === undefined ? {} : { budget: reopen.budget }) }),\n steerDir,\n // Settlement seals this segment; a later reopen replays its journal.\n retainedAtSettlement: 'release',\n hooks,\n }),\n (result) => result,\n opts.budget,\n )\n}\n\n/** Options for {@link superviseGraphPursuit}: every `runGraph` option, plus the pursuit identity,\n * the run directory this execution owns, and optional observer delivery. */\nexport interface SuperviseGraphPursuitOptions extends RunGraphOptions {\n /** Stable objective identity spanning concrete Runtime runs. */\n readonly pursuitId: string\n /** The directory this execution owns: journal, blobs, observer journal, lock and terminal\n * records. Re-running the same `runDir` and `runId` resumes an unsettled graph; a settled\n * graph requires an explicit `reopen`. */\n readonly runDir: string\n /** Always `'release'`: a reopened segment reuses its journal, not retired environments. */\n readonly retainedAtSettlement?: 'release'\n /** As for {@link supervisePursuit}. */\n readonly observerDelivery?: PursuitObserverDelivery\n /** Explicitly reopen a settled segment under this graph's existing run id and journal. */\n readonly reopen?: RunReopen\n}\n\n/**\n * Graph twin of `supervisePursuit`, using its directory lifecycle and `runGraph` execution.\n * The directory run id binds the supervised root; spawn-journal edge events own the ledger.\n * Explicit `reopen` archives the result and resumes this id; ordinary settled re-entry refuses.\n * Forks and version chains are offered by `supervisePursuit` only.\n */\nexport async function superviseGraphPursuit(\n graph: AgentGraph,\n opts: SuperviseGraphPursuitOptions,\n): Promise<SupervisedPursuitResult<GraphResult>> {\n assertPursuitDirectory(opts, 'superviseGraphPursuit')\n if (opts.reopen !== undefined) assertRunReopen(opts.reopen, {})\n const {\n pursuitId: _pursuitId,\n hooks: _hooks,\n observerDelivery: _observerDelivery,\n brain,\n reopen,\n ...graphOptions\n } = opts\n return runDurablePursuit(\n opts,\n ({ hooks, steerDir }) =>\n superviseAgentGraph(\n reopen?.budget === undefined ? graph : { ...graph, budget: reopen.budget },\n graphExecutionOptions({\n ...graphOptions,\n // The lock, the settle record and the journal name one run, so the graph takes the\n // directory's run id rather than its own digest-derived default.\n runId: graphOptions.runId ?? 'supervise',\n ...(reopen === undefined ? {} : { resume: true }),\n steerDir,\n retainedAtSettlement: 'release',\n hooks,\n }),\n brain,\n ),\n (result) => result.result,\n graph.budget,\n )\n}\n\n/** The pursuit identity and run directory both durable entries require. */\nfunction assertPursuitDirectory(\n opts: {\n readonly pursuitId: string\n readonly runDir: string\n readonly retainedAtSettlement?: string\n },\n entry: string,\n): void {\n for (const field of ['pursuitId', 'runDir'] as const) {\n if (opts[field].trim().length === 0) throw new TypeError(`${entry}: ${field} must be non-empty`)\n }\n if (opts.retainedAtSettlement === 'keep') {\n throw new TypeError(\n `${entry}: retainedAtSettlement 'keep' cannot hold, because a settled pursuit is never re-entered`,\n )\n }\n}\n\n/** Own the directory lock, terminal records and observer lifecycle for both pursuit entries. */\nasync function runDurablePursuit<Result>(\n opts: SupervisePursuitOptions | SuperviseGraphPursuitOptions,\n execute: (seams: { readonly hooks: RuntimeHooks; readonly steerDir: string }) => Promise<Result>,\n settled: (result: Result) => SupervisedResult<unknown>,\n budget: Budget,\n): Promise<SupervisedPursuitResult<Result>> {\n const pursuitId = opts.pursuitId.trim()\n const runDir = opts.runDir.trim()\n const observerPath = resolve(runDir, 'observer.jsonl')\n const settlePath = resolve(runDir, SETTLE_RECORD_FILE)\n const failurePath = resolve(runDir, FAILURE_RECORD_FILE)\n const runId = opts.runId ?? 'supervise'\n const now = opts.now ?? Date.now\n\n // The lock is taken before the settle record is read so a run that settles between the read\n // and the lock cannot be re-entered; both refusals happen before the observer journal is touched.\n const lock = await acquireRunDirectoryLock(runDir, runId, now)\n return lock.run(async () => {\n let delivery: PursuitObserverDeliverer | undefined\n let terminalState: 'done' | 'failed' | 'running' = 'failed'\n try {\n const observer = createFileObserverHooks(observerPath, pursuitId)\n if (opts.reopen !== undefined)\n await reopenSettledRun({\n runDir,\n runId,\n reopen: opts.reopen,\n journal: opts.journal,\n limits: {\n budget,\n ...(opts.reservationPolicy === undefined\n ? {}\n : { reservationPolicy: opts.reservationPolicy }),\n },\n observer: observer.journal,\n pursuitId,\n now,\n })\n else {\n const prior = await readSettleRecord(runDir)\n if (prior !== undefined) {\n throw new SettledRunDirectoryError(settlePath, prior.tree.root, runId)\n }\n }\n\n // Bind this attempt to existing journal boundaries while its directory lock is held.\n const events =\n (await (\n opts.journal ?? new FileSpawnJournal(resolve(runDir, 'spawn-journal.jsonl'))\n ).loadTree(runId)) ?? []\n const root = events.find((event) => event.kind === 'spawned' && event.id === runId)\n const prior =\n root?.kind === 'spawned' && root.identity\n ? await new FileCoordinationLog(resolve(runDir, 'coordination-log.jsonl')).load(\n runId,\n rootCoordinationOwner(root.identity),\n )\n : undefined\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'before', now(), {\n coordinationOffset: prior?.records.length ?? 0,\n }),\n )\n delivery =\n opts.observerDelivery === undefined\n ? undefined\n : startPursuitObserverDelivery(opts.observerDelivery, async () =>\n projectPursuit(await observer.journal.read()),\n )\n\n let result: Result\n try {\n result = await execute({\n // The observer runs first so a caller hook that throws cannot prevent the\n // canonical lifecycle fact from entering the durable journal.\n hooks: withPursuitContext(pursuitId, composeRuntimeHooks(observer.hooks, opts.hooks)),\n // `runDir` owns the pursuit journal and terminal records. The public steer writer\n // addresses the canonical per-run event directory beneath that root, so keep its control\n // plane there without moving the durable pursuit records.\n steerDir: opts.steerDir ?? supervisorRunDir(runDir, runId),\n })\n } catch (error) {\n if (error instanceof RunParkedError && error.runId === runId) {\n terminalState = 'running'\n throw error\n }\n let pursuit: PursuitProjection\n try {\n // The journal fact is raw evidence and lands first; the failure record summarizes it.\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'error', now(), {\n status: 'failed',\n error: errorMessage(error),\n failure: runtimeFailureCause(error),\n }),\n )\n pursuit = projectPursuit(await observer.journal.read())\n } catch (observerError) {\n throw new Error(\n 'supervisePursuit: Runtime failed and durable observer completeness could not be proven',\n { cause: new AggregateError([error, observerError]) },\n )\n }\n // A failure record that cannot be written must not hide the journal fact above; it is\n // reported as its own cause beside the run's error.\n try {\n // The root's stream is already on disk whether or not the run settled; the record names\n // it so a root that died mid-turn keeps what it had streamed.\n const rootStream = await readRootStreamReceipt(runDir)\n await writeFailureRecord(runDir, {\n runId,\n pursuitId,\n at: new Date(now()).toISOString(),\n error: {\n name: error instanceof Error ? error.name : 'NonError',\n message: errorMessage(error),\n },\n ...(rootStream === undefined ? {} : { rootStream }),\n })\n } catch (recordError) {\n throw new Error(\n `supervisePursuit: Runtime failed and the failure record ${failurePath} could not be written`,\n { cause: new AggregateError([error, recordError]) },\n )\n }\n throw new SupervisePursuitError(error, pursuit, observerPath, failurePath)\n }\n\n // The settle record is the re-entry guard, so it is durable before the journal says `done`.\n // A record that cannot be written leaves the attempt open in the journal and the run\n // re-enterable, which replays the settled children and settles again.\n const terminal = settled(result)\n try {\n await writeSettleRecord(runDir, terminal)\n } catch (cause) {\n throw new Error(\n `supervisePursuit: Runtime settled but the settle record ${settlePath} could not be written`,\n { cause },\n )\n }\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'after', now(), {\n status: 'done',\n ...(terminal.kind === 'no-winner' &&\n terminal.reason === 'driver-failed' &&\n terminal.error.failure\n ? { error: terminal.error.message, failure: terminal.error.failure }\n : {}),\n }),\n )\n terminalState = 'done'\n return Object.freeze({\n result,\n pursuit: projectPursuit(await observer.journal.read()),\n observerPath,\n settlePath,\n })\n } finally {\n // The terminal delivery reads the journal after its last fact, and is bounded so an\n // unreachable Intelligence delays the return by at most twice its timeout.\n await delivery?.close(terminalState)\n await lock.release()\n }\n })\n}\n\nfunction rootEvent(\n pursuitId: string,\n runId: string,\n phase: 'before' | 'after' | 'error',\n timestamp: number,\n payload?: Record<string, unknown>,\n): RuntimeHookEvent {\n return Object.freeze({\n id: `${runId}:pursuit:${phase}:${timestamp}`,\n pursuitId,\n runId,\n target: 'agent.run',\n phase,\n timestamp,\n ...(payload ? { payload: Object.freeze({ ...payload }) } : {}),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,0BAA0B,QAAwB;CAChE,OAAO,QAAQ,GAAG,QAAQ,OAAO,KAAK,CAAC,EAAE,UAAU,cAAc;AACnE;;;AA6BA,eAAsB,WACpB,QACA,SACmE;CACnE,MAAM,OAAO,QAAQ,QAAQ,kBAAkB;CAC/C,IAAI;CACJ,IAAI;EACF,QAAQ,MAAM,SAAS,IAAI;CAC7B,SAAS,OAAO;EACd,IAAI,CAAC,aAAa,KAAK,GAAG,MAAM;EAChC,MAAM,IAAI,qBACR,sCAAsC,QAAQ,2BAA2B,QAC3E;CACF;CACA,OAAO;EAAE;EAAO,QAAQ,kBAAkB,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI;CAAE;AACvF;;AAGA,SAAgB,YAAY,SAAgC;CAC1D,4BAA4B,OAAuB;CACnD,OAAO,KAAK,MAAM,KAAK,UAAU,mBAAmB,MAAM,OAAO,CAAC,CAAC;AACrE;AAEA,SAAgB,SACd,OACA,MACa;CACb,MAAM,SAAS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