@tangle-network/agent-runtime 10.0.19 → 10.0.20
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-DLnZJab0.js → activation-5TrUzeFd.js} +2 -2
- package/dist/{activation-DLnZJab0.js.map → activation-5TrUzeFd.js.map} +1 -1
- package/dist/{activation-BudDVuT6.d.ts → activation-B0arteLE.d.ts} +2 -2
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +4 -4
- package/dist/{delegate-9b8qGlXp.js → delegate-DnW85VY0.js} +2 -2
- package/dist/{delegate-9b8qGlXp.js.map → delegate-DnW85VY0.js.map} +1 -1
- package/dist/{driver-control-acknowledgers-b5MsXxR5.js → driver-control-acknowledgers-vgmZqgZ-.js} +8 -8
- package/dist/{driver-control-acknowledgers-b5MsXxR5.js.map → driver-control-acknowledgers-vgmZqgZ-.js.map} +1 -1
- package/dist/durable-writer-thread.js +4 -4
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +13 -14
- package/dist/durable.js.map +1 -1
- package/dist/{graph--n31XKWJ.js → graph-DHNPE7kw.js} +8 -8
- package/dist/{graph--n31XKWJ.js.map → graph-DHNPE7kw.js.map} +1 -1
- package/dist/{graph-registry-aMRd94PD.js → graph-registry-DI8o9iCB.js} +1 -1
- package/dist/{graph-registry-SgsCxCTZ.js → graph-registry-qyaNDATw.js} +2 -3
- package/dist/{graph-registry-SgsCxCTZ.js.map → graph-registry-qyaNDATw.js.map} +1 -1
- package/dist/{improve-sIZhpXqE.js → improve-BLFqeD3X.js} +6 -6
- package/dist/{improve-sIZhpXqE.js.map → improve-BLFqeD3X.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +10 -10
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +4 -4
- package/dist/{continuation-CDdjAkpk.js → jsonl-file-B2ESMrTh.js} +396 -4
- package/dist/jsonl-file-B2ESMrTh.js.map +1 -0
- package/dist/kernel.d.ts +1 -1
- package/dist/kernel.js +17 -18
- package/dist/{loop-runner-Bn7lFuQZ.d.ts → loop-runner-BFC781pC.d.ts} +2 -2
- package/dist/{loop-runner-Dt7I2oMa.js → loop-runner-CITvo-q1.js} +2 -2
- package/dist/{loop-runner-Dt7I2oMa.js.map → loop-runner-CITvo-q1.js.map} +1 -1
- 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 +6 -6
- package/dist/mcp/memory-bin.js +1 -1
- package/dist/profiles.d.ts +1 -1
- package/dist/{provision-supervisor-DfDAdtqb.js → provision-supervisor-CyUbiMz8.js} +6 -6
- package/dist/{provision-supervisor-DfDAdtqb.js.map → provision-supervisor-CyUbiMz8.js.map} +1 -1
- package/dist/{result-blob-store-Dke805sV.js → result-blob-store-CJjp44Mz.js} +3 -3
- package/dist/{result-blob-store-Dke805sV.js.map → result-blob-store-CJjp44Mz.js.map} +1 -1
- package/dist/{run-cancellation-B0SgcidY.js → run-cancellation-BNBmsY3a.js} +2 -2
- package/dist/{run-cancellation-B0SgcidY.js.map → run-cancellation-BNBmsY3a.js.map} +1 -1
- package/dist/{run-lock-BOg7BaXF.js → run-lock-Dcr79Wql.js} +2 -2
- package/dist/{run-lock-BOg7BaXF.js.map → run-lock-Dcr79Wql.js.map} +1 -1
- package/dist/{run-reopen-B7TN2aQQ.js → run-reopen-Cr2SHmYa.js} +6 -6
- package/dist/{run-reopen-B7TN2aQQ.js.map → run-reopen-Cr2SHmYa.js.map} +1 -1
- package/dist/{run-state-BNBUy2uK.js → run-state-AYXAe_lX.js} +7 -7
- package/dist/{run-state-BNBUy2uK.js.map → run-state-AYXAe_lX.js.map} +1 -1
- package/dist/{runtime-DXeWY00j.js → runtime-D-FpUoQg.js} +19 -20
- package/dist/{runtime-DXeWY00j.js.map → runtime-D-FpUoQg.js.map} +1 -1
- package/dist/{search-executor-BoQHI2Tz.js → search-executor-BHfb4p6C.js} +4 -4
- package/dist/{search-executor-BoQHI2Tz.js.map → search-executor-BHfb4p6C.js.map} +1 -1
- package/dist/{server-Xkgobp5y.js → server-CAXzZHVz.js} +4 -4
- package/dist/{server-Xkgobp5y.js.map → server-CAXzZHVz.js.map} +1 -1
- package/dist/{settle-record-B5OpVDnC.js → settle-record-BlIw2MU1.js} +3 -3
- package/dist/{settle-record-B5OpVDnC.js.map → settle-record-BlIw2MU1.js.map} +1 -1
- package/dist/{structural-rollout-BSF5tzUm.js → structural-rollout-BVuf5hFl.js} +4 -4
- package/dist/{structural-rollout-BSF5tzUm.js.map → structural-rollout-BVuf5hFl.js.map} +1 -1
- package/dist/{supervise-Drc1Pj1d.js → supervise-Ci8wiyla.js} +13 -13
- package/dist/supervise-Ci8wiyla.js.map +1 -0
- package/dist/{supervise-identity-Cz-Hzg9s.js → supervise-identity-CtxWEk1I.js} +3 -3
- package/dist/{supervise-identity-Cz-Hzg9s.js.map → supervise-identity-CtxWEk1I.js.map} +1 -1
- package/dist/{supervision-discovery-DdRd1lsz.js → supervision-discovery-DKxqbnHf.js} +4 -4
- package/dist/{supervision-discovery-DdRd1lsz.js.map → supervision-discovery-DKxqbnHf.js.map} +1 -1
- package/dist/{supervisor-CwUD7dsm.js → supervisor-KcnH2hC4.js} +10 -592
- package/dist/supervisor-KcnH2hC4.js.map +1 -0
- package/dist/{supervisor-accounting-CPDPG8mH.js → supervisor-accounting-DlDUl58C.js} +600 -8
- package/dist/supervisor-accounting-DlDUl58C.js.map +1 -0
- package/dist/{supervisor-root-contract-Uw2q3nvG.js → supervisor-root-contract-BCbu1A4n.js} +3 -3
- package/dist/{supervisor-root-contract-Uw2q3nvG.js.map → supervisor-root-contract-BCbu1A4n.js.map} +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +11 -11
- package/dist/{failure-cause-C96rzF-d.js → tool-server-n4XYpCok.js} +181 -2
- package/dist/tool-server-n4XYpCok.js.map +1 -0
- package/dist/{top-web-5ThvdyD0.js → top-web-B-sHmI3g.js} +8 -8
- package/dist/{top-web-5ThvdyD0.js.map → top-web-B-sHmI3g.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-BLhsL4qy.d.ts → types-YXZL7Wxi.d.ts} +5 -3
- package/package.json +1 -1
- package/dist/continuation-CDdjAkpk.js.map +0 -1
- package/dist/failure-cause-C96rzF-d.js.map +0 -1
- package/dist/jsonl-file-B8xfYz9M.js +0 -397
- package/dist/jsonl-file-B8xfYz9M.js.map +0 -1
- package/dist/supervise-Drc1Pj1d.js.map +0 -1
- package/dist/supervisor-CwUD7dsm.js.map +0 -1
- package/dist/supervisor-accounting-CPDPG8mH.js.map +0 -1
- package/dist/tool-server-BhsyVDj2.js +0 -174
- package/dist/tool-server-BhsyVDj2.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-cancellation-B0SgcidY.js","names":[],"sources":["../src/runtime/supervise/run-cancellation.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, watch } from 'node:fs'\nimport { join } from 'node:path'\nimport { runFencedAlways } from '../../durable/durable-writer'\nimport type { RetainedRunEffect } from '../retained-run-types'\nimport {\n assertNoSymlinkDescendant,\n publishExclusiveFenced,\n writeAtomicDurableFile,\n writeAtomicDurableFileAsync,\n} from './durable-file'\nimport {\n appendWorkerControlEvent,\n appendWorkerControlEventAsync,\n workerCancellationsDir,\n} from './run-layout'\n\ntype CancellationPath = 'observer' | 'turn-boundary' | 'fallback'\n\n/** Apply a durable request through the run's existing abort controller. */\nexport function applyRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n now: () => string,\n path: CancellationPath = 'turn-boundary',\n): RunCancellation | undefined {\n const applied = abortForRequest(dir, abortRun, now, path)\n if (applied?.fresh) writeRunCancellation(dir, applied.record)\n return applied?.record\n}\n\n/**\n * `applyRunCancellation` without blocking the calling thread on the disk: the abort is issued at\n * once, and the `cancel_requested` record reaches disk on the durable writer under the run's claim.\n */\nexport async function applyRunCancellationAsync(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n now: () => string,\n path: CancellationPath = 'turn-boundary',\n): Promise<RunCancellation | undefined> {\n const applied = abortForRequest(dir, abortRun, now, path)\n if (applied?.fresh) await writeRunCancellationAsync(dir, applied.record)\n return applied?.record\n}\n\n/** Abort for the pending request, and the record it owes: the standing one, or a fresh one to write. */\nfunction abortForRequest(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n now: () => string,\n path: CancellationPath,\n): { readonly record: RunCancellation; readonly fresh: boolean } | undefined {\n const request = readRunCancelRequest(dir)\n if (request === undefined) return undefined\n const prior = readRunCancellation(dir, request.operationId)\n // A request acknowledged only as `cancel_requested` is still owed by this run: the process\n // that issued the abort died before the run settled. Abort again; the record stands.\n if (prior?.effect === 'cancel_requested') {\n abortRun(request.reason ?? 'run cancel requested', request)\n }\n if (prior !== undefined) return { record: prior, fresh: false }\n abortRun(request.reason ?? 'run cancel requested', request)\n const observedAt = now()\n const appliedAfterMs = Math.max(0, Date.parse(observedAt) - Date.parse(request.at))\n const record: RunCancellation = {\n operationId: request.operationId,\n effect: 'cancel_requested',\n path,\n appliedAfterMs,\n ...(request.deadlineMs === undefined\n ? {}\n : { deadlineExceeded: appliedAfterMs > request.deadlineMs }),\n requestedAt: request.at,\n observedAt,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'root abort issued to the whole run; termination not yet proven',\n }\n return { record, fresh: true }\n}\n\n/** External drivers may remain silent indefinitely, so turn boundaries cannot observe control. */\nexport function watchRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n createWatch: typeof watch = watch,\n) {\n mkdirSync(workerCancellationsDir(dir), { recursive: true })\n let active = true\n let failure: unknown\n // One observer aborts its run once: a request this process already applied, or one a dead\n // process acknowledged, is not re-issued on every poll.\n let aborted = false\n const abortOnce = (reason: string, request?: RunCancelRequest): void => {\n if (aborted) return\n aborted = true\n abortRun(reason, request)\n }\n // One application at a time. The abort is immediate; its record goes to the durable writer, so a\n // saturated disk delays the record, never this event loop. A poll that finds one in flight skips.\n let inFlight: Promise<void> | undefined\n const apply = (path: 'observer' | 'fallback'): Promise<void> => {\n if (failure !== undefined) return Promise.reject(failure)\n if (!active) return Promise.resolve()\n const applying = applyRunCancellationAsync(\n dir,\n abortOnce,\n () => new Date().toISOString(),\n path,\n ).then(() => undefined)\n const settled = applying.then(\n () => {\n if (inFlight === settled) inFlight = undefined\n },\n (error: unknown) => {\n // Kept even after close, so the settle path's check() throws it instead of reading no record.\n failure ??= error\n if (inFlight === settled) inFlight = undefined\n },\n )\n inFlight = settled\n return applying\n }\n // A caller's check waits for the application in flight, so a closed observer's last record lands\n // before the run's settle record is written, and a failure it met is thrown here.\n const check = async (path: 'observer' | 'fallback' = 'observer'): Promise<void> => {\n while (inFlight !== undefined) await inFlight\n await apply(path)\n }\n const fail = (error: unknown): void => {\n if (!active) return\n failure = error\n abortRun(`durable run cancellation observer failed: ${String(error)}`)\n }\n const poll = (path: 'observer' | 'fallback'): void => {\n if (inFlight !== undefined) return\n apply(path).catch(fail)\n }\n // The watcher is an optimization over the poll loop below (instant pickup instead of ≤100 ms).\n // Creating it can fail for reasons that say NOTHING about this run: the host's inotify budget is\n // exhausted (EMFILE — a shared box with many agents held ~110 of the 128 default user instances\n // when this was measured), or the kernel caps watches (ENOSPC). Degrading to poll-only keeps\n // every durable behavior; failing the run would make a neighboring process's resource use kill\n // runs that never touched the limit. Any other creation error still fails loudly.\n let watcher: ReturnType<typeof watch> | undefined\n try {\n watcher = createWatch(workerCancellationsDir(dir), (_event, filename) => {\n if (!active || (filename !== null && filename !== 'run.request.json')) return\n poll('observer')\n })\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'EMFILE' && code !== 'ENOSPC') throw error\n }\n watcher?.on('error', fail)\n // Filesystem notifications are advisory. Scan the same durable inbox when one is dropped —\n // and carry the whole observer alone whenever the watcher above could not be created.\n const fallback = setInterval(() => poll('fallback'), 100)\n fallback.unref()\n return {\n check,\n close(): void {\n active = false\n watcher?.close()\n clearInterval(fallback)\n },\n }\n}\n\n/** One durable run-scoped cancel request: cancel the WHOLE run, not one worker. */\nexport interface RunCancelRequest {\n /** Caller-minted stable operation identifier — the idempotency key of the whole operation. */\n readonly operationId: string\n /** ISO timestamp of the write. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** Requested observation target, measured by the acknowledgement's deadlineExceeded field.\n * The observer always cascades eagerly. This does not guarantee scheduler latency or cleanup. */\n readonly deadlineMs?: number\n /** Who stops the run. `cancelRun` requires it on every new request; it is optional here only\n * so a request written before that rule still reads. The settle record carries it. */\n readonly operator?: string\n readonly reason?: string\n}\n\n/**\n * The durable acknowledgement state for the run-scoped cancel operation, keyed by `operationId`.\n * The runtime is the ONLY writer; {@link cancelRun} only reads it.\n *\n * `effect` is the same {@link RetainedRunEffect} vocabulary the worker-scoped and retained-run\n * paths use, so the runtime has one spelling of the four cancellation states:\n * - `'unknown'` — no runtime has answered yet. Never a success.\n * - `'cancel_requested'` — the root manager issued the run's cascading abort; the run's terminal\n * state is not yet observed.\n * - `'cancelled'` — the run reached its terminal cancelled state with confirmed teardown.\n * - `'not_live'` — the run was not live to cancel: it settled on its own despite the\n * request, or it ended before the request was applied.\n */\nexport interface RunCancellation {\n /** Runtime path that issued the cascade. */\n readonly path?: 'observer' | 'turn-boundary' | 'fallback'\n /** Runtime clock elapsed between request timestamp and cascade application. */\n readonly appliedAfterMs?: number\n /** Whether application exceeded the requested deadlineMs; absent when no target was requested. */\n readonly deadlineExceeded?: boolean\n readonly operationId: string\n readonly effect: RetainedRunEffect\n /** ISO timestamp of the original request. */\n readonly requestedAt: string\n /** ISO timestamp of the runtime's most recent observation of this operation. */\n readonly observedAt: string\n /** The caller's reason, carried verbatim from the request. */\n readonly reason?: string\n /** The caller's operator identity, carried verbatim from the request. */\n readonly operator?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\n}\n\n/** The run-scoped cancel request file of one run — one {@link RunCancelRequest}. */\nexport function runCancelRequestFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.request.json')\n}\n\n/** The run-scoped acknowledgement file of one run — one {@link RunCancellation}. */\nexport function runCancellationFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.json')\n}\n\n/** Read the run-scoped cancel request, or `undefined` when none was written. */\nexport function readRunCancelRequest(eventDir: string): RunCancelRequest | undefined {\n const dir = workerCancellationsDir(eventDir)\n const file = runCancelRequestFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n assertNoSymlinkDescendant(eventDir, file, 'run cancel request')\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<RunCancelRequest>\n if (!isRunCancelRequest(parsed)) {\n throw new Error(`run cancel request '${file}' is not a complete RunCancelRequest`)\n }\n return parsed\n}\n\n/**\n * Read the acknowledgement for the run-scoped cancel operation. `undefined` when the runtime has\n * not answered. A record holding a DIFFERENT `operationId` belongs to another operation on the\n * same run — fail loud rather than answer for it.\n */\nexport function readRunCancellation(\n eventDir: string,\n operationId: string,\n): RunCancellation | undefined {\n const dir = workerCancellationsDir(eventDir)\n const file = runCancellationFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n assertNoSymlinkDescendant(eventDir, file, 'run cancel acknowledgement')\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as RunCancellation\n if (parsed.operationId !== operationId) {\n throw new Error(\n `run cancel acknowledgement '${file}' holds operation '${parsed.operationId}', not ` +\n `'${operationId}' — one run carries one run-scoped cancel operation`,\n )\n }\n return parsed\n}\n\n/**\n * Durably write the run-scoped acknowledgement. The shared writer fsyncs the file and containing\n * directory, so a concurrent reader sees the prior complete record or the new complete record.\n *\n * @internal The runtime is the only intended writer; clients read via {@link readRunCancellation}\n * or {@link cancelRun}.\n */\nexport function writeRunCancellation(eventDir: string, record: RunCancellation): void {\n writeAtomicDurableFile(runCancellationTarget(eventDir), recordText(record), { mode: 0o600 })\n}\n\n/** `writeRunCancellation` without blocking the calling thread on the disk under a run claim. @internal */\nexport function writeRunCancellationAsync(\n eventDir: string,\n record: RunCancellation,\n): Promise<void> {\n return writeAtomicDurableFileAsync(runCancellationTarget(eventDir), recordText(record), {\n mode: 0o600,\n })\n}\n\nconst recordText = (record: RunCancellation | RunCancelRequest): string =>\n `${JSON.stringify(record, null, 2)}\\n`\n\n/** The acknowledgement file, its directory made and every path checked for symlinks. */\nfunction runCancellationTarget(eventDir: string): string {\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n const file = runCancellationFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'run cancel acknowledgement')\n return file\n}\n\n/**\n * Request the cancellation of the WHOLE run, idempotently, and return the operation's current\n * durable state.\n *\n * The run-scoped twin of {@link cancelWorker}: write the request into the run's cancellation\n * directory, where the run's own root manager applies it — aborting the root through the one\n * cascade controller the run already has, so every live worker comes down with it. This function\n * never applies the cancellation itself; writing a request file is not an acknowledgement.\n *\n * Idempotency is a lookup: when an acknowledgement for `operationId` already exists it is returned\n * AS-IS and nothing is written. A retry that changes the source, reason, deadline, or operator\n * fails closed. A request the runtime has not answered yet returns `effect: 'unknown'` (never a\n * success); call again with the same `operationId` — or {@link readRunCancellation} — to read the\n * acknowledged result after a reconnect.\n *\n * A run carries ONE run-scoped operation: a second request under a different `operationId` throws\n * rather than silently replacing the pending one, because both would claim the same single abort.\n * Reopening a settled run (`supervisePursuit`'s `reopen`) moves that operation aside.\n *\n * A NEW request must name its `operator`, so every stop says who made it. A replay of a request\n * or acknowledgement written before that rule is answered as it was.\n */\nexport function cancelRun(\n eventDir: string,\n operationId: string,\n // Inline, as published through 10.0.5: the archive admission reads a named type here as a new\n // shape, which would make this patch a major.\n options: {\n readonly reason?: string\n readonly source?: string\n readonly deadlineMs?: number\n readonly operator?: string\n } = {},\n): RunCancellation {\n const admission = admitRunCancel(eventDir, operationId, options)\n if ('answer' in admission) return admission.answer\n if (admission.file !== undefined) {\n writeAtomicDurableFile(admission.file, recordText(admission.request), { mode: 0o600 })\n appendWorkerControlEvent(eventDir, 'run', admission.event)\n }\n return queuedRunCancellation(admission.request)\n}\n\n/**\n * Request the cancellation of the whole run like {@link cancelRun}, without blocking the calling\n * thread on the disk. The request file is published by the durable writer whether or not the\n * caller holds a run claim (a coordinator outside the run holds none), so an event loop that stops\n * runs keeps running while the file and its directory reach disk. Same admission, replay and\n * conflict rules.\n * @stable\n */\nexport async function cancelRunAsync(\n eventDir: string,\n operationId: string,\n options: CancelRunOptions = {},\n): Promise<RunCancellation> {\n const admission = admitRunCancel(eventDir, operationId, options)\n if ('answer' in admission) return admission.answer\n if (admission.file !== undefined) {\n // Published only if no request is there yet: an overlapping call admitted against the same empty\n // inbox loses here, and is admitted again against the winner, which it replays or conflicts with.\n const published = await runFencedAlways(\n 'publishExclusiveDurableFile',\n publishExclusiveFenced,\n admission.file,\n recordText(admission.request),\n { mode: 0o600 },\n )\n if (!published) return cancelRunAsync(eventDir, operationId, options)\n await appendWorkerControlEventAsync(eventDir, 'run', admission.event)\n }\n return queuedRunCancellation(admission.request)\n}\n\n/** Options of {@link cancelRun} and {@link cancelRunAsync}. */\nexport interface CancelRunOptions {\n readonly reason?: string\n readonly source?: string\n readonly deadlineMs?: number\n readonly operator?: string\n}\n\n/**\n * The admission of one run cancel: the standing acknowledgement, or the request to answer for,\n * with the file and control event still to write when it is new.\n */\nfunction admitRunCancel(\n eventDir: string,\n operationId: string,\n options: CancelRunOptions,\n):\n | { readonly answer: RunCancellation }\n | {\n readonly request: RunCancelRequest\n readonly file?: string\n readonly event: Record<string, unknown>\n } {\n if (\n options.deadlineMs !== undefined &&\n (!Number.isFinite(options.deadlineMs) || options.deadlineMs < 0)\n ) {\n throw new Error('cancelRun: deadlineMs must be a finite nonnegative number')\n }\n const opId = operationId.trim()\n if (!opId) throw new Error('cancelRun: operationId is empty')\n const pending = readRunCancelRequest(eventDir)\n if (pending !== undefined && pending.operationId !== opId) {\n throw new Error(\n `cancelRun: run cancel '${pending.operationId}' is already pending for this run; ` +\n `read it with readRunCancellation instead of issuing '${opId}'`,\n )\n }\n const candidate = {\n operationId: opId,\n source: options.source ?? 'human',\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n }\n if (pending !== undefined) assertSameRunCancelRequest(pending, candidate)\n const acknowledged = readRunCancellation(eventDir, opId)\n if (acknowledged !== undefined) {\n if (pending === undefined && options.source !== undefined) {\n throw new Error(\n `cancelRun: operation '${opId}' cannot verify source without its admitted request`,\n )\n }\n assertRunCancellationMatchesCandidate(acknowledged, candidate)\n return { answer: acknowledged }\n }\n // A new request names who stops the run. A replay of a request written before this rule keeps\n // its absent operator: it was admitted above against the file it replays.\n if (pending === undefined && (options.operator === undefined || options.operator.trim() === '')) {\n throw new Error('cancelRun: operator is required; name who stops the run')\n }\n const source = options.source ?? 'human'\n const request: RunCancelRequest = pending ?? {\n operationId: opId,\n at: new Date().toISOString(),\n source,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n }\n const event = {\n kind: 'run-cancel-request',\n operationId: opId,\n source,\n queued: true,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n }\n if (pending !== undefined) return { request, event }\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n const file = runCancelRequestFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'run cancel request')\n return { request, file, event }\n}\n\n/** The answer to a request no runtime has acknowledged yet. */\nfunction queuedRunCancellation(request: RunCancelRequest): RunCancellation {\n return {\n operationId: request.operationId,\n effect: 'unknown',\n requestedAt: request.at,\n observedAt: request.at,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n }\n}\n\ntype RunCancelRequestCandidate = Omit<RunCancelRequest, 'at'>\n\nfunction assertSameRunCancelRequest(\n existing: RunCancelRequest,\n candidate: RunCancelRequestCandidate,\n): void {\n if (existing.operationId !== candidate.operationId) {\n throw new Error(`cancelRun: operation '${candidate.operationId}' has an id collision`)\n }\n if (existing.source !== candidate.source) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(source '${existing.source}' != '${candidate.source}')`,\n )\n }\n if (existing.deadlineMs !== candidate.deadlineMs) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request (deadlineMs differs)`,\n )\n }\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(reason differs)`,\n )\n }\n if (existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\n )\n }\n}\n\nfunction assertRunCancellationMatchesCandidate(\n existing: RunCancellation,\n candidate: RunCancelRequestCandidate,\n): void {\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(reason differs)`,\n )\n }\n // An acknowledgement written before acknowledgements carried the operator (0.251.0) names none\n // even when its admitted request does. The request comparator has already held the candidate\n // to that request, so a legacy record matches any candidate operator; a record that names one\n // must name the same one.\n if (existing.operator !== undefined && existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\n )\n }\n}\n\nfunction isRunCancelRequest(value: Partial<RunCancelRequest>): value is RunCancelRequest {\n return (\n typeof value.operationId === 'string' &&\n value.operationId.length > 0 &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n (value.deadlineMs === undefined ||\n (Number.isFinite(value.deadlineMs) && value.deadlineMs >= 0)) &&\n (value.reason === undefined || typeof value.reason === 'string') &&\n (value.operator === undefined || typeof value.operator === 'string')\n )\n}\n"],"mappings":";;;;;;AAmBA,SAAgB,qBACd,KACA,UACA,KACA,OAAyB,iBACI;CAC7B,MAAM,UAAU,gBAAgB,KAAK,UAAU,KAAK,IAAI;CACxD,IAAI,SAAS,OAAO,qBAAqB,KAAK,QAAQ,MAAM;CAC5D,OAAO,SAAS;AAClB;;;;;AAMA,eAAsB,0BACpB,KACA,UACA,KACA,OAAyB,iBACa;CACtC,MAAM,UAAU,gBAAgB,KAAK,UAAU,KAAK,IAAI;CACxD,IAAI,SAAS,OAAO,MAAM,0BAA0B,KAAK,QAAQ,MAAM;CACvE,OAAO,SAAS;AAClB;;AAGA,SAAS,gBACP,KACA,UACA,KACA,MAC2E;CAC3E,MAAM,UAAU,qBAAqB,GAAG;CACxC,IAAI,YAAY,KAAA,GAAW,OAAO,KAAA;CAClC,MAAM,QAAQ,oBAAoB,KAAK,QAAQ,WAAW;CAG1D,IAAI,OAAO,WAAW,oBACpB,SAAS,QAAQ,UAAU,wBAAwB,OAAO;CAE5D,IAAI,UAAU,KAAA,GAAW,OAAO;EAAE,QAAQ;EAAO,OAA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AC3B,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,WAAW,aACvB,MAAM,eAAe,KAAA,KACnB,OAAO,SAAS,MAAM,UAAU,KAAK,MAAM,cAAc,OAC3D,MAAM,WAAW,KAAA,KAAa,OAAO,MAAM,WAAW,cACtD,MAAM,aAAa,KAAA,KAAa,OAAO,MAAM,aAAa;AAE/D"}
|
|
1
|
+
{"version":3,"file":"run-cancellation-BNBmsY3a.js","names":[],"sources":["../src/runtime/supervise/run-cancellation.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, watch } from 'node:fs'\nimport { join } from 'node:path'\nimport { runFencedAlways } from '../../durable/durable-writer'\nimport type { RetainedRunEffect } from '../retained-run-types'\nimport {\n assertNoSymlinkDescendant,\n publishExclusiveFenced,\n writeAtomicDurableFile,\n writeAtomicDurableFileAsync,\n} from './durable-file'\nimport {\n appendWorkerControlEvent,\n appendWorkerControlEventAsync,\n workerCancellationsDir,\n} from './run-layout'\n\ntype CancellationPath = 'observer' | 'turn-boundary' | 'fallback'\n\n/** Apply a durable request through the run's existing abort controller. */\nexport function applyRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n now: () => string,\n path: CancellationPath = 'turn-boundary',\n): RunCancellation | undefined {\n const applied = abortForRequest(dir, abortRun, now, path)\n if (applied?.fresh) writeRunCancellation(dir, applied.record)\n return applied?.record\n}\n\n/**\n * `applyRunCancellation` without blocking the calling thread on the disk: the abort is issued at\n * once, and the `cancel_requested` record reaches disk on the durable writer under the run's claim.\n */\nexport async function applyRunCancellationAsync(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n now: () => string,\n path: CancellationPath = 'turn-boundary',\n): Promise<RunCancellation | undefined> {\n const applied = abortForRequest(dir, abortRun, now, path)\n if (applied?.fresh) await writeRunCancellationAsync(dir, applied.record)\n return applied?.record\n}\n\n/** Abort for the pending request, and the record it owes: the standing one, or a fresh one to write. */\nfunction abortForRequest(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n now: () => string,\n path: CancellationPath,\n): { readonly record: RunCancellation; readonly fresh: boolean } | undefined {\n const request = readRunCancelRequest(dir)\n if (request === undefined) return undefined\n const prior = readRunCancellation(dir, request.operationId)\n // A request acknowledged only as `cancel_requested` is still owed by this run: the process\n // that issued the abort died before the run settled. Abort again; the record stands.\n if (prior?.effect === 'cancel_requested') {\n abortRun(request.reason ?? 'run cancel requested', request)\n }\n if (prior !== undefined) return { record: prior, fresh: false }\n abortRun(request.reason ?? 'run cancel requested', request)\n const observedAt = now()\n const appliedAfterMs = Math.max(0, Date.parse(observedAt) - Date.parse(request.at))\n const record: RunCancellation = {\n operationId: request.operationId,\n effect: 'cancel_requested',\n path,\n appliedAfterMs,\n ...(request.deadlineMs === undefined\n ? {}\n : { deadlineExceeded: appliedAfterMs > request.deadlineMs }),\n requestedAt: request.at,\n observedAt,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'root abort issued to the whole run; termination not yet proven',\n }\n return { record, fresh: true }\n}\n\n/** External drivers may remain silent indefinitely, so turn boundaries cannot observe control. */\nexport function watchRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n createWatch: typeof watch = watch,\n) {\n mkdirSync(workerCancellationsDir(dir), { recursive: true })\n let active = true\n let failure: unknown\n // One observer aborts its run once: a request this process already applied, or one a dead\n // process acknowledged, is not re-issued on every poll.\n let aborted = false\n const abortOnce = (reason: string, request?: RunCancelRequest): void => {\n if (aborted) return\n aborted = true\n abortRun(reason, request)\n }\n // One application at a time. The abort is immediate; its record goes to the durable writer, so a\n // saturated disk delays the record, never this event loop. A poll that finds one in flight skips.\n let inFlight: Promise<void> | undefined\n const apply = (path: 'observer' | 'fallback'): Promise<void> => {\n if (failure !== undefined) return Promise.reject(failure)\n if (!active) return Promise.resolve()\n const applying = applyRunCancellationAsync(\n dir,\n abortOnce,\n () => new Date().toISOString(),\n path,\n ).then(() => undefined)\n const settled = applying.then(\n () => {\n if (inFlight === settled) inFlight = undefined\n },\n (error: unknown) => {\n // Kept even after close, so the settle path's check() throws it instead of reading no record.\n failure ??= error\n if (inFlight === settled) inFlight = undefined\n },\n )\n inFlight = settled\n return applying\n }\n // A caller's check waits for the application in flight, so a closed observer's last record lands\n // before the run's settle record is written, and a failure it met is thrown here.\n const check = async (path: 'observer' | 'fallback' = 'observer'): Promise<void> => {\n while (inFlight !== undefined) await inFlight\n await apply(path)\n }\n const fail = (error: unknown): void => {\n if (!active) return\n failure = error\n abortRun(`durable run cancellation observer failed: ${String(error)}`)\n }\n const poll = (path: 'observer' | 'fallback'): void => {\n if (inFlight !== undefined) return\n apply(path).catch(fail)\n }\n // The watcher is an optimization over the poll loop below (instant pickup instead of ≤100 ms).\n // Creating it can fail for reasons that say NOTHING about this run: the host's inotify budget is\n // exhausted (EMFILE — a shared box with many agents held ~110 of the 128 default user instances\n // when this was measured), or the kernel caps watches (ENOSPC). Degrading to poll-only keeps\n // every durable behavior; failing the run would make a neighboring process's resource use kill\n // runs that never touched the limit. Any other creation error still fails loudly.\n let watcher: ReturnType<typeof watch> | undefined\n try {\n watcher = createWatch(workerCancellationsDir(dir), (_event, filename) => {\n if (!active || (filename !== null && filename !== 'run.request.json')) return\n poll('observer')\n })\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'EMFILE' && code !== 'ENOSPC') throw error\n }\n watcher?.on('error', fail)\n // Filesystem notifications are advisory. Scan the same durable inbox when one is dropped —\n // and carry the whole observer alone whenever the watcher above could not be created.\n const fallback = setInterval(() => poll('fallback'), 100)\n fallback.unref()\n return {\n check,\n close(): void {\n active = false\n watcher?.close()\n clearInterval(fallback)\n },\n }\n}\n\n/** One durable run-scoped cancel request: cancel the WHOLE run, not one worker. */\nexport interface RunCancelRequest {\n /** Caller-minted stable operation identifier — the idempotency key of the whole operation. */\n readonly operationId: string\n /** ISO timestamp of the write. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** Requested observation target, measured by the acknowledgement's deadlineExceeded field.\n * The observer always cascades eagerly. This does not guarantee scheduler latency or cleanup. */\n readonly deadlineMs?: number\n /** Who stops the run. `cancelRun` requires it on every new request; it is optional here only\n * so a request written before that rule still reads. The settle record carries it. */\n readonly operator?: string\n readonly reason?: string\n}\n\n/**\n * The durable acknowledgement state for the run-scoped cancel operation, keyed by `operationId`.\n * The runtime is the ONLY writer; {@link cancelRun} only reads it.\n *\n * `effect` is the same {@link RetainedRunEffect} vocabulary the worker-scoped and retained-run\n * paths use, so the runtime has one spelling of the four cancellation states:\n * - `'unknown'` — no runtime has answered yet. Never a success.\n * - `'cancel_requested'` — the root manager issued the run's cascading abort; the run's terminal\n * state is not yet observed.\n * - `'cancelled'` — the run reached its terminal cancelled state with confirmed teardown.\n * - `'not_live'` — the run was not live to cancel: it settled on its own despite the\n * request, or it ended before the request was applied.\n */\nexport interface RunCancellation {\n /** Runtime path that issued the cascade. */\n readonly path?: 'observer' | 'turn-boundary' | 'fallback'\n /** Runtime clock elapsed between request timestamp and cascade application. */\n readonly appliedAfterMs?: number\n /** Whether application exceeded the requested deadlineMs; absent when no target was requested. */\n readonly deadlineExceeded?: boolean\n readonly operationId: string\n readonly effect: RetainedRunEffect\n /** ISO timestamp of the original request. */\n readonly requestedAt: string\n /** ISO timestamp of the runtime's most recent observation of this operation. */\n readonly observedAt: string\n /** The caller's reason, carried verbatim from the request. */\n readonly reason?: string\n /** The caller's operator identity, carried verbatim from the request. */\n readonly operator?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\n}\n\n/** The run-scoped cancel request file of one run — one {@link RunCancelRequest}. */\nexport function runCancelRequestFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.request.json')\n}\n\n/** The run-scoped acknowledgement file of one run — one {@link RunCancellation}. */\nexport function runCancellationFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.json')\n}\n\n/** Read the run-scoped cancel request, or `undefined` when none was written. */\nexport function readRunCancelRequest(eventDir: string): RunCancelRequest | undefined {\n const dir = workerCancellationsDir(eventDir)\n const file = runCancelRequestFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n assertNoSymlinkDescendant(eventDir, file, 'run cancel request')\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<RunCancelRequest>\n if (!isRunCancelRequest(parsed)) {\n throw new Error(`run cancel request '${file}' is not a complete RunCancelRequest`)\n }\n return parsed\n}\n\n/**\n * Read the acknowledgement for the run-scoped cancel operation. `undefined` when the runtime has\n * not answered. A record holding a DIFFERENT `operationId` belongs to another operation on the\n * same run — fail loud rather than answer for it.\n */\nexport function readRunCancellation(\n eventDir: string,\n operationId: string,\n): RunCancellation | undefined {\n const dir = workerCancellationsDir(eventDir)\n const file = runCancellationFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n assertNoSymlinkDescendant(eventDir, file, 'run cancel acknowledgement')\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as RunCancellation\n if (parsed.operationId !== operationId) {\n throw new Error(\n `run cancel acknowledgement '${file}' holds operation '${parsed.operationId}', not ` +\n `'${operationId}' — one run carries one run-scoped cancel operation`,\n )\n }\n return parsed\n}\n\n/**\n * Durably write the run-scoped acknowledgement. The shared writer fsyncs the file and containing\n * directory, so a concurrent reader sees the prior complete record or the new complete record.\n *\n * @internal The runtime is the only intended writer; clients read via {@link readRunCancellation}\n * or {@link cancelRun}.\n */\nexport function writeRunCancellation(eventDir: string, record: RunCancellation): void {\n writeAtomicDurableFile(runCancellationTarget(eventDir), recordText(record), { mode: 0o600 })\n}\n\n/** `writeRunCancellation` without blocking the calling thread on the disk under a run claim. @internal */\nexport function writeRunCancellationAsync(\n eventDir: string,\n record: RunCancellation,\n): Promise<void> {\n return writeAtomicDurableFileAsync(runCancellationTarget(eventDir), recordText(record), {\n mode: 0o600,\n })\n}\n\nconst recordText = (record: RunCancellation | RunCancelRequest): string =>\n `${JSON.stringify(record, null, 2)}\\n`\n\n/** The acknowledgement file, its directory made and every path checked for symlinks. */\nfunction runCancellationTarget(eventDir: string): string {\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n const file = runCancellationFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'run cancel acknowledgement')\n return file\n}\n\n/**\n * Request the cancellation of the WHOLE run, idempotently, and return the operation's current\n * durable state.\n *\n * The run-scoped twin of {@link cancelWorker}: write the request into the run's cancellation\n * directory, where the run's own root manager applies it — aborting the root through the one\n * cascade controller the run already has, so every live worker comes down with it. This function\n * never applies the cancellation itself; writing a request file is not an acknowledgement.\n *\n * Idempotency is a lookup: when an acknowledgement for `operationId` already exists it is returned\n * AS-IS and nothing is written. A retry that changes the source, reason, deadline, or operator\n * fails closed. A request the runtime has not answered yet returns `effect: 'unknown'` (never a\n * success); call again with the same `operationId` — or {@link readRunCancellation} — to read the\n * acknowledged result after a reconnect.\n *\n * A run carries ONE run-scoped operation: a second request under a different `operationId` throws\n * rather than silently replacing the pending one, because both would claim the same single abort.\n * Reopening a settled run (`supervisePursuit`'s `reopen`) moves that operation aside.\n *\n * A NEW request must name its `operator`, so every stop says who made it. A replay of a request\n * or acknowledgement written before that rule is answered as it was.\n */\nexport function cancelRun(\n eventDir: string,\n operationId: string,\n // Inline, as published through 10.0.5: the archive admission reads a named type here as a new\n // shape, which would make this patch a major.\n options: {\n readonly reason?: string\n readonly source?: string\n readonly deadlineMs?: number\n readonly operator?: string\n } = {},\n): RunCancellation {\n const admission = admitRunCancel(eventDir, operationId, options)\n if ('answer' in admission) return admission.answer\n if (admission.file !== undefined) {\n writeAtomicDurableFile(admission.file, recordText(admission.request), { mode: 0o600 })\n appendWorkerControlEvent(eventDir, 'run', admission.event)\n }\n return queuedRunCancellation(admission.request)\n}\n\n/**\n * Request the cancellation of the whole run like {@link cancelRun}, without blocking the calling\n * thread on the disk. The request file is published by the durable writer whether or not the\n * caller holds a run claim (a coordinator outside the run holds none), so an event loop that stops\n * runs keeps running while the file and its directory reach disk. Same admission, replay and\n * conflict rules.\n * @stable\n */\nexport async function cancelRunAsync(\n eventDir: string,\n operationId: string,\n options: CancelRunOptions = {},\n): Promise<RunCancellation> {\n const admission = admitRunCancel(eventDir, operationId, options)\n if ('answer' in admission) return admission.answer\n if (admission.file !== undefined) {\n // Published only if no request is there yet: an overlapping call admitted against the same empty\n // inbox loses here, and is admitted again against the winner, which it replays or conflicts with.\n const published = await runFencedAlways(\n 'publishExclusiveDurableFile',\n publishExclusiveFenced,\n admission.file,\n recordText(admission.request),\n { mode: 0o600 },\n )\n if (!published) return cancelRunAsync(eventDir, operationId, options)\n await appendWorkerControlEventAsync(eventDir, 'run', admission.event)\n }\n return queuedRunCancellation(admission.request)\n}\n\n/** Options of {@link cancelRun} and {@link cancelRunAsync}. */\nexport interface CancelRunOptions {\n readonly reason?: string\n readonly source?: string\n readonly deadlineMs?: number\n readonly operator?: string\n}\n\n/**\n * The admission of one run cancel: the standing acknowledgement, or the request to answer for,\n * with the file and control event still to write when it is new.\n */\nfunction admitRunCancel(\n eventDir: string,\n operationId: string,\n options: CancelRunOptions,\n):\n | { readonly answer: RunCancellation }\n | {\n readonly request: RunCancelRequest\n readonly file?: string\n readonly event: Record<string, unknown>\n } {\n if (\n options.deadlineMs !== undefined &&\n (!Number.isFinite(options.deadlineMs) || options.deadlineMs < 0)\n ) {\n throw new Error('cancelRun: deadlineMs must be a finite nonnegative number')\n }\n const opId = operationId.trim()\n if (!opId) throw new Error('cancelRun: operationId is empty')\n const pending = readRunCancelRequest(eventDir)\n if (pending !== undefined && pending.operationId !== opId) {\n throw new Error(\n `cancelRun: run cancel '${pending.operationId}' is already pending for this run; ` +\n `read it with readRunCancellation instead of issuing '${opId}'`,\n )\n }\n const candidate = {\n operationId: opId,\n source: options.source ?? 'human',\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n }\n if (pending !== undefined) assertSameRunCancelRequest(pending, candidate)\n const acknowledged = readRunCancellation(eventDir, opId)\n if (acknowledged !== undefined) {\n if (pending === undefined && options.source !== undefined) {\n throw new Error(\n `cancelRun: operation '${opId}' cannot verify source without its admitted request`,\n )\n }\n assertRunCancellationMatchesCandidate(acknowledged, candidate)\n return { answer: acknowledged }\n }\n // A new request names who stops the run. A replay of a request written before this rule keeps\n // its absent operator: it was admitted above against the file it replays.\n if (pending === undefined && (options.operator === undefined || options.operator.trim() === '')) {\n throw new Error('cancelRun: operator is required; name who stops the run')\n }\n const source = options.source ?? 'human'\n const request: RunCancelRequest = pending ?? {\n operationId: opId,\n at: new Date().toISOString(),\n source,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n }\n const event = {\n kind: 'run-cancel-request',\n operationId: opId,\n source,\n queued: true,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n }\n if (pending !== undefined) return { request, event }\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n const file = runCancelRequestFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'run cancel request')\n return { request, file, event }\n}\n\n/** The answer to a request no runtime has acknowledged yet. */\nfunction queuedRunCancellation(request: RunCancelRequest): RunCancellation {\n return {\n operationId: request.operationId,\n effect: 'unknown',\n requestedAt: request.at,\n observedAt: request.at,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n }\n}\n\ntype RunCancelRequestCandidate = Omit<RunCancelRequest, 'at'>\n\nfunction assertSameRunCancelRequest(\n existing: RunCancelRequest,\n candidate: RunCancelRequestCandidate,\n): void {\n if (existing.operationId !== candidate.operationId) {\n throw new Error(`cancelRun: operation '${candidate.operationId}' has an id collision`)\n }\n if (existing.source !== candidate.source) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(source '${existing.source}' != '${candidate.source}')`,\n )\n }\n if (existing.deadlineMs !== candidate.deadlineMs) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request (deadlineMs differs)`,\n )\n }\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(reason differs)`,\n )\n }\n if (existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\n )\n }\n}\n\nfunction assertRunCancellationMatchesCandidate(\n existing: RunCancellation,\n candidate: RunCancelRequestCandidate,\n): void {\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(reason differs)`,\n )\n }\n // An acknowledgement written before acknowledgements carried the operator (0.251.0) names none\n // even when its admitted request does. The request comparator has already held the candidate\n // to that request, so a legacy record matches any candidate operator; a record that names one\n // must name the same one.\n if (existing.operator !== undefined && existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\n )\n }\n}\n\nfunction isRunCancelRequest(value: Partial<RunCancelRequest>): value is RunCancelRequest {\n return (\n typeof value.operationId === 'string' &&\n value.operationId.length > 0 &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n (value.deadlineMs === undefined ||\n (Number.isFinite(value.deadlineMs) && value.deadlineMs >= 0)) &&\n (value.reason === undefined || typeof value.reason === 'string') &&\n (value.operator === undefined || typeof value.operator === 'string')\n )\n}\n"],"mappings":";;;;;;AAmBA,SAAgB,qBACd,KACA,UACA,KACA,OAAyB,iBACI;CAC7B,MAAM,UAAU,gBAAgB,KAAK,UAAU,KAAK,IAAI;CACxD,IAAI,SAAS,OAAO,qBAAqB,KAAK,QAAQ,MAAM;CAC5D,OAAO,SAAS;AAClB;;;;;AAMA,eAAsB,0BACpB,KACA,UACA,KACA,OAAyB,iBACa;CACtC,MAAM,UAAU,gBAAgB,KAAK,UAAU,KAAK,IAAI;CACxD,IAAI,SAAS,OAAO,MAAM,0BAA0B,KAAK,QAAQ,MAAM;CACvE,OAAO,SAAS;AAClB;;AAGA,SAAS,gBACP,KACA,UACA,KACA,MAC2E;CAC3E,MAAM,UAAU,qBAAqB,GAAG;CACxC,IAAI,YAAY,KAAA,GAAW,OAAO,KAAA;CAClC,MAAM,QAAQ,oBAAoB,KAAK,QAAQ,WAAW;CAG1D,IAAI,OAAO,WAAW,oBACpB,SAAS,QAAQ,UAAU,wBAAwB,OAAO;CAE5D,IAAI,UAAU,KAAA,GAAW,OAAO;EAAE,QAAQ;EAAO,OAAO;CAAM;CAC9D,SAAS,QAAQ,UAAU,wBAAwB,OAAO;CAC1D,MAAM,aAAa,IAAI;CACvB,MAAM,iBAAiB,KAAK,IAAI,GAAG,KAAK,MAAM,UAAU,IAAI,KAAK,MAAM,QAAQ,EAAE,CAAC;CAelF,OAAO;EAAE,QAAA;GAbP,aAAa,QAAQ;GACrB,QAAQ;GACR;GACA;GACA,GAAI,QAAQ,eAAe,KAAA,IACvB,CAAC,IACD,EAAE,kBAAkB,iBAAiB,QAAQ,WAAW;GAC5D,aAAa,QAAQ;GACrB;GACA,GAAI,QAAQ,WAAW,KA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,SAAS,2BACP,UACA,WACM;CACN,IAAI,SAAS,gBAAgB,UAAU,aACrC,MAAM,IAAI,MAAM,yBAAyB,UAAU,YAAY,sBAAsB;CAEvF,IAAI,SAAS,WAAW,UAAU,QAChC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,iDACjC,SAAS,OAAO,QAAQ,UAAU,OAAO,GACzD;CAEF,IAAI,SAAS,eAAe,UAAU,YACpC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,2DACjD;CAEF,IAAI,SAAS,WAAW,UAAU,QAChC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,uDAEjD;CAEF,IAAI,SAAS,aAAa,UAAU,UAClC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,mDAC/B,SAAS,SAAS,QAAQ,UAAU,SAAS,GAC/D;AAEJ;AAEA,SAAS,sCACP,UACA,WACM;CACN,IAAI,SAAS,WAAW,UAAU,QAChC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,sDAEjD;CAMF,IAAI,SAAS,aAAa,KAAA,KAAa,SAAS,aAAa,UAAU,UACrE,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,kDAC/B,SAAS,SAAS,QAAQ,UAAU,SAAS,GAC/D;AAEJ;AAEA,SAAS,mBAAmB,OAA6D;CACvF,OACE,OAAO,MAAM,gBAAgB,YAC7B,MAAM,YAAY,SAAS,KAC3B,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,WAAW,aACvB,MAAM,eAAe,KAAA,KACnB,OAAO,SAAS,MAAM,UAAU,KAAK,MAAM,cAAc,OAC3D,MAAM,WAAW,KAAA,KAAa,OAAO,MAAM,WAAW,cACtD,MAAM,aAAa,KAAA,KAAa,OAAO,MAAM,aAAa;AAE/D"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { C as runGenerationPath, S as mutateRunClaim, h as registerDurableErrorClass, o as publishExclusiveDurableFile, u as writeAtomicDurableFile, v as runFencedAlways, w as runWithWriteClaim } from "./durable-file-pao7FijS.js";
|
|
2
|
-
import { t as isNoEntError } from "./jsonl-file-
|
|
2
|
+
import { t as isNoEntError } from "./jsonl-file-B2ESMrTh.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-Dcr79Wql.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-lock-BOg7BaXF.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,cAAc,MAAM,MAAM;GAChC,WAAW;EACb;CACF,CAAC;AACH;;A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"],"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,GA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AgB,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,9 +1,9 @@
|
|
|
1
1
|
import { _ as runFenced, l as syncDurableDirectory, o as publishExclusiveDurableFile, x as fenceRunWrite } from "./durable-file-pao7FijS.js";
|
|
2
|
-
import { c as runCancellationFile, s as runCancelRequestFile } from "./run-cancellation-
|
|
3
|
-
import { O as workerCancellationsDir, X as FileSpawnJournal } from "./supervisor-accounting-
|
|
4
|
-
import {
|
|
5
|
-
import { n as assertResumeLimits } from "./supervisor-root-contract-
|
|
6
|
-
import { n as SETTLE_RECORD_FILE, s as settleRecordDigest } from "./settle-record-
|
|
2
|
+
import { c as runCancellationFile, s as runCancelRequestFile } from "./run-cancellation-BNBmsY3a.js";
|
|
3
|
+
import { O as workerCancellationsDir, X as FileSpawnJournal } from "./supervisor-accounting-DlDUl58C.js";
|
|
4
|
+
import { ct as assertValidBudget } from "./tool-server-n4XYpCok.js";
|
|
5
|
+
import { n as assertResumeLimits } from "./supervisor-root-contract-BCbu1A4n.js";
|
|
6
|
+
import { n as SETTLE_RECORD_FILE, s as settleRecordDigest } from "./settle-record-BlIw2MU1.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-Cr2SHmYa.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-reopen-B7TN2aQQ.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,U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AA2C;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-Cr2SHmYa.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,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mB;CACxD,oBAAoB,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC,CAAC;AACzD"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { a as readRunCancelRequest } from "./run-cancellation-
|
|
2
|
-
import { c 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 { Q as spawnJournalRecordEvents } from "./supervisor-accounting-
|
|
1
|
+
import { a as readRunCancelRequest } from "./run-cancellation-BNBmsY3a.js";
|
|
2
|
+
import { c as readRunParking } from "./supervisor-KcnH2hC4.js";
|
|
3
|
+
import { s as runDirectoryHolderIsLive } from "./run-lock-Dcr79Wql.js";
|
|
4
|
+
import { a as readFailureRecord, o as readSettleRecord } from "./settle-record-BlIw2MU1.js";
|
|
5
|
+
import { o as readCommittedJsonLines, t as isNoEntError } from "./jsonl-file-B2ESMrTh.js";
|
|
6
|
+
import { Q as spawnJournalRecordEvents } from "./supervisor-accounting-DlDUl58C.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-AYXAe_lX.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-state-BNBUy2uK.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;GAAO,gBAAgB;EAAE;EAExF,MAAM;CACR;CACA,IAAI;EACF,MAAM,WAAW,MAAM,OAAO,KAAK,EAAE,QAAQ,KAAK,CAAC;EACnD,IAAI,CAAC,SAAS,OAAO,GAAG,MAAM,IAAI,MAAM,GAAG,KAAK,0BAA0B;EAC1E,MAAM,OAAO,OAAO,SAAS,IAAI;EACjC,MAAM,OAAO,SAAS,QAAQ;EAC9B,MAAM,UACJ,UAAU,KAAA,KACV,MAAM,SAAS,QACf,OAAO,cAAc,MAAM,MAAM,KACjC,MAAM,UAAU,KAChB,MAAM,UAAU,QAChB,MAAM,aAAc,MAAM,SAAS,QAAQ,MAAM,MAAM;EACzD,IAA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O,SAAS,SAAS,GACtD,SAAS,WAAW,KAAA,IAAY,YAAY,KAAK,IAAI,QAAQ,SAAS;CAE1E;CACA,QAAQ,SAAS,EAAE;CACnB,QAAQ,SAAS,KAAK;CACtB,QAAQ,eAAe,EAAE;CACzB,QAAQ,OAAO,QAAQ,SAAS;CAChC,KAAK,MAAM,UAAU,QAAQ,SAC3B,QAAQ,OAAO,SAAS,UAAU,OAAO,KAAK,OAAO,MAAM,EAAE;CAC/D,KAAK,MAAM,QAAQ,QAAQ,KAAK,SAAS,CAAC,GAAG;EAC3C,QAAQ,KAAK,SAAS;EACtB,QAAQ,KAAK,SAAS;CACxB;CACA,MAAM,iBAAiB,WAAW,KAAA,IAAY,KAAA,IAAY,IAAI,KAAK,MAAM,CAAC,CAAC,YAAY;CACvF,OAAO;EACL,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;EACvC,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;EACnD,GAAI,WAAW,KAAA,IAAY,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-AYXAe_lX.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;GAAO,gBAAgB;EAAE;EAExF,MAAM;CACR;CACA,IAAI;EACF,MAAM,WAAW,MAAM,OAAO,KAAK,EAAE,QAAQ,KAAK,CAAC;EACnD,IAAI,CAAC,SAAS,OAAO,GAAG,MAAM,IAAI,MAAM,GAAG,KAAK,0BAA0B;EAC1E,MAAM,OAAO,OAAO,SAAS,IAAI;EACjC,MAAM,OAAO,SAAS,QAAQ;EAC9B,MAAM,UACJ,UAAU,KAAA,KACV,MAAM,SAAS,QACf,OAAO,cAAc,MAAM,MAAM,KACjC,MAAM,UAAU,KAChB,MAAM,UAAU,QAChB,MAAM,aAAc,MAAM,SAAS,QAAQ,MAAM,MAAM;EACzD,IAAI,SAAS,UAAU,MAAM,SAAS;EACtC,MAAM,UAAoC,CAAC;EAC3C,MAAM,OAAO,OAAO,OAAe,KAAa,YAAY,UAAyB;GACnF,SAAS;GACT,WAAW,MAAM,UAAU,uBAAgC,MAAM;IAC/D;IACA;IACA;IACA,YAAY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AAQ,SAAS;CAChC,KAAK,MAAM,UAAU,QAAQ,SAC3B,QAAQ,OAAO,SAAS,UAAU,OAAO,KAAK,OAAO,MAAM,EAAE;CAC/D,KAAK,MAAM,QAAQ,QAAQ,KAAK,SAAS,CAAC,GAAG;EAC3C,QAAQ,KAAK,SAAS;EACtB,QAAQ,KAAK,SAAS;CACxB;CACA,MAAM,iBAAiB,WAAW,KAAA,IAAY,KAAA,IAAY,IAAI,KAAK,MAAM,CAAC,CAAC,YAAY;CACvF,OAAO;EACL,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;EACvC,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;EACnD,GAAI,WAAW,KAAA,IAAY,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,30 +1,29 @@
|
|
|
1
|
-
import { A as readPromptOptions, F as defaultSelectWinner, H as routerBrain, M as createSandboxLineage, O as runAgentRounds,
|
|
2
|
-
import {
|
|
3
|
-
import "./run-state-
|
|
4
|
-
import { B as isTraceAnalysisStore, Kt as coordinationProfileToolPrefix, cr as harnessTranscriptArtifact, gn as insideCursorNamespace, hr as readBoundHarnessSessions,
|
|
5
|
-
import "./result-blob-store-
|
|
6
|
-
import { A as validateGraphTopology, D as validateFlowGraph, L as kernelPromptRegistry, a as bridgeProfileRefusal, h as runBrainLoop, t as supervise, x as coordinationControlToolNames } from "./supervise-
|
|
1
|
+
import { A as readPromptOptions, F as defaultSelectWinner, H as routerBrain, M as createSandboxLineage, O as runAgentRounds, Y as createWorktreeCliExecutor, b as InMemorySpawnJournal, k as assertBoxlessPromptOptions, n as createSupervisor, v as withDriverExecutor, w as createExecutor, x as createExecutorRegistry, y as InMemoryResultBlobStore } from "./supervisor-KcnH2hC4.js";
|
|
2
|
+
import { Et as notifySandboxEventObserver, Pt as recordValue, R as contentAddress, St as createSandboxTurnEventCollector, a as runtimeFailureCauseSchema } from "./tool-server-n4XYpCok.js";
|
|
3
|
+
import "./run-state-AYXAe_lX.js";
|
|
4
|
+
import { B as isTraceAnalysisStore, Br as CheckUnavailableError, Hr as gateOnDeliverable, Kt as coordinationProfileToolPrefix, Ur as mapExecutorResult, Wr as verdictFromJudgeScore, _i as executableAgentProfileSnapshot, cr as harnessTranscriptArtifact, gn as insideCursorNamespace, hr as readBoundHarnessSessions, ot as rollingDispatch, tt as settledToIteration, vi as executableAgentSpecSnapshot } from "./supervisor-accounting-DlDUl58C.js";
|
|
5
|
+
import "./result-blob-store-CJjp44Mz.js";
|
|
6
|
+
import { A as validateGraphTopology, D as validateFlowGraph, L as kernelPromptRegistry, a as bridgeProfileRefusal, h as runBrainLoop, t as supervise, x as coordinationControlToolNames } from "./supervise-Ci8wiyla.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-DHNPE7kw.js";
|
|
11
11
|
import { a as concreteProfileModel, b as harnessRunsAgent, c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, p as canonicalObservedModelParts, t as assertExecutableAgentProfile, x as resumingHarnesses, y as harnessResumesConversation } from "./model-policy-DFuhCC0-.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 {
|
|
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-BVuf5hFl.js";
|
|
15
|
+
import { a as readCommittedJsonFile, c as withJsonlFileLock, l as appendCommittedJsonLine, o as readCommittedJsonLines, s as upsertCommittedJsonLine, t as isNoEntError, w as runAbortable } from "./jsonl-file-B2ESMrTh.js";
|
|
16
16
|
import { n as detachedSnapshot, t as detachedFrozen } from "./snapshot-BKLziJ5K.js";
|
|
17
17
|
import { y as markPutStreamVerified } from "./workspace-streams-C7PGLAUd.js";
|
|
18
|
-
import "./provision-supervisor-
|
|
18
|
+
import "./provision-supervisor-CyUbiMz8.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 "./
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import { p as createInMemoryRunContext, s as downMessageRefusalReasons } from "./driver-control-acknowledgers-b5MsXxR5.js";
|
|
20
|
+
import { a as reconcileInterruptedSearchCalls, c as searchExecutor, r as dedicatedLane, x as runtimeShipDecision } from "./search-executor-BHfb4p6C.js";
|
|
21
|
+
import "./delegate-DnW85VY0.js";
|
|
22
|
+
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-qyaNDATw.js";
|
|
23
|
+
import { d as foldCoordinationRecords } from "./supervise-identity-CtxWEk1I.js";
|
|
24
|
+
import { p as createInMemoryRunContext, s as downMessageRefusalReasons } from "./driver-control-acknowledgers-vgmZqgZ-.js";
|
|
26
25
|
import { u as writeAtomicDurableFile } from "./durable-file-pao7FijS.js";
|
|
27
|
-
import "./run-cancellation-
|
|
26
|
+
import "./run-cancellation-BNBmsY3a.js";
|
|
28
27
|
import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, sameAgentRunControlRef, sha256Bytes, sha256DigestSchema, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
|
|
29
28
|
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
29
|
import { createAgentRunOutcomeTracker } from "@tangle-network/sandbox/runtime";
|
|
@@ -7074,7 +7073,7 @@ function graphDesignerExtraTools(env) {
|
|
|
7074
7073
|
})();
|
|
7075
7074
|
if (name === "designer_history") return (async () => {
|
|
7076
7075
|
const args = asRecord(raw ?? {}, "designer_history");
|
|
7077
|
-
const { listGraphRuns } = await import("./graph-registry-
|
|
7076
|
+
const { listGraphRuns } = await import("./graph-registry-DI8o9iCB.js");
|
|
7078
7077
|
const all = await listGraphRuns(registry);
|
|
7079
7078
|
return { runs: (args.taskShape === void 0 ? all : all.filter((row) => row.taskDigest === taskShapeDigest(asRecord(args.taskShape, "designer_history.taskShape")))).map(summarize) };
|
|
7080
7079
|
})();
|
|
@@ -7085,7 +7084,7 @@ function graphDesignerExtraTools(env) {
|
|
|
7085
7084
|
if (mode === "replay") {
|
|
7086
7085
|
const digest = args.graphDigest;
|
|
7087
7086
|
if (typeof digest !== "string" || digest.length === 0) throw new ValidationError("designer_run_graph: replay mode requires graphDigest from lookup");
|
|
7088
|
-
const { loadGraph } = await import("./graph-registry-
|
|
7087
|
+
const { loadGraph } = await import("./graph-registry-DI8o9iCB.js");
|
|
7089
7088
|
const stored = await loadGraph(registry, digest);
|
|
7090
7089
|
if (!stored) throw new ValidationError(`designer_run_graph: no stored graph ${digest.slice(0, 12)} — re-lookup`);
|
|
7091
7090
|
const graph = env.bindCheck(graphFromStored(stored, () => {
|
|
@@ -10013,4 +10012,4 @@ function tail(s) {
|
|
|
10013
10012
|
}
|
|
10014
10013
|
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 };
|
|
10015
10014
|
|
|
10016
|
-
//# sourceMappingURL=runtime-
|
|
10015
|
+
//# sourceMappingURL=runtime-D-FpUoQg.js.map
|