@tangle-network/agent-runtime 10.0.3 → 10.0.4
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.
- package/CHANGELOG.md +4 -0
- package/dist/{activation-kitznAHo.js → activation-38MolXIP.js} +2 -2
- package/dist/{activation-kitznAHo.js.map → activation-38MolXIP.js.map} +1 -1
- package/dist/{activation-DbSxPRUW.d.ts → activation-Ckx0yHjT.d.ts} +2 -2
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{continuation-BDeKJgV3.js → continuation-CL4B1Y4M.js} +3 -3
- package/dist/{continuation-BDeKJgV3.js.map → continuation-CL4B1Y4M.js.map} +1 -1
- package/dist/{delegate-D8yX_2K7.js → delegate-dhNeiaH_.js} +2 -2
- package/dist/{delegate-D8yX_2K7.js.map → delegate-dhNeiaH_.js.map} +1 -1
- package/dist/{driver-control-acknowledgers-BTSr3Znq.js → driver-control-acknowledgers-C6GaGBf_.js} +98 -57
- package/dist/{driver-control-acknowledgers-BTSr3Znq.js.map → driver-control-acknowledgers-C6GaGBf_.js.map} +1 -1
- package/dist/durable-file-DJ3JsA4B.js +1 -0
- package/dist/{durable-file-DUcTDWJD.js → durable-file-lXnojyij.js} +15 -4
- package/dist/{durable-file-DUcTDWJD.js.map → durable-file-lXnojyij.js.map} +1 -1
- package/dist/durable-writer-thread.js +5 -5
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +13 -13
- package/dist/{graph-4ep9laIH.js → graph-CwLg3LGC.js} +7 -7
- package/dist/{graph-4ep9laIH.js.map → graph-CwLg3LGC.js.map} +1 -1
- package/dist/{graph-registry-B-EGvJ-3.js → graph-registry-Bs6mGKou.js} +1 -1
- package/dist/{graph-registry-BxEBeihr.js → graph-registry-DtGd03zk.js} +4 -4
- package/dist/{graph-registry-BxEBeihr.js.map → graph-registry-DtGd03zk.js.map} +1 -1
- package/dist/{improve-CJf87tBs.js → improve-C_LKfgH9.js} +7 -7
- package/dist/{improve-CJf87tBs.js.map → improve-C_LKfgH9.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +9 -9
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +4 -4
- package/dist/{jsonl-file-CVAWegN-.js → jsonl-file-DyzefaZ6.js} +3 -3
- package/dist/{jsonl-file-CVAWegN-.js.map → jsonl-file-DyzefaZ6.js.map} +1 -1
- package/dist/kernel.d.ts +2 -2
- package/dist/kernel.js +18 -18
- package/dist/{loop-runner-Ckj-Zz3-.js → loop-runner-BS3ru-yj.js} +2 -2
- package/dist/{loop-runner-Ckj-Zz3-.js.map → loop-runner-BS3ru-yj.js.map} +1 -1
- package/dist/{loop-runner-CayC8e9K.d.ts → loop-runner-LWqWf8FD.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +5 -5
- package/dist/profiles.d.ts +1 -1
- package/dist/{provision-supervisor-NjROV7AQ.js → provision-supervisor-D8N0l2DM.js} +6 -6
- package/dist/{provision-supervisor-NjROV7AQ.js.map → provision-supervisor-D8N0l2DM.js.map} +1 -1
- package/dist/{result-blob-store-BR-BVZrg.js → result-blob-store-DfTcyQ05.js} +3 -3
- package/dist/{result-blob-store-BR-BVZrg.js.map → result-blob-store-DfTcyQ05.js.map} +1 -1
- package/dist/{run-cancellation-C9V1lYhq.js → run-cancellation-D3qc9wAD.js} +3 -3
- package/dist/{run-cancellation-C9V1lYhq.js.map → run-cancellation-D3qc9wAD.js.map} +1 -1
- package/dist/{run-lock-Y3u9kwM0.js → run-lock-D1xnb9ve.js} +3 -3
- package/dist/{run-lock-Y3u9kwM0.js.map → run-lock-D1xnb9ve.js.map} +1 -1
- package/dist/{run-reopen-CHYTHk7x.js → run-reopen-DVM5AEKV.js} +6 -6
- package/dist/{run-reopen-CHYTHk7x.js.map → run-reopen-DVM5AEKV.js.map} +1 -1
- package/dist/{run-state-DgKo8_tO.js → run-state-tgQ-S9Ln.js} +7 -7
- package/dist/{run-state-DgKo8_tO.js.map → run-state-tgQ-S9Ln.js.map} +1 -1
- package/dist/{runtime-CdthBQUs.js → runtime-BTECV05R.js} +20 -20
- package/dist/{runtime-CdthBQUs.js.map → runtime-BTECV05R.js.map} +1 -1
- package/dist/{search-executor-Bb0WuI_Z.js → search-executor-Uco2_KTB.js} +3 -3
- package/dist/{search-executor-Bb0WuI_Z.js.map → search-executor-Uco2_KTB.js.map} +1 -1
- package/dist/{server-BCtyL7jH.js → server-BMp24-xn.js} +3 -3
- package/dist/{server-BCtyL7jH.js.map → server-BMp24-xn.js.map} +1 -1
- package/dist/{settle-record-Beh-sXBW.js → settle-record-au3w7bQG.js} +4 -4
- package/dist/{settle-record-Beh-sXBW.js.map → settle-record-au3w7bQG.js.map} +1 -1
- package/dist/{structural-rollout-BRfSDPkv.js → structural-rollout-D8wufVJI.js} +3 -3
- package/dist/{structural-rollout-BRfSDPkv.js.map → structural-rollout-D8wufVJI.js.map} +1 -1
- package/dist/{supervise-DTUYxnoJ.js → supervise-DtVdvZpr.js} +9 -9
- package/dist/{supervise-DTUYxnoJ.js.map → supervise-DtVdvZpr.js.map} +1 -1
- package/dist/{supervise-identity-eMF-h1uP.js → supervise-identity-S5XwgaF3.js} +4 -4
- package/dist/{supervise-identity-eMF-h1uP.js.map → supervise-identity-S5XwgaF3.js.map} +1 -1
- package/dist/{supervision-discovery-CAUsSDno.js → supervision-discovery-Cqu4NxPV.js} +3 -3
- package/dist/{supervision-discovery-CAUsSDno.js.map → supervision-discovery-Cqu4NxPV.js.map} +1 -1
- package/dist/{supervisor-BtRRFbgF.js → supervisor-CHgCAMjm.js} +7 -7
- package/dist/{supervisor-BtRRFbgF.js.map → supervisor-CHgCAMjm.js.map} +1 -1
- package/dist/{supervisor-accounting-Cuehs4te.js → supervisor-accounting-CZ7i4cd5.js} +117 -46
- package/dist/{supervisor-accounting-Cuehs4te.js.map → supervisor-accounting-CZ7i4cd5.js.map} +1 -1
- package/dist/{supervisor-root-contract-CmFKzPps.js → supervisor-root-contract-D70KTGXF.js} +2 -2
- package/dist/{supervisor-root-contract-CmFKzPps.js.map → supervisor-root-contract-D70KTGXF.js.map} +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +11 -11
- package/dist/{top-web-D-wuEVdM.js → top-web-COrMqTRC.js} +7 -7
- package/dist/{top-web-D-wuEVdM.js.map → top-web-COrMqTRC.js.map} +1 -1
- package/dist/tui/bin.js +3 -3
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +2 -2
- package/dist/{types-PBoTtcbX.d.ts → types-9xsn2GGY.d.ts} +9 -2
- package/package.json +1 -1
- package/dist/durable-file-XqOyDf7q.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as
|
|
2
|
-
import { t as isNoEntError } from "./jsonl-file-
|
|
1
|
+
import { C as mutateRunClaim, T as runWithWriteClaim, d as writeAtomicDurableFile, g as registerDurableErrorClass, s as publishExclusiveDurableFile, w as runGenerationPath, y as runFencedAlways } from "./durable-file-lXnojyij.js";
|
|
2
|
+
import { t as isNoEntError } from "./jsonl-file-DyzefaZ6.js";
|
|
3
3
|
import { setTimeout } from "node:timers/promises";
|
|
4
4
|
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, unlinkSync } from "node:fs";
|
|
5
5
|
import { resolve } from "node:path";
|
|
@@ -190,4 +190,4 @@ function removeIfPresent(path) {
|
|
|
190
190
|
}
|
|
191
191
|
export { readRunDirectoryLock as a, acquireRunLockFenced as i, RunDirectoryLockedError as n, releaseRunLockFenced as o, acquireRunDirectoryLock as r, runDirectoryHolderIsLive as s, RUN_DIRECTORY_LOCK_FILE as t };
|
|
192
192
|
|
|
193
|
-
//# sourceMappingURL=run-lock-
|
|
193
|
+
//# sourceMappingURL=run-lock-D1xnb9ve.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-lock-Y3u9kwM0.js","names":["delay"],"sources":["../src/durable/run-lock.ts"],"sourcesContent":["import {\n closeSync,\n existsSync,\n fstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n unlinkSync,\n} from 'node:fs'\nimport { resolve } from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport {\n type LockHolderRecord,\n type LockIdentity,\n lockHolderVerdict,\n lockIdentity,\n parseLockHolderRecord,\n readLockHolderIdentity,\n} from '@tangle-network/agent-eval/lock-holder'\nimport {\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from '../runtime/supervise/durable-file'\nimport { registerDurableErrorClass, runFencedAlways } from './durable-writer'\nimport { isNoEntError } from './jsonl-file'\nimport { mutateRunClaim, runGenerationPath, runWithWriteClaim } from './run-fence'\n\n/*\n * Exclusive ownership of one durable run directory for the life of one `supervisePursuit` call.\n *\n * Measured motive (discovery-lab recursive smoke r1): the recovery protocol is\n * `SIGKILL` the runner while a child is live, then resume on the same directory. PID 1527 was\n * killed at 06:20:27Z and PID 2058 resumed at 06:24:59Z. Nothing refused a second process while\n * the first was still alive; two processes on one directory both append to `spawn-journal.jsonl`\n * and `observer.jsonl`, and the recorded assignment keys and settlements stop being one sequence.\n * The operator relied on timing. This lock makes the second process refuse and name the holder.\n *\n * The holder is identified by its pid and the OS's start token for that pid. r1 ran in a\n * container whose pids are small (1527, 2058) and restart from 1, so a pid alone names the wrong\n * process after enough spawns: a lock left by a killed run would then match an unrelated live\n * process and hold the directory until an operator removed the file. Whether a holder is dead is\n * agent-eval's one dead-owner rule (`@tangle-network/agent-eval/lock-holder`): the record carries\n * the start token, host, boot id, pid namespace and the lock file's own inode identity, and a\n * holder is reclaimed only when those prove it gone or its pid reused. A record that cannot prove\n * that, such as one written before these fields existed, is refused and is removed by hand.\n *\n * The lock is operational state, not evidence: replay, projection, and the settle record ignore\n * it. A holder whose process is gone is reclaimed through Eval's crash-recoverable mutation lock.\n */\n\n/** The lock file `supervisePursuit` holds inside a run directory for the life of one call. */\nexport const RUN_DIRECTORY_LOCK_FILE = 'supervise.lock'\n\n/** What the lock file records about its holder. */\nexport interface RunDirectoryLockHolder {\n readonly pid: number\n /** Monotonic acquisition generation; absent on legacy lock records. */\n readonly generation?: number\n /** ISO instant the holder took the lock. */\n readonly startedAt: string\n readonly runId: string\n /** The OS's start token for `pid` when the host reports one. A holder without one is never proved dead. */\n readonly processStart?: string\n /** Hostname of the holder. Records written before it existed are never proved dead. */\n readonly host?: string\n readonly bootId?: string\n readonly pidNamespace?: string\n /** Inode identity of the lock file this record was written into. */\n readonly lock?: LockIdentity\n}\n\n/** A held lock. `release()` removes the file; it is safe to call more than once. */\nexport interface RunDirectoryLock extends RunDirectoryLockHolder {\n readonly generation: number\n readonly path: string\n /** Bind durable writes to this acquisition, including work queued before release. */\n run<T>(operation: () => T): T\n release(): Promise<void>\n}\n\n/** The directory is held by a live process. `holder` is what that process recorded. */\nexport class RunDirectoryLockedError extends Error {\n readonly path: string\n readonly holder: RunDirectoryLockHolder\n\n constructor(path: string, holder: RunDirectoryLockHolder) {\n super(\n `supervisePursuit: ${path} is held by pid ${holder.pid} (run '${holder.runId}', since ${holder.startedAt}); one process drives a run directory at a time`,\n )\n this.name = 'RunDirectoryLockedError'\n this.path = path\n this.holder = holder\n }\n}\n\nregisterDurableErrorClass('RunDirectoryLockedError', RunDirectoryLockedError)\n\n/**\n * Take `runDir/supervise.lock`, or refuse.\n *\n * The file is published with its full content or not at all, so a contender never reads a\n * half-written holder. A lock whose holder is proved dead (its pid no longer exists, the pid now\n * belongs to a process with a different start token, or the host rebooted) is stale and is removed\n * under the mutation guard; a holder that is alive or cannot be proved dead refuses. An empty file\n * names no holder and is reclaimed. A file with unreadable content is left in place and refused:\n * reclaiming it could evict a live holder written by something other than this module.\n */\nexport async function acquireRunDirectoryLock(\n runDir: string,\n runId: string,\n now: () => number = Date.now,\n): Promise<RunDirectoryLock> {\n const dir = resolve(runDir)\n const path = resolve(dir, RUN_DIRECTORY_LOCK_FILE)\n mkdirSync(dir, { recursive: true })\n const { pid, ...identity } = readLockHolderIdentity(process.pid)\n const owner = { pid, startedAt: new Date(now()).toISOString(), runId, ...identity }\n // The whole critical section, generation decision and holder record included, runs on the\n // durable writer: the one thread that takes this directory's mutation lock in this process.\n const holder = await runFencedAlways('acquireRunLock', acquireRunLockFenced, dir, path, owner)\n const generation = holder.generation\n if (generation === undefined)\n throw new Error(`supervisePursuit: ${path} was taken without a generation`)\n let released = false\n return Object.freeze({\n ...holder,\n generation,\n path,\n run: <T>(operation: () => T): T => {\n if (holder.lock === undefined) throw new Error('run lock has no inode identity')\n return runWithWriteClaim({ path, generation, lock: holder.lock }, operation)\n },\n release: async () => {\n if (released) return\n await releaseHolder(path, holder)\n released = true\n },\n })\n}\n\n/** Take the run directory under its mutation lock and return the holder record it wrote. @internal */\nexport function acquireRunLockFenced(\n dir: string,\n path: string,\n owner: Omit<RunDirectoryLockHolder, 'generation' | 'lock'>,\n): RunDirectoryLockHolder {\n return mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state === 'holder' && !holderIsDead(existing)) {\n throw new RunDirectoryLockedError(path, existing.holder)\n }\n let previousGeneration = 0\n try {\n previousGeneration = Number(readFileSync(runGenerationPath(dir), 'utf8'))\n if (!Number.isSafeInteger(previousGeneration) || previousGeneration < 1) {\n throw new Error('invalid run directory generation counter')\n }\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n const generation =\n Math.max(\n previousGeneration,\n existing.state === 'holder' ? (existing.holder.generation ?? 0) : 0,\n ) + 1\n if (!Number.isSafeInteger(generation)) throw new Error('run directory generation exhausted')\n writeAtomicDurableFile(runGenerationPath(dir), `${generation}\\n`)\n if (existing.state !== 'missing') removeIfPresent(path)\n const written: { holder?: RunDirectoryLockHolder } = {}\n // The lock file is a hard link of the temporary file, so the temporary file's inode identity\n // is the lock's, and a later verdict can prove this record was written for this very lock.\n const published = publishExclusiveDurableFile(path, (file) => {\n written.holder = Object.freeze({ ...owner, generation, lock: lockIdentity(file) })\n return `${JSON.stringify(written.holder)}\\n`\n })\n if (!published || written.holder === undefined) {\n throw new Error(`supervisePursuit: could not take ${path}`)\n }\n return written.holder\n })\n}\n\n/** Read the holder a lock file names, or `undefined` when no lock file names one. */\nexport async function readRunDirectoryLock(\n runDir: string,\n): Promise<RunDirectoryLockHolder | undefined> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n return existing.state === 'holder' ? existing.holder : undefined\n}\n\n/** What {@link runDirectoryHolderIsLive} proved about a run directory's recorded holder. */\nexport interface RunDirectoryHolderLiveness {\n /** False only when the holder that took the lock is proved dead; a holder that cannot be proved dead reads as live. */\n readonly live: boolean\n /** The holder could not be verified on this host. `live` stays conservative for exclusion. */\n readonly unknown?: true\n /** The holder the lock file names. Absent when no lock file names one, which reads as not live. */\n readonly holder?: RunDirectoryLockHolder\n}\n\n/**\n * Whether a run directory is still held by the live process that took its lock.\n *\n * The same rule `acquireRunDirectoryLock` applies to decide whether a lock is stale, exposed so a\n * caller — a supervisor picking up an abandoned directory, an operator tool listing runs — asks\n * the question instead of hand-rolling `process.kill(pid, 0)`. A bare signal probe cannot tell a\n * live holder from an unrelated process that later took the same pid, which is the failure this\n * lock's start token exists to prevent.\n *\n * The answer is ADVISORY: it is read outside the mutation guard `acquireRunDirectoryLock` holds,\n * so a `false` can be stale by the time the caller acts on it and a concurrent acquire can take\n * the directory in between. Reporting and listing are what this is for. A caller that intends to\n * TAKE the directory calls `acquireRunDirectoryLock`, which evaluates the same rule under the\n * guard and refuses atomically.\n */\nexport async function runDirectoryHolderIsLive(\n runDir: string,\n): Promise<RunDirectoryHolderLiveness> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n if (existing.state !== 'holder') return { live: false }\n const verdict = lockHolderVerdict(existing.record, existing.current)\n return {\n live: verdict.liveness !== 'dead',\n holder: existing.holder,\n ...(verdict.liveness === 'unknown' ? { unknown: true as const } : {}),\n }\n}\n\ntype LockFileState =\n | { readonly state: 'missing' }\n | { readonly state: 'empty' }\n | {\n readonly state: 'holder'\n readonly holder: RunDirectoryLockHolder\n /** The holder as agent-eval's rule reads it; absent when the record names no host. */\n readonly record: LockHolderRecord | undefined\n /** Inode identity of the file the holder was read from. */\n readonly current: LockIdentity\n }\n\nfunction readLockFile(path: string): LockFileState {\n let text: string\n let current: LockIdentity\n try {\n const file = openSync(path, 'r')\n try {\n current = lockIdentity(fstatSync(file, { bigint: true }))\n text = readFileSync(file, 'utf8')\n } finally {\n closeSync(file)\n }\n } catch (error) {\n if (isNoEntError(error)) return { state: 'missing' }\n throw error\n }\n // This module publishes the file with its full content or not at all, so an empty file was\n // not left by a live holder.\n if (text.trim().length === 0) return { state: 'empty' }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (cause) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`, {\n cause,\n })\n }\n const record = parsed as Partial<RunDirectoryLockHolder> | null\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.pid !== 'number' ||\n !Number.isInteger(record.pid) ||\n record.pid <= 0 ||\n typeof record.startedAt !== 'string' ||\n typeof record.runId !== 'string' ||\n (record.processStart !== undefined && typeof record.processStart !== 'string') ||\n (record.generation !== undefined &&\n (!Number.isSafeInteger(record.generation) || record.generation < 1))\n ) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`)\n }\n const { pid, startedAt, runId, processStart } = record\n // A missing or malformed identity field is dropped, which leaves the holder never provably dead.\n const verdictRecord = parseLockHolderRecord(parsed)\n const { pid: _pid, ...identity } = verdictRecord ?? { pid }\n return {\n state: 'holder',\n holder: Object.freeze({\n pid,\n startedAt,\n runId,\n ...(record.generation === undefined ? {} : { generation: record.generation }),\n ...(processStart === undefined ? {} : { processStart }),\n ...identity,\n }),\n record: verdictRecord,\n current,\n }\n}\n\n/** agent-eval's dead-owner rule: only a holder proved dead is stale; alive or unknown stays held. */\nfunction holderIsDead(existing: Extract<LockFileState, { state: 'holder' }>): boolean {\n return lockHolderVerdict(existing.record, existing.current).liveness === 'dead'\n}\n\n/** Remove the lock only while it still names this holder; a reclaimed lock belongs to its new owner. */\nasync function releaseHolder(path: string, holder: RunDirectoryLockHolder): Promise<void> {\n const deadline = performance.now() + 1_000\n while (existsSync(`${path}.guard`) && performance.now() < deadline) await delay(10)\n await runFencedAlways('releaseRunLock', releaseRunLockFenced, path, holder)\n}\n\n/** Remove the lock under its mutation lock while it still names `holder`. @internal */\nexport function releaseRunLockFenced(path: string, holder: RunDirectoryLockHolder): void {\n mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state !== 'holder') return\n if (\n existing.holder.pid !== holder.pid ||\n existing.holder.startedAt !== holder.startedAt ||\n existing.holder.runId !== holder.runId ||\n existing.holder.processStart !== holder.processStart ||\n existing.holder.generation !== holder.generation ||\n existing.holder.lock?.dev !== holder.lock?.dev ||\n existing.holder.lock?.ino !== holder.lock?.ino ||\n existing.holder.lock?.birthtimeNs !== holder.lock?.birthtimeNs\n )\n return\n removeIfPresent(path)\n })\n}\n\nfunction removeIfPresent(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n}\n"],"mappings":";;;;;;;;AAmDA,MAAa,0BAA0B;;AA8BvC,IAAa,0BAAb,cAA6C,MAAM;CACjD;CACA;CAEA,YAAY,MAAc,QAAgC;EACxD,MACE,qBAAqB,KAAK,kBAAkB,OAAO,IAAI,SAAS,OAAO,MAAM,WAAW,OAAO,UAAU,gDAC3G;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AAEA,0BAA0B,2BAA2B,uBAAuB;;;;;;;;;;;AAY5E,eAAsB,wBACpB,QACA,OACA,MAAoB,KAAK,KACE;CAC3B,MAAM,MAAM,QAAQ,MAAM;CAC1B,MAAM,OAAO,QAAQ,KAAK,uBAAuB;CACjD,UAAU,KAAK,EAAE,WAAW,K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sBAAsB,MAAM,MAAM;AAC5E;;AAGA,SAAgB,qBAAqB,MAAc,QAAsC;CACvF,eAAe,YAAY;EACzB,MAAM,WAAW,aAAa,IAAI;EAClC,IAAI,SAAS,UAAU,UAAU;EACjC,IACE,SAAS,OAAO,QAAQ,OAAO,OAC/B,SAAS,OAAO,cAAc,OAAO,aACrC,SAAS,OAAO,UAAU,OAAO,SACjC,SAAS,OAAO,iBAAiB,OAAO,gBACxC,SAAS,OAAO,eAAe,OAAO,cACtC,SAAS,OAAO,MAAM,QAAQ,OAAO,MAAM,OAC3C,SAAS,OAAO,MAAM,QAAQ,OAAO,MAAM,OAC3C,SAAS,OAAO,MAAM,gBAAgB,OAAO,MAAM,aAEnD;EACF,gBAAgB,IAAI;CACtB,CAAC;AACH;AAEA,SAAS,gBAAgB,MAAoB;CAC3C,IAAI;EACF,WAAW,IAAI;CACjB,SAAS,OAAO;EACd,IAAI,CAAC,aAAa,KAAK,GAAG,MAAM;CAClC;AACF"}
|
|
1
|
+
{"version":3,"file":"run-lock-D1xnb9ve.js","names":["delay"],"sources":["../src/durable/run-lock.ts"],"sourcesContent":["import {\n closeSync,\n existsSync,\n fstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n unlinkSync,\n} from 'node:fs'\nimport { resolve } from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport {\n type LockHolderRecord,\n type LockIdentity,\n lockHolderVerdict,\n lockIdentity,\n parseLockHolderRecord,\n readLockHolderIdentity,\n} from '@tangle-network/agent-eval/lock-holder'\nimport {\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from '../runtime/supervise/durable-file'\nimport { registerDurableErrorClass, runFencedAlways } from './durable-writer'\nimport { isNoEntError } from './jsonl-file'\nimport { mutateRunClaim, runGenerationPath, runWithWriteClaim } from './run-fence'\n\n/*\n * Exclusive ownership of one durable run directory for the life of one `supervisePursuit` call.\n *\n * Measured motive (discovery-lab recursive smoke r1): the recovery protocol is\n * `SIGKILL` the runner while a child is live, then resume on the same directory. PID 1527 was\n * killed at 06:20:27Z and PID 2058 resumed at 06:24:59Z. Nothing refused a second process while\n * the first was still alive; two processes on one directory both append to `spawn-journal.jsonl`\n * and `observer.jsonl`, and the recorded assignment keys and settlements stop being one sequence.\n * The operator relied on timing. This lock makes the second process refuse and name the holder.\n *\n * The holder is identified by its pid and the OS's start token for that pid. r1 ran in a\n * container whose pids are small (1527, 2058) and restart from 1, so a pid alone names the wrong\n * process after enough spawns: a lock left by a killed run would then match an unrelated live\n * process and hold the directory until an operator removed the file. Whether a holder is dead is\n * agent-eval's one dead-owner rule (`@tangle-network/agent-eval/lock-holder`): the record carries\n * the start token, host, boot id, pid namespace and the lock file's own inode identity, and a\n * holder is reclaimed only when those prove it gone or its pid reused. A record that cannot prove\n * that, such as one written before these fields existed, is refused and is removed by hand.\n *\n * The lock is operational state, not evidence: replay, projection, and the settle record ignore\n * it. A holder whose process is gone is reclaimed through Eval's crash-recoverable mutation lock.\n */\n\n/** The lock file `supervisePursuit` holds inside a run directory for the life of one call. */\nexport const RUN_DIRECTORY_LOCK_FILE = 'supervise.lock'\n\n/** What the lock file records about its holder. */\nexport interface RunDirectoryLockHolder {\n readonly pid: number\n /** Monotonic acquisition generation; absent on legacy lock records. */\n readonly generation?: number\n /** ISO instant the holder took the lock. */\n readonly startedAt: string\n readonly runId: string\n /** The OS's start token for `pid` when the host reports one. A holder without one is never proved dead. */\n readonly processStart?: string\n /** Hostname of the holder. Records written before it existed are never proved dead. */\n readonly host?: string\n readonly bootId?: string\n readonly pidNamespace?: string\n /** Inode identity of the lock file this record was written into. */\n readonly lock?: LockIdentity\n}\n\n/** A held lock. `release()` removes the file; it is safe to call more than once. */\nexport interface RunDirectoryLock extends RunDirectoryLockHolder {\n readonly generation: number\n readonly path: string\n /** Bind durable writes to this acquisition, including work queued before release. */\n run<T>(operation: () => T): T\n release(): Promise<void>\n}\n\n/** The directory is held by a live process. `holder` is what that process recorded. */\nexport class RunDirectoryLockedError extends Error {\n readonly path: string\n readonly holder: RunDirectoryLockHolder\n\n constructor(path: string, holder: RunDirectoryLockHolder) {\n super(\n `supervisePursuit: ${path} is held by pid ${holder.pid} (run '${holder.runId}', since ${holder.startedAt}); one process drives a run directory at a time`,\n )\n this.name = 'RunDirectoryLockedError'\n this.path = path\n this.holder = holder\n }\n}\n\nregisterDurableErrorClass('RunDirectoryLockedError', RunDirectoryLockedError)\n\n/**\n * Take `runDir/supervise.lock`, or refuse.\n *\n * The file is published with its full content or not at all, so a contender never reads a\n * half-written holder. A lock whose holder is proved dead (its pid no longer exists, the pid now\n * belongs to a process with a different start token, or the host rebooted) is stale and is removed\n * under the mutation guard; a holder that is alive or cannot be proved dead refuses. An empty file\n * names no holder and is reclaimed. A file with unreadable content is left in place and refused:\n * reclaiming it could evict a live holder written by something other than this module.\n */\nexport async function acquireRunDirectoryLock(\n runDir: string,\n runId: string,\n now: () => number = Date.now,\n): Promise<RunDirectoryLock> {\n const dir = resolve(runDir)\n const path = resolve(dir, RUN_DIRECTORY_LOCK_FILE)\n mkdirSync(dir, { recursive: true })\n const { pid, ...identity } = readLockHolderIdentity(process.pid)\n const owner = { pid, startedAt: new Date(now()).toISOString(), runId, ...identity }\n // The whole critical section, generation decision and holder record included, runs on the\n // durable writer: the one thread that takes this directory's mutation lock in this process.\n const holder = await runFencedAlways('acquireRunLock', acquireRunLockFenced, dir, path, owner)\n const generation = holder.generation\n if (generation === undefined)\n throw new Error(`supervisePursuit: ${path} was taken without a generation`)\n let released = false\n return Object.freeze({\n ...holder,\n generation,\n path,\n run: <T>(operation: () => T): T => {\n if (holder.lock === undefined) throw new Error('run lock has no inode identity')\n return runWithWriteClaim({ path, generation, lock: holder.lock }, operation)\n },\n release: async () => {\n if (released) return\n await releaseHolder(path, holder)\n released = true\n },\n })\n}\n\n/** Take the run directory under its mutation lock and return the holder record it wrote. @internal */\nexport function acquireRunLockFenced(\n dir: string,\n path: string,\n owner: Omit<RunDirectoryLockHolder, 'generation' | 'lock'>,\n): RunDirectoryLockHolder {\n return mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state === 'holder' && !holderIsDead(existing)) {\n throw new RunDirectoryLockedError(path, existing.holder)\n }\n let previousGeneration = 0\n try {\n previousGeneration = Number(readFileSync(runGenerationPath(dir), 'utf8'))\n if (!Number.isSafeInteger(previousGeneration) || previousGeneration < 1) {\n throw new Error('invalid run directory generation counter')\n }\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n const generation =\n Math.max(\n previousGeneration,\n existing.state === 'holder' ? (existing.holder.generation ?? 0) : 0,\n ) + 1\n if (!Number.isSafeInteger(generation)) throw new Error('run directory generation exhausted')\n writeAtomicDurableFile(runGenerationPath(dir), `${generation}\\n`)\n if (existing.state !== 'missing') removeIfPresent(path)\n const written: { holder?: RunDirectoryLockHolder } = {}\n // The lock file is a hard link of the temporary file, so the temporary file's inode identity\n // is the lock's, and a later verdict can prove this record was written for this very lock.\n const published = publishExclusiveDurableFile(path, (file) => {\n written.holder = Object.freeze({ ...owner, generation, lock: lockIdentity(file) })\n return `${JSON.stringify(written.holder)}\\n`\n })\n if (!published || written.holder === undefined) {\n throw new Error(`supervisePursuit: could not take ${path}`)\n }\n return written.holder\n })\n}\n\n/** Read the holder a lock file names, or `undefined` when no lock file names one. */\nexport async function readRunDirectoryLock(\n runDir: string,\n): Promise<RunDirectoryLockHolder | undefined> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n return existing.state === 'holder' ? existing.holder : undefined\n}\n\n/** What {@link runDirectoryHolderIsLive} proved about a run directory's recorded holder. */\nexport interface RunDirectoryHolderLiveness {\n /** False only when the holder that took the lock is proved dead; a holder that cannot be proved dead reads as live. */\n readonly live: boolean\n /** The holder could not be verified on this host. `live` stays conservative for exclusion. */\n readonly unknown?: true\n /** The holder the lock file names. Absent when no lock file names one, which reads as not live. */\n readonly holder?: RunDirectoryLockHolder\n}\n\n/**\n * Whether a run directory is still held by the live process that took its lock.\n *\n * The same rule `acquireRunDirectoryLock` applies to decide whether a lock is stale, exposed so a\n * caller — a supervisor picking up an abandoned directory, an operator tool listing runs — asks\n * the question instead of hand-rolling `process.kill(pid, 0)`. A bare signal probe cannot tell a\n * live holder from an unrelated process that later took the same pid, which is the failure this\n * lock's start token exists to prevent.\n *\n * The answer is ADVISORY: it is read outside the mutation guard `acquireRunDirectoryLock` holds,\n * so a `false` can be stale by the time the caller acts on it and a concurrent acquire can take\n * the directory in between. Reporting and listing are what this is for. A caller that intends to\n * TAKE the directory calls `acquireRunDirectoryLock`, which evaluates the same rule under the\n * guard and refuses atomically.\n */\nexport async function runDirectoryHolderIsLive(\n runDir: string,\n): Promise<RunDirectoryHolderLiveness> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n if (existing.state !== 'holder') return { live: false }\n const verdict = lockHolderVerdict(existing.record, existing.current)\n return {\n live: verdict.liveness !== 'dead',\n holder: existing.holder,\n ...(verdict.liveness === 'unknown' ? { unknown: true as const } : {}),\n }\n}\n\ntype LockFileState =\n | { readonly state: 'missing' }\n | { readonly state: 'empty' }\n | {\n readonly state: 'holder'\n readonly holder: RunDirectoryLockHolder\n /** The holder as agent-eval's rule reads it; absent when the record names no host. */\n readonly record: LockHolderRecord | undefined\n /** Inode identity of the file the holder was read from. */\n readonly current: LockIdentity\n }\n\nfunction readLockFile(path: string): LockFileState {\n let text: string\n let current: LockIdentity\n try {\n const file = openSync(path, 'r')\n try {\n current = lockIdentity(fstatSync(file, { bigint: true }))\n text = readFileSync(file, 'utf8')\n } finally {\n closeSync(file)\n }\n } catch (error) {\n if (isNoEntError(error)) return { state: 'missing' }\n throw error\n }\n // This module publishes the file with its full content or not at all, so an empty file was\n // not left by a live holder.\n if (text.trim().length === 0) return { state: 'empty' }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (cause) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`, {\n cause,\n })\n }\n const record = parsed as Partial<RunDirectoryLockHolder> | null\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.pid !== 'number' ||\n !Number.isInteger(record.pid) ||\n record.pid <= 0 ||\n typeof record.startedAt !== 'string' ||\n typeof record.runId !== 'string' ||\n (record.processStart !== undefined && typeof record.processStart !== 'string') ||\n (record.generation !== undefined &&\n (!Number.isSafeInteger(record.generation) || record.generation < 1))\n ) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`)\n }\n const { pid, startedAt, runId, processStart } = record\n // A missing or malformed identity field is dropped, which leaves the holder never provably dead.\n const verdictRecord = parseLockHolderRecord(parsed)\n const { pid: _pid, ...identity } = verdictRecord ?? { pid }\n return {\n state: 'holder',\n holder: Object.freeze({\n pid,\n startedAt,\n runId,\n ...(record.generation === undefined ? {} : { generation: record.generation }),\n ...(processStart === undefined ? {} : { processStart }),\n ...identity,\n }),\n record: verdictRecord,\n current,\n }\n}\n\n/** agent-eval's dead-owner rule: only a holder proved dead is stale; alive or unknown stays held. */\nfunction holderIsDead(existing: Extract<LockFileState, { state: 'holder' }>): boolean {\n return lockHolderVerdict(existing.record, existing.current).liveness === 'dead'\n}\n\n/** Remove the lock only while it still names this holder; a reclaimed lock belongs to its new owner. */\nasync function releaseHolder(path: string, holder: RunDirectoryLockHolder): Promise<void> {\n const deadline = performance.now() + 1_000\n while (existsSync(`${path}.guard`) && performance.now() < deadline) await delay(10)\n await runFencedAlways('releaseRunLock', releaseRunLockFenced, path, holder)\n}\n\n/** Remove the lock under its mutation lock while it still names `holder`. @internal */\nexport function releaseRunLockFenced(path: string, holder: RunDirectoryLockHolder): void {\n mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state !== 'holder') return\n if (\n existing.holder.pid !== holder.pid ||\n existing.holder.startedAt !== holder.startedAt ||\n existing.holder.runId !== holder.runId ||\n existing.holder.processStart !== holder.processStart ||\n existing.holder.generation !== holder.generation ||\n existing.holder.lock?.dev !== holder.lock?.dev ||\n existing.holder.lock?.ino !== holder.lock?.ino ||\n existing.holder.lock?.birthtimeNs !== holder.lock?.birthtimeNs\n )\n return\n removeIfPresent(path)\n })\n}\n\nfunction removeIfPresent(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n}\n"],"mappings":";;;;;;;;AAmDA,MAAa,0BAA0B;;AA8BvC,IAAa,0BAAb,cAA6C,MAAM;CACjD;CACA;CAEA,YAAY,MAAc,QAAgC;EACxD,MACE,qBAAqB,KAAK,kBAAkB,OAAO,IAAI,SAAS,OAAO,MAAM,WAAW,OAAO,UAAU,gDAC3G;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AAEA,0BAA0B,2BAA2B,uBAAuB;;;;;;;;;;;AAY5E,eAAsB,wBACpB,QACA,OACA,MAAoB,KAAK,KACE;CAC3B,MAAM,MAAM,QAAQ,MAAM;CAC1B,MAAM,OAAO,QAAQ,KAAK,uBAAuB;CACjD,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;CAClC,MAAM,EAAE,KAAK,GAAG,aAAa,uBAAuB,QAAQ,GAAG;CAC/D,MAAM,QAAQ;EAAE;EAAK,WAAW,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,YAAY;EAAG;EAAO,GAAG;CAAS;CAGlF,MAAM,SAAS,MAAM,gBAAgB,kBAAkB,sBAAsB,KAAK,MAAM,KAAK;CAC7F,MAAM,aAAa,OAAO;CAC1B,IAAI,eAAe,KAAA,GACjB,MAAM,IAAI,MAAM,qBAAqB,KAAK,gCAAgC;CAC5E,IAAI,WAAW;CACf,OAAO,OAAO,OAAO;EACnB,GAAG;EACH;EACA;EACA,MAAS,cAA0B;GACjC,IAAI,OAAO,SAAS,KAAA,GAAW,MAAM,IAAI,MAAM,gCAAgC;GAC/E,OAAO,kBAAkB;IAAE;IAAM;IAAY,MAAM,OAAO;GAAK,GAAG,SAAS;EAC7E;EACA,SAAS,YAAY;GACnB,IAAI,UAAU;GACd,MAAM,cAA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|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as runCancelRequestFile, o as runCancellationFile } from "./run-cancellation-
|
|
3
|
-
import { D as workerCancellationsDir,
|
|
1
|
+
import { S as fenceRunWrite, s as publishExclusiveDurableFile, u as syncDurableDirectory, v as runFenced } from "./durable-file-lXnojyij.js";
|
|
2
|
+
import { a as runCancelRequestFile, o as runCancellationFile } from "./run-cancellation-D3qc9wAD.js";
|
|
3
|
+
import { D as workerCancellationsDir, Y as FileSpawnJournal } from "./supervisor-accounting-CZ7i4cd5.js";
|
|
4
4
|
import { nt as assertValidBudget } from "./failure-cause-DoCCGLDH.js";
|
|
5
|
-
import { n as assertResumeLimits } from "./supervisor-root-contract-
|
|
6
|
-
import { n as SETTLE_RECORD_FILE, s as settleRecordDigest } from "./settle-record-
|
|
5
|
+
import { n as assertResumeLimits } from "./supervisor-root-contract-D70KTGXF.js";
|
|
6
|
+
import { n as SETTLE_RECORD_FILE, s as settleRecordDigest } from "./settle-record-au3w7bQG.js";
|
|
7
7
|
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync } from "node:fs";
|
|
8
8
|
import { join, resolve } from "node:path";
|
|
9
9
|
import { readFile } from "node:fs/promises";
|
|
@@ -131,4 +131,4 @@ function makeRunDirectoryFenced(dir) {
|
|
|
131
131
|
}
|
|
132
132
|
export { reopenSettledRun as i, makeRunDirectoryFenced as n, reopenSettleFenced as r, assertRunReopen as t };
|
|
133
133
|
|
|
134
|
-
//# sourceMappingURL=run-reopen-
|
|
134
|
+
//# sourceMappingURL=run-reopen-DVM5AEKV.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-reopen-CHYTHk7x.js","names":[],"sources":["../src/durable/run-reopen.ts"],"sourcesContent":["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 { runFenced } from './durable-writer'\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 runFenced('reopenSettle', reopenSettleFenced, runDir, operationId, settlePath)\n}\n\n/** Set the settled run's cancellation aside and remove its settle record, under the fence. @internal */\nexport function reopenSettleFenced(runDir: string, operationId: string, settlePath: string): void {\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 runFenced('makeRunDirectory', makeRunDirectoryFenced, dir)\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\n/** Create a directory inside the run under the fence. @internal */\nexport function makeRunDirectoryFenced(dir: string): void {\n fenceRunWrite(() => mkdirSync(dir, { recursive: true }))\n}\n"],"mappings":";;;;;;;;;;;AA8DA,MAAa,qBAAqB;;AAGlC,SAAgB,gBACd,QACA,MACM;CACN,IAAI,OAAO,SAAS,KAAK,CAAC,CAAC,WAAW,GACpC,MAAM,IAAI,UAAU,qDAAqD;CAE3E,IAAI,OAAO,OAAO,KAAK,CAAC,CAAC,WAAW,GAClC,MAAM,IAAI,UAAU,mDAAmD;CAEzE,IAAI,OAAO,YAAY,KAAK,CAAC,CAAC,WAAW,GACvC,MAAM,IAAI,UAAU,wDAAwD;CAE9E,IAAI,OAAO,WAAW,KAAA,GAAW,kBAAkB,OAAO,QAAQ,eAAe;CACjF,IAAI,KAAK,SAAS,KAAA,KAAa,KAAK,aAAa,KAAA,GAC/C,MAAM,IAAI,UACR,gGACF;AAEJ;;;;;;AAOA,eAAsB,iBAAiB,OAUrB;CAChB,MAAM,EAAE,QAAQ,OAAO,QAAQ,UAAU,WAAW,QAAQ;CAC5D,MAAM,cAAc,OAAO,YAAY,KAAK;CAC5C,MAAM,aAAa,QAAQ,QAAQ,kBAAkB;CACrD,MAAM,UAAU,MAAM,WAAW,IAAI,iBAAiB,QAAQ,QAAQ,qBAAqB,CAAC;CAC5F,MAAM,SAAU,MAA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AM;CAC1C,IAAI,CAAC,WAAW,WAAW,KAAK,CAAC,WAAW,OAAO,GAAG;CACtD,MAAM,SAAS,WAAW,WAAW,IAAI,cAAc;CACvD,MAAM,EAAE,gBAAgB,KAAK,MAAM,aAAa,QAAQ,MAAM,CAAC;CAG/D,MAAM,cAAc,KAAK,uBAAuB,MAAM,GAAG,UAAU;CACnE,MAAM,QAAQ,KACZ,aACA,mBAAmB,iBAAiB,GACpC,mBAAmB,WAAW,CAChC;CACA,UAAU,OAAO,EAAE,WAAW,KAAK,CAAC;CACpC,IAAI,WAAW,OAAO,GAAG,WAAW,SAAS,KAAK,OAAO,UAAU,CAAC;CACpE,IAAI,WAAW,WAAW,GAAG,WAAW,aAAa,KAAK,OAAO,kBAAkB,CAAC;CACpF,qBAAqB,KAAK;CAC1B,qBAAqB,KAAK,aAAa,mBAAmB,iBAAiB,CAAC,CAAC;CAC7E,qBAAqB,WAAW;CAChC,qBAAqB,uBAAuB,MAAM,CAAC;AACrD;AAEA,eAAe,UAAU,MAA2C;CAClE,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,MAAM;CACpC,SAAS,OAAO;EACd,IAAK,MAAgC,SAAS,UAAU,OAAO,KAAA;EAC/D,MAAM;CACR;AACF;;AAGA,SAAgB,uBAAuB,KAAmB;CACxD,oBAAoB,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC,CAAC;AACzD"}
|
|
1
|
+
{"version":3,"file":"run-reopen-DVM5AEKV.js","names":[],"sources":["../src/durable/run-reopen.ts"],"sourcesContent":["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 { runFenced } from './durable-writer'\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 runFenced('reopenSettle', reopenSettleFenced, runDir, operationId, settlePath)\n}\n\n/** Set the settled run's cancellation aside and remove its settle record, under the fence. @internal */\nexport function reopenSettleFenced(runDir: string, operationId: string, settlePath: string): void {\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 runFenced('makeRunDirectory', makeRunDirectoryFenced, dir)\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\n/** Create a directory inside the run under the fence. @internal */\nexport function makeRunDirectoryFenced(dir: string): void {\n fenceRunWrite(() => mkdirSync(dir, { recursive: true }))\n}\n"],"mappings":";;;;;;;;;;;AA8DA,MAAa,qBAAqB;;AAGlC,SAAgB,gBACd,QACA,MACM;CACN,IAAI,OAAO,SAAS,KAAK,CAAC,CAAC,WAAW,GACpC,MAAM,IAAI,UAAU,qDAAqD;CAE3E,IAAI,OAAO,OAAO,KAAK,CAAC,CAAC,WAAW,GAClC,MAAM,IAAI,UAAU,mDAAmD;CAEzE,IAAI,OAAO,YAAY,KAAK,CAAC,CAAC,WAAW,GACvC,MAAM,IAAI,UAAU,wDAAwD;CAE9E,IAAI,OAAO,WAAW,KAAA,GAAW,kBAAkB,OAAO,QAAQ,eAAe;CACjF,IAAI,KAAK,SAAS,KAAA,KAAa,KAAK,aAAa,KAAA,GAC/C,MAAM,IAAI,UACR,gGACF;AAEJ;;;;;;AAOA,eAAsB,iBAAiB,OAUrB;CAChB,MAAM,EAAE,QAAQ,OAAO,QAAQ,UAAU,WAAW,QAAQ;CAC5D,MAAM,cAAc,OAAO,YAAY,KAAK;CAC5C,MAAM,aAAa,QAAQ,QAAQ,kBAAkB;CACrD,MAAM,UAAU,MAAM,WAAW,IAAI,iBAAiB,QAAQ,QAAQ,qBAAqB,CAAC;CAC5F,MAAM,SAAU,MAAM,QAAQ,SAAS,KAAK,KAAM,CAAC;CACnD,MAAM,WAAW,OAAO,QACrB,UACC,MAAM,SAAS,cAAc,MAAM,OAAO,KAC9C;CACA,MAAM,OAAO,SAAS,MAAM,UAAU,MAAM,gBAAgB,WAAW;CAC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,CAAC;CAG/D,MAAM,cAAc,KAAK,uBAAuB,MAAM,GAAG,UAAU;CACnE,MAAM,QAAQ,KACZ,aACA,mBAAmB,iBAAiB,GACpC,mBAAmB,WAAW,CAChC;CACA,UAAU,OAAO,EAAE,WAAW,KAAK,CAAC;CACpC,IAAI,WAAW,OAAO,GAAG,WAAW,SAAS,KAAK,OAAO,UAAU,CAAC;CACpE,IAAI,WAAW,WAAW,GAAG,WAAW,aAAa,KAAK,OAAO,kBAAkB,CAAC;CACpF,qBAAqB,KAAK;CAC1B,qBAAqB,KAAK,aAAa,mBAAmB,iBAAiB,CAAC,CAAC;CAC7E,qBAAqB,WAAW;CAChC,qBAAqB,uBAAuB,MAAM,CAAC;AACrD;AAEA,eAAe,UAAU,MAA2C;CAClE,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,MAAM;CACpC,SAAS,OAAO;EACd,IAAK,MAAgC,SAAS,UAAU,OAAO,KAAA;EAC/D,MAAM;CACR;AACF;;AAGA,SAAgB,uBAAuB,KAAmB;CACxD,oBAAoB,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC,CAAC;AACzD"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { r as readRunCancelRequest } from "./run-cancellation-
|
|
2
|
-
import { s as readRunParking } from "./supervisor-
|
|
3
|
-
import { s as runDirectoryHolderIsLive } from "./run-lock-
|
|
4
|
-
import { a as readFailureRecord, o as readSettleRecord } from "./settle-record-
|
|
5
|
-
import { o as readCommittedJsonLines, t as isNoEntError } from "./jsonl-file-
|
|
6
|
-
import {
|
|
1
|
+
import { r as readRunCancelRequest } from "./run-cancellation-D3qc9wAD.js";
|
|
2
|
+
import { s as readRunParking } from "./supervisor-CHgCAMjm.js";
|
|
3
|
+
import { s as runDirectoryHolderIsLive } from "./run-lock-D1xnb9ve.js";
|
|
4
|
+
import { a as readFailureRecord, o as readSettleRecord } from "./settle-record-au3w7bQG.js";
|
|
5
|
+
import { o as readCommittedJsonLines, t as isNoEntError } from "./jsonl-file-DyzefaZ6.js";
|
|
6
|
+
import { Z as spawnJournalRecordEvents } from "./supervisor-accounting-CZ7i4cd5.js";
|
|
7
7
|
import { isRecord } from "@tangle-network/agent-core";
|
|
8
8
|
import { createHash } from "node:crypto";
|
|
9
9
|
import { join } from "node:path";
|
|
@@ -177,4 +177,4 @@ async function readRunState(runDir) {
|
|
|
177
177
|
}
|
|
178
178
|
export { readSpawnJournal as n, readRunState as t };
|
|
179
179
|
|
|
180
|
-
//# sourceMappingURL=run-state-
|
|
180
|
+
//# sourceMappingURL=run-state-tgQ-S9Ln.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-state-DgKo8_tO.js","names":[],"sources":["../src/durable/spawn-journal/read.ts","../src/durable/run-state.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport type { BigIntStats } from 'node:fs'\nimport { type FileHandle, open, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { isRecord } from '@tangle-network/agent-core'\nimport type { NodeId, SpawnEvent } from '../../runtime/supervise/types'\nimport { isNoEntError, readCommittedJsonLines } from '../jsonl-file'\nimport { spawnJournalRecordEvents } from './record-events'\n\n/** Serializable checkpoint of a committed byte boundary, bound to one file and its bytes. */\nexport interface SpawnJournalCursor {\n readonly file: string\n readonly offset: number\n readonly boundary: string\n}\n\n/** Physical groups expand to event records; the owning tree is preserved for every event. */\nexport type SpawnJournalReadRecord =\n | { readonly kind: 'begin'; readonly root: NodeId; readonly at: string }\n | { readonly kind: 'event'; readonly root: NodeId; readonly event: SpawnEvent }\n\nexport interface SpawnJournalReadOptions {\n /** Read-only projections may skip malformed physical rows; execution readers stay strict. */\n readonly invalid?: 'throw' | 'skip'\n readonly after?: SpawnJournalCursor\n /** Initial opening-and-tail window, or an incremental page's byte budget. A crossing record\n * is read whole, so one large record can exceed this budget. Omit for complete history. */\n readonly tailBytes?: number\n}\n\nexport interface SpawnJournalReadResult {\n readonly records: ReadonlyArray<SpawnJournalReadRecord>\n /** Absent only when the journal does not exist. Treat as opaque and persist unchanged. */\n readonly cursor?: SpawnJournalCursor\n /** The supplied cursor no longer matches; this page starts over. */\n readonly reset: boolean\n /** An initial opening-and-tail window omitted records between its two windows. */\n readonly truncated: boolean\n /** Bytes after the committed cursor in this snapshot, including an incomplete final write. */\n readonly remainingBytes: number\n}\n\n/** Read a fixed journal prefix, with historical envelopes and framing owned by Runtime.\n * Missing journals return an empty page. Malformed committed records fail by default; incomplete final\n * writes remain unread for the next call. Cursors detect replacement, truncation and edits at\n * their sampled opening/boundary; they are not integrity proofs against arbitrary file edits.\n */\nexport async function readSpawnJournal(\n runDir: string,\n options: SpawnJournalReadOptions = {},\n): Promise<SpawnJournalReadResult> {\n const { after, tailBytes } = options\n if (tailBytes !== undefined && (!Number.isSafeInteger(tailBytes) || tailBytes < 1)) {\n throw new RangeError('readSpawnJournal: tailBytes must be a positive safe integer')\n }\n const path = join(runDir, 'spawn-journal.jsonl')\n let handle: FileHandle\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if (isNoEntError(error)) {\n return { records: [], reset: after !== undefined, truncated: false, remainingBytes: 0 }\n }\n throw error\n }\n try {\n const snapshot = await handle.stat({ bigint: true })\n if (!snapshot.isFile()) throw new Error(`${path}: expected a regular file`)\n const size = Number(snapshot.size)\n const file = identity(snapshot)\n const resumed =\n after !== undefined &&\n after.file === file &&\n Number.isSafeInteger(after.offset) &&\n after.offset >= 0 &&\n after.offset <= size &&\n after.boundary === (await boundary(handle, after.offset))\n let offset = resumed ? after.offset : 0\n const records: SpawnJournalReadRecord[] = []\n const read = async (start: number, end: number, firstOnly = false): Promise<void> => {\n offset = start\n for await (const record of readCommittedJsonLines<unknown>(path, {\n handle,\n start,\n end,\n strictUtf8: true,\n invalid: options.invalid,\n onCommit: (committed) => {\n offset = committed\n },\n })) {\n if (\n !isRecord(record) ||\n typeof record.root !== 'string' ||\n (record.kind === 'begin' && typeof record.at !== 'string')\n ) {\n if (options.invalid === 'skip') continue\n throw new Error(`${path}: spawn journal record has no root or begin timestamp`)\n }\n if (record.kind === 'begin') {\n records.push({ kind: 'begin', root: record.root, at: record.at as string })\n } else {\n const events = spawnJournalRecordEvents(record, options.invalid)\n if (\n events.some(\n (event) =>\n !isRecord(event) || typeof event.kind !== 'string' || typeof event.id !== 'string',\n )\n ) {\n if (options.invalid === 'skip') continue\n throw new Error(`${path}: spawn journal record has no event identity`)\n }\n for (const event of events) records.push({ kind: 'event', root: record.root, event })\n }\n if (firstOnly) break\n }\n }\n let truncated = false\n if (!resumed && tailBytes !== undefined && size > tailBytes) {\n await read(0, size, true)\n const openingEnd = offset\n const tailStart = await lineBoundary(handle, size - tailBytes, size, -1)\n truncated = tailStart > openingEnd\n await read(Math.max(openingEnd, tailStart), size)\n // A long torn tail must not hide the latest committed activity before it.\n if (offset === tailStart && tailStart > openingEnd) {\n const previous = await lineBoundary(handle, tailStart - 1, size, -1)\n truncated = previous > openingEnd\n await read(Math.max(openingEnd, previous), tailStart)\n }\n } else {\n const end =\n resumed && tailBytes !== undefined && size - offset > tailBytes\n ? await lineBoundary(handle, offset + tailBytes, size, 1)\n : size\n await read(offset, end)\n }\n if (identity(await stat(path, { bigint: true })) !== file || (await handle.stat()).size < size)\n throw new Error(`${path}: journal changed while reading its committed prefix`)\n return {\n records,\n cursor: { file, offset, boundary: await boundary(handle, offset) },\n reset: after !== undefined && !resumed,\n truncated,\n remainingBytes: size - offset,\n }\n } finally {\n await handle.close()\n }\n}\n\nfunction identity(info: BigIntStats): string {\n return `${info.dev}:${info.ino}:${info.birthtimeNs}`\n}\n\nasync function bytes(handle: FileHandle, start: number, length: number): Promise<Buffer> {\n const buffer = Buffer.alloc(length)\n const { bytesRead } = await handle.read(buffer, 0, length, start)\n if (bytesRead !== length) throw new Error('spawn journal changed while reading its boundary')\n return buffer\n}\n\nasync function boundary(handle: FileHandle, offset: number): Promise<string> {\n const length = Math.min(offset, 128)\n return createHash('sha256')\n .update(await bytes(handle, 0, length))\n .update(await bytes(handle, offset - length, length))\n .digest('hex')\n}\n\n/** Include the record crossing a tail window or incremental page boundary. */\nasync function lineBoundary(\n handle: FileHandle,\n position: number,\n size: number,\n direction: -1 | 1,\n): Promise<number> {\n while (position > 0 && position < size) {\n const start = direction === -1 ? Math.max(0, position - 65_536) : position\n const end = direction === -1 ? position : Math.min(size, position + 65_536)\n const part = await bytes(handle, start, end - start)\n const newline = direction === -1 ? part.lastIndexOf(10) : part.indexOf(10)\n if (newline !== -1) return start + newline + 1\n position = direction === -1 ? start : end\n }\n return position\n}\n","import type { RuntimeFailureCause } from '../runtime/failure-cause'\nimport { type RunCancelRequest, readRunCancelRequest } from '../runtime/supervise/run-cancellation'\nimport { readRunParking } from '../runtime/supervise/run-parking'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport { runDirectoryHolderIsLive } from './run-lock'\nimport { readFailureRecord, readSettleRecord } from './settle-record'\nimport { readSpawnJournal } from './spawn-journal/read'\n\n/** Runtime evidence only. Product-specific launch, checks and trace completeness belong to callers. */\nexport interface RunState {\n /** Absent when a recorded holder cannot be verified on this host. */\n readonly phase?: 'running' | 'parked' | 'cancelling' | 'settled' | 'down'\n /** A persisted typed root failure; legacy failure messages do not establish a code. */\n readonly failureCode?: RuntimeFailureCause['code']\n readonly settle?: SupervisedResult<unknown>\n readonly cancelRequest?: RunCancelRequest\n /** Absent when holder liveness is unknown. This is advisory, never ownership authorization. */\n readonly holderLive?: boolean\n /** Latest explicit Runtime timestamp observed, as ISO UTC; never a filesystem mtime. */\n readonly lastActivityAt?: string\n}\n\n/** Compose maintained record readers. Terminal settlement outranks cancellation and parking;\n * a request remains cancelling until settlement. An unheld run with evidence is down.\n * No Runtime evidence (including a missing or empty directory) returns undefined. Reads are\n * advisory snapshots across independently published files, not a transaction or a resume gate.\n */\nexport async function readRunState(runDir: string): Promise<RunState | undefined> {\n const [settle, failure, parking, holder, journal] = await Promise.all([\n readSettleRecord(runDir),\n readFailureRecord(runDir),\n readRunParking(runDir),\n runDirectoryHolderIsLive(runDir),\n readSpawnJournal(runDir, { tailBytes: 65_536 }),\n ])\n const cancelRequest = readRunCancelRequest(runDir)\n if (\n !settle &&\n !failure &&\n !parking &&\n !holder.holder &&\n !cancelRequest &&\n journal.records.length === 0\n ) {\n return undefined\n }\n const holderLive = holder.unknown ? undefined : holder.live\n const phase = settle\n ? 'settled'\n : cancelRequest\n ? 'cancelling'\n : parking\n ? 'parked'\n : holderLive === true\n ? 'running'\n : holderLive === false\n ? 'down'\n : undefined\n const root = settle?.tree.nodes?.find((node) => node.id === settle.tree.root)\n const failureCode =\n (settle?.kind === 'no-winner' && settle.reason === 'driver-failed'\n ? settle.error?.failure?.code\n : undefined) ?? root?.failure?.code\n let latest: number | undefined\n const observe = (at: string | number | undefined): void => {\n const timestamp = at === undefined ? undefined : new Date(at).getTime()\n if (timestamp !== undefined && Number.isFinite(timestamp)) {\n latest = latest === undefined ? timestamp : Math.max(latest, timestamp)\n }\n }\n observe(failure?.at)\n observe(parking?.since)\n observe(cancelRequest?.at)\n observe(holder.holder?.startedAt)\n for (const record of journal.records)\n observe(record.kind === 'begin' ? record.at : record.event.at)\n for (const node of settle?.tree.nodes ?? []) {\n observe(node.spawnedAt)\n observe(node.settledAt)\n }\n const lastActivityAt = latest === undefined ? undefined : new Date(latest).toISOString()\n return {\n ...(phase === undefined ? {} : { phase }),\n ...(failureCode === undefined ? {} : { failureCode }),\n ...(settle === undefined ? {} : { settle }),\n ...(cancelRequest === undefined ? {} : { cancelRequest }),\n ...(holderLive === undefined ? {} : { holderLive }),\n ...(lastActivityAt === undefined ? {} : { lastActivityAt }),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+CA,eAAsB,iBACpB,QACA,UAAmC,CAAC,GACH;CACjC,MAAM,EAAE,OAAO,cAAc;CAC7B,IAAI,cAAc,KAAA,MAAc,CAAC,OAAO,cAAc,SAAS,KAAK,YAAY,IAC9E,MAAM,IAAI,WAAW,6DAA6D;CAEpF,MAAM,OAAO,KAAK,QAAQ,q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AY,CAAC,IAAI,EAAE,OAAO;EACzC,GAAI,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc;EACvD,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW;EACjD,GAAI,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe;CAC3D;AACF"}
|
|
1
|
+
{"version":3,"file":"run-state-tgQ-S9Ln.js","names":[],"sources":["../src/durable/spawn-journal/read.ts","../src/durable/run-state.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport type { BigIntStats } from 'node:fs'\nimport { type FileHandle, open, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { isRecord } from '@tangle-network/agent-core'\nimport type { NodeId, SpawnEvent } from '../../runtime/supervise/types'\nimport { isNoEntError, readCommittedJsonLines } from '../jsonl-file'\nimport { spawnJournalRecordEvents } from './record-events'\n\n/** Serializable checkpoint of a committed byte boundary, bound to one file and its bytes. */\nexport interface SpawnJournalCursor {\n readonly file: string\n readonly offset: number\n readonly boundary: string\n}\n\n/** Physical groups expand to event records; the owning tree is preserved for every event. */\nexport type SpawnJournalReadRecord =\n | { readonly kind: 'begin'; readonly root: NodeId; readonly at: string }\n | { readonly kind: 'event'; readonly root: NodeId; readonly event: SpawnEvent }\n\nexport interface SpawnJournalReadOptions {\n /** Read-only projections may skip malformed physical rows; execution readers stay strict. */\n readonly invalid?: 'throw' | 'skip'\n readonly after?: SpawnJournalCursor\n /** Initial opening-and-tail window, or an incremental page's byte budget. A crossing record\n * is read whole, so one large record can exceed this budget. Omit for complete history. */\n readonly tailBytes?: number\n}\n\nexport interface SpawnJournalReadResult {\n readonly records: ReadonlyArray<SpawnJournalReadRecord>\n /** Absent only when the journal does not exist. Treat as opaque and persist unchanged. */\n readonly cursor?: SpawnJournalCursor\n /** The supplied cursor no longer matches; this page starts over. */\n readonly reset: boolean\n /** An initial opening-and-tail window omitted records between its two windows. */\n readonly truncated: boolean\n /** Bytes after the committed cursor in this snapshot, including an incomplete final write. */\n readonly remainingBytes: number\n}\n\n/** Read a fixed journal prefix, with historical envelopes and framing owned by Runtime.\n * Missing journals return an empty page. Malformed committed records fail by default; incomplete final\n * writes remain unread for the next call. Cursors detect replacement, truncation and edits at\n * their sampled opening/boundary; they are not integrity proofs against arbitrary file edits.\n */\nexport async function readSpawnJournal(\n runDir: string,\n options: SpawnJournalReadOptions = {},\n): Promise<SpawnJournalReadResult> {\n const { after, tailBytes } = options\n if (tailBytes !== undefined && (!Number.isSafeInteger(tailBytes) || tailBytes < 1)) {\n throw new RangeError('readSpawnJournal: tailBytes must be a positive safe integer')\n }\n const path = join(runDir, 'spawn-journal.jsonl')\n let handle: FileHandle\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if (isNoEntError(error)) {\n return { records: [], reset: after !== undefined, truncated: false, remainingBytes: 0 }\n }\n throw error\n }\n try {\n const snapshot = await handle.stat({ bigint: true })\n if (!snapshot.isFile()) throw new Error(`${path}: expected a regular file`)\n const size = Number(snapshot.size)\n const file = identity(snapshot)\n const resumed =\n after !== undefined &&\n after.file === file &&\n Number.isSafeInteger(after.offset) &&\n after.offset >= 0 &&\n after.offset <= size &&\n after.boundary === (await boundary(handle, after.offset))\n let offset = resumed ? after.offset : 0\n const records: SpawnJournalReadRecord[] = []\n const read = async (start: number, end: number, firstOnly = false): Promise<void> => {\n offset = start\n for await (const record of readCommittedJsonLines<unknown>(path, {\n handle,\n start,\n end,\n strictUtf8: true,\n invalid: options.invalid,\n onCommit: (committed) => {\n offset = committed\n },\n })) {\n if (\n !isRecord(record) ||\n typeof record.root !== 'string' ||\n (record.kind === 'begin' && typeof record.at !== 'string')\n ) {\n if (options.invalid === 'skip') continue\n throw new Error(`${path}: spawn journal record has no root or begin timestamp`)\n }\n if (record.kind === 'begin') {\n records.push({ kind: 'begin', root: record.root, at: record.at as string })\n } else {\n const events = spawnJournalRecordEvents(record, options.invalid)\n if (\n events.some(\n (event) =>\n !isRecord(event) || typeof event.kind !== 'string' || typeof event.id !== 'string',\n )\n ) {\n if (options.invalid === 'skip') continue\n throw new Error(`${path}: spawn journal record has no event identity`)\n }\n for (const event of events) records.push({ kind: 'event', root: record.root, event })\n }\n if (firstOnly) break\n }\n }\n let truncated = false\n if (!resumed && tailBytes !== undefined && size > tailBytes) {\n await read(0, size, true)\n const openingEnd = offset\n const tailStart = await lineBoundary(handle, size - tailBytes, size, -1)\n truncated = tailStart > openingEnd\n await read(Math.max(openingEnd, tailStart), size)\n // A long torn tail must not hide the latest committed activity before it.\n if (offset === tailStart && tailStart > openingEnd) {\n const previous = await lineBoundary(handle, tailStart - 1, size, -1)\n truncated = previous > openingEnd\n await read(Math.max(openingEnd, previous), tailStart)\n }\n } else {\n const end =\n resumed && tailBytes !== undefined && size - offset > tailBytes\n ? await lineBoundary(handle, offset + tailBytes, size, 1)\n : size\n await read(offset, end)\n }\n if (identity(await stat(path, { bigint: true })) !== file || (await handle.stat()).size < size)\n throw new Error(`${path}: journal changed while reading its committed prefix`)\n return {\n records,\n cursor: { file, offset, boundary: await boundary(handle, offset) },\n reset: after !== undefined && !resumed,\n truncated,\n remainingBytes: size - offset,\n }\n } finally {\n await handle.close()\n }\n}\n\nfunction identity(info: BigIntStats): string {\n return `${info.dev}:${info.ino}:${info.birthtimeNs}`\n}\n\nasync function bytes(handle: FileHandle, start: number, length: number): Promise<Buffer> {\n const buffer = Buffer.alloc(length)\n const { bytesRead } = await handle.read(buffer, 0, length, start)\n if (bytesRead !== length) throw new Error('spawn journal changed while reading its boundary')\n return buffer\n}\n\nasync function boundary(handle: FileHandle, offset: number): Promise<string> {\n const length = Math.min(offset, 128)\n return createHash('sha256')\n .update(await bytes(handle, 0, length))\n .update(await bytes(handle, offset - length, length))\n .digest('hex')\n}\n\n/** Include the record crossing a tail window or incremental page boundary. */\nasync function lineBoundary(\n handle: FileHandle,\n position: number,\n size: number,\n direction: -1 | 1,\n): Promise<number> {\n while (position > 0 && position < size) {\n const start = direction === -1 ? Math.max(0, position - 65_536) : position\n const end = direction === -1 ? position : Math.min(size, position + 65_536)\n const part = await bytes(handle, start, end - start)\n const newline = direction === -1 ? part.lastIndexOf(10) : part.indexOf(10)\n if (newline !== -1) return start + newline + 1\n position = direction === -1 ? start : end\n }\n return position\n}\n","import type { RuntimeFailureCause } from '../runtime/failure-cause'\nimport { type RunCancelRequest, readRunCancelRequest } from '../runtime/supervise/run-cancellation'\nimport { readRunParking } from '../runtime/supervise/run-parking'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport { runDirectoryHolderIsLive } from './run-lock'\nimport { readFailureRecord, readSettleRecord } from './settle-record'\nimport { readSpawnJournal } from './spawn-journal/read'\n\n/** Runtime evidence only. Product-specific launch, checks and trace completeness belong to callers. */\nexport interface RunState {\n /** Absent when a recorded holder cannot be verified on this host. */\n readonly phase?: 'running' | 'parked' | 'cancelling' | 'settled' | 'down'\n /** A persisted typed root failure; legacy failure messages do not establish a code. */\n readonly failureCode?: RuntimeFailureCause['code']\n readonly settle?: SupervisedResult<unknown>\n readonly cancelRequest?: RunCancelRequest\n /** Absent when holder liveness is unknown. This is advisory, never ownership authorization. */\n readonly holderLive?: boolean\n /** Latest explicit Runtime timestamp observed, as ISO UTC; never a filesystem mtime. */\n readonly lastActivityAt?: string\n}\n\n/** Compose maintained record readers. Terminal settlement outranks cancellation and parking;\n * a request remains cancelling until settlement. An unheld run with evidence is down.\n * No Runtime evidence (including a missing or empty directory) returns undefined. Reads are\n * advisory snapshots across independently published files, not a transaction or a resume gate.\n */\nexport async function readRunState(runDir: string): Promise<RunState | undefined> {\n const [settle, failure, parking, holder, journal] = await Promise.all([\n readSettleRecord(runDir),\n readFailureRecord(runDir),\n readRunParking(runDir),\n runDirectoryHolderIsLive(runDir),\n readSpawnJournal(runDir, { tailBytes: 65_536 }),\n ])\n const cancelRequest = readRunCancelRequest(runDir)\n if (\n !settle &&\n !failure &&\n !parking &&\n !holder.holder &&\n !cancelRequest &&\n journal.records.length === 0\n ) {\n return undefined\n }\n const holderLive = holder.unknown ? undefined : holder.live\n const phase = settle\n ? 'settled'\n : cancelRequest\n ? 'cancelling'\n : parking\n ? 'parked'\n : holderLive === true\n ? 'running'\n : holderLive === false\n ? 'down'\n : undefined\n const root = settle?.tree.nodes?.find((node) => node.id === settle.tree.root)\n const failureCode =\n (settle?.kind === 'no-winner' && settle.reason === 'driver-failed'\n ? settle.error?.failure?.code\n : undefined) ?? root?.failure?.code\n let latest: number | undefined\n const observe = (at: string | number | undefined): void => {\n const timestamp = at === undefined ? undefined : new Date(at).getTime()\n if (timestamp !== undefined && Number.isFinite(timestamp)) {\n latest = latest === undefined ? timestamp : Math.max(latest, timestamp)\n }\n }\n observe(failure?.at)\n observe(parking?.since)\n observe(cancelRequest?.at)\n observe(holder.holder?.startedAt)\n for (const record of journal.records)\n observe(record.kind === 'begin' ? record.at : record.event.at)\n for (const node of settle?.tree.nodes ?? []) {\n observe(node.spawnedAt)\n observe(node.settledAt)\n }\n const lastActivityAt = latest === undefined ? undefined : new Date(latest).toISOString()\n return {\n ...(phase === undefined ? {} : { phase }),\n ...(failureCode === undefined ? {} : { failureCode }),\n ...(settle === undefined ? {} : { settle }),\n ...(cancelRequest === undefined ? {} : { cancelRequest }),\n ...(holderLive === undefined ? {} : { holderLive }),\n ...(lastActivityAt === undefined ? {} : { lastActivityAt }),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+CA,eAAsB,iBACpB,QACA,UAAmC,CAAC,GACH;CACjC,MAAM,EAAE,OAAO,cAAc;CAC7B,IAAI,cAAc,KAAA,MAAc,CAAC,OAAO,cAAc,SAAS,KAAK,YAAY,IAC9E,MAAM,IAAI,WAAW,6DAA6D;CAEpF,MAAM,OAAO,KAAK,QAAQ,qBAAqB;CAC/C,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,KAAK,MAAM,GAAG;CAC/B,SAAS,OAAO;EACd,IAAI,aAAa,KAAK,GACpB,OAAO;GAAE,SAAS,CAAC;GAAG,OAAO,UAAU,KAAA;GAAW,WAAW;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,IAAI,EAAE,eAAe;CAC3D;AACF"}
|
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
import { C as createExecutor, D as runAgentRounds, J as createWorktreeCliExecutor, O as assertBoxlessPromptOptions, P as defaultSelectWinner, V as routerBrain, _ as withDriverExecutor, _t as CheckUnavailableError, b as createExecutorRegistry, bt as mapExecutorResult, j as createSandboxLineage, k as readPromptOptions, n as createSupervisor, v as InMemoryResultBlobStore, xt as verdictFromJudgeScore, y as InMemorySpawnJournal, yt as gateOnDeliverable } from "./supervisor-
|
|
1
|
+
import { C as createExecutor, D as runAgentRounds, J as createWorktreeCliExecutor, O as assertBoxlessPromptOptions, P as defaultSelectWinner, V as routerBrain, _ as withDriverExecutor, _t as CheckUnavailableError, b as createExecutorRegistry, bt as mapExecutorResult, j as createSandboxLineage, k as readPromptOptions, n as createSupervisor, v as InMemoryResultBlobStore, xt as verdictFromJudgeScore, y as InMemorySpawnJournal, yt as gateOnDeliverable } from "./supervisor-CHgCAMjm.js";
|
|
2
2
|
import { M as contentAddress, Ot as recordValue, bt as notifySandboxEventObserver, gt as createSandboxTurnEventCollector, r as runtimeFailureCauseSchema } from "./failure-cause-DoCCGLDH.js";
|
|
3
|
-
import "./run-state-
|
|
4
|
-
import {
|
|
5
|
-
import "./result-blob-store-
|
|
6
|
-
import { E as validateFlowGraph, I as kernelPromptRegistry, b as coordinationControlToolNames, k as validateGraphTopology, m as runBrainLoop, t as supervise } from "./supervise-
|
|
3
|
+
import "./run-state-tgQ-S9Ln.js";
|
|
4
|
+
import { Gt as coordinationProfileToolPrefix, at as rollingDispatch, et as settledToIteration, hn as insideCursorNamespace, mr as readBoundHarnessSessions, ni as executableAgentSpecSnapshot, sr as harnessTranscriptArtifact, ti as executableAgentProfileSnapshot, z as isTraceAnalysisStore } from "./supervisor-accounting-CZ7i4cd5.js";
|
|
5
|
+
import "./result-blob-store-DfTcyQ05.js";
|
|
6
|
+
import { E as validateFlowGraph, I as kernelPromptRegistry, b as coordinationControlToolNames, k as validateGraphTopology, m as runBrainLoop, t as supervise } from "./supervise-DtVdvZpr.js";
|
|
7
7
|
import { T as zeroSpend, a as cloneSpend, c as errorMessage, d as isAbortError, f as isAsyncIterable, h as randomSuffix, i as chargedTokens, l as fnv1a32Hex, n as addSpend, p as mapWithConcurrency, u as hasCompleteCacheBreakdown, v as sleep, y as stringifySafe } from "./util-qsH5cC9S.js";
|
|
8
8
|
import { a as captureMaterializedWorkspace, b as sha256Bytes$1, m as canonicalCandidateDigest$1, v as immutableCandidateValue } from "./output-artifacts-AqkZ8lO2.js";
|
|
9
9
|
import { i as ConfigError, m as ValidationError, n as AnalystError, s as PlannerError } from "./errors-DG8yufqX.js";
|
|
10
|
-
import { c as runIsolatedCheck, l as createIsolatedCheckCpuSession } from "./graph-
|
|
10
|
+
import { c as runIsolatedCheck, l as createIsolatedCheckCpuSession } from "./graph-CwLg3LGC.js";
|
|
11
11
|
import { a as concreteProfileModel, c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, p as canonicalObservedModelParts, t as assertExecutableAgentProfile, y as harnessRunsAgent } from "./model-policy-DZnL8Yj9.js";
|
|
12
12
|
import { i as redactProtectedValue, r as redactProtectedReason } from "./protected-redaction-DilFZch5.js";
|
|
13
13
|
import { o as armDeadlineTimer } from "./deadline-CySmJ_0S.js";
|
|
14
|
-
import { D as runAgentic, E as refine, M as renderReport, N as profileChatClient, O as sample, j as observe, k as ObservationError, v as loadAuthoredStrategy, x as strategyAuthorContract, y as requestStrategySource } from "./structural-rollout-
|
|
15
|
-
import { _ as runAbortable, a as readCommittedJsonFile, c as withJsonlFileLock, l as appendCommittedJsonLine, o as readCommittedJsonLines, s as upsertCommittedJsonLine, t as isNoEntError } from "./jsonl-file-
|
|
14
|
+
import { D as runAgentic, E as refine, M as renderReport, N as profileChatClient, O as sample, j as observe, k as ObservationError, v as loadAuthoredStrategy, x as strategyAuthorContract, y as requestStrategySource } from "./structural-rollout-D8wufVJI.js";
|
|
15
|
+
import { _ as runAbortable, a as readCommittedJsonFile, c as withJsonlFileLock, l as appendCommittedJsonLine, o as readCommittedJsonLines, s as upsertCommittedJsonLine, t as isNoEntError } from "./jsonl-file-DyzefaZ6.js";
|
|
16
16
|
import { n as detachedSnapshot, t as detachedFrozen } from "./snapshot-BKI_w3JD.js";
|
|
17
17
|
import { y as markPutStreamVerified } from "./workspace-streams-C7PGLAUd.js";
|
|
18
|
-
import "./provision-supervisor-
|
|
18
|
+
import "./provision-supervisor-D8N0l2DM.js";
|
|
19
19
|
import { i as notifyRuntimeHookEvent } from "./runtime-hooks-CsW2pfFk.js";
|
|
20
|
-
import { a as reconcileInterruptedSearchCalls, c as searchExecutor, r as dedicatedLane, x as runtimeShipDecision } from "./search-executor-
|
|
21
|
-
import "./delegate-
|
|
22
|
-
import "./continuation-
|
|
23
|
-
import { S as graphRouteWhenSchema, _ as compileGraphParameters, a as graphRegistry, d as recordGraphRun, g as bindGraphParameters, h as assertGraphTriggerBindings, i as graphFromStored, j as assertJsonData, l as lookupGraph, m as taskShapeDigest, o as graphRunsFor, r as graphDigest, t as digestOfGraph, v as graphTriggerBindingsSchema, x as graphFileSchema, y as graphCheckNodeSchema } from "./graph-registry-
|
|
24
|
-
import { d as foldCoordinationRecords } from "./supervise-identity-
|
|
25
|
-
import { p as createInMemoryRunContext, s as downMessageRefusalReasons } from "./driver-control-acknowledgers-
|
|
26
|
-
import {
|
|
27
|
-
import "./run-cancellation-
|
|
20
|
+
import { a as reconcileInterruptedSearchCalls, c as searchExecutor, r as dedicatedLane, x as runtimeShipDecision } from "./search-executor-Uco2_KTB.js";
|
|
21
|
+
import "./delegate-dhNeiaH_.js";
|
|
22
|
+
import "./continuation-CL4B1Y4M.js";
|
|
23
|
+
import { S as graphRouteWhenSchema, _ as compileGraphParameters, a as graphRegistry, d as recordGraphRun, g as bindGraphParameters, h as assertGraphTriggerBindings, i as graphFromStored, j as assertJsonData, l as lookupGraph, m as taskShapeDigest, o as graphRunsFor, r as graphDigest, t as digestOfGraph, v as graphTriggerBindingsSchema, x as graphFileSchema, y as graphCheckNodeSchema } from "./graph-registry-DtGd03zk.js";
|
|
24
|
+
import { d as foldCoordinationRecords } from "./supervise-identity-S5XwgaF3.js";
|
|
25
|
+
import { p as createInMemoryRunContext, s as downMessageRefusalReasons } from "./driver-control-acknowledgers-C6GaGBf_.js";
|
|
26
|
+
import { d as writeAtomicDurableFile } from "./durable-file-lXnojyij.js";
|
|
27
|
+
import "./run-cancellation-D3qc9wAD.js";
|
|
28
28
|
import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, sameAgentRunControlRef, sha256Bytes, sha256DigestSchema, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
|
|
29
29
|
import { CODING_HARNESSES, DEFAULT_TRACE_ANALYST_KINDS, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, createTraceAnalyst, expandProfileAxes, makeFinding as makeFinding$1, meanConfidenceInterval, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
|
|
30
30
|
import { createAgentRunOutcomeTracker } from "@tangle-network/sandbox/runtime";
|
|
@@ -7083,7 +7083,7 @@ function graphDesignerExtraTools(env) {
|
|
|
7083
7083
|
})();
|
|
7084
7084
|
if (name === "designer_history") return (async () => {
|
|
7085
7085
|
const args = asRecord(raw ?? {}, "designer_history");
|
|
7086
|
-
const { listGraphRuns } = await import("./graph-registry-
|
|
7086
|
+
const { listGraphRuns } = await import("./graph-registry-Bs6mGKou.js");
|
|
7087
7087
|
const all = await listGraphRuns(registry);
|
|
7088
7088
|
return { runs: (args.taskShape === void 0 ? all : all.filter((row) => row.taskDigest === taskShapeDigest(asRecord(args.taskShape, "designer_history.taskShape")))).map(summarize) };
|
|
7089
7089
|
})();
|
|
@@ -7094,7 +7094,7 @@ function graphDesignerExtraTools(env) {
|
|
|
7094
7094
|
if (mode === "replay") {
|
|
7095
7095
|
const digest = args.graphDigest;
|
|
7096
7096
|
if (typeof digest !== "string" || digest.length === 0) throw new ValidationError("designer_run_graph: replay mode requires graphDigest from lookup");
|
|
7097
|
-
const { loadGraph } = await import("./graph-registry-
|
|
7097
|
+
const { loadGraph } = await import("./graph-registry-Bs6mGKou.js");
|
|
7098
7098
|
const stored = await loadGraph(registry, digest);
|
|
7099
7099
|
if (!stored) throw new ValidationError(`designer_run_graph: no stored graph ${digest.slice(0, 12)} — re-lookup`);
|
|
7100
7100
|
const graph = env.bindCheck(graphFromStored(stored, () => {
|
|
@@ -9984,4 +9984,4 @@ function tail(s) {
|
|
|
9984
9984
|
}
|
|
9985
9985
|
export { strategyTournament as $, completionAuthorizes as $t, searchPresets as A, readHarnessTranscriptSessions as At, graphFromSessionFacts as B, resolveMcpServerLaunch as Bt, withUntrackedArtifacts as C, createScopeAnalyst as Ct, SEARCH_SPEC_CORRELATION_KEY as D, inProcessSandboxClient as Dt, createFencedSqlRunContext as E, observationFromRegistry as Et, loadProfile as F, materializeLocalMcp as Ft, readGraphStrings as G, loopDispatch as Gt, graphWorkspace as H, secretEnvOfMcpServer as Ht, pickBestProfile as I, createMcpEnvironment as It, graphDesignerExtraTools as J, checkProgramDigest as Jt, setGraphProfile as K, superviseDispatch as Kt, profileRegistry as L, sanitizeMcpToolSchema as Lt, connectRemoteSupervisor as M, resolveSandboxClient as Mt, connectRemoteSupervisorControl as N, McpSpawnFault as Nt, assertSearchSpec as O, HarvestError as Ot, bestProfileFor as P, connectStdioMcp as Pt, runStrategyEvolution as Q, readDeclaredCheck as Qt, profileRunsForName as R, envKeyProvider as Rt, copyUntrackedIntoClone as S, buildSteerContext as St, validateStoredGraph as T, measurePairedCommands as Tt, loadGraphFile as U, inlineSandboxClient as Ut, GraphFileResolutionError as V, resolveSecretEnv as Vt, readGraphProfile as W, loopCampaignDispatch as Wt, chatWorkerSeam as X, declaredCheckDigest as Xt, chatTransportExecutor as Y, declaredCheckDeliverable as Yt, createChatSessionStore as Z, declaredCheckJudge as Zt, NOTE_MAX_CHARS as _, pipeline as _t, localShell as a, renderLeaderboardHtml as an, createPrivateCasArtifactPort as at, composeWorkerEvidence as b, widen as bt, createVerifierEnvironment as c, renderPairwiseMarkdown as cn, definePersona as ct, harvestSurfaceDiffs as d, InMemoryCorpus as dt, deterministicCompletion as en, SandboxRunAbortError as et, analystsFromRegistry as f, renderCorpusToInstructions as ft, EVIDENCE_MAX_CHARS as g, panel as gt, runCoderChecks as h, loopUntil as ht, jjWorkspace as i, pairwiseSignificance as in, runBenchmark as it, searchSpecDigest as j, defineLeaderboard as jt, compileSearchSpec as k, harvestCorpus as kt, boxSurfaceReader as l, SqlRunOwnershipError as ln, runPersonified as lt, worktreeFanout as m, flatWidenGate as mt, makeFinding$1 as n, stopSentinel as nn, createS3PrivateCasStore as nt, runInWorkspace as o, renderLeaderboardMarkdown as on, equalKOnCost as ot, failuresAnalyst as p, fanout as pt, setGraphStrings as q, assertDeclaredCheck as qt, gitWorkspace as r, leaderboard as rn, printBenchmarkReport as rt, createWaterfallCollector as s, renderLeaderboardSvg as sn, trajectoryReport as st, computeFindingId$1 as t, sentinelCompletion as tn, openSandboxRun as tt, fsSurfaceReader as u, openSqlRunStore as un, FileCorpus as ut, VERIFY_TAIL_CHARS as v, selectValidWinner as vt, analyzeTrace as w, registryScopeAnalyst as wt, settledWorkerOut as x, assertTraceDerivedFindings as xt, closingWorkerNote as y, verify as yt, recordProfileRun as z, mcpSecretEnvMetadataKey as zt };
|
|
9986
9986
|
|
|
9987
|
-
//# sourceMappingURL=runtime-
|
|
9987
|
+
//# sourceMappingURL=runtime-BTECV05R.js.map
|