@staix/agent-research 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +261 -24
  3. package/package.json +2 -2
  4. package/src/cli.ts +117 -10
  5. package/src/commands-table.ts +39 -8
  6. package/src/commands.ts +201 -34
  7. package/src/exp/artifacts.ts +20 -2
  8. package/src/exp/attempts.ts +505 -65
  9. package/src/exp/executor.ts +264 -17
  10. package/src/exp/final.ts +1 -1
  11. package/src/exp/logs.ts +25 -12
  12. package/src/exp/metrics.ts +8 -9
  13. package/src/exp/pipeline.ts +92 -0
  14. package/src/exp/protocol.ts +87 -20
  15. package/src/exp/retention-script.ts +649 -0
  16. package/src/exp/retention.ts +70 -0
  17. package/src/exp/reuse-admission.ts +65 -0
  18. package/src/exp/reuse-contract.ts +48 -0
  19. package/src/exp/reuse-runtime.ts +91 -0
  20. package/src/exp/reuse.ts +87 -0
  21. package/src/exp/selection.ts +1 -1
  22. package/src/exp/snapshot.ts +30 -10
  23. package/src/exp/stages.ts +117 -0
  24. package/src/harness/experience-source.ts +34 -0
  25. package/src/harness/experience.ts +206 -0
  26. package/src/harness/hub-guidance.ts +140 -0
  27. package/src/harness/hub-reference.ts +18 -0
  28. package/src/harness/lesson-candidates.ts +162 -0
  29. package/src/harness/limits.ts +2 -0
  30. package/src/harness/privacy.ts +4 -0
  31. package/src/harness/receipts.ts +84 -0
  32. package/src/harness/rounds.ts +198 -0
  33. package/src/harness/transitions.ts +152 -0
  34. package/src/lit/candidates.ts +13 -5
  35. package/src/lit/cards.ts +55 -4
  36. package/src/lit/flow.ts +82 -0
  37. package/src/lit/queries.ts +62 -0
  38. package/src/manifest.ts +13 -6
  39. package/src/mcp-tools.ts +123 -25
  40. package/src/mcp.ts +4 -0
  41. package/src/memory/amem-show.ts +135 -0
  42. package/src/memory/amem.ts +3 -0
  43. package/src/memory/archive.ts +17 -8
  44. package/src/memory/evidence-local.ts +77 -0
  45. package/src/memory/evidence.ts +39 -0
  46. package/src/memory/lessons.ts +4 -2
  47. package/src/memory/skill-check.ts +56 -0
  48. package/src/memory/skill-format.ts +77 -0
  49. package/src/memory/skills.ts +72 -26
  50. package/src/memory/source-budget.ts +11 -0
  51. package/src/memory/vault-cards.ts +226 -0
  52. package/src/paper/build.ts +16 -7
  53. package/src/paper/check.ts +37 -10
  54. package/src/paper/headings.ts +39 -0
  55. package/src/paper/hygiene.ts +153 -0
  56. package/src/paper/placeholders.ts +16 -1
  57. package/src/paper/plan.ts +170 -0
  58. package/src/paper/point-evidence.ts +63 -0
  59. package/src/paper/points.ts +83 -0
  60. package/src/paper/review.ts +102 -9
  61. package/src/paper/scopes.ts +51 -0
  62. package/src/plan/definition.ts +5 -1
  63. package/src/plan/hub.ts +6 -0
  64. package/src/plan/state.ts +5 -0
  65. package/src/playbook.ts +35 -20
  66. package/src/privacy.ts +9 -0
  67. package/src/provenance.ts +679 -0
  68. package/src/scope.ts +24 -3
  69. package/src/study-export.ts +55 -27
  70. package/src/study.ts +54 -14
  71. package/src/ui/panel.css +4 -0
  72. package/src/ui/panel.js +263 -6
  73. package/src/ui/plugin.ts +68 -10
@@ -1,3 +1,7 @@
1
+ import { prepareStageReuse } from "./reuse-admission.ts";
2
+ import { executionView, materializePipeline, sealPipeline, pipelinePaths, pipelineInputRoot, type PipelineState, type AttemptReuseState } from "./pipeline.ts";
3
+ import { retainedOperation, RetentionError } from "./retention.ts";
4
+ import { validateStageProtocol } from "./stages.ts";
1
5
  import { requireCopilotAccept } from "../copilot.ts";
2
6
  import { resolveAutonomy } from "../autonomy.ts";
3
7
  import { readFinalSeeds, authorizeFinalAttempt, finalGateBinding, requirePosthocClosed } from "./final.ts";
@@ -6,25 +10,27 @@ import { hostname } from "node:os";
6
10
  import { join, posix } from "node:path";
7
11
  import { randomUUID } from "node:crypto";
8
12
  import { AsyncLocalStorage } from "node:async_hooks";
9
- import { boundedText, commit, openStudy, plain, readJsonFile, readTextBounded, requireExperiment, requireGate, sha256, withLock, type Actor, type PendingEvent } from "../study.ts";
10
- import { designBinding, protocolHash, readDesign, type Protocol } from "./protocol.ts";
11
- import { buildContainerArgs, checkExecutorInputs, containerName, readExecutor, runOnExecutor, shellQuote, spawnRunner, startWatchdog, type ContainerPaths, type Executor, type ProcessRunner, type Stage } from "./executor.ts";
13
+ import { boundedText, commit, openStudy, plain, readJsonFile, readTextBounded, requireExperiment, requireGate, sha256, withLock, StudyLockBusyError, type Actor, type PendingEvent } from "../study.ts";
14
+ import { canonical, designBinding, sameProtocolInputs, frozenProtocol, validateStoredProtocol, protocolHash, readProtocol, readDesign, type Protocol } from "./protocol.ts";
15
+ import { buildContainerArgs, probeGpuAdmission, GpuAdmissionDeferred, validateGpuDevices, validateContainerInputSources, executionPathsOverlap, verifyExecutorInputs, InputVerificationError, checkExecutorInputs, stageContainerName, readExecutor, runOnExecutor, shellQuote, spawnRunner, startWatchdog, type ContainerPaths, type Executor, type ProcessRunner, type Stage } from "./executor.ts";
12
16
  import { resolveSnapshot, transferSnapshot, transferTask } from "./snapshot.ts";
13
- import { collectEvaluation as defaultEvaluationCollector, collectStageEvidence as defaultStageCollector, EvidenceError, MetricsError, outputBudget, type StageEvidence } from "./metrics.ts";
17
+ import { collectEvaluation as defaultEvaluationCollector, collectStageEvidence as defaultStageCollector, EvidenceError, MetricsError, OUTPUT_METADATA_BYTES, outputBudget, type StageEvidence } from "./metrics.ts";
14
18
 
15
19
  export type AttemptStatus = "running" | "succeeded" | "failed" | "cancelled" | "unknown";
16
- export interface AttemptStage { image: string; argv: string[]; mounts: { target: string; readOnly: boolean }[]; network: "none"; limits: Protocol["limits"]; user: string; containerId?: string; startedAt: string; endedAt?: string; exitCode?: number; evidence?: StageEvidence; evidenceError?: { reason: string; message: string } }
20
+ export interface AttemptStage { image: string; argv: string[]; mounts: { target: string; readOnly: boolean }[]; network: "none"; limits: Protocol["limits"]; user: string; containerName?: string; containerId?: string; startedAt: string; endedAt?: string; exitCode?: number; evidence?: StageEvidence; evidenceError?: { reason: string; message: string }; launchPending?: true }
17
21
  export interface Evaluation { metrics: { name: string; unit: string; value: number; provenance: "ares-observed" }[]; outputs: { path: string; sha256: string; bytes: number }[] }
18
22
  export interface Attempt {
19
- v: 1; id: string; studyId: string; run: string; protocolHash: string; sealBinding: string; commit: string; treeId: string; snapshotSha256?: string; seed: number; label: string; retryOf?: string;
23
+ v: 1 | 2 | 3; pipeline?: PipelineState; reuse?: AttemptReuseState; freshRequest?: { reuse: "off" | "eligible"; forceFresh: boolean }; id: string; studyId: string; run: string; protocolHash: string; sealBinding: string; commit: string; treeId: string; snapshotSha256?: string; seed: number; label: string; retryOf?: string;
20
24
  executor: Executor; protocol: Protocol; paths: ContainerPaths; status: AttemptStatus; stage: Stage; reason?: string; error?: string; startedAt: string; endedAt?: string;
21
25
  stages: Partial<Record<Stage, AttemptStage>>; metrics: Evaluation["metrics"]; outputs: Evaluation["outputs"];
22
26
  sealing: { separateContainers: boolean; evaluatorReadOnly: boolean; candidateHasNoEvaluator: boolean; verifiedBy: "ares-observed" };
23
27
  launching?: { pid: number; host: string; token: string; claimedAt: string; expiresAt: string };
28
+ verifiedInputs?: Record<string, string>;
29
+ gpuDevices?: string[];
24
30
  pendingAutoApproval?: string;
25
31
  finalBinding?: string; finalWinner?: string; pendingFinalApproval?: string;
26
32
  }
27
- export interface AttemptOptions { repo: string; commit: string; seed?: number; run?: string; label?: string; retry?: string; detach?: boolean; expectedId?: string }
33
+ export interface AttemptOptions { repo: string; commit: string; seed?: number; run?: string; label?: string; retry?: string; detach?: boolean; expectedId?: string; reuse?: "off" | "eligible"; forceFresh?: boolean }
28
34
  /** collectEvaluation is T4's validating adapter; T3 does not parse or validate metric schemas. */
29
35
  export interface AttemptContext { actor: Actor; runner?: ProcessRunner; now?: () => number; sleep?: (ms: number) => Promise<void>; collectEvaluation?: (attempt: Attempt, runner: ProcessRunner) => Promise<Evaluation>; collectStageEvidence?: (attempt: Attempt, stage: Stage, runner: ProcessRunner) => Promise<StageEvidence> }
30
36
  export const ATTEMPT_BYTES = 1024 * 1024;
@@ -69,13 +75,66 @@ function* records(dir: string): Generator<Attempt> {
69
75
  const path = join(dir, "runs", run, "attempts", name), stat = lstatSync(path);
70
76
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("attempt record: regular file required; restore the record without symlinks");
71
77
  const raw = readJsonFile(path, ATTEMPT_BYTES);
72
- if (plain(raw) && (raw.v !== 1 || (typeof raw.status === "string" && !STATUSES.includes(raw.status as AttemptStatus)) || (typeof raw.stage === "string" && !["candidate", "evaluator"].includes(raw.stage)))) throw new Error("attempt record: unsupported schema version, status or stage; use an ares version that supports this record, keeping the original file unchanged");
73
- if (!plain(raw) || raw.v !== 1 || raw.run !== run || raw.id !== name.slice(0, 16) || !STATUSES.includes(raw.status as AttemptStatus) || !["candidate", "evaluator"].includes(raw.stage as string) || !plain(raw.stages) || !plain(raw.protocol) || !plain(raw.executor) || typeof raw.startedAt !== "string" || !Number.isFinite(Date.parse(raw.startedAt))) throw new Error("attempt record: malformed; restore its last valid version before retrying");
78
+ const attempt = validateAttemptRecord(raw, run, name.slice(0, 16));
74
79
  if (++count > 1_000_000) throw new Error("attempt store: more than 1000000 records; archive the study and start a new one");
75
- yield raw as unknown as Attempt;
80
+ yield attempt;
76
81
  }
77
82
  }
78
83
  }
84
+ function reuseMilliseconds(value: unknown): boolean { return typeof value === "number" && Number.isFinite(value) && value >= 0; }
85
+ function reuseContext(value: unknown): boolean {
86
+ if (!plain(value) || typeof value.populationSha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.populationSha256) || !plain(value.runtime) || !plain(value.platform)) return false;
87
+ return [value.runtime.semantics, value.runtime.producerVersion, value.platform.os, value.platform.arch, value.platform.abi].every(text => typeof text === "string" && !!text.trim() && Buffer.byteLength(text) <= 128 && !/\p{Cc}/u.test(text));
88
+ }
89
+ function validateReuseState(raw: Record<string, unknown>, definition: import("./stages.ts").ProtocolV2, completed: unknown[], wanted: string, run: string): void {
90
+ const reuse = raw.reuse;
91
+ if (!plain(reuse) || !["off", "eligible"].includes(String(reuse.mode)) || typeof reuse.forceFresh !== "boolean" || !plain(reuse.stages) || Object.keys(reuse.stages).length > 16 || !reuseMilliseconds(reuse.verificationMs) || !reuseMilliseconds(reuse.materializationMs) || (reuse.failureMs !== undefined && !reuseMilliseconds(reuse.failureMs))) throw new Error("reuse: malformed attempt control receipt; restore the last valid attempt record before running ares attempt reconcile <dir>");
92
+ for (const [name, entry] of Object.entries(reuse.stages)) {
93
+ if (!definition.candidate.stages.some(stage => stage.name === name) || !plain(entry) || !["fresh", "reused"].includes(String(entry.outcome)) || typeof entry.reason !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(entry.reason) || !reuseMilliseconds(entry.verificationMs) || !reuseMilliseconds(entry.materializationMs) || (entry.key !== undefined && (typeof entry.key !== "string" || !/^[a-f0-9]{64}$/.test(entry.key) || !reuseContext(entry.context)))) throw new Error("reuse: malformed named stage outcome; restore the last valid attempt record before running ares attempt reconcile <dir>");
94
+ if (entry.outcome === "reused" && !completed.some(parent => plain(parent) && parent.name === name && plain(parent.reuse))) throw new Error("reuse: outcome has no atomic completed-stage receipt; restore the last valid attempt record before running ares attempt reconcile <dir>");
95
+ if (entry.outcome === "fresh" && entry.source !== undefined) throw new Error("reuse: fresh execution cannot carry a reused source; restore the last valid attempt record before running ares attempt reconcile <dir>");
96
+ }
97
+ const measurement = (value: unknown) => value === "unknown" || reuseMilliseconds(value);
98
+ for (const parent of completed) if (plain(parent) && parent.reuse !== undefined) {
99
+ const receipt = parent.reuse, ref = parent.ref, declared = definition.candidate.stages.find(stage => stage.name === parent.name);
100
+ if (reuse.mode !== "eligible" || reuse.forceFresh || ["ablate", "final", "posthoc"].includes(run) || !declared?.reuse || !Object.keys(declared.outputs).length || !plain(ref) || ref.attemptId === wanted || !/^[a-f0-9]{16}$/.test(String(ref.attemptId)) || !plain(receipt) || receipt.v !== 1 || typeof receipt.key !== "string" || !/^[a-f0-9]{64}$/.test(receipt.key) || canonical(receipt.source) !== canonical(ref) || !reuseContext(receipt.context) || !plain(receipt.original) || !measurement(receipt.original.wallSeconds) || !measurement(receipt.original.gpuHours) || receipt.original.cpuSeconds !== "unknown" || !reuseMilliseconds(receipt.verificationMs) || !reuseMilliseconds(receipt.materializationMs)) throw new Error("reuse: malformed source receipt; restore the last valid attempt record before running ares attempt reconcile <dir>");
101
+ const outcome = reuse.stages[parent.name as string];
102
+ if (!plain(outcome) || outcome.outcome !== "reused" || outcome.key !== receipt.key || canonical(outcome.source) !== canonical(ref) || canonical(outcome.context) !== canonical(receipt.context)) throw new Error("reuse: source receipt and admitted outcome differ; restore the last valid attempt record before running ares attempt reconcile <dir>");
103
+ }
104
+ }
105
+ /** Shared store validation for provenance snapshots without a second directory traversal. */
106
+ export function validateAttemptRecord(raw: unknown, run: string, wanted: string): Attempt {
107
+ runName(run); id(wanted);
108
+ if (plain(raw) && ((raw.v !== 1 && raw.v !== 2 && raw.v !== 3) || (typeof raw.status === "string" && !STATUSES.includes(raw.status as AttemptStatus)) || (typeof raw.stage === "string" && !["candidate", "evaluator"].includes(raw.stage)))) throw new Error("attempt record: unsupported schema version, status or stage; use an ares version that supports this record, keeping the original file unchanged");
109
+ if (!plain(raw) || (raw.v !== 1 && raw.v !== 2 && raw.v !== 3) || raw.run !== run || raw.id !== wanted || !STATUSES.includes(raw.status as AttemptStatus) || !["candidate", "evaluator"].includes(raw.stage as string) || !plain(raw.stages) || !plain(raw.protocol) || !plain(raw.executor) || typeof raw.startedAt !== "string" || !Number.isFinite(Date.parse(raw.startedAt))) throw new Error("attempt record: malformed; restore its last valid version before retrying");
110
+ if (raw.v === 2 || raw.v === 3) {
111
+ if (!plain(raw.pipeline) || !Number.isSafeInteger(raw.pipeline.index) || !Array.isArray(raw.pipeline.completed)) throw new Error("pipeline: malformed attempt state; restore its last valid record");
112
+ const definition = validateStageProtocol(raw.pipeline.definition);
113
+ if (!plain(raw.pipeline.inputHashes) || typeof raw.pipeline.taskTreeHash !== "string" || !/^[a-f0-9]{64}$/.test(raw.pipeline.taskTreeHash)) throw new Error("pipeline: invalid input snapshot identities");
114
+ if (raw.pipeline.preflightRevision !== undefined && (!Number.isSafeInteger(raw.pipeline.preflightRevision) || (raw.pipeline.preflightRevision as number) < 0)) throw new Error("pipeline: invalid launch revision");
115
+ if (raw.pipeline.reusedSidecarBytes !== undefined && (!reuseMilliseconds(raw.pipeline.reusedSidecarBytes) || (raw.pipeline.reusedSidecarBytes as number) > OUTPUT_METADATA_BYTES)) throw new Error("reuse: invalid retained metadata allowance; restore the last valid attempt record before running ares attempt reconcile <dir>");
116
+ const completed = raw.pipeline.completed;
117
+ if (completed.length !== (raw.pipeline.index as number) + (raw.stage === "evaluator" ? 1 : 0)) throw new Error("pipeline: completed stage receipts do not match current stage");
118
+ for (const [index, parent] of completed.entries()) if (!plain(parent) || parent.name !== definition.candidate.stages[index]?.name || !plain(parent.ref) || (parent.reuse === undefined && parent.ref.attemptId !== wanted) || !/^[a-f0-9]{16}$/.test(String(parent.ref.attemptId)) || parent.ref.stage !== parent.name || typeof parent.ref.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(parent.ref.sha256) || !plain(parent.record) || parent.record.exitCode !== 0 || typeof parent.record.containerId !== "string" || typeof parent.record.endedAt !== "string") throw new Error("pipeline: malformed completed-stage provenance");
119
+ if (canonical(raw.protocol) !== canonical(executionView(definition, raw.pipeline.index as number))) throw new Error("pipeline: execution projection differs from frozen definition");
120
+ if ((raw.pipeline.index as number) < 0 || (raw.pipeline.index as number) >= definition.candidate.stages.length || raw.protocolHash !== protocolHash(definition)) throw new Error("pipeline: invalid frozen identity or stage index");
121
+ if (raw.v === 3) {
122
+ validateReuseState(raw, definition, completed, wanted, run);
123
+ } else if (raw.reuse !== undefined || completed.some(parent => plain(parent) && parent.reuse !== undefined)) throw new Error("reuse: version 3 attempt required; use a compatible ares reader, keeping the original record unchanged");
124
+ } else if (raw.pipeline !== undefined) throw new Error("pipeline: version 2 attempt required");
125
+ if (Object.hasOwn(raw.protocol, "inputs")) {
126
+ const protocol = validateStoredProtocol(raw.protocol);
127
+ const expected = Object.entries(protocol.inputs ?? {}), verified = raw.verifiedInputs;
128
+ if (!plain(verified) || Object.keys(verified).length !== expected.length || expected.some(([name, input]) => verified[name] !== input.sha256)) throw new Error("attempt inputs: verified hashes do not match the frozen input identities; restore the last valid attempt record before retrying");
129
+ }
130
+ if (raw.freshRequest !== undefined && (raw.v !== 1 || !plain(raw.freshRequest) || !["off", "eligible"].includes(String(raw.freshRequest.reuse)) || typeof raw.freshRequest.forceFresh !== "boolean")) throw new Error("attempt request controls: malformed fresh request; restore the last valid record before retrying");
131
+ if (raw.executor.gpu !== undefined && plain(raw.protocol.limits) && typeof raw.protocol.limits.gpus === "number" && raw.protocol.limits.gpus > 0 && raw.gpuDevices === undefined) throw new Error("attempt GPU: frozen assignment missing; restore the chosen GPU UUIDs from the last valid attempt record before retrying");
132
+ if (raw.gpuDevices !== undefined) {
133
+ if (!plain(raw.protocol.limits)) throw new Error("attempt GPU: limits missing; restore the frozen attempt record before retrying");
134
+ validateGpuDevices(raw.gpuDevices, raw.protocol.limits.gpus as number);
135
+ }
136
+ return raw as unknown as Attempt;
137
+ }
79
138
  function load(dir: string): Attempt[] { return [...records(dir)]; }
80
139
  function studyDir(dirArg: string): string { const { dir, study } = openStudy(dirArg); requireExperiment(study); return dir; }
81
140
  /** One pass of regular, byte-bounded records; callers retain only the projections they need. */
@@ -113,7 +172,9 @@ export function showAttempt(dirArg: string, attemptId: string): Attempt {
113
172
  return found;
114
173
  }
115
174
  function save(dir: string, attempt: Attempt, ctx: AttemptContext, event: string, approvals: PendingEvent[] = []): void {
116
- commit(dir, [[file(dir, attempt), JSON.stringify(attempt, null, 2) + "\n", ATTEMPT_BYTES]], [...approvals, { actor: ctx.actor, type: event, data: { id: attempt.id, run: attempt.run, stage: attempt.stage, status: attempt.status, ...(attempt.reason ? { reason: attempt.reason } : {}) } }]);
175
+ if (attempt.pipeline && attempt.status === "running" && Buffer.byteLength(JSON.stringify(attempt, null, 2) + "\n") > ATTEMPT_BYTES - 1024) throw new EvidenceError("artifact-limit", "pipeline: reserve terminal receipt capacity within the 1 MiB attempt record");
176
+ const reused = event === "attempt.stage.reused" ? attempt.pipeline?.completed.at(-1) : undefined;
177
+ commit(dir, [[file(dir, attempt), JSON.stringify(attempt, null, 2) + "\n", ATTEMPT_BYTES]], [...approvals, { actor: ctx.actor, type: event, data: { id: attempt.id, run: attempt.run, stage: attempt.stage, status: attempt.status, ...(attempt.reason ? { reason: attempt.reason } : {}), ...(reused?.reuse ? { candidateStage: reused.name, key: reused.reuse.key, sourceAttemptId: reused.reuse.source.attemptId, sourceStage: reused.reuse.source.stage, sourceSha256: reused.reuse.source.sha256, reuse: reused.reuse } : {}) } }]);
117
178
  }
118
179
  export function budgetUsage(attempts: Attempt[], time = Date.now()) {
119
180
  let wallHours = 0, gpuHours = 0;
@@ -123,8 +184,7 @@ export function budgetUsage(attempts: Attempt[], time = Date.now()) {
123
184
  if (!Number.isFinite(elapsed)) throw new Error("attempt timing: malformed; restore valid timestamps before starting an attempt");
124
185
  wallHours += elapsed;
125
186
  // Unknown kinds cannot be accounted for safely; read-only operations do not call this function.
126
- for (const name of ["candidate", "evaluator"] as const) {
127
- const stage = attempt.stages[name];
187
+ for (const stage of [...Object.values(attempt.stages), ...(attempt.pipeline?.completed.filter(value => !value.reuse).map(value => value.record) ?? [])]) {
128
188
  if (!stage) continue;
129
189
  const end = stage.endedAt ? Date.parse(stage.endedAt) : attempt.endedAt ? Date.parse(attempt.endedAt) : time;
130
190
  const hours = Math.max(0, end - Date.parse(stage.startedAt)) / 3_600_000;
@@ -206,23 +266,52 @@ async function command(attempt: Attempt, step: string, executable: string, args:
206
266
  return result;
207
267
  } catch { throw hostError(attempt, step); }
208
268
  }
269
+ /** Locators are transient and never copied to an attempt or a second store. */
270
+ function executionProtocol(dir: string, attempt: Attempt): Protocol {
271
+ if (!Object.keys(attempt.protocol.inputs ?? {}).length) return attempt.protocol;
272
+ let current: Protocol | undefined;
273
+ try { const definition = readProtocol(dir); current = definition ? executionView(definition) : undefined; } catch { /* Return safe recovery guidance rather than private parser details. */ }
274
+ if (!current || !sameProtocolInputs(current, attempt.protocol)) throw new InputVerificationError("attempt inputs: current design identities differ from the frozen attempt; restore the matching input names, hashes and mounts in design/protocol.json before reconciling or retrying");
275
+ return { ...attempt.protocol, inputs: current.inputs };
276
+ }
209
277
  function stageRecord(attempt: Attempt, stage: Stage, user: string, ctx: AttemptContext): AttemptStage {
210
- return { image: attempt.protocol[stage].image, argv: attempt.protocol[stage].command, mounts: stage === "candidate" ? [{ target: "/workspace", readOnly: true }, { target: "/out", readOnly: false }] : [{ target: "/eval", readOnly: true }, { target: "/candidate", readOnly: true }, { target: "/result", readOnly: false }], network: "none", limits: attempt.protocol.limits, user, startedAt: at(ctx) };
278
+ return { image: attempt.protocol[stage].image, argv: attempt.protocol[stage].command, mounts: [...(stage === "candidate" ? [{ target: "/workspace", readOnly: true }, { target: "/out", readOnly: false }] : [{ target: "/eval", readOnly: true }, { target: "/candidate", readOnly: true }, { target: "/result", readOnly: false }]), ...(pipelineInputRoot(attempt) ? [{ target: "/in", readOnly: true }] : []), ...Object.values(attempt.protocol.inputs ?? {}).flatMap(input => input.mount[stage] ? [{ target: input.mount[stage]!, readOnly: true }] : [])], network: "none", limits: attempt.protocol.limits, user, containerName: stageContainerName(attempt.studyId, attempt.id, stage, attempt.pipeline && stage === "candidate" ? attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name : undefined), startedAt: at(ctx) };
211
279
  }
212
280
 
213
281
  /** Validate observed container settings before describing its sealing as ares-observed. */
214
- function observed(raw: unknown, attempt: Attempt): { id: string; running: boolean; exitCode: number; finishedAt?: string; startedAt?: string } {
282
+ function observed(raw: unknown, attempt: Attempt, protocol: Protocol, ownershipOnly = false): { id: string; running: boolean; exitCode: number; finishedAt?: string; startedAt?: string } {
215
283
  const value = Array.isArray(raw) && raw.length === 1 ? raw[0] : undefined;
216
284
  if (!plain(value) || typeof value.Id !== "string" || !/^[a-f0-9]{64}$/.test(value.Id) || !plain(value.State) || typeof value.State.Running !== "boolean" || !Number.isSafeInteger(value.State.ExitCode) || !plain(value.Config) || !plain(value.HostConfig) || !Array.isArray(value.Mounts)) throw hostError(attempt, "container inspection");
217
285
  const expected = attempt.stages[attempt.stage]!, config = value.Config, settings = value.HostConfig;
286
+ if (ownershipOnly) {
287
+ if (!plain(config.Labels) || config.Labels["ares.study"] !== attempt.studyId || config.Labels["ares.attempt"] !== attempt.id || config.Labels["ares.stage"] !== attempt.stage || (expected?.containerId && value.Id !== expected.containerId)) throw hostError(attempt, "container ownership verification");
288
+ const finishedAt = typeof value.State.FinishedAt === "string" && Number.isFinite(Date.parse(value.State.FinishedAt)) ? value.State.FinishedAt : undefined;
289
+ const startedAt = typeof value.State.StartedAt === "string" && Number.isFinite(Date.parse(value.State.StartedAt)) ? value.State.StartedAt : undefined;
290
+ return { id: value.Id, running: value.State.Running, exitCode: value.State.ExitCode as number, ...(finishedAt ? { finishedAt } : {}), ...(startedAt ? { startedAt } : {}) };
291
+ }
218
292
  const mounts = attempt.stage === "candidate" ? [[attempt.paths.snapshot, "/workspace", false], [attempt.paths.output, "/out", true]] : [[attempt.paths.evaluator, "/eval", false], [attempt.paths.output, "/candidate", false], [attempt.paths.result, "/result", true]];
293
+ const inputRoot = pipelineInputRoot(attempt);
294
+ if (inputRoot) mounts.push([inputRoot, "/in", false]);
219
295
  const bindMounts = value.Mounts.filter(m => !(plain(m) && m.Type === "tmpfs" && m.Destination === "/tmp"));
296
+ // Input content was verified at launch. A locator relocation must not invalidate an in-flight mount.
297
+ const inputs = Object.values(protocol.inputs ?? {}), visible = inputs.filter(input => input.mount[attempt.stage] !== undefined);
298
+ const privateInputs = inputs.filter(input => input.mount[attempt.stage] === undefined);
299
+ const workspace = Object.values(attempt.paths);
300
+ const inputMountsValid = visible.every(input => {
301
+ const mount = bindMounts.find(m => plain(m) && m.Destination === input.mount[attempt.stage]);
302
+ if (!plain(mount) || mount.Type !== "bind" || mount.RW !== false || typeof mount.Source !== "string" || !mount.Source.startsWith("/") || /[\0\r\n,"]/.test(mount.Source)) return false;
303
+ const source = mount.Source;
304
+ return !workspace.some(path => executionPathsOverlap(source, path)) && !privateInputs.some(other => executionPathsOverlap(source, other.path!));
305
+ });
220
306
  const devices = settings.DeviceRequests;
221
- const gpuMatches = expected.limits.gpus === 0 ? devices === null || devices === undefined || (Array.isArray(devices) && devices.length === 0) : Array.isArray(devices) && devices.length === 1 && plain(devices[0]) && devices[0].Count === expected.limits.gpus && Array.isArray(devices[0].Capabilities) && devices[0].Capabilities.some(c => Array.isArray(c) && c.includes("gpu"));
307
+ const capabilitiesMatch = Array.isArray(devices) && devices.length === 1 && plain(devices[0]) && Array.isArray(devices[0].Capabilities) && devices[0].Capabilities.some(c => Array.isArray(c) && c.includes("gpu"));
308
+ const gpuMatches = expected.limits.gpus === 0 ? devices === null || devices === undefined || (Array.isArray(devices) && devices.length === 0)
309
+ : attempt.gpuDevices !== undefined ? capabilitiesMatch && devices[0].Count === 0 && Array.isArray(devices[0].DeviceIDs) && devices[0].DeviceIDs.length === attempt.gpuDevices.length && new Set(devices[0].DeviceIDs).size === attempt.gpuDevices.length && attempt.gpuDevices.every(device => (devices[0].DeviceIDs as unknown[]).includes(device))
310
+ : capabilitiesMatch && devices[0].Count === expected.limits.gpus;
222
311
  if (!gpuMatches) throw hostError(attempt, "GPU limit verification");
223
- if (config.Seed !== `ARES_SEED=${attempt.seed}`) throw hostError(attempt, "selected seed verification");
224
- if (config.Image !== expected.image || config.User !== expected.user || JSON.stringify(config.Cmd) !== JSON.stringify(expected.argv) || !plain(config.Labels) || config.Labels["ares.study"] !== attempt.studyId || config.Labels["ares.attempt"] !== attempt.id || config.Labels["ares.stage"] !== attempt.stage || settings.NetworkMode !== "none" || settings.ReadonlyRootfs !== true || !Array.isArray(settings.CapDrop) || !settings.CapDrop.some(c => c === "ALL" || c === "all") || !Array.isArray(settings.SecurityOpt) || !settings.SecurityOpt.includes("no-new-privileges") || !plain(settings.Tmpfs) || !("/tmp" in settings.Tmpfs) || settings.Memory !== expected.limits.memoryMb * 1024 * 1024 || settings.PidsLimit !== expected.limits.pidsLimit || settings.NanoCpus !== Math.round(expected.limits.cpus * 1e9) || bindMounts.length !== mounts.length || !mounts.every(([source, target, writable]) => bindMounts.some(m => plain(m) && m.Type === "bind" && m.Source === source && m.Destination === target && m.RW === writable))) throw hostError(attempt, "container isolation verification");
225
- if (expected.containerId && value.Id !== expected.containerId) throw hostError(attempt, "container identity verification");
312
+ if (config.Seed !== (attempt.pipeline && attempt.stage === "candidate" && !attempt.pipeline!.definition.candidate.stages[attempt.pipeline!.index]!.seed ? "" : `ARES_SEED=${attempt.seed}`)) throw hostError(attempt, "selected seed verification");
313
+ if (config.Image !== expected.image || config.User !== expected.user || JSON.stringify(config.Cmd) !== JSON.stringify(expected.argv) || !plain(config.Labels) || config.Labels["ares.study"] !== attempt.studyId || config.Labels["ares.attempt"] !== attempt.id || config.Labels["ares.stage"] !== attempt.stage || settings.NetworkMode !== "none" || settings.ReadonlyRootfs !== true || !Array.isArray(settings.CapDrop) || !settings.CapDrop.some(c => c === "ALL" || c === "all") || !Array.isArray(settings.SecurityOpt) || !settings.SecurityOpt.includes("no-new-privileges") || !plain(settings.Tmpfs) || !("/tmp" in settings.Tmpfs) || settings.Memory !== expected.limits.memoryMb * 1024 * 1024 || settings.PidsLimit !== expected.limits.pidsLimit || settings.NanoCpus !== Math.round(expected.limits.cpus * 1e9) || (!inputMountsValid || bindMounts.length !== mounts.length + visible.length) || !mounts.every(([source, target, writable]) => bindMounts.some(m => plain(m) && m.Type === "bind" && m.Source === source && m.Destination === target && m.RW === writable))) throw hostError(attempt, "container isolation verification");
314
+ if (expected?.containerId && value.Id !== expected.containerId) throw hostError(attempt, "container identity verification");
226
315
  const finishedAt = typeof value.State.FinishedAt === "string" && Number.isFinite(Date.parse(value.State.FinishedAt)) ? value.State.FinishedAt : undefined;
227
316
  const startedAt = typeof value.State.StartedAt === "string" && Number.isFinite(Date.parse(value.State.StartedAt)) ? value.State.StartedAt : undefined;
228
317
  return { id: value.Id, running: value.State.Running, exitCode: value.State.ExitCode as number, ...(finishedAt ? { finishedAt } : {}), ...(startedAt ? { startedAt } : {}) };
@@ -239,7 +328,7 @@ async function recordVerifiedStage(dir: string, attempt: Attempt, state: Observe
239
328
  if (current.status !== "running" || current.stage !== attempt.stage) return undefined;
240
329
  const stage = current.stages[current.stage]!;
241
330
  stage.containerId = state.id; if (state.startedAt) stage.startedAt = state.startedAt;
242
- if (current.reason === "executor-start" || current.reason === "executor-start-uncertain") { delete current.reason; delete current.error; }
331
+ if (current.reason === "executor-start" || current.reason === "executor-start-uncertain" || current.reason === "executor-preflight" || current.reason === "executor-seal") { delete current.reason; delete current.error; }
243
332
  delete current.launching;
244
333
  if (current.stage === "candidate") {
245
334
  current.sealing.candidateHasNoEvaluator = true;
@@ -254,44 +343,208 @@ async function recordVerifiedStage(dir: string, attempt: Attempt, state: Observe
254
343
  delete current.pendingAutoApproval; delete current.pendingFinalApproval;
255
344
  } else {
256
345
  current.sealing.evaluatorReadOnly = true;
257
- current.sealing.separateContainers = !!current.stages.candidate?.containerId && state.id !== current.stages.candidate.containerId;
346
+ current.sealing.separateContainers = (current.pipeline ? current.pipeline.completed.every(parent => !!parent.record.containerId && state.id !== parent.record.containerId) : !!current.stages.candidate?.containerId && state.id !== current.stages.candidate.containerId);
258
347
  }
259
348
  return event;
260
349
  }, approvals);
261
350
  }
262
- async function inspect(attempt: Attempt, ctx: AttemptContext) {
351
+ function legacyContainerName(attempt: Attempt): string {
352
+ // Records written before study-scoped names carry no launched name; keep resolving the one they used.
353
+ const base = `ares-${attempt.id}-${attempt.stage}`;
354
+ return attempt.pipeline && attempt.stage === "candidate" ? `${base}-${attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name}` : base;
355
+ }
356
+ function attemptContainerName(attempt: Attempt): string {
357
+ return attempt.stages[attempt.stage]?.containerName ?? legacyContainerName(attempt);
358
+ }
359
+ async function inspect(dir: string, attempt: Attempt, ctx: AttemptContext, ownershipOnly = false) {
360
+ const protocol = ownershipOnly ? attempt.protocol : executionProtocol(dir, attempt);
263
361
  let result;
264
- try { result = await runOnExecutor(attempt.executor, "docker", ["inspect", "--format", INSPECT_FORMAT, containerName(attempt.id, attempt.stage)], ctx.runner ?? spawnRunner, { maxOutputBytes: ATTEMPT_BYTES }); }
362
+ try { result = await runOnExecutor(attempt.executor, "docker", ["inspect", "--format", INSPECT_FORMAT, attemptContainerName(attempt)], ctx.runner ?? spawnRunner, { maxOutputBytes: ATTEMPT_BYTES }); }
265
363
  catch { throw hostError(attempt, "container inspection"); }
266
364
  if (result.timedOut || result.truncated) throw hostError(attempt, "container inspection");
267
365
  if (result.exitCode === 1) {
268
366
  // inspect also exits 1 for daemon outages. Only a successful empty daemon listing confirms absence.
269
- const probe = await command(attempt, "container absence confirmation", "docker", ["ps", "--all", "--filter", `name=^/${containerName(attempt.id, attempt.stage)}$`, "--format", "{{.ID}}"], ctx);
367
+ const probe = await command(attempt, "container absence confirmation", "docker", ["ps", "--all", "--filter", `name=^/${attemptContainerName(attempt)}$`, "--format", "{{.ID}}"], ctx);
270
368
  if (probe.stdout.trim() === "") return undefined;
271
369
  throw hostError(attempt, "container inspection");
272
370
  }
273
371
  if (result.exitCode !== 0) throw hostError(attempt, "container inspection");
274
372
  let raw: unknown; try { raw = JSON.parse(result.stdout); } catch { throw hostError(attempt, "container inspection"); }
275
- return observed(raw, attempt);
373
+ return observed(raw, attempt, protocol, ownershipOnly);
374
+ }
375
+ /** Caller holds a fresh control fence; potentially long input hashing has already completed. */
376
+ const recoveryRunners = new WeakMap<AttemptContext, ProcessRunner>();
377
+ function boundedPipelineContext(dir: string, attempt: Attempt, ctx: AttemptContext): AttemptContext {
378
+ if (!attempt.pipeline) return ctx;
379
+ const runner = ctx.runner ?? spawnRunner;
380
+ const bounded: AttemptContext = { ...ctx, runner: async request => {
381
+ const seconds = remainingWallSeconds(dir, attempt, ctx);
382
+ const result = await runner({ ...request, timeoutMs: Math.min(request.timeoutMs ?? 300_000, seconds * 1000) });
383
+ return result;
384
+ } };
385
+ recoveryRunners.set(bounded, recoveryRunners.get(ctx) ?? runner);
386
+ return bounded;
387
+ }
388
+ function remainingWallSeconds(dir: string, attempt: Attempt, ctx: AttemptContext): number {
389
+ if (!attempt.pipeline) return attempt.protocol.limits.wallSeconds;
390
+ const usage = budgetUsage(load(dir), now(ctx)), budget = attempt.protocol.budget;
391
+ const seconds = Math.floor(Math.min(
392
+ (Date.parse(attempt.startedAt) + attempt.protocol.limits.wallSeconds * 1000 - now(ctx)) / 1000,
393
+ (budget.maxWallHours - usage.wallHours) * 3600,
394
+ attempt.protocol.limits.gpus > 0 ? (budget.maxGpuHours - usage.gpuHours) * 3600 / attempt.protocol.limits.gpus : Infinity,
395
+ ));
396
+ if (seconds < 1) throw new EvidenceError("wall-clock", "pipeline: aggregate wall budget exhausted");
397
+ return seconds;
398
+ }
399
+ function pipelineFailure(error: unknown): EvidenceError {
400
+ if (error instanceof EvidenceError) return error;
401
+ const message = error instanceof Error ? error.message : "pipeline verification failed";
402
+ if (/budget exhausted|deadline/i.test(message)) return new EvidenceError("wall-clock", message);
403
+ if (/metadata.*limit|payload.*bound|file.*bound|output budget|reservation exceeded|output.*limit/i.test(message)) return new EvidenceError("artifact-limit", message);
404
+ return new EvidenceError("evidence-read", message);
405
+ }
406
+ function pipelineFailureAt(dir: string, attempt: Attempt, error: unknown, ctx: AttemptContext): EvidenceError {
407
+ try { remainingWallSeconds(dir, attempt, ctx); } catch (budget) { return pipelineFailure(budget); }
408
+ return pipelineFailure(error);
276
409
  }
277
- async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptContext): Promise<Attempt> {
410
+ function retryablePipelineFailure(error: unknown): boolean {
411
+ if (error instanceof RetentionError) return error.retryable;
412
+ const message = error instanceof Error ? error.message : "";
413
+ return /retention operation active|executor operation failed|malformed executor receipt|mismatched executor receipt|process start failed/i.test(message);
414
+ }
415
+ async function recordPipelinePreflightFailure(dir: string, attempt: Attempt, error: unknown, ctx: AttemptContext, elapsedMs = 0): Promise<Attempt> {
416
+ try { remainingWallSeconds(dir, attempt, ctx); } catch (budget) { error = budget; }
417
+ const failure = pipelineFailure(error), retryable = retryablePipelineFailure(error) && failure.reason !== "wall-clock";
418
+ return update(dir, attempt.id, ctx, current => {
419
+ if (current.status !== "running" || current.stage !== attempt.stage || current.pipeline?.index !== attempt.pipeline?.index || current.stages[current.stage]?.containerId) return undefined;
420
+ if ((current.pipeline?.preflightRevision ?? 0) !== (attempt.pipeline?.preflightRevision ?? 0)) return undefined;
421
+ if (attempt.launching) { if (current.launching?.token !== attempt.launching.token) return undefined; }
422
+ else if (!current.stages[current.stage]?.launchPending || current.launching) return undefined;
423
+ current.error = failure.message;
424
+ if (current.reuse) current.reuse.failureMs = (current.reuse.failureMs ?? 0) + elapsedMs;
425
+ delete current.launching;
426
+ if (retryable) {
427
+ current.stages[current.stage]!.launchPending = true; current.reason = "executor-preflight";
428
+ return "attempt.executor-error";
429
+ }
430
+ delete current.stages[current.stage]!.launchPending;
431
+ finish(current, "failed", failure.reason, ctx);
432
+ return "attempt.failed";
433
+ });
434
+ }
435
+ function addMaterialization(attempt: Attempt, elapsedMs: number): void {
436
+ if (!attempt.reuse || !attempt.pipeline) return;
437
+ const name = attempt.stage === "evaluator" ? "evaluator" : attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name;
438
+ attempt.reuse.materializationMs += elapsedMs;
439
+ (attempt.pipeline.materializationMs ??= {})[name] = (attempt.pipeline.materializationMs?.[name] ?? 0) + elapsedMs;
440
+ }
441
+ async function recordMaterialization(dir: string, attempt: Attempt, elapsedMs: number, ctx: AttemptContext): Promise<Attempt> {
442
+ return update(dir, attempt.id, ctx, current => {
443
+ if (current.status !== "running" || current.stage !== attempt.stage || current.pipeline?.index !== attempt.pipeline?.index || current.launching?.token !== attempt.launching?.token) throw new InputVerificationError("reuse: stage ownership changed during materialization; run ares attempt reconcile <dir> after the active control operation finishes before retrying");
444
+ addMaterialization(current, elapsedMs); return "attempt.reuse.materialized";
445
+ });
446
+ }
447
+ async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptContext, verifiedProtocol?: Protocol): Promise<Attempt> {
448
+ const preflightStarted = performance.now();
449
+ const recoveryCtx = { ...ctx, runner: recoveryRunners.get(ctx) ?? ctx.runner };
450
+ ctx = boundedPipelineContext(dir, attempt, ctx);
451
+ let args: string[];
452
+ try {
453
+ if (attempt.reuse) {
454
+ attempt = await update(dir, attempt.id, recoveryCtx, current => {
455
+ if (current.status !== "running" || current.stage !== attempt.stage || current.pipeline?.index !== attempt.pipeline?.index || current.launching?.token !== attempt.launching?.token) throw new InputVerificationError("reuse: preflight ownership changed; run ares attempt reconcile <dir> after the active control operation finishes before retrying");
456
+ requireCopilotAccept(dir, "hypotheses");
457
+ if (designBinding(dir) !== current.sealBinding) throw new InputVerificationError("reuse: design changed before preflight; inspect ares gate list <dir>, restore or approve the current design, then run ares attempt reconcile <dir> before retrying");
458
+ requireGate(dir, openStudy(dir).study, "design", () => current.sealBinding);
459
+ if (current.stages[current.stage]!.launchPending) return undefined;
460
+ current.stages[current.stage]!.launchPending = true;
461
+ return "attempt.reuse.preflight";
462
+ });
463
+ }
464
+ if (attempt.pipeline) {
465
+ if (designBinding(dir) !== attempt.sealBinding) throw new InputVerificationError("pipeline: design changed; restore the frozen approved definition before consumption");
466
+ remainingWallSeconds(dir, attempt, ctx);
467
+ const materialized = await materializePipeline(attempt, ctx), hashes = materialized.inputHashes;
468
+ if (attempt.reuse) attempt = await recordMaterialization(dir, attempt, materialized.materializationMs, ctx);
469
+ remainingWallSeconds(dir, attempt, ctx);
470
+ if (JSON.stringify(hashes) !== JSON.stringify(attempt.pipeline!.inputHashes)) throw new InputVerificationError("pipeline: verified input identities changed before consumption");
471
+ }
472
+ const currentProtocol = executionProtocol(dir, attempt), protocol = attempt.pipeline ? currentProtocol : verifiedProtocol ?? currentProtocol;
473
+ if (!sameProtocolInputs(currentProtocol, protocol)) throw new InputVerificationError("attempt inputs: identities changed after verification; restore the frozen input identities and retry ares attempt reconcile <dir>");
474
+ if (attempt.pipeline && attempt.reuse && attempt.stage === "candidate") {
475
+ requireCopilotAccept(dir, "hypotheses");
476
+ requireGate(dir, openStudy(dir).study, "design", () => designBinding(dir));
477
+ const decision = await prepareStageReuse(dir, attempt, ctx, source => showAttempt(dir, source));
478
+ remainingWallSeconds(dir, attempt, ctx);
479
+ const approvals: PendingEvent[] = [];
480
+ const index = attempt.pipeline.index, name = attempt.pipeline.definition.candidate.stages[index]!.name;
481
+ attempt = await update(dir, attempt.id, ctx, current => {
482
+ if (current.status !== "running" || current.stage !== "candidate" || current.pipeline?.index !== index || current.pipeline.preflightRevision !== attempt.pipeline!.preflightRevision || current.launching?.token !== attempt.launching?.token) throw new InputVerificationError("reuse: stage ownership changed before admission; run ares attempt reconcile <dir> after the active control operation finishes before retrying");
483
+ if (designBinding(dir) !== current.sealBinding) throw new InputVerificationError("reuse: current design changed before admission; inspect ares gate list <dir>, restore or approve the current design, then run ares attempt reconcile <dir> before retrying");
484
+ requireCopilotAccept(dir, "hypotheses");
485
+ const gate = requireGate(dir, openStudy(dir).study, "design", () => current.sealBinding);
486
+ remainingWallSeconds(dir, current, ctx);
487
+ decision.materializationMs = current.pipeline.materializationMs?.[name] ?? 0;
488
+ if (decision.outcome === "reused") decision.receipt.materializationMs = decision.materializationMs;
489
+ current.reuse!.verificationMs += decision.verificationMs;
490
+ current.reuse!.stages[name] = { outcome: decision.outcome, reason: decision.reason, ...(decision.key ? { key: decision.key, context: decision.context } : {}), verificationMs: decision.verificationMs, materializationMs: decision.materializationMs, ...(decision.outcome === "reused" ? { source: decision.source } : {}) };
491
+ if (decision.outcome === "fresh") return "attempt.reuse.miss";
492
+ const outputs = outputBudget([...current.outputs, ...decision.outputs]);
493
+ const sidecarBytes = (current.pipeline.sidecarBytes ?? 0) + decision.manifestBytes;
494
+ if (Buffer.byteLength(JSON.stringify(outputs, null, 2)) + sidecarBytes > OUTPUT_METADATA_BYTES) throw new EvidenceError("artifact-limit", "reuse: shared output and retained metadata budget exhausted; reduce declared output count or metadata and use ares attempt run <dir> --retry ID");
495
+ current.outputs = outputs; current.pipeline.sidecarBytes = sidecarBytes;
496
+ current.pipeline.reusedSidecarBytes = (current.pipeline.reusedSidecarBytes ?? 0) + decision.manifestBytes;
497
+ current.pipeline.completed.push({ name, record: decision.record, ref: decision.source, reuse: decision.receipt });
498
+ current.sealing.candidateHasNoEvaluator = true;
499
+ if (current.pendingAutoApproval === current.sealBinding) { approvals.push(...gate); delete current.pendingAutoApproval; }
500
+ delete current.stages.candidate;
501
+ if (index + 1 < current.pipeline.definition.candidate.stages.length) { current.pipeline.index++; current.protocol = executionView(current.pipeline.definition, current.pipeline.index); }
502
+ else current.stage = "evaluator";
503
+ current.paths = pipelinePaths(current);
504
+ current.stages[current.stage] = stageRecord(current, current.stage, user, ctx);
505
+ current.stages[current.stage]!.launchPending = true; delete current.launching;
506
+ return "attempt.stage.reused";
507
+ }, approvals);
508
+ if (decision.outcome === "reused") return attempt;
509
+ }
510
+ // Keep configuration refusals outside the uncertain container-start catch.
511
+ // The record's own name is authoritative: a stage recorded before study-scoped names must start where inspect looks.
512
+ args = buildContainerArgs({ protocol, stage: attempt.stage, studyId: attempt.studyId, attemptId: attempt.id, name: attemptContainerName(attempt), seed: attempt.seed, user, paths: attempt.paths, ...(attempt.gpuDevices ? { gpuDevices: attempt.gpuDevices } : {}), ...(attempt.pipeline && attempt.stage === "candidate" ? { pipeline: { name: attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name, inputRoot: pipelineInputRoot(attempt)!, seed: attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.seed } } : {}) });
513
+ if (attempt.reuse) attempt = await update(dir, attempt.id, recoveryCtx, current => {
514
+ if (current.status !== "running" || current.stage !== attempt.stage || current.pipeline?.index !== attempt.pipeline?.index || current.launching?.token !== attempt.launching?.token) throw new InputVerificationError("reuse: container launch ownership changed; run ares attempt reconcile <dir> after the active control operation finishes before retrying");
515
+ requireCopilotAccept(dir, "hypotheses");
516
+ if (designBinding(dir) !== current.sealBinding) throw new InputVerificationError("reuse: design changed before fresh execution; inspect ares gate list <dir>, restore or approve the current design, then run ares attempt reconcile <dir> before retrying");
517
+ requireGate(dir, openStudy(dir).study, "design", () => current.sealBinding);
518
+ delete current.stages[current.stage]!.launchPending;
519
+ return "attempt.reuse.fresh-intent";
520
+ });
521
+ } catch (error) {
522
+ if (attempt.pipeline) return recordPipelinePreflightFailure(dir, attempt, error, recoveryCtx, performance.now() - preflightStarted);
523
+ if (error instanceof InputVerificationError) await update(dir, attempt.id, ctx, current => {
524
+ if (current.status !== "running" || current.stage !== attempt.stage || current.stages[current.stage]?.containerId || current.launching?.token !== attempt.launching?.token) return undefined;
525
+ const stage = current.stages[current.stage]!;
526
+ if (stage.launchPending && !current.launching) return undefined;
527
+ stage.launchPending = true; delete current.launching;
528
+ return "attempt.input-unavailable";
529
+ });
530
+ throw error;
531
+ }
278
532
  let startedId: string | undefined;
279
533
  try {
280
- const args = buildContainerArgs({ protocol: attempt.protocol, stage: attempt.stage, studyId: openStudy(dir).study.id, attemptId: attempt.id, seed: attempt.seed, user, paths: attempt.paths });
281
534
  const result = await command(attempt, "container start", "docker", args, ctx), cid = result.stdout.trim();
282
535
  if (!/^[a-f0-9]{64}$/.test(cid)) throw hostError(attempt, "container start");
283
536
  startedId = cid;
284
537
  attempt.stages[attempt.stage]!.containerId = cid;
285
- await startWatchdog(attempt.executor, attempt.id, attempt.stage, attempt.protocol.limits.wallSeconds, ctx.runner ?? spawnRunner, cid);
286
- const state = await inspect(attempt, ctx); if (!state) throw hostError(attempt, "container start verification");
538
+ await startWatchdog(attempt.executor, attemptContainerName(attempt), remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, cid);
539
+ const state = await inspect(dir, attempt, ctx); if (!state) throw hostError(attempt, "container start verification");
287
540
  return recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.started");
288
541
  } catch {
289
542
  if (!startedId) {
290
543
  try {
291
544
  // A lost response is not proof that Docker rejected the start. Adopt only a verified owned container.
292
- const state = await inspect(attempt, ctx);
545
+ const state = await inspect(dir, attempt, ctx);
293
546
  if (state) {
294
- if (state.running) await startWatchdog(attempt.executor, attempt.id, attempt.stage, attempt.protocol.limits.wallSeconds, ctx.runner ?? spawnRunner, state.id);
547
+ if (state.running) await startWatchdog(attempt.executor, attemptContainerName(attempt), remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, state.id);
295
548
  return recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.recovered");
296
549
  }
297
550
  } catch {
@@ -300,7 +553,7 @@ async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptC
300
553
  }
301
554
  // A name conflict can belong to another study with the same identity. Only clean up our returned container id.
302
555
  if (startedId) {
303
- try { await command(attempt, "failed launch cleanup", "docker", ["kill", startedId], ctx); }
556
+ try { await command(attempt, "failed launch cleanup", "docker", ["kill", startedId], recoveryCtx); }
304
557
  catch { return update(dir, attempt.id, ctx, current => { delete current.launching; current.reason = "executor-start"; current.error = hostError(current, "failed start cleanup").message; return "attempt.executor-error"; }); }
305
558
  }
306
559
  return update(dir, attempt.id, ctx, current => { if (current.status !== "running") return undefined; current.error = startupError(current, "container start"); finish(current, "failed", "executor-start", ctx); return "attempt.failed"; });
@@ -322,7 +575,16 @@ async function captureStage(dir: string, attempt: Attempt, ctx: AttemptContext,
322
575
  }
323
576
  }
324
577
 
578
+ function existingReuseControls(attempt: Attempt, options: AttemptOptions): Attempt {
579
+ const recordedMode = attempt.v === 3 ? attempt.reuse!.mode : attempt.freshRequest?.reuse ?? "off", recordedForceFresh = attempt.v === 3 ? attempt.reuse!.forceFresh : attempt.freshRequest?.forceFresh ?? false;
580
+ if ((options.reuse ?? "off") !== recordedMode || (options.forceFresh ?? false) !== recordedForceFresh) throw new Error(`attempt: existing identity recorded reuse=${recordedMode}, forceFresh=${recordedForceFresh}; resend those controls or use --retry ${attempt.id} for an explicit new attempt`);
581
+ return attempt;
582
+ }
325
583
  export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: AttemptContext): Promise<Attempt> {
584
+ if (options.reuse !== undefined && options.reuse !== "off" && options.reuse !== "eligible") throw new Error("reuse: choose off or eligible; select --reuse off|eligible (MCP reuse) and retry");
585
+ if (options.forceFresh !== undefined && typeof options.forceFresh !== "boolean") throw new Error("force-fresh: boolean required; set forceFresh to true/false or use the CLI --force-fresh flag, then retry");
586
+ const controlCtx = ctx;
587
+ const cleanupRunner = ctx.runner ?? spawnRunner;
326
588
  const dir = studyDir(dirArg), { study } = openStudy(dir);
327
589
  const frozen = await withLock(dir, () => {
328
590
  requireCopilotAccept(dir, "hypotheses");
@@ -331,7 +593,7 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
331
593
  if (!executor) throw new Error("executor: missing; run ares executor set <dir> --kind local|ssh --workdir PATH before attempt run");
332
594
  return { ...design, executor, finalSeeds: readFinalSeeds(dir, design.protocol) };
333
595
  });
334
- const { protocol, executor } = frozen;
596
+ const definition = frozen.protocol, protocol = executionView(definition), executor = frozen.executor;
335
597
  if (!/^[A-Za-z0-9_-]{1,80}$/.test(study.id)) throw new Error("study id: invalid; restore the id generated by ares init before attempt run");
336
598
  const run = runName(options.run ?? "main"), label = boundedText(options.label ?? "baseline", "label", 128), seed = options.seed ?? protocol.seeds[0]!;
337
599
  if (!Number.isSafeInteger(seed) || !protocol.seeds.includes(seed)) throw new Error("seed: undeclared; choose a seed from protocol.seeds");
@@ -340,40 +602,79 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
340
602
  const finalAuthorization = run === "final" ? await withLock(dir, () => authorizeFinalAttempt(dir, options.commit, seed)) : undefined;
341
603
  if (options.retry !== undefined) id(options.retry);
342
604
  const initialBinding = frozen.binding;
343
- const snapshot = await resolveSnapshot(options.repo, options.commit, ctx.runner ?? spawnRunner), hash = protocolHash(protocol);
605
+ const snapshot = await resolveSnapshot(options.repo, options.commit, ctx.runner ?? spawnRunner), hash = protocolHash(definition);
344
606
  const wanted = attemptId(hash, snapshot.commit, snapshot.treeId, seed, run, options.retry);
345
607
  if (options.expectedId !== undefined && wanted !== options.expectedId) throw new Error("attempt identity: changed since plan intent; reconcile the plan node before retrying");
346
- let created = false;
347
- let attempt = await withLock(dir, () => {
608
+ const inputRoot = posix.join(executor.workdir, study.id, wanted);
609
+ validateContainerInputSources(protocol, { snapshot: posix.join(inputRoot, "snapshot"), output: posix.join(inputRoot, "output"), evaluator: posix.join(inputRoot, "task", "evaluator"), result: posix.join(inputRoot, "result") });
610
+ const existingAttempt = await withLock(dir, () => load(dir).find(a => a.id === wanted)), existing = existingAttempt !== undefined;
611
+ if (existingAttempt) existingReuseControls(existingAttempt, options);
612
+ const verifiedInputs = !existing && protocol.inputs !== undefined ? await verifyExecutorInputs(executor, protocol, ctx.runner ?? spawnRunner) : undefined;
613
+ let gpuDevices: string[] | undefined;
614
+ if (!existing && executor.gpu && protocol.limits.gpus > 0) {
615
+ const admission = await probeGpuAdmission(executor, protocol.limits.gpus, ctx.runner ?? spawnRunner);
616
+ if (admission.status === "deferred") {
617
+ // An overlapping duplicate may have admitted the same identity during this read-only probe.
618
+ const duplicate = await withLock(dir, () => load(dir).find(attempt => attempt.id === wanted));
619
+ if (duplicate) return duplicate;
620
+ throw new GpuAdmissionDeferred(admission);
621
+ }
622
+ gpuDevices = admission.devices;
623
+ }
624
+ let created = false, reserved = false;
625
+ let attempt: Attempt;
626
+ try { attempt = await withLock(dir, async () => {
348
627
  requireCopilotAccept(dir, "hypotheses");
349
628
  if (run === "posthoc") requirePosthocClosed(dir);
350
629
  if (finalAuthorization && authorizeFinalAttempt(dir, options.commit, seed).binding !== finalAuthorization.binding) throw new Error("final inputs changed during snapshot resolution; approve the current final gate before retrying");
351
- const attempts = load(dir), existing = attempts.find(a => a.id === wanted); if (existing) return existing;
630
+ const attempts = load(dir), existing = attempts.find(a => a.id === wanted); if (existing) return existingReuseControls(existing, options);
352
631
  if (designBinding(dir) !== initialBinding) throw new Error("design: changed while resolving the snapshot; approve the current design and retry attempt run");
353
632
  if (options.retry && !attempts.some(a => a.id === options.retry)) throw new Error("retry: attempt not found; choose an existing id from ares attempt list");
354
633
  if (attempts.some(a => a.status === "running")) throw new Error("attempt: another attempt is running; reconcile or cancel it before starting a new one");
355
634
  const binding = designBinding(dir), approval = requireGate(dir, openStudy(dir).study, "design", () => binding);
356
635
  enforceBudget(protocol, attempts, now(ctx));
636
+ if (definition.v === 2) { await retainedOperation(executor, { op: "reserve", studyId: study.id, attemptId: wanted, ...(executor.retentionCapBytes === undefined ? {} : { capBytes: executor.retentionCapBytes }) }, cleanupRunner); reserved = true; }
357
637
  const root = posix.join(executor.workdir, study.id, wanted);
358
- const record: Attempt = { v: 1, id: wanted, studyId: study.id, run, protocolHash: hash, sealBinding: binding!, ...snapshot, seed, label, ...(options.retry ? { retryOf: options.retry } : {}), executor, protocol, paths: { snapshot: posix.join(root, "snapshot"), output: posix.join(root, "output"), evaluator: posix.join(root, "task", "evaluator"), result: posix.join(root, "result") }, status: "running", stage: "candidate", startedAt: at(ctx), stages: {}, metrics: [], outputs: [], sealing: { separateContainers: false, evaluatorReadOnly: false, candidateHasNoEvaluator: false, verifiedBy: "ares-observed" }, launching: owner(ctx) };
638
+ const controlled = definition.v === 2 && (options.reuse === "eligible" || options.forceFresh === true);
639
+ const record: Attempt = { v: controlled ? 3 : definition.v, ...(definition.v === 1 && (options.reuse !== undefined || options.forceFresh !== undefined) ? { freshRequest: { reuse: options.reuse ?? "off", forceFresh: options.forceFresh ?? false } } : {}), ...(controlled ? { reuse: { mode: options.reuse ?? "off", forceFresh: options.forceFresh ?? false, stages: {}, verificationMs: 0, materializationMs: 0, failureMs: 0 } } : {}), ...(definition.v === 2 ? { pipeline: { definition, index: 0, completed: [], inputHashes: {}, taskTreeHash: frozen.treeHash } } : {}), id: wanted, studyId: study.id, run, protocolHash: hash, sealBinding: binding!, ...snapshot, seed, label, ...(options.retry ? { retryOf: options.retry } : {}), executor, ...(gpuDevices ? { gpuDevices } : {}), protocol: frozenProtocol(protocol), ...(verifiedInputs !== undefined ? { verifiedInputs } : {}), paths: { snapshot: posix.join(root, "snapshot"), output: posix.join(root, "output"), evaluator: posix.join(root, "task", "evaluator"), result: posix.join(root, "result") }, status: "running", stage: "candidate", startedAt: at(ctx), stages: {}, metrics: [], outputs: [], sealing: { separateContainers: false, evaluatorReadOnly: false, candidateHasNoEvaluator: false, verifiedBy: "ares-observed" }, launching: owner(ctx) };
640
+ if (record.pipeline) record.paths = pipelinePaths(record);
359
641
  if (approval.length) record.pendingAutoApproval = binding!;
360
642
  if (finalAuthorization) { record.finalBinding = finalAuthorization.binding; record.finalWinner = finalAuthorization.winner; if (finalAuthorization.auto) record.pendingFinalApproval = finalAuthorization.binding; }
361
643
  commit(dir, [[file(dir, record), JSON.stringify(record, null, 2) + "\n", ATTEMPT_BYTES]], [{ actor: ctx.actor, type: "attempt.started", data: { id: wanted, run, seed, commit: record.commit, treeId: record.treeId } }]);
362
644
  created = true; return record;
363
- });
645
+ }); } catch (error) {
646
+ if (reserved) await withLock(dir, async () => {
647
+ if (!load(dir).some(record => record.id === wanted)) await retainedOperation(executor, { op: "release", studyId: study.id, attemptId: wanted }, cleanupRunner);
648
+ });
649
+ throw error;
650
+ }
651
+ if (attempt.pipeline) ctx = boundedPipelineContext(dir, attempt, ctx);
364
652
  if (created) {
365
653
  let preparationStep = "executor check";
366
654
  try {
367
- const checked = await checkExecutorInputs(attempt.executor, attempt.protocol, ctx.runner ?? spawnRunner);
655
+ const checked = await checkExecutorInputs(attempt.executor, executionProtocol(dir, attempt), ctx.runner ?? spawnRunner);
368
656
  const root = posix.dirname(attempt.paths.snapshot), studyRoot = posix.dirname(root), base = executor.workdir;
369
657
  // Require a private, owned, physical root. Attempt mkdir is exclusive, never a shared pre-existing directory.
370
- const script = `set -eu; umask 077; base=${shellQuote(base)}; test -d "$base"; test ! -L "$base"; test -O "$base"; test "$(cd -P "$base" && pwd -P)" = "$base"; mode=$(stat -c %a "$base" 2>/dev/null || stat -f %Lp "$base"); test "$mode" = 700; study=${shellQuote(studyRoot)}; if test ! -e "$study"; then mkdir -m 700 "$study"; fi; test -d "$study"; test ! -L "$study"; test -O "$study"; mode=$(stat -c %a "$study" 2>/dev/null || stat -f %Lp "$study"); test "$mode" = 700; mkdir -m 700 ${shellQuote(root)}; mkdir -m 700 ${[attempt.paths.snapshot, attempt.paths.output, attempt.paths.result, posix.dirname(attempt.paths.evaluator)].map(shellQuote).join(" ")}`;
658
+ const stageDirectories = attempt.pipeline ? attempt.pipeline.definition.candidate.stages.map(stage => posix.join(root, "stages", stage.name, "output")) : [];
659
+ const script = `set -eu; umask 077; base=${shellQuote(base)}; test -d "$base"; test ! -L "$base"; test -O "$base"; test "$(cd -P "$base" && pwd -P)" = "$base"; mode=$(stat -c %a "$base" 2>/dev/null || stat -f %Lp "$base"); test "$mode" = 700; study=${shellQuote(studyRoot)}; if test ! -e "$study"; then mkdir -m 700 "$study"; fi; test -d "$study"; test ! -L "$study"; test -O "$study"; mode=$(stat -c %a "$study" 2>/dev/null || stat -f %Lp "$study"); test "$mode" = 700; mkdir -m 700 ${shellQuote(root)}; mkdir -p -m 700 ${stageDirectories.length ? stageDirectories.map(shellQuote).join(" ") : shellQuote(posix.join(root, "stages"))}; mkdir -m 700 ${[attempt.paths.snapshot, ...(!attempt.pipeline ? [attempt.paths.output] : []), attempt.paths.result, posix.dirname(attempt.paths.evaluator)].map(shellQuote).join(" ")}`;
371
660
  preparationStep = "private workspace preparation";
372
661
  await command(attempt, "private workspace preparation", "sh", ["-c", script], ctx);
373
662
  preparationStep = "snapshot transfer";
374
663
  const transferred = await transferSnapshot(options.repo, snapshot.commit, executor, attempt.paths.snapshot, ctx.runner ?? spawnRunner);
664
+ if (attempt.pipeline) {
665
+ preparationStep = "code snapshot verification";
666
+ const receipt = await retainedOperation(attempt.executor, { op: "snapshot", studyId: attempt.studyId, attemptId: attempt.id, source: attempt.paths.snapshot }, ctx.runner ?? spawnRunner);
667
+ if (!receipt.sha256 || !/^[a-f0-9]{64}$/.test(receipt.sha256)) throw new Error("pipeline: invalid frozen code snapshot receipt");
668
+ attempt = await update(dir, attempt.id, ctx, current => { current.pipeline!.codeSnapshotHash = receipt.sha256; return "attempt.pipeline.code"; });
669
+ }
375
670
  preparationStep = "evaluator transfer";
376
- await transferTask(join(dir, "task"), executor, posix.dirname(attempt.paths.evaluator), ctx.runner ?? spawnRunner, frozen.treeHash);
671
+ await transferTask(join(dir, "task"), executor, posix.dirname(attempt.paths.evaluator), ctx.runner ?? spawnRunner, frozen.treeHash, !!attempt.pipeline);
672
+ if (attempt.pipeline) {
673
+ for (let index = 1; index < attempt.pipeline.definition.candidate.stages.length; index++) await checkExecutorInputs(executor, executionView(attempt.pipeline.definition, index), ctx.runner ?? spawnRunner);
674
+ const materialized = await materializePipeline(attempt, ctx);
675
+ if (attempt.reuse) attempt = await recordMaterialization(dir, attempt, materialized.materializationMs, ctx);
676
+ attempt = await update(dir, attempt.id, ctx, current => { current.pipeline!.inputHashes = materialized.inputHashes; return "attempt.pipeline.inputs"; });
677
+ }
377
678
  preparationStep = "design recheck";
378
679
  if (designBinding(dir) !== attempt.sealBinding) throw new Error("design changed during preparation");
379
680
  if (attempt.finalBinding && finalGateBinding(dir) !== attempt.finalBinding) throw new Error("final inputs changed during preparation");
@@ -383,40 +684,93 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
383
684
  attempt = await withControl(dir, async () => {
384
685
  const current = showAttempt(dir, attempt.id);
385
686
  if (current.status !== "running" || current.launching?.token !== claim) return current;
386
- return launch(dir, current, checked.user, ctx);
687
+ return launch(dir, current, checked.user, ctx, protocol);
387
688
  });
388
- } catch {
389
- attempt = await update(dir, attempt.id, ctx, current => { if (current.status !== "running") return undefined; current.error = startupError(current, preparationStep); finish(current, "failed", "preparation", ctx); return "attempt.failed"; });
689
+ } catch (error) {
690
+ if (!attempt.pipeline && error instanceof InputVerificationError) throw error;
691
+ const failure = attempt.pipeline ? pipelineFailureAt(dir, attempt, error, controlCtx) : undefined;
692
+ attempt = await update(dir, attempt.id, ctx, current => { if (current.status !== "running") return undefined; current.error = failure ? `${preparationStep}: ${failure.message}` : startupError(current, preparationStep); finish(current, "failed", failure?.reason ?? "preparation", ctx); return "attempt.failed"; });
390
693
  }
391
694
  }
695
+ if (attempt.pipeline && attempt.status === "failed") await reconcileRetentionReservations(dir, controlCtx);
392
696
  if (!options.detach) {
393
697
  let delay = 1000;
394
698
  while (attempt.status === "running") {
395
699
  await (ctx.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms))))(delay);
396
700
  const previousStage = attempt.stage;
397
- await reconcileAttempts(dir, ctx); attempt = showAttempt(dir, wanted);
701
+ await reconcileAttempts(dir, controlCtx); attempt = showAttempt(dir, wanted);
398
702
  delay = attempt.stage === previousStage ? Math.min(delay * 2, 30_000) : 1000;
399
703
  }
400
704
  }
401
705
  return attempt;
402
706
  }
403
707
 
708
+ async function verifyAndLaunchPending(dir: string, pending: Attempt, ctx: AttemptContext): Promise<Attempt | undefined> {
709
+ ctx = boundedPipelineContext(dir, pending, ctx);
710
+ const protocol = executionProtocol(dir, pending);
711
+ let hashes: Record<string, string> | undefined, materializationMs = 0;
712
+ const preflightStarted = performance.now();
713
+ try {
714
+ if (pending.reuse) {
715
+ requireCopilotAccept(dir, "hypotheses");
716
+ if (designBinding(dir) !== pending.sealBinding) throw new InputVerificationError("reuse: design changed before pending consumption; inspect ares gate list <dir>, restore or approve the current design, then run ares attempt reconcile <dir> before retrying");
717
+ requireGate(dir, openStudy(dir).study, "design", () => pending.sealBinding);
718
+ }
719
+ const materialized = pending.pipeline ? await materializePipeline(pending, ctx) : undefined;
720
+ hashes = materialized?.inputHashes; materializationMs = materialized?.materializationMs ?? 0;
721
+ validateContainerInputSources(protocol, pending.paths);
722
+ await verifyExecutorInputs(pending.executor, protocol, ctx.runner ?? spawnRunner);
723
+ } catch (error) {
724
+ if (!pending.pipeline) throw error;
725
+ return withControl(dir, () => recordPipelinePreflightFailure(dir, pending, error, ctx, performance.now() - preflightStarted));
726
+ }
727
+ return withControl(dir, async () => {
728
+ const current = showAttempt(dir, pending.id);
729
+ if (current.status !== "running" || current.stage !== pending.stage || !current.stages[current.stage]?.launchPending || alive(current, ctx)) return undefined;
730
+ if (pending.pipeline && (current.pipeline?.index !== pending.pipeline.index || current.protocolHash !== pending.protocolHash || (current.pipeline?.preflightRevision ?? 0) !== (pending.pipeline.preflightRevision ?? 0) || canonical(current.protocol) !== canonical(protocol))) return undefined;
731
+ executionProtocol(dir, current); // Recheck the frozen identities after hashing, under the fresh launch fence.
732
+ const claimed = await update(dir, current.id, ctx, value => {
733
+ if (hashes) value.pipeline!.inputHashes = hashes;
734
+ if (value.reuse) addMaterialization(value, materializationMs);
735
+ if (value.pipeline) value.pipeline.preflightRevision = (value.pipeline.preflightRevision ?? 0) + 1;
736
+ delete value.stages[value.stage]!.launchPending; value.launching = owner(ctx);
737
+ return "attempt.stage.retry-intent";
738
+ });
739
+ return launch(dir, claimed, claimed.stages[claimed.stage]!.user, ctx, protocol);
740
+ });
741
+ }
742
+
404
743
  export async function reconcileAttempts(dirArg: string, ctx: AttemptContext): Promise<Attempt[]> {
405
744
  const dir = studyDir(dirArg);
406
- return withControl(dir, async () => {
745
+ const pending: Attempt[] = [];
746
+ const changed = await withControl(dir, async () => {
407
747
  const changed: Attempt[] = [];
408
748
  for (let attempt of load(dir).filter(a => a.status === "running")) {
409
749
  if (alive(attempt, ctx)) continue;
750
+ let observedState: ObservedStage | undefined;
410
751
  try {
411
- let state = await inspect(attempt, ctx);
412
- if (!state) { changed.push(await update(dir, attempt.id, ctx, current => { finish(current, "unknown", "lost", ctx); return "attempt.unknown"; })); continue; }
752
+ let state = await inspect(dir, attempt, ctx);
753
+ observedState = state;
754
+ if (!state) {
755
+ if (attempt.stages[attempt.stage]?.launchPending) pending.push(attempt);
756
+ else changed.push(await update(dir, attempt.id, ctx, current => { finish(current, "unknown", "lost", ctx); return "attempt.unknown"; }));
757
+ continue;
758
+ }
413
759
  const recovered = needsReceipt(attempt, state);
414
760
  if (recovered) attempt = await recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.recovered");
415
761
  const stage = attempt.stages[attempt.stage];
416
762
  if (!stage) throw hostError(attempt, "stage record");
417
- const deadline = Date.parse(stage.startedAt) + stage.limits.wallSeconds * 1000;
418
- if ((state.running && now(ctx) >= deadline) || (!state.running && state.finishedAt !== undefined && Date.parse(state.finishedAt) >= deadline)) {
419
- if (state.running) { await command(attempt, "wall-clock kill", "docker", ["kill", state.id], ctx); const stopped = await inspect(attempt, ctx); if (stopped) state = stopped; }
763
+ const deadline = (attempt.pipeline ? Date.parse(attempt.startedAt) : Date.parse(stage.startedAt)) + stage.limits.wallSeconds * 1000;
764
+ const usage = attempt.pipeline ? budgetUsage(load(dir), now(ctx)) : undefined;
765
+ const exhausted = usage && (usage.wallHours >= attempt.protocol.budget.maxWallHours || (attempt.protocol.limits.gpus > 0 && usage.gpuHours >= attempt.protocol.budget.maxGpuHours));
766
+ if ((state.running && (now(ctx) >= deadline || exhausted)) || (!state.running && ((attempt.pipeline && (now(ctx) >= deadline || exhausted)) || (state.finishedAt !== undefined && Date.parse(state.finishedAt) >= deadline)))) {
767
+ if (state.running) {
768
+ await command(attempt, "wall-clock kill", "docker", ["kill", state.id], ctx);
769
+ const stopped = await inspect(dir, attempt, ctx);
770
+ if (stopped) state = stopped;
771
+ else if (attempt.pipeline) state = { ...state, running: false, exitCode: 137, finishedAt: at(ctx) };
772
+ if (attempt.pipeline && state.running) throw new EvidenceError("executor-stop", "pipeline: container termination is not yet observed; active attempt and retention reservation remain held");
773
+ }
420
774
  attempt = await captureStage(dir, attempt, ctx, true);
421
775
  const ended = state;
422
776
  changed.push(await update(dir, attempt.id, ctx, current => { if (ended.finishedAt) current.stages[current.stage]!.endedAt = ended.finishedAt; if (!ended.running) current.stages[current.stage]!.exitCode = ended.exitCode; finish(current, "failed", "wall-clock", ctx); return "attempt.failed"; })); continue;
@@ -426,36 +780,110 @@ export async function reconcileAttempts(dirArg: string, ctx: AttemptContext): Pr
426
780
  continue;
427
781
  }
428
782
  if (state.exitCode !== 0) { attempt = await captureStage(dir, attempt, ctx, true); const ended = state; changed.push(await update(dir, attempt.id, ctx, current => { current.stages[current.stage]!.exitCode = ended.exitCode; if (ended.finishedAt) current.stages[current.stage]!.endedAt = ended.finishedAt; finish(current, "failed", `${current.stage}-exit`, ctx); return "attempt.failed"; })); continue; }
429
- try { attempt = await captureStage(dir, attempt, ctx, false); }
783
+ try { attempt = await captureStage(dir, attempt, boundedPipelineContext(dir, attempt, ctx), false); }
430
784
  catch (error) {
431
- const failure = error as EvidenceError, ended = state;
785
+ const failure = attempt.pipeline ? pipelineFailureAt(dir, attempt, error, ctx) : error as EvidenceError, ended = state;
432
786
  changed.push(await update(dir, attempt.id, ctx, current => {
433
787
  current.stages[current.stage]!.exitCode = ended.exitCode;
434
788
  if (ended.finishedAt) current.stages[current.stage]!.endedAt = ended.finishedAt;
435
789
  current.error = failure.message; finish(current, "failed", failure.reason, ctx); return "attempt.failed";
436
790
  })); continue;
437
791
  }
438
- if (attempt.stage === "candidate") {
439
- const next = await update(dir, attempt.id, ctx, current => { current.stages.candidate!.exitCode = 0; current.stages.candidate!.endedAt = state.finishedAt ?? at(ctx); current.stage = "evaluator"; current.stages.evaluator = stageRecord(current, "evaluator", stage.user, ctx); current.launching = owner(ctx); return "attempt.stage.changed"; });
440
- changed.push(await launch(dir, next, stage.user, ctx));
792
+ if (attempt.stage === "candidate" && attempt.pipeline) {
793
+ attempt = await update(dir, attempt.id, ctx, current => { current.stages.candidate!.exitCode = 0; current.stages.candidate!.endedAt = state.finishedAt ?? at(ctx); return "attempt.stage.terminated"; });
794
+ const ref = await sealPipeline(attempt, boundedPipelineContext(dir, attempt, ctx));
795
+ const next = await update(dir, attempt.id, ctx, current => {
796
+ const pipeline = current.pipeline!, completed = current.stages.candidate!;
797
+ pipeline.sidecarBytes = attempt.pipeline!.sidecarBytes;
798
+ pipeline.completed.push({ name: pipeline.definition.candidate.stages[pipeline.index]!.name, record: completed, ref });
799
+ delete current.stages.candidate;
800
+ if (pipeline.index + 1 < pipeline.definition.candidate.stages.length) { pipeline.index++; current.protocol = executionView(pipeline.definition, pipeline.index); }
801
+ else current.stage = "evaluator";
802
+ current.paths = pipelinePaths(current);
803
+ current.stages[current.stage] = stageRecord(current, current.stage, stage.user, ctx);
804
+ current.stages[current.stage]!.launchPending = true; delete current.launching;
805
+ return "attempt.stage.changed";
806
+ });
807
+ pending.push(next);
808
+ } else if (attempt.stage === "candidate") {
809
+ const next = await update(dir, attempt.id, ctx, current => {
810
+ current.stages.candidate!.exitCode = 0; current.stages.candidate!.endedAt = state.finishedAt ?? at(ctx); current.stage = "evaluator";
811
+ current.stages.evaluator = stageRecord(current, "evaluator", stage.user, ctx);
812
+ if (Object.keys(current.protocol.inputs ?? {}).length) { current.stages.evaluator.launchPending = true; delete current.launching; }
813
+ else current.launching = owner(ctx);
814
+ return "attempt.stage.changed";
815
+ });
816
+ if (next.stages.evaluator?.launchPending) pending.push(next);
817
+ else changed.push(await launch(dir, next, stage.user, ctx));
441
818
  } else {
442
819
  let evaluation: Evaluation | undefined, failure: EvidenceError | undefined;
443
- try { evaluation = await (ctx.collectEvaluation ?? defaultEvaluationCollector)(attempt, ctx.runner ?? spawnRunner); }
444
- catch (error) { failure = error instanceof EvidenceError ? error : new MetricsError("invalid-metrics", "evaluator result validation failed"); }
820
+ try {
821
+ const bounded = boundedPipelineContext(dir, attempt, ctx);
822
+ evaluation = await (ctx.collectEvaluation ?? defaultEvaluationCollector)(attempt, bounded.runner ?? spawnRunner);
823
+ if (attempt.pipeline) remainingWallSeconds(dir, attempt, ctx);
824
+ }
825
+ catch (error) {
826
+ evaluation = undefined;
827
+ if (attempt.pipeline) failure = pipelineFailureAt(dir, attempt, error, ctx);
828
+ else failure = error instanceof EvidenceError ? error : new MetricsError("invalid-metrics", "evaluator result validation failed");
829
+ }
445
830
  changed.push(await update(dir, attempt.id, ctx, current => {
446
831
  current.stages.evaluator!.exitCode = 0;
447
832
  if (state.finishedAt) current.stages.evaluator!.endedAt = state.finishedAt;
448
833
  if (!evaluation) { const rejected = failure ?? new MetricsError("invalid-metrics", "the collector returned no result"); current.error = rejected.message; finish(current, "failed", rejected.reason, ctx); return "attempt.failed"; }
834
+ if (current.pipeline && Buffer.byteLength(JSON.stringify(outputBudget([...current.outputs, ...evaluation.outputs]), null, 2)) + (current.pipeline.sidecarBytes ?? 0) > OUTPUT_METADATA_BYTES) {
835
+ current.error = "pipeline: total output metadata including retained sidecars exceeds the attempt limit"; finish(current, "failed", "artifact-limit", ctx); return "attempt.failed";
836
+ }
449
837
  current.metrics = evaluation.metrics; current.outputs = outputBudget([...current.outputs, ...evaluation.outputs]); finish(current, "succeeded", undefined, ctx); return "attempt.succeeded";
450
838
  }));
451
839
  }
452
- } catch {
453
- await update(dir, attempt.id, ctx, current => { delete current.launching; return "attempt.executor-error"; });
840
+ } catch (error) {
841
+ if (attempt.pipeline && observedState && !observedState.running) {
842
+ const failure = pipelineFailureAt(dir, attempt, error, ctx);
843
+ const retryable = retryablePipelineFailure(error) && failure.reason !== "wall-clock";
844
+ changed.push(await update(dir, attempt.id, ctx, current => {
845
+ if (current.status !== "running") return undefined;
846
+ const stage = current.stages[current.stage];
847
+ if (stage) { stage.exitCode = observedState!.exitCode; stage.endedAt = observedState!.finishedAt ?? at(ctx); delete stage.launchPending; }
848
+ current.error = failure.message;
849
+ if (retryable) { current.reason = "executor-seal"; return "attempt.executor-error"; }
850
+ finish(current, "failed", failure.reason, ctx); return "attempt.failed";
851
+ }));
852
+ continue;
853
+ }
854
+ if (error instanceof InputVerificationError) throw error;
855
+ await update(dir, attempt.id, ctx, current => { delete current.launching; current.error = error instanceof Error ? error.message : hostError(current, "reconcile").message; if (current.pipeline && error instanceof EvidenceError) current.reason = error.reason; return "attempt.executor-error"; });
454
856
  throw hostError(attempt, "reconcile");
455
857
  }
456
858
  }
457
859
  return changed;
458
860
  });
861
+ // No control lock or launch claim is held across a potentially 40-minute manifest pass.
862
+ for (const attempt of pending) {
863
+ const launched = await verifyAndLaunchPending(dir, attempt, ctx);
864
+ if (launched) changed.push(launched);
865
+ }
866
+ await reconcileRetentionReservations(dir, ctx);
867
+ return changed;
868
+ }
869
+ /** Explicit reconciliation only frees a hold after the executor confirms no owned live container. */
870
+ async function reconcileRetentionReservations(dir: string, ctx: AttemptContext): Promise<void> {
871
+ const executor = readExecutor(dir), { study } = openStudy(dir);
872
+ if (!executor || (!load(dir).some(attempt => !!attempt.pipeline) && readProtocol(dir)?.v !== 2)) return;
873
+ if (load(dir).some(attempt => attempt.status === "running")) return;
874
+ const view = await retainedOperation(executor, { op: "inspect", studyId: study.id }, ctx.runner ?? spawnRunner);
875
+ for (const reservation of view.reservations ?? []) {
876
+ if (!reservation.active) continue;
877
+ const attempt = load(dir).find(value => value.id === reservation.attemptId);
878
+ if (attempt?.status === "running") continue;
879
+ try { await withControl(dir, () => withLock(dir, async () => {
880
+ const current = load(dir).find(value => value.id === reservation.attemptId);
881
+ if (current?.status === "running") return;
882
+ const live = await runOnExecutor(executor, "docker", ["ps", "--filter", `label=ares.study=${study.id}`, "--filter", `label=ares.attempt=${reservation.attemptId}`, "--format", "{{.ID}}"], ctx.runner ?? spawnRunner);
883
+ if (live.exitCode !== 0 || live.timedOut || live.truncated || live.stdout.trim()) return;
884
+ await retainedOperation(executor, { op: "release", studyId: study.id, attemptId: reservation.attemptId }, ctx.runner ?? spawnRunner);
885
+ })); } catch (error) { if (!(error instanceof StudyLockBusyError)) throw error; }
886
+ }
459
887
  }
460
888
  export async function cancelAttempt(dirArg: string, wanted: string, reason: string | undefined, ctx: AttemptContext, completion?: (attempt: Attempt) => PendingEvent[]): Promise<Attempt> {
461
889
  const dir = studyDir(dirArg), why = reason === undefined ? undefined : boundedText(reason, "reason", 500);
@@ -469,14 +897,26 @@ export async function cancelAttempt(dirArg: string, wanted: string, reason: stri
469
897
  });
470
898
  if (alive(attempt, ctx)) throw new Error("attempt: another startup operation is active; retry cancel when it finishes (abandoned claims expire after 30 minutes)");
471
899
  try {
472
- let state = await inspect(attempt, ctx);
473
- if (state && needsReceipt(attempt, state)) attempt = await recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.recovered", false);
474
- if (state?.running) { await command(attempt, "cancel kill", "docker", ["kill", state.id], ctx); state = await inspect(attempt, ctx); }
900
+ let state = await inspect(dir, attempt, ctx, true);
901
+ if (state && needsReceipt(attempt, state)) {
902
+ const owned = state;
903
+ attempt = await update(dir, attempt.id, ctx, current => {
904
+ current.stages[current.stage]!.containerId = owned.id;
905
+ if (owned.startedAt) current.stages[current.stage]!.startedAt = owned.startedAt;
906
+ delete current.launching;
907
+ // Ownership permits cancellation; it does not establish isolation or approve any gate.
908
+ return "attempt.stage.recovered";
909
+ });
910
+ }
911
+ if (state?.running) { await command(attempt, "cancel kill", "docker", ["kill", state.id], ctx); state = await inspect(dir, attempt, ctx, true); }
912
+ if (attempt.pipeline && state?.running) throw hostError(attempt, "cancellation termination confirmation");
475
913
  if (state) attempt = await captureStage(dir, attempt, ctx, true);
914
+ if (attempt.pipeline) await retainedOperation(attempt.executor, { op: "release", studyId: attempt.studyId, attemptId: attempt.id }, ctx.runner ?? spawnRunner);
476
915
  const ended = state;
477
916
  return update(dir, attempt.id, ctx, current => { if (ended && !ended.running) { current.stages[current.stage]!.exitCode = ended.exitCode; if (ended.finishedAt) current.stages[current.stage]!.endedAt = ended.finishedAt; } finish(current, "cancelled", why ?? "cancelled", ctx); return "attempt.cancelled"; }, [], completion);
478
- } catch {
917
+ } catch (error) {
479
918
  await update(dir, attempt.id, ctx, current => { delete current.launching; return "attempt.executor-error"; });
919
+ if (error instanceof InputVerificationError) throw error;
480
920
  throw hostError(attempt, "cancel");
481
921
  }
482
922
  });