@staix/agent-research 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +137 -0
  2. package/README.md +356 -31
  3. package/package.json +4 -2
  4. package/src/autonomy.ts +50 -0
  5. package/src/cli.ts +134 -14
  6. package/src/commands-table.ts +43 -9
  7. package/src/commands.ts +244 -43
  8. package/src/copilot.ts +91 -0
  9. package/src/exp/attempts.ts +512 -69
  10. package/src/exp/executor.ts +235 -12
  11. package/src/exp/final.ts +1 -1
  12. package/src/exp/investigate.ts +7 -2
  13. package/src/exp/logs.ts +25 -12
  14. package/src/exp/metrics.ts +6 -5
  15. package/src/exp/pipeline.ts +92 -0
  16. package/src/exp/protocol.ts +88 -18
  17. package/src/exp/retention-script.ts +649 -0
  18. package/src/exp/retention.ts +70 -0
  19. package/src/exp/reuse-admission.ts +63 -0
  20. package/src/exp/reuse-contract.ts +48 -0
  21. package/src/exp/reuse-runtime.ts +87 -0
  22. package/src/exp/reuse.ts +87 -0
  23. package/src/exp/selection.ts +1 -1
  24. package/src/exp/snapshot.ts +3 -3
  25. package/src/exp/stages.ts +117 -0
  26. package/src/harness/experience-source.ts +34 -0
  27. package/src/harness/experience.ts +206 -0
  28. package/src/harness/hub-guidance.ts +140 -0
  29. package/src/harness/hub-reference.ts +18 -0
  30. package/src/harness/lesson-candidates.ts +162 -0
  31. package/src/harness/limits.ts +2 -0
  32. package/src/harness/privacy.ts +4 -0
  33. package/src/harness/receipts.ts +84 -0
  34. package/src/harness/rounds.ts +198 -0
  35. package/src/harness/transitions.ts +152 -0
  36. package/src/http.ts +46 -2
  37. package/src/lit/candidates.ts +13 -5
  38. package/src/lit/cards.ts +55 -4
  39. package/src/lit/flow.ts +82 -0
  40. package/src/lit/queries.ts +62 -0
  41. package/src/lit/watch.ts +14 -1
  42. package/src/manifest.ts +15 -7
  43. package/src/mcp-tools.ts +140 -32
  44. package/src/mcp.ts +6 -0
  45. package/src/memory/amem-show.ts +135 -0
  46. package/src/memory/amem.ts +3 -0
  47. package/src/memory/archive.ts +20 -8
  48. package/src/memory/evidence-local.ts +77 -0
  49. package/src/memory/evidence.ts +39 -0
  50. package/src/memory/lessons.ts +4 -2
  51. package/src/memory/skill-check.ts +56 -0
  52. package/src/memory/skill-format.ts +77 -0
  53. package/src/memory/skills.ts +72 -26
  54. package/src/memory/source-budget.ts +11 -0
  55. package/src/memory/vault-cards.ts +226 -0
  56. package/src/paper/build.ts +20 -8
  57. package/src/paper/check.ts +40 -12
  58. package/src/paper/headings.ts +39 -0
  59. package/src/paper/hygiene.ts +153 -0
  60. package/src/paper/placeholders.ts +21 -4
  61. package/src/paper/plan.ts +170 -0
  62. package/src/paper/point-evidence.ts +63 -0
  63. package/src/paper/points.ts +83 -0
  64. package/src/paper/review.ts +116 -11
  65. package/src/paper/scopes.ts +51 -0
  66. package/src/plan/controller.ts +42 -12
  67. package/src/plan/definition.ts +22 -6
  68. package/src/plan/hub.ts +6 -0
  69. package/src/plan/state.ts +58 -17
  70. package/src/playbook.ts +47 -20
  71. package/src/privacy.ts +9 -0
  72. package/src/provenance.ts +679 -0
  73. package/src/scope.ts +24 -3
  74. package/src/study-export.ts +282 -0
  75. package/src/study.ts +94 -26
  76. package/src/ui/panel.css +4 -0
  77. package/src/ui/panel.js +271 -9
  78. package/src/ui/plugin.ts +89 -17
@@ -1,33 +1,43 @@
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";
5
+ import { requireCopilotAccept } from "../copilot.ts";
6
+ import { resolveAutonomy } from "../autonomy.ts";
1
7
  import { readFinalSeeds, authorizeFinalAttempt, finalGateBinding, requirePosthocClosed } from "./final.ts";
2
8
  import { closeSync, existsSync, lstatSync, openSync, opendirSync, statSync, unlinkSync, writeSync } from "node:fs";
3
9
  import { hostname } from "node:os";
4
10
  import { join, posix } from "node:path";
5
11
  import { randomUUID } from "node:crypto";
6
12
  import { AsyncLocalStorage } from "node:async_hooks";
7
- import { boundedText, commit, openStudy, plain, readJsonFile, readTextBounded, requireExperiment, requireGate, sha256, withLock, type Actor, type PendingEvent } from "../study.ts";
8
- import { designBinding, protocolHash, readDesign, type Protocol } from "./protocol.ts";
9
- 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, containerName, readExecutor, runOnExecutor, shellQuote, spawnRunner, startWatchdog, type ContainerPaths, type Executor, type ProcessRunner, type Stage } from "./executor.ts";
10
16
  import { resolveSnapshot, transferSnapshot, transferTask } from "./snapshot.ts";
11
- 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";
12
18
 
13
19
  export type AttemptStatus = "running" | "succeeded" | "failed" | "cancelled" | "unknown";
14
- 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; containerId?: string; startedAt: string; endedAt?: string; exitCode?: number; evidence?: StageEvidence; evidenceError?: { reason: string; message: string }; launchPending?: true }
15
21
  export interface Evaluation { metrics: { name: string; unit: string; value: number; provenance: "ares-observed" }[]; outputs: { path: string; sha256: string; bytes: number }[] }
16
22
  export interface Attempt {
17
- 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;
18
24
  executor: Executor; protocol: Protocol; paths: ContainerPaths; status: AttemptStatus; stage: Stage; reason?: string; error?: string; startedAt: string; endedAt?: string;
19
25
  stages: Partial<Record<Stage, AttemptStage>>; metrics: Evaluation["metrics"]; outputs: Evaluation["outputs"];
20
26
  sealing: { separateContainers: boolean; evaluatorReadOnly: boolean; candidateHasNoEvaluator: boolean; verifiedBy: "ares-observed" };
21
27
  launching?: { pid: number; host: string; token: string; claimedAt: string; expiresAt: string };
28
+ verifiedInputs?: Record<string, string>;
29
+ gpuDevices?: string[];
22
30
  pendingAutoApproval?: string;
23
31
  finalBinding?: string; finalWinner?: string; pendingFinalApproval?: string;
24
32
  }
25
- 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 }
26
34
  /** collectEvaluation is T4's validating adapter; T3 does not parse or validate metric schemas. */
27
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> }
28
36
  export const ATTEMPT_BYTES = 1024 * 1024;
29
37
  // Startup includes bounded image pulls and two 5-minute transfers; claims never survive indefinitely after a crash.
30
38
  export const CONTROL_STALE_MS = 30 * 60_000;
39
+ // Filesystem mtime has sub-ms precision; Date.now is integral. Tolerate small future skew on live locks.
40
+ export const CONTROL_FUTURE_SKEW_MS = 60_000;
31
41
  const controlScope = new AsyncLocalStorage<{ dir: string; token: string }>();
32
42
  const STATUSES: AttemptStatus[] = ["running", "succeeded", "failed", "cancelled", "unknown"];
33
43
  const inspectFields = (prefix: string, fields: string[]) => fields.map(field => `${JSON.stringify(field)}:{{json ${prefix}.${field}}}`).join(",");
@@ -65,13 +75,66 @@ function* records(dir: string): Generator<Attempt> {
65
75
  const path = join(dir, "runs", run, "attempts", name), stat = lstatSync(path);
66
76
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("attempt record: regular file required; restore the record without symlinks");
67
77
  const raw = readJsonFile(path, ATTEMPT_BYTES);
68
- 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");
69
- 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));
70
79
  if (++count > 1_000_000) throw new Error("attempt store: more than 1000000 records; archive the study and start a new one");
71
- yield raw as unknown as Attempt;
80
+ yield attempt;
72
81
  }
73
82
  }
74
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
+ }
75
138
  function load(dir: string): Attempt[] { return [...records(dir)]; }
76
139
  function studyDir(dirArg: string): string { const { dir, study } = openStudy(dirArg); requireExperiment(study); return dir; }
77
140
  /** One pass of regular, byte-bounded records; callers retain only the projections they need. */
@@ -109,7 +172,9 @@ export function showAttempt(dirArg: string, attemptId: string): Attempt {
109
172
  return found;
110
173
  }
111
174
  function save(dir: string, attempt: Attempt, ctx: AttemptContext, event: string, approvals: PendingEvent[] = []): void {
112
- 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 } : {}) } }]);
113
178
  }
114
179
  export function budgetUsage(attempts: Attempt[], time = Date.now()) {
115
180
  let wallHours = 0, gpuHours = 0;
@@ -119,8 +184,7 @@ export function budgetUsage(attempts: Attempt[], time = Date.now()) {
119
184
  if (!Number.isFinite(elapsed)) throw new Error("attempt timing: malformed; restore valid timestamps before starting an attempt");
120
185
  wallHours += elapsed;
121
186
  // Unknown kinds cannot be accounted for safely; read-only operations do not call this function.
122
- for (const name of ["candidate", "evaluator"] as const) {
123
- 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) ?? [])]) {
124
188
  if (!stage) continue;
125
189
  const end = stage.endedAt ? Date.parse(stage.endedAt) : attempt.endedAt ? Date.parse(attempt.endedAt) : time;
126
190
  const hours = Math.max(0, end - Date.parse(stage.startedAt)) / 3_600_000;
@@ -159,7 +223,7 @@ async function withControl<T>(dir: string, fn: () => Promise<T>): Promise<T> {
159
223
  if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
160
224
  let age = 0; try { age = Date.now() - statSync(path).mtimeMs; } catch { /* owner removed it */ }
161
225
  if (performance.now() - waitingSince >= 2000) throw new Error("attempt control: another operation is active; retry reconcile or cancel when it finishes (abandoned claims expire after 30 minutes)");
162
- if (age < 0 || age >= CONTROL_STALE_MS) {
226
+ if (age < -CONTROL_FUTURE_SKEW_MS || age >= CONTROL_STALE_MS) {
163
227
  try { unlinkSync(path); }
164
228
  catch (failure) { if ((failure as NodeJS.ErrnoException).code !== "ENOENT") throw new Error("attempt control: abandoned lock could not be removed; restore study-directory ownership and permissions, then retry"); }
165
229
  continue;
@@ -202,23 +266,52 @@ async function command(attempt: Attempt, step: string, executable: string, args:
202
266
  return result;
203
267
  } catch { throw hostError(attempt, step); }
204
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
+ }
205
277
  function stageRecord(attempt: Attempt, stage: Stage, user: string, ctx: AttemptContext): AttemptStage {
206
- 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, startedAt: at(ctx) };
207
279
  }
208
280
 
209
281
  /** Validate observed container settings before describing its sealing as ares-observed. */
210
- 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 } {
211
283
  const value = Array.isArray(raw) && raw.length === 1 ? raw[0] : undefined;
212
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");
213
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
+ }
214
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]);
215
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
+ });
216
306
  const devices = settings.DeviceRequests;
217
- 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;
218
311
  if (!gpuMatches) throw hostError(attempt, "GPU limit verification");
219
- if (config.Seed !== `ARES_SEED=${attempt.seed}`) throw hostError(attempt, "selected seed verification");
220
- 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");
221
- 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");
222
315
  const finishedAt = typeof value.State.FinishedAt === "string" && Number.isFinite(Date.parse(value.State.FinishedAt)) ? value.State.FinishedAt : undefined;
223
316
  const startedAt = typeof value.State.StartedAt === "string" && Number.isFinite(Date.parse(value.State.StartedAt)) ? value.State.StartedAt : undefined;
224
317
  return { id: value.Id, running: value.State.Running, exitCode: value.State.ExitCode as number, ...(finishedAt ? { finishedAt } : {}), ...(startedAt ? { startedAt } : {}) };
@@ -235,57 +328,218 @@ async function recordVerifiedStage(dir: string, attempt: Attempt, state: Observe
235
328
  if (current.status !== "running" || current.stage !== attempt.stage) return undefined;
236
329
  const stage = current.stages[current.stage]!;
237
330
  stage.containerId = state.id; if (state.startedAt) stage.startedAt = state.startedAt;
238
- 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; }
239
332
  delete current.launching;
240
333
  if (current.stage === "candidate") {
241
334
  current.sealing.candidateHasNoEvaluator = true;
242
335
  if (approveDesign && current.pendingAutoApproval === current.sealBinding && designBinding(dir) === current.sealBinding) {
243
- approvals.push(...requireGate(dir, { ...openStudy(dir).study, autonomy: "auto" }, "design", () => current.sealBinding));
336
+ const study = openStudy(dir).study;
337
+ if (resolveAutonomy(study.autonomy, "design") === "auto") approvals.push(...requireGate(dir, study, "design", () => current.sealBinding));
244
338
  }
245
339
  if (approveDesign && current.pendingFinalApproval === current.finalBinding && current.finalBinding && finalGateBinding(dir) === current.finalBinding) {
246
- approvals.push(...requireGate(dir, { ...openStudy(dir).study, autonomy: "auto" }, "final", () => current.finalBinding));
340
+ const study = openStudy(dir).study;
341
+ if (resolveAutonomy(study.autonomy, "final") === "auto") approvals.push(...requireGate(dir, study, "final", () => current.finalBinding));
247
342
  }
248
343
  delete current.pendingAutoApproval; delete current.pendingFinalApproval;
249
344
  } else {
250
345
  current.sealing.evaluatorReadOnly = true;
251
- 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);
252
347
  }
253
348
  return event;
254
349
  }, approvals);
255
350
  }
256
- async function inspect(attempt: Attempt, ctx: AttemptContext) {
351
+ function attemptContainerName(attempt: Attempt): string {
352
+ const base = containerName(attempt.id, attempt.stage);
353
+ return attempt.pipeline && attempt.stage === "candidate" ? `${base}-${attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name}` : base;
354
+ }
355
+ async function inspect(dir: string, attempt: Attempt, ctx: AttemptContext, ownershipOnly = false) {
356
+ const protocol = ownershipOnly ? attempt.protocol : executionProtocol(dir, attempt);
257
357
  let result;
258
- try { result = await runOnExecutor(attempt.executor, "docker", ["inspect", "--format", INSPECT_FORMAT, containerName(attempt.id, attempt.stage)], ctx.runner ?? spawnRunner, { maxOutputBytes: ATTEMPT_BYTES }); }
358
+ try { result = await runOnExecutor(attempt.executor, "docker", ["inspect", "--format", INSPECT_FORMAT, attemptContainerName(attempt)], ctx.runner ?? spawnRunner, { maxOutputBytes: ATTEMPT_BYTES }); }
259
359
  catch { throw hostError(attempt, "container inspection"); }
260
360
  if (result.timedOut || result.truncated) throw hostError(attempt, "container inspection");
261
361
  if (result.exitCode === 1) {
262
362
  // inspect also exits 1 for daemon outages. Only a successful empty daemon listing confirms absence.
263
- const probe = await command(attempt, "container absence confirmation", "docker", ["ps", "--all", "--filter", `name=^/${containerName(attempt.id, attempt.stage)}$`, "--format", "{{.ID}}"], ctx);
363
+ const probe = await command(attempt, "container absence confirmation", "docker", ["ps", "--all", "--filter", `name=^/${attemptContainerName(attempt)}$`, "--format", "{{.ID}}"], ctx);
264
364
  if (probe.stdout.trim() === "") return undefined;
265
365
  throw hostError(attempt, "container inspection");
266
366
  }
267
367
  if (result.exitCode !== 0) throw hostError(attempt, "container inspection");
268
368
  let raw: unknown; try { raw = JSON.parse(result.stdout); } catch { throw hostError(attempt, "container inspection"); }
269
- return observed(raw, attempt);
369
+ return observed(raw, attempt, protocol, ownershipOnly);
370
+ }
371
+ /** Caller holds a fresh control fence; potentially long input hashing has already completed. */
372
+ const recoveryRunners = new WeakMap<AttemptContext, ProcessRunner>();
373
+ function boundedPipelineContext(dir: string, attempt: Attempt, ctx: AttemptContext): AttemptContext {
374
+ if (!attempt.pipeline) return ctx;
375
+ const runner = ctx.runner ?? spawnRunner;
376
+ const bounded: AttemptContext = { ...ctx, runner: async request => {
377
+ const seconds = remainingWallSeconds(dir, attempt, ctx);
378
+ const result = await runner({ ...request, timeoutMs: Math.min(request.timeoutMs ?? 300_000, seconds * 1000) });
379
+ return result;
380
+ } };
381
+ recoveryRunners.set(bounded, recoveryRunners.get(ctx) ?? runner);
382
+ return bounded;
383
+ }
384
+ function remainingWallSeconds(dir: string, attempt: Attempt, ctx: AttemptContext): number {
385
+ if (!attempt.pipeline) return attempt.protocol.limits.wallSeconds;
386
+ const usage = budgetUsage(load(dir), now(ctx)), budget = attempt.protocol.budget;
387
+ const seconds = Math.floor(Math.min(
388
+ (Date.parse(attempt.startedAt) + attempt.protocol.limits.wallSeconds * 1000 - now(ctx)) / 1000,
389
+ (budget.maxWallHours - usage.wallHours) * 3600,
390
+ attempt.protocol.limits.gpus > 0 ? (budget.maxGpuHours - usage.gpuHours) * 3600 / attempt.protocol.limits.gpus : Infinity,
391
+ ));
392
+ if (seconds < 1) throw new EvidenceError("wall-clock", "pipeline: aggregate wall budget exhausted");
393
+ return seconds;
394
+ }
395
+ function pipelineFailure(error: unknown): EvidenceError {
396
+ if (error instanceof EvidenceError) return error;
397
+ const message = error instanceof Error ? error.message : "pipeline verification failed";
398
+ if (/budget exhausted|deadline/i.test(message)) return new EvidenceError("wall-clock", message);
399
+ if (/metadata.*limit|payload.*bound|file.*bound|output budget|reservation exceeded|output.*limit/i.test(message)) return new EvidenceError("artifact-limit", message);
400
+ return new EvidenceError("evidence-read", message);
401
+ }
402
+ function pipelineFailureAt(dir: string, attempt: Attempt, error: unknown, ctx: AttemptContext): EvidenceError {
403
+ try { remainingWallSeconds(dir, attempt, ctx); } catch (budget) { return pipelineFailure(budget); }
404
+ return pipelineFailure(error);
405
+ }
406
+ function retryablePipelineFailure(error: unknown): boolean {
407
+ if (error instanceof RetentionError) return error.retryable;
408
+ const message = error instanceof Error ? error.message : "";
409
+ return /retention operation active|executor operation failed|malformed executor receipt|mismatched executor receipt|process start failed/i.test(message);
270
410
  }
271
- async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptContext): Promise<Attempt> {
411
+ async function recordPipelinePreflightFailure(dir: string, attempt: Attempt, error: unknown, ctx: AttemptContext, elapsedMs = 0): Promise<Attempt> {
412
+ try { remainingWallSeconds(dir, attempt, ctx); } catch (budget) { error = budget; }
413
+ const failure = pipelineFailure(error), retryable = retryablePipelineFailure(error) && failure.reason !== "wall-clock";
414
+ return update(dir, attempt.id, ctx, current => {
415
+ if (current.status !== "running" || current.stage !== attempt.stage || current.pipeline?.index !== attempt.pipeline?.index || current.stages[current.stage]?.containerId) return undefined;
416
+ if ((current.pipeline?.preflightRevision ?? 0) !== (attempt.pipeline?.preflightRevision ?? 0)) return undefined;
417
+ if (attempt.launching) { if (current.launching?.token !== attempt.launching.token) return undefined; }
418
+ else if (!current.stages[current.stage]?.launchPending || current.launching) return undefined;
419
+ current.error = failure.message;
420
+ if (current.reuse) current.reuse.failureMs = (current.reuse.failureMs ?? 0) + elapsedMs;
421
+ delete current.launching;
422
+ if (retryable) {
423
+ current.stages[current.stage]!.launchPending = true; current.reason = "executor-preflight";
424
+ return "attempt.executor-error";
425
+ }
426
+ delete current.stages[current.stage]!.launchPending;
427
+ finish(current, "failed", failure.reason, ctx);
428
+ return "attempt.failed";
429
+ });
430
+ }
431
+ function addMaterialization(attempt: Attempt, elapsedMs: number): void {
432
+ if (!attempt.reuse || !attempt.pipeline) return;
433
+ const name = attempt.stage === "evaluator" ? "evaluator" : attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name;
434
+ attempt.reuse.materializationMs += elapsedMs;
435
+ (attempt.pipeline.materializationMs ??= {})[name] = (attempt.pipeline.materializationMs?.[name] ?? 0) + elapsedMs;
436
+ }
437
+ async function recordMaterialization(dir: string, attempt: Attempt, elapsedMs: number, ctx: AttemptContext): Promise<Attempt> {
438
+ return update(dir, attempt.id, ctx, current => {
439
+ 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");
440
+ addMaterialization(current, elapsedMs); return "attempt.reuse.materialized";
441
+ });
442
+ }
443
+ async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptContext, verifiedProtocol?: Protocol): Promise<Attempt> {
444
+ const preflightStarted = performance.now();
445
+ const recoveryCtx = { ...ctx, runner: recoveryRunners.get(ctx) ?? ctx.runner };
446
+ ctx = boundedPipelineContext(dir, attempt, ctx);
447
+ let args: string[];
448
+ try {
449
+ if (attempt.reuse) {
450
+ attempt = await update(dir, attempt.id, recoveryCtx, current => {
451
+ 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");
452
+ requireCopilotAccept(dir, "hypotheses");
453
+ 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");
454
+ requireGate(dir, openStudy(dir).study, "design", () => current.sealBinding);
455
+ if (current.stages[current.stage]!.launchPending) return undefined;
456
+ current.stages[current.stage]!.launchPending = true;
457
+ return "attempt.reuse.preflight";
458
+ });
459
+ }
460
+ if (attempt.pipeline) {
461
+ if (designBinding(dir) !== attempt.sealBinding) throw new InputVerificationError("pipeline: design changed; restore the frozen approved definition before consumption");
462
+ remainingWallSeconds(dir, attempt, ctx);
463
+ const materialized = await materializePipeline(attempt, ctx), hashes = materialized.inputHashes;
464
+ if (attempt.reuse) attempt = await recordMaterialization(dir, attempt, materialized.materializationMs, ctx);
465
+ remainingWallSeconds(dir, attempt, ctx);
466
+ if (JSON.stringify(hashes) !== JSON.stringify(attempt.pipeline!.inputHashes)) throw new InputVerificationError("pipeline: verified input identities changed before consumption");
467
+ }
468
+ const currentProtocol = executionProtocol(dir, attempt), protocol = attempt.pipeline ? currentProtocol : verifiedProtocol ?? currentProtocol;
469
+ if (!sameProtocolInputs(currentProtocol, protocol)) throw new InputVerificationError("attempt inputs: identities changed after verification; restore the frozen input identities and retry ares attempt reconcile <dir>");
470
+ if (attempt.pipeline && attempt.reuse && attempt.stage === "candidate") {
471
+ requireCopilotAccept(dir, "hypotheses");
472
+ requireGate(dir, openStudy(dir).study, "design", () => designBinding(dir));
473
+ const decision = await prepareStageReuse(dir, attempt, ctx, source => showAttempt(dir, source));
474
+ remainingWallSeconds(dir, attempt, ctx);
475
+ const approvals: PendingEvent[] = [];
476
+ const index = attempt.pipeline.index, name = attempt.pipeline.definition.candidate.stages[index]!.name;
477
+ attempt = await update(dir, attempt.id, ctx, current => {
478
+ 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");
479
+ 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");
480
+ requireCopilotAccept(dir, "hypotheses");
481
+ const gate = requireGate(dir, openStudy(dir).study, "design", () => current.sealBinding);
482
+ remainingWallSeconds(dir, current, ctx);
483
+ decision.materializationMs = current.pipeline.materializationMs?.[name] ?? 0;
484
+ if (decision.outcome === "reused") decision.receipt.materializationMs = decision.materializationMs;
485
+ current.reuse!.verificationMs += decision.verificationMs;
486
+ 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 } : {}) };
487
+ if (decision.outcome === "fresh") return "attempt.reuse.miss";
488
+ const outputs = outputBudget([...current.outputs, ...decision.outputs]);
489
+ const sidecarBytes = (current.pipeline.sidecarBytes ?? 0) + decision.manifestBytes;
490
+ 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");
491
+ current.outputs = outputs; current.pipeline.sidecarBytes = sidecarBytes;
492
+ current.pipeline.reusedSidecarBytes = (current.pipeline.reusedSidecarBytes ?? 0) + decision.manifestBytes;
493
+ current.pipeline.completed.push({ name, record: decision.record, ref: decision.source, reuse: decision.receipt });
494
+ current.sealing.candidateHasNoEvaluator = true;
495
+ if (current.pendingAutoApproval === current.sealBinding) { approvals.push(...gate); delete current.pendingAutoApproval; }
496
+ delete current.stages.candidate;
497
+ if (index + 1 < current.pipeline.definition.candidate.stages.length) { current.pipeline.index++; current.protocol = executionView(current.pipeline.definition, current.pipeline.index); }
498
+ else current.stage = "evaluator";
499
+ current.paths = pipelinePaths(current);
500
+ current.stages[current.stage] = stageRecord(current, current.stage, user, ctx);
501
+ current.stages[current.stage]!.launchPending = true; delete current.launching;
502
+ return "attempt.stage.reused";
503
+ }, approvals);
504
+ if (decision.outcome === "reused") return attempt;
505
+ }
506
+ // Keep configuration refusals outside the uncertain container-start catch.
507
+ args = buildContainerArgs({ protocol, stage: attempt.stage, studyId: openStudy(dir).study.id, attemptId: attempt.id, 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 } } : {}) });
508
+ if (attempt.reuse) attempt = await update(dir, attempt.id, recoveryCtx, current => {
509
+ 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");
510
+ requireCopilotAccept(dir, "hypotheses");
511
+ 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");
512
+ requireGate(dir, openStudy(dir).study, "design", () => current.sealBinding);
513
+ delete current.stages[current.stage]!.launchPending;
514
+ return "attempt.reuse.fresh-intent";
515
+ });
516
+ } catch (error) {
517
+ if (attempt.pipeline) return recordPipelinePreflightFailure(dir, attempt, error, recoveryCtx, performance.now() - preflightStarted);
518
+ if (error instanceof InputVerificationError) await update(dir, attempt.id, ctx, current => {
519
+ if (current.status !== "running" || current.stage !== attempt.stage || current.stages[current.stage]?.containerId || current.launching?.token !== attempt.launching?.token) return undefined;
520
+ const stage = current.stages[current.stage]!;
521
+ if (stage.launchPending && !current.launching) return undefined;
522
+ stage.launchPending = true; delete current.launching;
523
+ return "attempt.input-unavailable";
524
+ });
525
+ throw error;
526
+ }
272
527
  let startedId: string | undefined;
273
528
  try {
274
- const args = buildContainerArgs({ protocol: attempt.protocol, stage: attempt.stage, studyId: openStudy(dir).study.id, attemptId: attempt.id, seed: attempt.seed, user, paths: attempt.paths });
275
529
  const result = await command(attempt, "container start", "docker", args, ctx), cid = result.stdout.trim();
276
530
  if (!/^[a-f0-9]{64}$/.test(cid)) throw hostError(attempt, "container start");
277
531
  startedId = cid;
278
532
  attempt.stages[attempt.stage]!.containerId = cid;
279
- await startWatchdog(attempt.executor, attempt.id, attempt.stage, attempt.protocol.limits.wallSeconds, ctx.runner ?? spawnRunner, cid);
280
- const state = await inspect(attempt, ctx); if (!state) throw hostError(attempt, "container start verification");
533
+ await startWatchdog(attempt.executor, attempt.id, attempt.stage, remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, cid);
534
+ const state = await inspect(dir, attempt, ctx); if (!state) throw hostError(attempt, "container start verification");
281
535
  return recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.started");
282
536
  } catch {
283
537
  if (!startedId) {
284
538
  try {
285
539
  // A lost response is not proof that Docker rejected the start. Adopt only a verified owned container.
286
- const state = await inspect(attempt, ctx);
540
+ const state = await inspect(dir, attempt, ctx);
287
541
  if (state) {
288
- if (state.running) await startWatchdog(attempt.executor, attempt.id, attempt.stage, attempt.protocol.limits.wallSeconds, ctx.runner ?? spawnRunner, state.id);
542
+ if (state.running) await startWatchdog(attempt.executor, attempt.id, attempt.stage, remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, state.id);
289
543
  return recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.recovered");
290
544
  }
291
545
  } catch {
@@ -294,7 +548,7 @@ async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptC
294
548
  }
295
549
  // A name conflict can belong to another study with the same identity. Only clean up our returned container id.
296
550
  if (startedId) {
297
- try { await command(attempt, "failed launch cleanup", "docker", ["kill", startedId], ctx); }
551
+ try { await command(attempt, "failed launch cleanup", "docker", ["kill", startedId], recoveryCtx); }
298
552
  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"; }); }
299
553
  }
300
554
  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"; });
@@ -316,15 +570,25 @@ async function captureStage(dir: string, attempt: Attempt, ctx: AttemptContext,
316
570
  }
317
571
  }
318
572
 
573
+ function existingReuseControls(attempt: Attempt, options: AttemptOptions): Attempt {
574
+ const recordedMode = attempt.v === 3 ? attempt.reuse!.mode : attempt.freshRequest?.reuse ?? "off", recordedForceFresh = attempt.v === 3 ? attempt.reuse!.forceFresh : attempt.freshRequest?.forceFresh ?? false;
575
+ 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`);
576
+ return attempt;
577
+ }
319
578
  export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: AttemptContext): Promise<Attempt> {
579
+ 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");
580
+ 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");
581
+ const controlCtx = ctx;
582
+ const cleanupRunner = ctx.runner ?? spawnRunner;
320
583
  const dir = studyDir(dirArg), { study } = openStudy(dir);
321
584
  const frozen = await withLock(dir, () => {
585
+ requireCopilotAccept(dir, "hypotheses");
322
586
  const design = readDesign(dir), executor = readExecutor(dir);
323
587
  if (!design) throw new Error("protocol: missing; run ares protocol <dir> --file PATH before attempt run");
324
588
  if (!executor) throw new Error("executor: missing; run ares executor set <dir> --kind local|ssh --workdir PATH before attempt run");
325
589
  return { ...design, executor, finalSeeds: readFinalSeeds(dir, design.protocol) };
326
590
  });
327
- const { protocol, executor } = frozen;
591
+ const definition = frozen.protocol, protocol = executionView(definition), executor = frozen.executor;
328
592
  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");
329
593
  const run = runName(options.run ?? "main"), label = boundedText(options.label ?? "baseline", "label", 128), seed = options.seed ?? protocol.seeds[0]!;
330
594
  if (!Number.isSafeInteger(seed) || !protocol.seeds.includes(seed)) throw new Error("seed: undeclared; choose a seed from protocol.seeds");
@@ -333,39 +597,79 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
333
597
  const finalAuthorization = run === "final" ? await withLock(dir, () => authorizeFinalAttempt(dir, options.commit, seed)) : undefined;
334
598
  if (options.retry !== undefined) id(options.retry);
335
599
  const initialBinding = frozen.binding;
336
- const snapshot = await resolveSnapshot(options.repo, options.commit, ctx.runner ?? spawnRunner), hash = protocolHash(protocol);
600
+ const snapshot = await resolveSnapshot(options.repo, options.commit, ctx.runner ?? spawnRunner), hash = protocolHash(definition);
337
601
  const wanted = attemptId(hash, snapshot.commit, snapshot.treeId, seed, run, options.retry);
338
602
  if (options.expectedId !== undefined && wanted !== options.expectedId) throw new Error("attempt identity: changed since plan intent; reconcile the plan node before retrying");
339
- let created = false;
340
- let attempt = await withLock(dir, () => {
603
+ const inputRoot = posix.join(executor.workdir, study.id, wanted);
604
+ validateContainerInputSources(protocol, { snapshot: posix.join(inputRoot, "snapshot"), output: posix.join(inputRoot, "output"), evaluator: posix.join(inputRoot, "task", "evaluator"), result: posix.join(inputRoot, "result") });
605
+ const existingAttempt = await withLock(dir, () => load(dir).find(a => a.id === wanted)), existing = existingAttempt !== undefined;
606
+ if (existingAttempt) existingReuseControls(existingAttempt, options);
607
+ const verifiedInputs = !existing && protocol.inputs !== undefined ? await verifyExecutorInputs(executor, protocol, ctx.runner ?? spawnRunner) : undefined;
608
+ let gpuDevices: string[] | undefined;
609
+ if (!existing && executor.gpu && protocol.limits.gpus > 0) {
610
+ const admission = await probeGpuAdmission(executor, protocol.limits.gpus, ctx.runner ?? spawnRunner);
611
+ if (admission.status === "deferred") {
612
+ // An overlapping duplicate may have admitted the same identity during this read-only probe.
613
+ const duplicate = await withLock(dir, () => load(dir).find(attempt => attempt.id === wanted));
614
+ if (duplicate) return duplicate;
615
+ throw new GpuAdmissionDeferred(admission);
616
+ }
617
+ gpuDevices = admission.devices;
618
+ }
619
+ let created = false, reserved = false;
620
+ let attempt: Attempt;
621
+ try { attempt = await withLock(dir, async () => {
622
+ requireCopilotAccept(dir, "hypotheses");
341
623
  if (run === "posthoc") requirePosthocClosed(dir);
342
624
  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");
343
- const attempts = load(dir), existing = attempts.find(a => a.id === wanted); if (existing) return existing;
625
+ const attempts = load(dir), existing = attempts.find(a => a.id === wanted); if (existing) return existingReuseControls(existing, options);
344
626
  if (designBinding(dir) !== initialBinding) throw new Error("design: changed while resolving the snapshot; approve the current design and retry attempt run");
345
627
  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");
346
628
  if (attempts.some(a => a.status === "running")) throw new Error("attempt: another attempt is running; reconcile or cancel it before starting a new one");
347
- const binding = designBinding(dir), approval = requireGate(dir, study, "design", () => binding);
629
+ const binding = designBinding(dir), approval = requireGate(dir, openStudy(dir).study, "design", () => binding);
348
630
  enforceBudget(protocol, attempts, now(ctx));
631
+ if (definition.v === 2) { await retainedOperation(executor, { op: "reserve", studyId: study.id, attemptId: wanted, ...(executor.retentionCapBytes === undefined ? {} : { capBytes: executor.retentionCapBytes }) }, cleanupRunner); reserved = true; }
349
632
  const root = posix.join(executor.workdir, study.id, wanted);
350
- 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) };
633
+ const controlled = definition.v === 2 && (options.reuse === "eligible" || options.forceFresh === true);
634
+ 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) };
635
+ if (record.pipeline) record.paths = pipelinePaths(record);
351
636
  if (approval.length) record.pendingAutoApproval = binding!;
352
637
  if (finalAuthorization) { record.finalBinding = finalAuthorization.binding; record.finalWinner = finalAuthorization.winner; if (finalAuthorization.auto) record.pendingFinalApproval = finalAuthorization.binding; }
353
638
  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 } }]);
354
639
  created = true; return record;
355
- });
640
+ }); } catch (error) {
641
+ if (reserved) await withLock(dir, async () => {
642
+ if (!load(dir).some(record => record.id === wanted)) await retainedOperation(executor, { op: "release", studyId: study.id, attemptId: wanted }, cleanupRunner);
643
+ });
644
+ throw error;
645
+ }
646
+ if (attempt.pipeline) ctx = boundedPipelineContext(dir, attempt, ctx);
356
647
  if (created) {
357
648
  let preparationStep = "executor check";
358
649
  try {
359
- const checked = await checkExecutorInputs(attempt.executor, attempt.protocol, ctx.runner ?? spawnRunner);
650
+ const checked = await checkExecutorInputs(attempt.executor, executionProtocol(dir, attempt), ctx.runner ?? spawnRunner);
360
651
  const root = posix.dirname(attempt.paths.snapshot), studyRoot = posix.dirname(root), base = executor.workdir;
361
652
  // Require a private, owned, physical root. Attempt mkdir is exclusive, never a shared pre-existing directory.
362
- 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(" ")}`;
653
+ const stageDirectories = attempt.pipeline ? attempt.pipeline.definition.candidate.stages.map(stage => posix.join(root, "stages", stage.name, "output")) : [];
654
+ 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(" ")}`;
363
655
  preparationStep = "private workspace preparation";
364
656
  await command(attempt, "private workspace preparation", "sh", ["-c", script], ctx);
365
657
  preparationStep = "snapshot transfer";
366
658
  const transferred = await transferSnapshot(options.repo, snapshot.commit, executor, attempt.paths.snapshot, ctx.runner ?? spawnRunner);
659
+ if (attempt.pipeline) {
660
+ preparationStep = "code snapshot verification";
661
+ const receipt = await retainedOperation(attempt.executor, { op: "snapshot", studyId: attempt.studyId, attemptId: attempt.id, source: attempt.paths.snapshot }, ctx.runner ?? spawnRunner);
662
+ if (!receipt.sha256 || !/^[a-f0-9]{64}$/.test(receipt.sha256)) throw new Error("pipeline: invalid frozen code snapshot receipt");
663
+ attempt = await update(dir, attempt.id, ctx, current => { current.pipeline!.codeSnapshotHash = receipt.sha256; return "attempt.pipeline.code"; });
664
+ }
367
665
  preparationStep = "evaluator transfer";
368
- await transferTask(join(dir, "task"), executor, posix.dirname(attempt.paths.evaluator), ctx.runner ?? spawnRunner, frozen.treeHash);
666
+ await transferTask(join(dir, "task"), executor, posix.dirname(attempt.paths.evaluator), ctx.runner ?? spawnRunner, frozen.treeHash, !!attempt.pipeline);
667
+ if (attempt.pipeline) {
668
+ for (let index = 1; index < attempt.pipeline.definition.candidate.stages.length; index++) await checkExecutorInputs(executor, executionView(attempt.pipeline.definition, index), ctx.runner ?? spawnRunner);
669
+ const materialized = await materializePipeline(attempt, ctx);
670
+ if (attempt.reuse) attempt = await recordMaterialization(dir, attempt, materialized.materializationMs, ctx);
671
+ attempt = await update(dir, attempt.id, ctx, current => { current.pipeline!.inputHashes = materialized.inputHashes; return "attempt.pipeline.inputs"; });
672
+ }
369
673
  preparationStep = "design recheck";
370
674
  if (designBinding(dir) !== attempt.sealBinding) throw new Error("design changed during preparation");
371
675
  if (attempt.finalBinding && finalGateBinding(dir) !== attempt.finalBinding) throw new Error("final inputs changed during preparation");
@@ -375,40 +679,93 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
375
679
  attempt = await withControl(dir, async () => {
376
680
  const current = showAttempt(dir, attempt.id);
377
681
  if (current.status !== "running" || current.launching?.token !== claim) return current;
378
- return launch(dir, current, checked.user, ctx);
682
+ return launch(dir, current, checked.user, ctx, protocol);
379
683
  });
380
- } catch {
381
- 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"; });
684
+ } catch (error) {
685
+ if (!attempt.pipeline && error instanceof InputVerificationError) throw error;
686
+ const failure = attempt.pipeline ? pipelineFailureAt(dir, attempt, error, controlCtx) : undefined;
687
+ 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"; });
382
688
  }
383
689
  }
690
+ if (attempt.pipeline && attempt.status === "failed") await reconcileRetentionReservations(dir, controlCtx);
384
691
  if (!options.detach) {
385
692
  let delay = 1000;
386
693
  while (attempt.status === "running") {
387
694
  await (ctx.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms))))(delay);
388
695
  const previousStage = attempt.stage;
389
- await reconcileAttempts(dir, ctx); attempt = showAttempt(dir, wanted);
696
+ await reconcileAttempts(dir, controlCtx); attempt = showAttempt(dir, wanted);
390
697
  delay = attempt.stage === previousStage ? Math.min(delay * 2, 30_000) : 1000;
391
698
  }
392
699
  }
393
700
  return attempt;
394
701
  }
395
702
 
703
+ async function verifyAndLaunchPending(dir: string, pending: Attempt, ctx: AttemptContext): Promise<Attempt | undefined> {
704
+ ctx = boundedPipelineContext(dir, pending, ctx);
705
+ const protocol = executionProtocol(dir, pending);
706
+ let hashes: Record<string, string> | undefined, materializationMs = 0;
707
+ const preflightStarted = performance.now();
708
+ try {
709
+ if (pending.reuse) {
710
+ requireCopilotAccept(dir, "hypotheses");
711
+ 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");
712
+ requireGate(dir, openStudy(dir).study, "design", () => pending.sealBinding);
713
+ }
714
+ const materialized = pending.pipeline ? await materializePipeline(pending, ctx) : undefined;
715
+ hashes = materialized?.inputHashes; materializationMs = materialized?.materializationMs ?? 0;
716
+ validateContainerInputSources(protocol, pending.paths);
717
+ await verifyExecutorInputs(pending.executor, protocol, ctx.runner ?? spawnRunner);
718
+ } catch (error) {
719
+ if (!pending.pipeline) throw error;
720
+ return withControl(dir, () => recordPipelinePreflightFailure(dir, pending, error, ctx, performance.now() - preflightStarted));
721
+ }
722
+ return withControl(dir, async () => {
723
+ const current = showAttempt(dir, pending.id);
724
+ if (current.status !== "running" || current.stage !== pending.stage || !current.stages[current.stage]?.launchPending || alive(current, ctx)) return undefined;
725
+ 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;
726
+ executionProtocol(dir, current); // Recheck the frozen identities after hashing, under the fresh launch fence.
727
+ const claimed = await update(dir, current.id, ctx, value => {
728
+ if (hashes) value.pipeline!.inputHashes = hashes;
729
+ if (value.reuse) addMaterialization(value, materializationMs);
730
+ if (value.pipeline) value.pipeline.preflightRevision = (value.pipeline.preflightRevision ?? 0) + 1;
731
+ delete value.stages[value.stage]!.launchPending; value.launching = owner(ctx);
732
+ return "attempt.stage.retry-intent";
733
+ });
734
+ return launch(dir, claimed, claimed.stages[claimed.stage]!.user, ctx, protocol);
735
+ });
736
+ }
737
+
396
738
  export async function reconcileAttempts(dirArg: string, ctx: AttemptContext): Promise<Attempt[]> {
397
739
  const dir = studyDir(dirArg);
398
- return withControl(dir, async () => {
740
+ const pending: Attempt[] = [];
741
+ const changed = await withControl(dir, async () => {
399
742
  const changed: Attempt[] = [];
400
743
  for (let attempt of load(dir).filter(a => a.status === "running")) {
401
744
  if (alive(attempt, ctx)) continue;
745
+ let observedState: ObservedStage | undefined;
402
746
  try {
403
- let state = await inspect(attempt, ctx);
404
- if (!state) { changed.push(await update(dir, attempt.id, ctx, current => { finish(current, "unknown", "lost", ctx); return "attempt.unknown"; })); continue; }
747
+ let state = await inspect(dir, attempt, ctx);
748
+ observedState = state;
749
+ if (!state) {
750
+ if (attempt.stages[attempt.stage]?.launchPending) pending.push(attempt);
751
+ else changed.push(await update(dir, attempt.id, ctx, current => { finish(current, "unknown", "lost", ctx); return "attempt.unknown"; }));
752
+ continue;
753
+ }
405
754
  const recovered = needsReceipt(attempt, state);
406
755
  if (recovered) attempt = await recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.recovered");
407
756
  const stage = attempt.stages[attempt.stage];
408
757
  if (!stage) throw hostError(attempt, "stage record");
409
- const deadline = Date.parse(stage.startedAt) + stage.limits.wallSeconds * 1000;
410
- if ((state.running && now(ctx) >= deadline) || (!state.running && state.finishedAt !== undefined && Date.parse(state.finishedAt) >= deadline)) {
411
- if (state.running) { await command(attempt, "wall-clock kill", "docker", ["kill", state.id], ctx); const stopped = await inspect(attempt, ctx); if (stopped) state = stopped; }
758
+ const deadline = (attempt.pipeline ? Date.parse(attempt.startedAt) : Date.parse(stage.startedAt)) + stage.limits.wallSeconds * 1000;
759
+ const usage = attempt.pipeline ? budgetUsage(load(dir), now(ctx)) : undefined;
760
+ const exhausted = usage && (usage.wallHours >= attempt.protocol.budget.maxWallHours || (attempt.protocol.limits.gpus > 0 && usage.gpuHours >= attempt.protocol.budget.maxGpuHours));
761
+ if ((state.running && (now(ctx) >= deadline || exhausted)) || (!state.running && ((attempt.pipeline && (now(ctx) >= deadline || exhausted)) || (state.finishedAt !== undefined && Date.parse(state.finishedAt) >= deadline)))) {
762
+ if (state.running) {
763
+ await command(attempt, "wall-clock kill", "docker", ["kill", state.id], ctx);
764
+ const stopped = await inspect(dir, attempt, ctx);
765
+ if (stopped) state = stopped;
766
+ else if (attempt.pipeline) state = { ...state, running: false, exitCode: 137, finishedAt: at(ctx) };
767
+ if (attempt.pipeline && state.running) throw new EvidenceError("executor-stop", "pipeline: container termination is not yet observed; active attempt and retention reservation remain held");
768
+ }
412
769
  attempt = await captureStage(dir, attempt, ctx, true);
413
770
  const ended = state;
414
771
  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;
@@ -418,36 +775,110 @@ export async function reconcileAttempts(dirArg: string, ctx: AttemptContext): Pr
418
775
  continue;
419
776
  }
420
777
  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; }
421
- try { attempt = await captureStage(dir, attempt, ctx, false); }
778
+ try { attempt = await captureStage(dir, attempt, boundedPipelineContext(dir, attempt, ctx), false); }
422
779
  catch (error) {
423
- const failure = error as EvidenceError, ended = state;
780
+ const failure = attempt.pipeline ? pipelineFailureAt(dir, attempt, error, ctx) : error as EvidenceError, ended = state;
424
781
  changed.push(await update(dir, attempt.id, ctx, current => {
425
782
  current.stages[current.stage]!.exitCode = ended.exitCode;
426
783
  if (ended.finishedAt) current.stages[current.stage]!.endedAt = ended.finishedAt;
427
784
  current.error = failure.message; finish(current, "failed", failure.reason, ctx); return "attempt.failed";
428
785
  })); continue;
429
786
  }
430
- if (attempt.stage === "candidate") {
431
- 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"; });
432
- changed.push(await launch(dir, next, stage.user, ctx));
787
+ if (attempt.stage === "candidate" && attempt.pipeline) {
788
+ 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"; });
789
+ const ref = await sealPipeline(attempt, boundedPipelineContext(dir, attempt, ctx));
790
+ const next = await update(dir, attempt.id, ctx, current => {
791
+ const pipeline = current.pipeline!, completed = current.stages.candidate!;
792
+ pipeline.sidecarBytes = attempt.pipeline!.sidecarBytes;
793
+ pipeline.completed.push({ name: pipeline.definition.candidate.stages[pipeline.index]!.name, record: completed, ref });
794
+ delete current.stages.candidate;
795
+ if (pipeline.index + 1 < pipeline.definition.candidate.stages.length) { pipeline.index++; current.protocol = executionView(pipeline.definition, pipeline.index); }
796
+ else current.stage = "evaluator";
797
+ current.paths = pipelinePaths(current);
798
+ current.stages[current.stage] = stageRecord(current, current.stage, stage.user, ctx);
799
+ current.stages[current.stage]!.launchPending = true; delete current.launching;
800
+ return "attempt.stage.changed";
801
+ });
802
+ pending.push(next);
803
+ } else if (attempt.stage === "candidate") {
804
+ const next = await update(dir, attempt.id, ctx, current => {
805
+ current.stages.candidate!.exitCode = 0; current.stages.candidate!.endedAt = state.finishedAt ?? at(ctx); current.stage = "evaluator";
806
+ current.stages.evaluator = stageRecord(current, "evaluator", stage.user, ctx);
807
+ if (Object.keys(current.protocol.inputs ?? {}).length) { current.stages.evaluator.launchPending = true; delete current.launching; }
808
+ else current.launching = owner(ctx);
809
+ return "attempt.stage.changed";
810
+ });
811
+ if (next.stages.evaluator?.launchPending) pending.push(next);
812
+ else changed.push(await launch(dir, next, stage.user, ctx));
433
813
  } else {
434
814
  let evaluation: Evaluation | undefined, failure: EvidenceError | undefined;
435
- try { evaluation = await (ctx.collectEvaluation ?? defaultEvaluationCollector)(attempt, ctx.runner ?? spawnRunner); }
436
- catch (error) { failure = error instanceof EvidenceError ? error : new MetricsError("invalid-metrics", "evaluator result validation failed"); }
815
+ try {
816
+ const bounded = boundedPipelineContext(dir, attempt, ctx);
817
+ evaluation = await (ctx.collectEvaluation ?? defaultEvaluationCollector)(attempt, bounded.runner ?? spawnRunner);
818
+ if (attempt.pipeline) remainingWallSeconds(dir, attempt, ctx);
819
+ }
820
+ catch (error) {
821
+ evaluation = undefined;
822
+ if (attempt.pipeline) failure = pipelineFailureAt(dir, attempt, error, ctx);
823
+ else failure = error instanceof EvidenceError ? error : new MetricsError("invalid-metrics", "evaluator result validation failed");
824
+ }
437
825
  changed.push(await update(dir, attempt.id, ctx, current => {
438
826
  current.stages.evaluator!.exitCode = 0;
439
827
  if (state.finishedAt) current.stages.evaluator!.endedAt = state.finishedAt;
440
828
  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"; }
829
+ if (current.pipeline && Buffer.byteLength(JSON.stringify(outputBudget([...current.outputs, ...evaluation.outputs]), null, 2)) + (current.pipeline.sidecarBytes ?? 0) > OUTPUT_METADATA_BYTES) {
830
+ current.error = "pipeline: total output metadata including retained sidecars exceeds the attempt limit"; finish(current, "failed", "artifact-limit", ctx); return "attempt.failed";
831
+ }
441
832
  current.metrics = evaluation.metrics; current.outputs = outputBudget([...current.outputs, ...evaluation.outputs]); finish(current, "succeeded", undefined, ctx); return "attempt.succeeded";
442
833
  }));
443
834
  }
444
- } catch {
445
- await update(dir, attempt.id, ctx, current => { delete current.launching; return "attempt.executor-error"; });
835
+ } catch (error) {
836
+ if (attempt.pipeline && observedState && !observedState.running) {
837
+ const failure = pipelineFailureAt(dir, attempt, error, ctx);
838
+ const retryable = retryablePipelineFailure(error) && failure.reason !== "wall-clock";
839
+ changed.push(await update(dir, attempt.id, ctx, current => {
840
+ if (current.status !== "running") return undefined;
841
+ const stage = current.stages[current.stage];
842
+ if (stage) { stage.exitCode = observedState!.exitCode; stage.endedAt = observedState!.finishedAt ?? at(ctx); delete stage.launchPending; }
843
+ current.error = failure.message;
844
+ if (retryable) { current.reason = "executor-seal"; return "attempt.executor-error"; }
845
+ finish(current, "failed", failure.reason, ctx); return "attempt.failed";
846
+ }));
847
+ continue;
848
+ }
849
+ if (error instanceof InputVerificationError) throw error;
850
+ 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"; });
446
851
  throw hostError(attempt, "reconcile");
447
852
  }
448
853
  }
449
854
  return changed;
450
855
  });
856
+ // No control lock or launch claim is held across a potentially 40-minute manifest pass.
857
+ for (const attempt of pending) {
858
+ const launched = await verifyAndLaunchPending(dir, attempt, ctx);
859
+ if (launched) changed.push(launched);
860
+ }
861
+ await reconcileRetentionReservations(dir, ctx);
862
+ return changed;
863
+ }
864
+ /** Explicit reconciliation only frees a hold after the executor confirms no owned live container. */
865
+ async function reconcileRetentionReservations(dir: string, ctx: AttemptContext): Promise<void> {
866
+ const executor = readExecutor(dir), { study } = openStudy(dir);
867
+ if (!executor || (!load(dir).some(attempt => !!attempt.pipeline) && readProtocol(dir)?.v !== 2)) return;
868
+ if (load(dir).some(attempt => attempt.status === "running")) return;
869
+ const view = await retainedOperation(executor, { op: "inspect", studyId: study.id }, ctx.runner ?? spawnRunner);
870
+ for (const reservation of view.reservations ?? []) {
871
+ if (!reservation.active) continue;
872
+ const attempt = load(dir).find(value => value.id === reservation.attemptId);
873
+ if (attempt?.status === "running") continue;
874
+ try { await withControl(dir, () => withLock(dir, async () => {
875
+ const current = load(dir).find(value => value.id === reservation.attemptId);
876
+ if (current?.status === "running") return;
877
+ const live = await runOnExecutor(executor, "docker", ["ps", "--filter", `label=ares.study=${study.id}`, "--filter", `label=ares.attempt=${reservation.attemptId}`, "--format", "{{.ID}}"], ctx.runner ?? spawnRunner);
878
+ if (live.exitCode !== 0 || live.timedOut || live.truncated || live.stdout.trim()) return;
879
+ await retainedOperation(executor, { op: "release", studyId: study.id, attemptId: reservation.attemptId }, ctx.runner ?? spawnRunner);
880
+ })); } catch (error) { if (!(error instanceof StudyLockBusyError)) throw error; }
881
+ }
451
882
  }
452
883
  export async function cancelAttempt(dirArg: string, wanted: string, reason: string | undefined, ctx: AttemptContext, completion?: (attempt: Attempt) => PendingEvent[]): Promise<Attempt> {
453
884
  const dir = studyDir(dirArg), why = reason === undefined ? undefined : boundedText(reason, "reason", 500);
@@ -461,14 +892,26 @@ export async function cancelAttempt(dirArg: string, wanted: string, reason: stri
461
892
  });
462
893
  if (alive(attempt, ctx)) throw new Error("attempt: another startup operation is active; retry cancel when it finishes (abandoned claims expire after 30 minutes)");
463
894
  try {
464
- let state = await inspect(attempt, ctx);
465
- if (state && needsReceipt(attempt, state)) attempt = await recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.recovered", false);
466
- if (state?.running) { await command(attempt, "cancel kill", "docker", ["kill", state.id], ctx); state = await inspect(attempt, ctx); }
895
+ let state = await inspect(dir, attempt, ctx, true);
896
+ if (state && needsReceipt(attempt, state)) {
897
+ const owned = state;
898
+ attempt = await update(dir, attempt.id, ctx, current => {
899
+ current.stages[current.stage]!.containerId = owned.id;
900
+ if (owned.startedAt) current.stages[current.stage]!.startedAt = owned.startedAt;
901
+ delete current.launching;
902
+ // Ownership permits cancellation; it does not establish isolation or approve any gate.
903
+ return "attempt.stage.recovered";
904
+ });
905
+ }
906
+ if (state?.running) { await command(attempt, "cancel kill", "docker", ["kill", state.id], ctx); state = await inspect(dir, attempt, ctx, true); }
907
+ if (attempt.pipeline && state?.running) throw hostError(attempt, "cancellation termination confirmation");
467
908
  if (state) attempt = await captureStage(dir, attempt, ctx, true);
909
+ if (attempt.pipeline) await retainedOperation(attempt.executor, { op: "release", studyId: attempt.studyId, attemptId: attempt.id }, ctx.runner ?? spawnRunner);
468
910
  const ended = state;
469
911
  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);
470
- } catch {
912
+ } catch (error) {
471
913
  await update(dir, attempt.id, ctx, current => { delete current.launching; return "attempt.executor-error"; });
914
+ if (error instanceof InputVerificationError) throw error;
472
915
  throw hostError(attempt, "cancel");
473
916
  }
474
917
  });