@staix/agent-research 0.2.1 → 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 (72) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +255 -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 +192 -32
  7. package/src/exp/attempts.ts +500 -65
  8. package/src/exp/executor.ts +235 -12
  9. package/src/exp/final.ts +1 -1
  10. package/src/exp/logs.ts +25 -12
  11. package/src/exp/metrics.ts +6 -5
  12. package/src/exp/pipeline.ts +92 -0
  13. package/src/exp/protocol.ts +85 -18
  14. package/src/exp/retention-script.ts +649 -0
  15. package/src/exp/retention.ts +70 -0
  16. package/src/exp/reuse-admission.ts +63 -0
  17. package/src/exp/reuse-contract.ts +48 -0
  18. package/src/exp/reuse-runtime.ts +87 -0
  19. package/src/exp/reuse.ts +87 -0
  20. package/src/exp/selection.ts +1 -1
  21. package/src/exp/snapshot.ts +3 -3
  22. package/src/exp/stages.ts +117 -0
  23. package/src/harness/experience-source.ts +34 -0
  24. package/src/harness/experience.ts +206 -0
  25. package/src/harness/hub-guidance.ts +140 -0
  26. package/src/harness/hub-reference.ts +18 -0
  27. package/src/harness/lesson-candidates.ts +162 -0
  28. package/src/harness/limits.ts +2 -0
  29. package/src/harness/privacy.ts +4 -0
  30. package/src/harness/receipts.ts +84 -0
  31. package/src/harness/rounds.ts +198 -0
  32. package/src/harness/transitions.ts +152 -0
  33. package/src/lit/candidates.ts +13 -5
  34. package/src/lit/cards.ts +55 -4
  35. package/src/lit/flow.ts +82 -0
  36. package/src/lit/queries.ts +62 -0
  37. package/src/manifest.ts +13 -6
  38. package/src/mcp-tools.ts +123 -25
  39. package/src/mcp.ts +4 -0
  40. package/src/memory/amem-show.ts +135 -0
  41. package/src/memory/amem.ts +3 -0
  42. package/src/memory/archive.ts +17 -8
  43. package/src/memory/evidence-local.ts +77 -0
  44. package/src/memory/evidence.ts +39 -0
  45. package/src/memory/lessons.ts +4 -2
  46. package/src/memory/skill-check.ts +56 -0
  47. package/src/memory/skill-format.ts +77 -0
  48. package/src/memory/skills.ts +72 -26
  49. package/src/memory/source-budget.ts +11 -0
  50. package/src/memory/vault-cards.ts +226 -0
  51. package/src/paper/build.ts +16 -7
  52. package/src/paper/check.ts +37 -10
  53. package/src/paper/headings.ts +39 -0
  54. package/src/paper/hygiene.ts +153 -0
  55. package/src/paper/placeholders.ts +16 -1
  56. package/src/paper/plan.ts +170 -0
  57. package/src/paper/point-evidence.ts +63 -0
  58. package/src/paper/points.ts +83 -0
  59. package/src/paper/review.ts +102 -9
  60. package/src/paper/scopes.ts +51 -0
  61. package/src/plan/definition.ts +5 -1
  62. package/src/plan/hub.ts +6 -0
  63. package/src/plan/state.ts +5 -0
  64. package/src/playbook.ts +35 -20
  65. package/src/privacy.ts +9 -0
  66. package/src/provenance.ts +679 -0
  67. package/src/scope.ts +24 -3
  68. package/src/study-export.ts +55 -27
  69. package/src/study.ts +54 -14
  70. package/src/ui/panel.css +4 -0
  71. package/src/ui/panel.js +263 -6
  72. package/src/ui/plugin.ts +68 -10
@@ -2,9 +2,10 @@ import { spawn } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
3
  import { join, posix } from "node:path";
4
4
  import { commit, openStudy, plain, readJsonFile, requireExperiment, type Actor } from "../study.ts";
5
- import { readProtocol, validateProtocol, type Protocol } from "./protocol.ts";
5
+ import { readProtocol, canonicalExecutorPath, validateProtocol, type Protocol } from "./protocol.ts";
6
6
 
7
- export interface Executor { v: 1; kind: "local" | "ssh"; host?: string; workdir: string }
7
+ export interface ExecutorGpu { devices: (number | string)[]; minFreeMemoryMb: number; maxLoadRatio: number }
8
+ export interface Executor { v: 1; kind: "local" | "ssh"; host?: string; workdir: string; retentionCapBytes?: number; gpu?: ExecutorGpu }
8
9
  export interface ProcessRequest {
9
10
  command: string; args: string[]; stdin?: Uint8Array | AsyncIterable<Uint8Array>;
10
11
  stdoutSink?: (chunk: Uint8Array) => void | Promise<void>; signal?: AbortSignal;
@@ -92,17 +93,42 @@ function failed(executor: Executor, step: string): Error {
92
93
  }
93
94
  function directory(value: unknown, field: string): string {
94
95
  if (typeof value !== "string" || value.length > 4096 || !value.startsWith("/") || /[\0\r\n,"]/.test(value)) throw new Error(`${field}: invalid directory; use an absolute path of at most 4096 characters without NUL, newlines, commas or double quotes`);
95
- return posix.normalize(value);
96
+ return canonicalExecutorPath(value);
97
+ }
98
+ export const GPU_UUID = /^GPU-[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
99
+ function gpuConfigurationError(field: string): never { throw new Error(`executor.gpu.${field}: invalid explicit GPU settings; set 1..64 distinct index/UUID devices, minFreeMemoryMb integer 0..2147483647 and maxLoadRatio >0..1000000 with no other fields`); }
100
+ function gpuSelector(raw: unknown): string {
101
+ if (typeof raw === "number" && Number.isSafeInteger(raw) && raw >= 0) return String(raw);
102
+ if (typeof raw === "string" && /^(?:0|[1-9][0-9]*)$/.test(raw) && Number.isSafeInteger(Number(raw))) return raw;
103
+ if (typeof raw === "string" && GPU_UUID.test(raw)) return "GPU-" + raw.slice(4).toLowerCase();
104
+ return gpuConfigurationError("devices");
105
+ }
106
+ export function validateExecutorGpu(raw: unknown): ExecutorGpu {
107
+ if (!plain(raw) || Object.keys(raw).some(key => !["devices", "minFreeMemoryMb", "maxLoadRatio"].includes(key))) gpuConfigurationError("configuration");
108
+ if (!Array.isArray(raw.devices) || raw.devices.length < 1 || raw.devices.length > 64) gpuConfigurationError("devices");
109
+ const devices = raw.devices.map(gpuSelector);
110
+ if (new Set(devices).size !== devices.length) gpuConfigurationError("devices");
111
+ if (!Number.isSafeInteger(raw.minFreeMemoryMb) || Number(raw.minFreeMemoryMb) < 0 || Number(raw.minFreeMemoryMb) > 2_147_483_647) gpuConfigurationError("minFreeMemoryMb");
112
+ if (typeof raw.maxLoadRatio !== "number" || !Number.isFinite(raw.maxLoadRatio) || raw.maxLoadRatio <= 0 || raw.maxLoadRatio > 1_000_000) gpuConfigurationError("maxLoadRatio");
113
+ return { devices, minFreeMemoryMb: raw.minFreeMemoryMb as number, maxLoadRatio: raw.maxLoadRatio };
114
+ }
115
+ /** Frozen assignments and explicit Docker device arguments contain unique UUIDs only. */
116
+ export function validateGpuDevices(raw: unknown, count: number): string[] {
117
+ if (!Number.isSafeInteger(count) || count < 0 || count > 64 || !Array.isArray(raw) || raw.length !== count || raw.some(id => typeof id !== "string" || !GPU_UUID.test(id))) throw new Error("GPU devices: invalid frozen assignment; restore exactly the requested number of distinct GPU UUIDs before retrying the attempt");
118
+ const devices = (raw as string[]).map(id => "GPU-" + id.slice(4).toLowerCase());
119
+ if (new Set(devices).size !== devices.length) throw new Error("GPU devices: duplicate frozen assignment; restore distinct GPU UUIDs before retrying the attempt");
120
+ return devices;
96
121
  }
97
122
  export function validateExecutor(raw: unknown): Executor {
98
123
  if (!plain(raw)) throw new Error("executor: object required; pass kind and workdir to ares executor set");
99
- const extra = Object.keys(raw).find(key => !["v", "kind", "host", "workdir"].includes(key));
100
- if (extra !== undefined) throw new Error(`executor: unknown field ${extra}; use only v, kind, host and workdir`);
124
+ const extra = Object.keys(raw).find(key => !["v", "kind", "host", "workdir", "gpu", "retentionCapBytes"].includes(key));
125
+ if (extra !== undefined) throw new Error(`executor: unknown field ${extra}; use only v, kind, host, workdir and optional gpu`);
101
126
  if (raw.v !== 1 || (raw.kind !== "local" && raw.kind !== "ssh")) throw new Error("executor: invalid version or kind; set v to 1 and kind to local or ssh");
102
127
  if (raw.kind === "ssh" && (typeof raw.host !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(raw.host))) throw new Error("executor.host: invalid SSH alias; configure an SSH alias and pass its name only (letters, digits, dot, underscore or hyphen)");
103
128
  if (raw.kind === "local" && raw.host !== undefined) throw new Error("executor.host: local executor has no SSH host; remove host or set kind to ssh");
104
129
  if (raw.workdir === undefined || raw.workdir === null) throw new Error("executor.workdir: required with no default; run ares executor set <dir> --kind local|ssh [--host ALIAS] --workdir PATH using a private directory on the executor host");
105
- return { v: 1, kind: raw.kind, ...(raw.kind === "ssh" ? { host: raw.host as string } : {}), workdir: directory(raw.workdir, "executor.workdir") };
130
+ if (raw.retentionCapBytes !== undefined && (typeof raw.retentionCapBytes !== "number" || !Number.isSafeInteger(raw.retentionCapBytes) || raw.retentionCapBytes < 1 || raw.retentionCapBytes > 1024 ** 4)) throw new Error("executor.retentionCapBytes: expected 1..1099511627776 bytes");
131
+ return { v: 1, ...(raw.retentionCapBytes !== undefined ? { retentionCapBytes: raw.retentionCapBytes as number } : {}), kind: raw.kind, ...(raw.kind === "ssh" ? { host: raw.host as string } : {}), workdir: directory(raw.workdir, "executor.workdir"), ...(raw.gpu === undefined ? {} : { gpu: validateExecutorGpu(raw.gpu) }) };
106
132
  }
107
133
  export function readExecutor(dir: string): Executor | undefined {
108
134
  const file = join(dir, "executor.json");
@@ -125,6 +151,166 @@ export async function runOnExecutor(executorArg: Executor, command: string, args
125
151
  try { return await runner(executor.kind === "local" ? { ...options, command, args } : { ...options, command: "ssh", args: ["-o", "BatchMode=yes", executor.host!, shellQuote(command), ...args.map(shellQuote)] }); }
126
152
  catch { throw failed(executor, "process start"); }
127
153
  }
154
+ export class InputVerificationError extends Error {}
155
+ export class InputConfigurationError extends InputVerificationError {
156
+ constructor(message: string) { super(message); this.name = "InputConfigurationError"; }
157
+ }
158
+ export interface GpuDeferred { status: "deferred"; reason: "devices" | "load" | "probe"; message: string; exitCode: 75 }
159
+ export type GpuAdmission = { status: "admitted"; devices: string[] } | GpuDeferred;
160
+ export class GpuAdmissionDeferred extends Error {
161
+ constructor(readonly result: GpuDeferred) { super(result.message); this.name = "GpuAdmissionDeferred"; }
162
+ }
163
+ export const GPU_PROBE_TIMEOUT_MS = 10_000, GPU_PROBE_OUTPUT_BYTES = 65_536, GPU_INVENTORY_LIMIT = 256;
164
+ export const GPU_ADMISSION_SCRIPT = `set -eu
165
+ printf 'ARES_GPU_INVENTORY\n'
166
+ nvidia-smi --query-gpu=index,uuid,memory.free --format=csv,noheader,nounits
167
+ printf 'ARES_GPU_LOAD\n'
168
+ cat /proc/loadavg
169
+ printf 'ARES_GPU_CPUS\n'
170
+ if command -v nproc >/dev/null 2>&1; then nproc; else getconf _NPROCESSORS_ONLN; fi
171
+ printf 'ARES_GPU_END\n'
172
+ `;
173
+ function gpuDeferred(reason: GpuDeferred["reason"]): GpuDeferred {
174
+ const message = reason === "probe" ? "GPU admission deferred: probe unavailable or malformed; restore nvidia-smi, load and CPU telemetry before retrying" : reason === "load" ? "GPU admission deferred: load ratio exceeds the configured limit; retry after host pressure falls" : "GPU admission deferred: insufficient configured devices meet the free-memory requirement; free the configured devices or retry later";
175
+ return { status: "deferred", reason, message, exitCode: 75 };
176
+ }
177
+ interface GpuInventoryRow { index: string; uuid: string; memory: number }
178
+ function gpuProbe(stdout: string): { inventory: GpuInventoryRow[]; loadRatio: number } {
179
+ const lines = stdout.split(/\r?\n/); if (lines.at(-1) === "") lines.pop();
180
+ const load = lines.indexOf("ARES_GPU_LOAD"), cpus = lines.indexOf("ARES_GPU_CPUS");
181
+ if (lines[0] !== "ARES_GPU_INVENTORY" || load < 1 || load - 1 > GPU_INVENTORY_LIMIT || cpus !== load + 2 || lines.length !== cpus + 3 || lines.at(-1) !== "ARES_GPU_END") throw new Error("probe shape");
182
+ const indexes = new Set<string>(), uuids = new Set<string>(), inventory: GpuInventoryRow[] = [];
183
+ for (const line of lines.slice(1, load)) {
184
+ const fields = line.split(",").map(field => field.trim());
185
+ if (fields.length !== 3 || !/^(?:0|[1-9][0-9]*)$/.test(fields[0]!) || !Number.isSafeInteger(Number(fields[0])) || !GPU_UUID.test(fields[1]!) || !/^[0-9]+(?:\.[0-9]+)?$/.test(fields[2]!) || !Number.isFinite(Number(fields[2]))) throw new Error("GPU inventory");
186
+ const index = fields[0]!, uuid = "GPU-" + fields[1]!.slice(4).toLowerCase();
187
+ if (indexes.has(index) || uuids.has(uuid)) throw new Error("duplicate GPU identity");
188
+ indexes.add(index); uuids.add(uuid); inventory.push({ index, uuid, memory: Number(fields[2]) });
189
+ }
190
+ const parts = lines[load + 1]!.split(/ +/), decimal = /^[0-9]+(?:\.[0-9]+)?$/;
191
+ if (parts.length !== 5 || parts.slice(0, 3).some(value => !decimal.test(value) || !Number.isFinite(Number(value))) || !/^[0-9]+\/[0-9]+$/.test(parts[3]!) || !/^[0-9]+$/.test(parts[4]!)) throw new Error("load telemetry");
192
+ const [active, total] = parts[3]!.split("/").map(Number);
193
+ if (![active, total, Number(parts[4])].every(Number.isSafeInteger) || total! < 1 || active! > total!) throw new Error("load identity");
194
+ const cpu = lines[cpus + 1]!;
195
+ if (!/^[1-9][0-9]*$/.test(cpu) || !Number.isSafeInteger(Number(cpu))) throw new Error("CPU telemetry");
196
+ return { inventory, loadRatio: Number(parts[0]) / Number(cpu) };
197
+ }
198
+ /** One read-only probe; admission never sleeps, retries or reserves a physical GPU. */
199
+ export async function probeGpuAdmission(executorArg: Executor, count: number, runner: ProcessRunner = spawnRunner): Promise<GpuAdmission> {
200
+ const executor = validateExecutor(executorArg);
201
+ if (!Number.isSafeInteger(count) || count < 0 || count > 64) throw new Error("GPU admission count: integer 0..64 required; use the protocol GPU count before retrying");
202
+ if (!executor.gpu || count === 0) return { status: "admitted", devices: [] };
203
+ let parsed: ReturnType<typeof gpuProbe>;
204
+ try {
205
+ const result = await runOnExecutor(executor, "sh", ["-c", GPU_ADMISSION_SCRIPT], runner, { timeoutMs: GPU_PROBE_TIMEOUT_MS, maxOutputBytes: GPU_PROBE_OUTPUT_BYTES });
206
+ if (result.exitCode !== 0 || result.timedOut || result.truncated || Buffer.byteLength(result.stdout) > GPU_PROBE_OUTPUT_BYTES) return gpuDeferred("probe");
207
+ parsed = gpuProbe(result.stdout);
208
+ } catch { return gpuDeferred("probe"); }
209
+ if (parsed.loadRatio > executor.gpu.maxLoadRatio) return gpuDeferred("load");
210
+ const devices: string[] = [];
211
+ for (const selector of executor.gpu.devices) {
212
+ const gpu = parsed.inventory.find(gpu => gpu.index === String(selector) || gpu.uuid === selector);
213
+ if (!gpu || gpu.memory < executor.gpu.minFreeMemoryMb || devices.includes(gpu.uuid)) continue;
214
+ devices.push(gpu.uuid); if (devices.length === count) return { status: "admitted", devices };
215
+ }
216
+ return gpuDeferred("devices");
217
+ }
218
+
219
+ export interface InputManifest { sha256: string; files: number; bytes: number }
220
+ export const INPUT_MANIFEST_FILES = 100_000, INPUT_MANIFEST_TIMEOUT_MS = 300_000, INPUT_MANIFEST_OUTPUT_BYTES = 4096;
221
+ // ponytail: ceiling 100,000 files/directories, depth 64 and 5 minutes; bytes stream in 1 MiB chunks, never into the study.
222
+ export const INPUT_MANIFEST_SCRIPT = String.raw`import os,sys,stat,hashlib,json
223
+ MAX=100000
224
+ records=[]
225
+ entries=0
226
+ directories=0
227
+ total=0
228
+ def identity(s):
229
+ return (s.st_dev,s.st_ino,s.st_size,s.st_mtime_ns,s.st_ctime_ns)
230
+ def walk(fd,prefix,depth):
231
+ global entries,directories,total
232
+ if depth>64: raise ValueError()
233
+ directories+=1
234
+ if directories>MAX: raise ValueError()
235
+ before=os.fstat(fd)
236
+ with os.scandir(fd) as stream:
237
+ for item in stream:
238
+ entries+=1
239
+ if entries>2*MAX or item.name in ('.','..'): raise ValueError()
240
+ name=prefix+'/'+item.name if prefix else item.name
241
+ if len(name.encode('utf-8'))>4096: raise ValueError()
242
+ info=os.stat(item.name,dir_fd=fd,follow_symlinks=False)
243
+ if stat.S_ISDIR(info.st_mode):
244
+ child=os.open(item.name,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW|os.O_NONBLOCK,dir_fd=fd)
245
+ try:
246
+ if identity(os.fstat(child))!=identity(info): raise ValueError()
247
+ walk(child,name,depth+1)
248
+ finally: os.close(child)
249
+ elif stat.S_ISREG(info.st_mode):
250
+ if len(records)>=MAX or info.st_size>9007199254740991-total: raise ValueError()
251
+ child=os.open(item.name,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK,dir_fd=fd)
252
+ try:
253
+ opened=os.fstat(child)
254
+ if not stat.S_ISREG(opened.st_mode) or identity(opened)!=identity(info): raise ValueError()
255
+ digest=hashlib.sha256()
256
+ size=0
257
+ while True:
258
+ chunk=os.read(child,1048576)
259
+ if not chunk: break
260
+ size+=len(chunk)
261
+ if size>info.st_size: raise ValueError()
262
+ digest.update(chunk)
263
+ if size!=info.st_size or identity(os.fstat(child))!=identity(opened): raise ValueError()
264
+ finally: os.close(child)
265
+ total+=size
266
+ records.append((name,size,digest.hexdigest()))
267
+ else: raise ValueError()
268
+ if identity(os.fstat(fd))!=identity(before): raise ValueError()
269
+ try:
270
+ root=sys.argv[1]
271
+ if not os.path.isabs(root): raise ValueError()
272
+ fd=os.open('/',os.O_RDONLY|os.O_DIRECTORY)
273
+ try:
274
+ for part in root.split('/'):
275
+ if not part: continue
276
+ if part in ('.','..'): raise ValueError()
277
+ child=os.open(part,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW|os.O_NONBLOCK,dir_fd=fd)
278
+ os.close(fd)
279
+ fd=child
280
+ walk(fd,'',0)
281
+ finally: os.close(fd)
282
+ digest=hashlib.sha256()
283
+ for row in sorted(records,key=lambda row:row[0].encode('utf-8')):
284
+ digest.update((json.dumps(row,ensure_ascii=False,separators=(',',':'))+'\n').encode('utf-8'))
285
+ print(json.dumps({'sha256':digest.hexdigest(),'files':len(records),'bytes':total},separators=(',',':')))
286
+ except Exception:
287
+ sys.stderr.write('input manifest refused\n')
288
+ sys.exit(1)
289
+ `;
290
+ /** Host-local streaming only: stdout is bounded metadata, never file names, contents or host paths. */
291
+ export async function hashExecutorInput(executorArg: Executor, path: string, runner: ProcessRunner = spawnRunner): Promise<InputManifest> {
292
+ const executor = validateExecutor(executorArg), source = directory(path, "executor input path");
293
+ const refuse = () => new Error("executor input manifest: hashing failed; check Python3 and a stable readable regular directory without special files on the executor; the path and its ancestors must not be symlinks; then rerun ares executor inputs hash <dir> <path>");
294
+ let result: ProcessResult;
295
+ try {result = await runOnExecutor(executor, "python3", ["-I", "-S", "-c", INPUT_MANIFEST_SCRIPT, source], runner, {timeoutMs: INPUT_MANIFEST_TIMEOUT_MS, maxOutputBytes: INPUT_MANIFEST_OUTPUT_BYTES});}
296
+ catch {throw refuse();}
297
+ if (result.exitCode !== 0 || result.timedOut || result.truncated || Buffer.byteLength(result.stdout) > INPUT_MANIFEST_OUTPUT_BYTES) throw refuse();
298
+ let raw: unknown; try {raw = JSON.parse(result.stdout);} catch {throw refuse();}
299
+ if (!plain(raw) || Object.keys(raw).some(key => !["sha256", "files", "bytes"].includes(key)) || typeof raw.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(raw.sha256) || !Number.isSafeInteger(raw.files) || Number(raw.files)<0 || Number(raw.files)>INPUT_MANIFEST_FILES || !Number.isSafeInteger(raw.bytes) || Number(raw.bytes)<0) throw refuse();
300
+ return {sha256: raw.sha256, files: raw.files as number, bytes: raw.bytes as number};
301
+ }
302
+ /** Verify every declared input without persisting its host locator or manifest rows. */
303
+ export async function verifyExecutorInputs(executor: Executor, protocol: Protocol, runner: ProcessRunner = spawnRunner): Promise<Record<string, string>> {
304
+ const inputs = validateProtocol(protocol).inputs ?? {}, verified: [string, string][] = [];
305
+ for (const [name, input] of Object.entries(inputs)) {
306
+ let manifest: InputManifest;
307
+ try { manifest = await hashExecutorInput(executor, input.path!, runner); }
308
+ catch { throw new InputVerificationError(`executor input ${name}: manifest could not be verified; restore the staged directory and rerun ares executor inputs hash <dir> <path> before retrying the attempt`); }
309
+ if (manifest.sha256 !== input.sha256) throw new InputVerificationError(`executor input ${name}: manifest hash mismatch; restore the staged input or update its protocol hash and approve the design before retrying the attempt`);
310
+ verified.push([name, manifest.sha256]);
311
+ }
312
+ return Object.fromEntries(verified);
313
+ }
128
314
  async function step(executor: Executor, name: string, command: string, args: string[], runner: ProcessRunner, options: Omit<ProcessRequest, "command" | "args"> = {}): Promise<ProcessResult> {
129
315
  try {
130
316
  const result = await runOnExecutor(executor, command, args, runner, options);
@@ -132,16 +318,22 @@ async function step(executor: Executor, name: string, command: string, args: str
132
318
  return result;
133
319
  } catch { throw failed(executor, name); }
134
320
  }
135
- export interface ExecutorCheck { executor: Executor; serverVersion: string; user: string; images: { image: string; available: true }[]; pull: "missing" }
321
+ export interface ExecutorCheck { inputRuntime?: "python3"; executor: Executor; serverVersion: string; user: string; images: { image: string; available: true }[]; pull: "missing" }
136
322
  export async function checkExecutor(dir: string, runner: ProcessRunner = spawnRunner): Promise<ExecutorCheck> {
137
323
  requireExperiment(openStudy(dir).study);
138
324
  const executor = readExecutor(dir), protocol = readProtocol(dir);
139
325
  if (!executor) throw new Error("executor: not configured; run ares executor set <dir> --kind local|ssh [--host ALIAS] --workdir PATH");
140
326
  if (!protocol) throw new Error("protocol: missing; run ares protocol <dir> --file PATH before executor check");
327
+ if (protocol.v === 2) {
328
+ const { executionView } = await import("./pipeline.ts");
329
+ for (let index = 1; index < protocol.candidate.stages.length; index++) await checkExecutorInputs(executor, executionView(protocol, index), runner);
330
+ return checkExecutorInputs(executor, executionView(protocol), runner);
331
+ }
141
332
  return checkExecutorInputs(executor, protocol, runner);
142
333
  }
143
334
  /** Check a frozen attempt's configuration rather than mutable study files. */
144
335
  export async function checkExecutorInputs(executor: Executor, protocol: Protocol, runner: ProcessRunner = spawnRunner): Promise<ExecutorCheck> {
336
+ if (Object.keys(protocol.inputs ?? {}).length) await step(executor, "Python3 input manifest runtime", "python3", ["-I", "-S", "-c", "import sys; assert sys.version_info.major == 3"], runner);
145
337
  const version = (await step(executor, "Docker server version", "docker", ["version", "--format", "{{.Server.Version}}"], runner)).stdout.trim();
146
338
  if (!/^[0-9]+\.[0-9]+(?:\.[0-9]+)?[A-Za-z0-9.+_-]*$/.test(version) || version.length > 128) throw failed(executor, "Docker server version");
147
339
  const uid = (await step(executor, "host uid", "id", ["-u"], runner)).stdout.trim();
@@ -156,19 +348,35 @@ export async function checkExecutorInputs(executor: Executor, protocol: Protocol
156
348
  if (present.exitCode !== 0) await step(executor, "image pull", "docker", ["pull", image], runner, { timeoutMs: 300_000 });
157
349
  images.push({ image, available: true });
158
350
  }
159
- return { executor, serverVersion: version, user: `${uid}:${gid}`, images, pull: "missing" };
351
+ return { ...(Object.keys(protocol.inputs ?? {}).length ? { inputRuntime: "python3" as const } : {}), executor, serverVersion: version, user: `${uid}:${gid}`, images, pull: "missing" };
160
352
  }
161
353
 
354
+ export function executionPathsOverlap(left: string, right: string): boolean {
355
+ const a = canonicalExecutorPath(left), b = canonicalExecutorPath(right);
356
+ return a === b || a.startsWith(b === "/" ? b : `${b}/`) || b.startsWith(a === "/" ? a : `${a}/`);
357
+ }
162
358
  export type Stage = "candidate" | "evaluator";
163
359
  export interface ContainerPaths { snapshot: string; output: string; evaluator: string; result: string }
164
- export interface ContainerOptions { protocol: Protocol; stage: Stage; studyId: string; attemptId: string; user: string; paths: ContainerPaths; seed?: number }
360
+ export interface ContainerOptions { protocol: Protocol; stage: Stage; studyId: string; attemptId: string; user: string; paths: ContainerPaths; seed?: number; gpuDevices?: string[]; pipeline?: { name: string; inputRoot: string; seed: boolean } }
165
361
  export function containerName(attemptId: string, stage: Stage): string {
166
362
  if (!/^[a-f0-9]{16}$/.test(attemptId) || !["candidate", "evaluator"].includes(stage)) throw new Error("container identity: invalid attempt or stage; use a 16-hex attempt id and candidate or evaluator stage");
167
363
  return `ares-${attemptId}-${stage}`;
168
364
  }
365
+ /** Pure preflight for host input isolation; no hashing, transport or attempt side effects. */
366
+ export function validateContainerInputSources(protocol: Protocol, pathsArg: ContainerPaths): void {
367
+ const p = validateProtocol(protocol);
368
+ const paths = Object.fromEntries(Object.entries(pathsArg).map(([key, value]) => [key, directory(value, `container.paths.${key}`)])) as unknown as ContainerPaths;
369
+ const sources = [paths.snapshot, paths.output, paths.evaluator, paths.result], inputs = Object.values(p.inputs ?? {});
370
+ for (const input of inputs) if (sources.some(source => executionPathsOverlap(source, input.path!))) throw new InputConfigurationError("container inputs: source overlaps the attempt workspace; stage inputs in a separate executor directory before retrying");
371
+ for (let a = 0; a < inputs.length; a++) for (let b = a + 1; b < inputs.length; b++) {
372
+ const x = inputs[a]!, y = inputs[b]!;
373
+ if (executionPathsOverlap(x.path!, y.path!) && (!!x.mount.candidate !== !!y.mount.candidate || !!x.mount.evaluator !== !!y.mount.evaluator)) throw new InputConfigurationError("container inputs: overlapping sources expose a stage-private input; stage private inputs in separate directories before retrying");
374
+ }
375
+ }
169
376
  /** Mounts are fixed by stage, never supplied as free-form Docker options. */
170
377
  export function buildContainerArgs(options: ContainerOptions): string[] {
171
- const p = validateProtocol(options.protocol), name = containerName(options.attemptId, options.stage);
378
+ const p = validateProtocol(options.protocol), name = containerName(options.attemptId, options.stage) + (options.pipeline ? `-${options.pipeline.name}` : "");
379
+ if (options.pipeline && (options.stage !== "candidate" || !/^[a-z][a-z0-9_-]{0,31}$/.test(options.pipeline.name))) throw new Error("pipeline container: invalid stage name");
172
380
  const seed = options.seed === undefined ? p.seeds[0]! : options.seed;
173
381
  if (!Number.isSafeInteger(seed) || !p.seeds.includes(seed)) throw new Error("container seed: undeclared or non-integer; choose a seed from protocol.seeds for ares attempt run --seed N");
174
382
  if (!/^[A-Za-z0-9_-]{1,80}$/.test(options.studyId)) throw new Error("study id: invalid label; use the id from study.json");
@@ -180,10 +388,16 @@ export function buildContainerArgs(options: ContainerOptions): string[] {
180
388
  const x = sources[a]!, y = sources[b]!;
181
389
  if (!x || !y || x === y || x.startsWith(y === "/" ? y : `${y}/`) || y.startsWith(x === "/" ? x : `${x}/`)) throw new Error("container mounts: overlapping sources; use separate snapshot, output, evaluator and result directories");
182
390
  }
391
+ validateContainerInputSources(p, paths);
392
+ const inputs = Object.values(p.inputs ?? {});
183
393
  const argv = ["run", "--detach", "--pull", "missing", "--name", name, "--label", `ares.study=${options.studyId}`, "--label", `ares.attempt=${options.attemptId}`, "--label", `ares.stage=${options.stage}`,
184
394
  "--network", "none", "--read-only", "--tmpfs", "/tmp", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--user", options.user,
185
- "--cpus", String(p.limits.cpus), "--memory", `${p.limits.memoryMb}m`, "--pids-limit", String(p.limits.pidsLimit), "--env", `ARES_SEED=${seed}`];
186
- if (p.limits.gpus > 0) argv.push("--gpus", String(p.limits.gpus));
395
+ "--cpus", String(p.limits.cpus), "--memory", `${p.limits.memoryMb}m`, "--pids-limit", String(p.limits.pidsLimit)];
396
+ if (!options.pipeline || options.pipeline.seed) argv.push("--env", `ARES_SEED=${seed}`);
397
+ if (options.gpuDevices !== undefined) {
398
+ const devices = validateGpuDevices(options.gpuDevices, p.limits.gpus);
399
+ if (devices.length) argv.push("--gpus", `"device=${devices.join(",")}"`);
400
+ } else if (p.limits.gpus > 0) argv.push("--gpus", String(p.limits.gpus));
187
401
  const mount = (source: string, target: string, readonly: boolean) => argv.push("--mount", `type=bind,src=${source},dst=${target}${readonly ? ",readonly" : ""}`);
188
402
  if (options.stage === "candidate") {
189
403
  mount(paths.snapshot, "/workspace", true); mount(paths.output, "/out", false);
@@ -193,6 +407,15 @@ export function buildContainerArgs(options: ContainerOptions): string[] {
193
407
  mount(paths.evaluator, "/eval", true); mount(paths.output, "/candidate", true); mount(paths.result, "/result", false);
194
408
  argv.push("--workdir", "/eval");
195
409
  }
410
+ if (options.pipeline) {
411
+ const source = directory(options.pipeline.inputRoot, "pipeline inputs");
412
+ if (sources.some(path => executionPathsOverlap(source, path))) throw new Error("pipeline inputs: source overlaps workspace mounts");
413
+ mount(source, "/in", true);
414
+ }
415
+ for (const input of inputs) {
416
+ const target = input.mount[options.stage];
417
+ if (target !== undefined) mount(input.path!, target, true);
418
+ }
196
419
  argv.push(p[options.stage].image, ...p[options.stage].command);
197
420
  return argv;
198
421
  }
package/src/exp/final.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { commit, onlyKeys, openStudy, plain, readTextBounded, requireExperiment, sha256, assertWritable, gateState, readLedger, requireGate, type Actor, type LedgerEvent } from "../study.ts";
4
- import { readDesign, readProtocol, type Protocol } from "./protocol.ts";
4
+ import { readDesign, readProtocol, type ProtocolDefinition as Protocol } from "./protocol.ts";
5
5
  import { listAttempts, type Attempt, type AttemptStatus } from "./attempts.ts";
6
6
  import { ablateResultPath, ABLATE_BYTES, foldAblations, readClosedAblate } from "./ablate.ts";
7
7
  import { INVESTIGATE_BYTES, investigateResultPath, metricValue, pairSamples, readClosedInvestigation, type PairedSamples, type Sample } from "./investigate.ts";
package/src/exp/logs.ts CHANGED
@@ -1,14 +1,15 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { posix } from "node:path";
3
3
  import { openStudy, requireExperiment } from "../study.ts";
4
- import { showAttempt } from "./attempts.ts";
4
+ import { showAttempt, type AttemptStage } from "./attempts.ts";
5
5
  import { runOnExecutor, shellQuote, spawnRunner, validateExecutor, type ProcessRunner, type Stage } from "./executor.ts";
6
6
  import { LOG_COPY_BYTES } from "./metrics.ts";
7
7
 
8
8
  export type LogStream = "stdout" | "stderr";
9
- export interface LogOptions { stage?: string; stream?: string; tailBytes?: number }
10
- export interface LogReadResult { id: string; logs: { stage: Stage; stream: LogStream; path: string; sha256: string; bytes: number; truncated: boolean; text: string; tailBytes: number }[] }
9
+ export interface LogOptions { stage?: string; candidateStage?: string; stream?: string; tailBytes?: number }
10
+ export interface LogReadResult { id: string; logs: { stage: Stage; candidateStage?: string; stream: LogStream; path: string; sha256: string; bytes: number; truncated: boolean; text: string; tailBytes: number }[] }
11
11
  export const DEFAULT_LOG_TAIL_BYTES = 16_384, MAX_LOG_TAIL_BYTES = 65_536;
12
+ export const MAX_LOG_TOTAL_TAIL_BYTES = 256 * 1024;
12
13
 
13
14
  /** Explicit read-only log access. Nothing, including the returned text, is written to the study. */
14
15
  export async function readAttemptLogs(dir: string, wanted: string, options: LogOptions = {}, runner: ProcessRunner = spawnRunner): Promise<LogReadResult> {
@@ -22,20 +23,32 @@ export async function readAttemptLogs(dir: string, wanted: string, options: LogO
22
23
  const root = posix.join(executor.workdir, attempt.studyId, attempt.id), logsDir = posix.join(root, "logs");
23
24
  if (!attempt.paths || attempt.paths.snapshot !== posix.join(root, "snapshot")) throw new Error("attempt logs: workspace differs from recorded executor identity; restore the original record before reading logs");
24
25
  const result: LogReadResult = { id: attempt.id, logs: [] };
25
- const stages: Stage[] = options.stage ? [options.stage as Stage] : ["candidate", "evaluator"];
26
+ const sources: { stage: Stage; candidateStage?: string; record?: AttemptStage }[] = [];
27
+ if (attempt.pipeline) {
28
+ const reused = attempt.pipeline.completed.find(parent => parent.reuse && parent.name === options.candidateStage);
29
+ if (reused) throw new Error(`attempt logs: candidate was reused; read source attempt ${reused.ref.attemptId} with --candidate-stage ${reused.name}`);
30
+ for (const parent of attempt.pipeline.completed.filter(parent => !parent.reuse)) sources.push({ stage: "candidate", candidateStage: parent.name, record: parent.record });
31
+ if (attempt.stage === "candidate") sources.push({ stage: "candidate", candidateStage: attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name, record: attempt.stages.candidate });
32
+ } else sources.push({ stage: "candidate", record: attempt.stages.candidate });
33
+ sources.push({ stage: "evaluator", record: attempt.stages.evaluator });
34
+ if (options.candidateStage !== undefined && (!attempt.pipeline || options.stage === "evaluator" || !attempt.pipeline.definition.candidate.stages.some(stage => stage.name === options.candidateStage))) throw new Error("attempt logs: invalid candidate stage; choose a declared v2 candidate name and --stage candidate");
35
+ const selected = sources.filter(source => (options.stage === undefined || source.stage === options.stage) && (options.candidateStage === undefined || source.candidateStage === options.candidateStage));
26
36
  const streams: LogStream[] = options.stream ? [options.stream as LogStream] : ["stdout", "stderr"];
27
- const requests: { stage: Stage; stream: LogStream; path: string; sha256: string; bytes: number; truncated: boolean }[] = [];
28
- for (const stage of stages) for (const stream of streams) {
29
- const metadata = attempt.stages[stage]?.evidence?.logs?.[stream];
37
+ const requests: { stage: Stage; candidateStage?: string; stream: LogStream; path: string; sha256: string; bytes: number; truncated: boolean }[] = [];
38
+ for (const source of selected) for (const stream of streams) {
39
+ const metadata = source.record?.evidence?.logs?.[stream];
30
40
  if (!metadata) {
31
- if (options.stage) throw new Error("attempt logs: the selected stage has no collected logs; reconcile after the stage finishes, then retry");
41
+ if ((options.stage !== undefined && !attempt.pipeline) || options.candidateStage !== undefined) throw new Error("attempt logs: the selected stage has no collected logs; reconcile after the stage finishes, then retry");
32
42
  continue;
33
43
  }
34
- const expected = posix.join(logsDir, `${stage}.${stream}.log`);
44
+ const label = source.candidateStage === undefined ? source.stage : `candidate-${source.candidateStage}`;
45
+ const expected = posix.join(logsDir, `${label}.${stream}.log`);
35
46
  if (metadata.path !== expected || typeof metadata.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(metadata.sha256) || !Number.isSafeInteger(metadata.bytes) || metadata.bytes < 0 || metadata.bytes > LOG_COPY_BYTES || typeof metadata.truncated !== "boolean") throw new Error("attempt logs: invalid log receipt or path; restore the original metadata before reading logs");
36
- requests.push({ stage, stream, path: expected, sha256: metadata.sha256, bytes: metadata.bytes, truncated: metadata.truncated });
47
+ requests.push({ stage: source.stage, ...(source.candidateStage === undefined ? {} : { candidateStage: source.candidateStage }), stream, path: expected, sha256: metadata.sha256, bytes: metadata.bytes, truncated: metadata.truncated });
37
48
  }
38
- if (!requests.length) throw new Error("attempt logs: no collected logs yet; reconcile after a stage finishes, then retry");
49
+ if (!requests.length) throw new Error("attempt logs: no collected logs for the selected stage yet; reconcile after the stage finishes, then retry");
50
+ const tailCount = options.tailBytes === undefined ? Math.min(count, Math.floor(MAX_LOG_TOTAL_TAIL_BYTES / requests.length)) : count;
51
+ if (tailCount * requests.length > MAX_LOG_TOTAL_TAIL_BYTES) throw new Error("attempt logs: combined tail bound exceeded; select --candidate-stage NAME or --stream, or lower --tail");
39
52
  for (const entry of requests) {
40
53
  const controller = new AbortController(), hash = createHash("sha256");
41
54
  let bytes = 0, tail: Buffer = Buffer.alloc(0);
@@ -50,7 +63,7 @@ export async function readAttemptLogs(dir: string, wanted: string, options: LogO
50
63
  const response = await runOnExecutor(executor, "sh", ["-c", script], runner, { signal: controller.signal, timeoutMs: 300_000, stdoutSink: chunk => {
51
64
  if (bytes + chunk.byteLength > LOG_COPY_BYTES) { controller.abort(); throw new Error("log receipt read bound"); }
52
65
  bytes += chunk.byteLength; hash.update(chunk);
53
- if (count) tail = chunk.byteLength >= count ? Buffer.from(chunk.subarray(chunk.byteLength - count)) : Buffer.concat([tail.subarray(Math.max(0, tail.length + chunk.byteLength - count)), chunk]);
66
+ if (tailCount) tail = chunk.byteLength >= tailCount ? Buffer.from(chunk.subarray(chunk.byteLength - tailCount)) : Buffer.concat([tail.subarray(Math.max(0, tail.length + chunk.byteLength - tailCount)), chunk]);
54
67
  } });
55
68
  if (response.exitCode !== 0 || response.timedOut || response.truncated) throw new Error("log read failed");
56
69
  } catch {
@@ -81,9 +81,10 @@ export async function collectEvaluation(attempt: Attempt, runner: ProcessRunner)
81
81
 
82
82
  /** Raw copies remain in the executor's private attempt directory; only metadata enters the study. */
83
83
  export async function collectStageEvidence(attempt: Attempt, stage: Stage, runner: ProcessRunner): Promise<StageEvidence> {
84
+ const stageLabel = attempt.pipeline && stage === "candidate" ? `candidate-${attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name}` : stage;
84
85
  const cid = container(attempt, stage), root = posix.dirname(attempt.paths.snapshot), logs = posix.join(root, "logs");
85
- const stdout = posix.join(logs, `${stage}.stdout.log`), stderr = posix.join(logs, `${stage}.stderr.log`), suffix = randomUUID();
86
- const statePath = `logs/${stage}.state.json`, stateFile = posix.join(root, statePath);
86
+ const stdout = posix.join(logs, `${stageLabel}.stdout.log`), stderr = posix.join(logs, `${stageLabel}.stderr.log`), suffix = randomUUID();
87
+ const statePath = `logs/${stageLabel}.state.json`, stateFile = posix.join(root, statePath);
87
88
  const script = [
88
89
  "set -eu", "umask 077", `logs=${shellQuote(logs)}`,
89
90
  'if test ! -e "$logs"; then mkdir -m 700 "$logs"; fi', 'test -d "$logs"; test ! -L "$logs"; test -O "$logs"',
@@ -91,7 +92,7 @@ export async function collectStageEvidence(attempt: Attempt, stage: Stage, runne
91
92
  'for file in "$out" "$err" "$state"; do if test -e "$file" || test -L "$file"; then test -f "$file"; test ! -L "$file"; fi; done',
92
93
  `if test -f "$out" && test -f "$err" && test -f "$state" && test "$(wc -c < "$out")" -le ${LOG_COPY_BYTES} && test "$(wc -c < "$err")" -le ${LOG_COPY_BYTES}; then :; else`,
93
94
  `outtmp=${shellQuote(`${stdout}.${suffix}.tmp`)}; errtmp=${shellQuote(`${stderr}.${suffix}.tmp`)}; statetmp=${shellQuote(`${stateFile}.${suffix}.tmp`)}`,
94
- `outpipe=${shellQuote(posix.join(logs, `${stage}.${suffix}.stdout.pipe`))}; errpipe=${shellQuote(posix.join(logs, `${stage}.${suffix}.stderr.pipe`))}`,
95
+ `outpipe=${shellQuote(posix.join(logs, `${stageLabel}.${suffix}.stdout.pipe`))}; errpipe=${shellQuote(posix.join(logs, `${stageLabel}.${suffix}.stderr.pipe`))}`,
95
96
  'trap \'rm -f "$outtmp" "$errtmp" "$statetmp" "$outpipe" "$errpipe"\' 0',
96
97
  'mkfifo "$outpipe" "$errpipe"',
97
98
  `head -c ${LOG_COPY_BYTES} < "$outpipe" > "$outtmp" & outpid=$!`,
@@ -106,7 +107,7 @@ export async function collectStageEvidence(attempt: Attempt, stage: Stage, runne
106
107
  // Archive content only: BSD tar otherwise emits binary xattr PAX and AppleDouble entries.
107
108
  // ponytail: requires GNU tar >= 1.27 or bsdtar with --no-xattrs; unsupported tar
108
109
  // (e.g. BusyBox) fails closed with the generic stage-log collection error, never a metadata fallback.
109
- `COPYFILE_DISABLE=1 tar --no-xattrs -C ${shellQuote(root)} -cf - ${shellQuote(`logs/${stage}.stdout.log`)} ${shellQuote(`logs/${stage}.stderr.log`)} ${shellQuote(statePath)}`,
110
+ `COPYFILE_DISABLE=1 tar --no-xattrs -C ${shellQuote(root)} -cf - ${shellQuote(`logs/${stageLabel}.stdout.log`)} ${shellQuote(`logs/${stageLabel}.stderr.log`)} ${shellQuote(statePath)}`,
110
111
  ].join("\n");
111
112
  let logArchive;
112
113
  try { logArchive = await readArtifactArchive(attempt.executor, "sh", ["-c", script], runner, { capture: statePath, captureBytes: 1024, maxFiles: 3, maxBytes: LOG_COPY_BYTES * 2 + 1024 }); }
@@ -116,7 +117,7 @@ export async function collectStageEvidence(attempt: Attempt, stage: Stage, runne
116
117
  if (!plain(truncated) || Object.keys(truncated).length !== 2 || typeof truncated.stdout !== "boolean" || typeof truncated.stderr !== "boolean") throw new EvidenceError("invalid-log-state", "stage evidence: truncation metadata is missing or malformed; remove incomplete log copies on the executor host and retry collection");
117
118
  const cuts = truncated as { stdout: boolean; stderr: boolean };
118
119
  const log = (kind: "stdout" | "stderr"): LogEvidence => {
119
- const file = logArchive.files.find(item => item.path === `logs/${stage}.${kind}.log`);
120
+ const file = logArchive.files.find(item => item.path === `logs/${stageLabel}.${kind}.log`);
120
121
  if (!file) throw new EvidenceError("missing-logs", "stage evidence: a stdout/stderr copy is missing; inspect the executor log directory and retry collection");
121
122
  return { path: posix.join(root, file.path), sha256: file.sha256, bytes: file.bytes, truncated: cuts[kind] || file.bytes >= LOG_COPY_BYTES };
122
123
  };
@@ -0,0 +1,92 @@
1
+ import type { StageReuseSourceFacts } from "./reuse-runtime.ts";
2
+ import { posix } from "node:path";
3
+ import { canonical, type Protocol, type ProtocolDefinition } from "./protocol.ts";
4
+ import { sha256 } from "../study.ts";
5
+ import { type ProtocolV2 } from "./stages.ts";
6
+ import { retainedOperation, type RetainedRef, type RetainedInput } from "./retention.ts";
7
+ import type { Attempt, AttemptContext, AttemptStage } from "./attempts.ts";
8
+ import { spawnRunner, type ContainerPaths } from "./executor.ts";
9
+ import { EvidenceError, OUTPUT_METADATA_BYTES } from "./metrics.ts";
10
+ import { version } from "../../package.json";
11
+
12
+ export interface StageReuseReceipt {
13
+ v: 1; key: string; source: RetainedRef; context?: StageReuseSourceFacts;
14
+ original: { wallSeconds: number | "unknown"; gpuHours: number | "unknown"; cpuSeconds: "unknown" };
15
+ verificationMs: number; materializationMs: number; failureMs?: number;
16
+ }
17
+ export interface AttemptReuseState {
18
+ mode: "off" | "eligible"; forceFresh: boolean;
19
+ stages: Record<string, { outcome: "fresh" | "reused"; reason: string; key?: string; source?: RetainedRef; context?: StageReuseSourceFacts; verificationMs: number; materializationMs: number }>;
20
+ verificationMs: number; materializationMs: number; failureMs?: number;
21
+ }
22
+ export interface PipelineState {
23
+ definition: ProtocolV2;
24
+ index: number;
25
+ preflightRevision?: number;
26
+ completed: { name: string; record: AttemptStage; ref: RetainedRef; reuse?: StageReuseReceipt }[];
27
+ inputHashes: Record<string, string>;
28
+ taskTreeHash: string;
29
+ codeSnapshotHash?: string;
30
+ sidecarBytes?: number;
31
+ reusedSidecarBytes?: number;
32
+ materializationMs?: Record<string, number>;
33
+ }
34
+ /** Execution projection is transient; v2 identity always binds the original definition. */
35
+ export function executionView(definition: ProtocolDefinition, index = 0): Protocol {
36
+ if (definition.v === 1) return definition;
37
+ const stage = definition.candidate.stages[index];
38
+ if (!stage) throw new Error("pipeline: missing stage; restore the frozen attempt definition");
39
+ const { candidate: _candidate, v: _v, ...common } = definition;
40
+ return { ...common, v: 1, candidate: { image: stage.image, command: stage.command, ...(stage.env ? { env: stage.env } : {}) } };
41
+ }
42
+ export function pipelineRoot(attempt: Attempt): string { return posix.join(attempt.executor.workdir, attempt.studyId, attempt.id); }
43
+ export function pipelinePaths(attempt: Attempt): ContainerPaths {
44
+ const root = pipelineRoot(attempt), stage = attempt.pipeline!.definition.candidate.stages[attempt.pipeline!.index]!;
45
+ return { snapshot: posix.join(root, "snapshot"), output: attempt.stage === "evaluator" ? posix.join(root, "candidate") : posix.join(root, "stages", stage.name, "output"), evaluator: posix.join(root, "task", "evaluator"), result: posix.join(root, "result") };
46
+ }
47
+ export function pipelineInputRoot(attempt: Attempt): string | undefined {
48
+ if (!attempt.pipeline || attempt.stage === "evaluator") return undefined;
49
+ return posix.join(pipelineRoot(attempt), "stages", attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name, "inputs");
50
+ }
51
+ /** Verify retained parents and materialize a fresh, private, read-only input snapshot per stage. */
52
+ export async function materializePipeline(attempt: Attempt, ctx: AttemptContext): Promise<{ inputHashes: Record<string, string>; materializationMs: number }> {
53
+ const started = performance.now();
54
+ const pipeline = attempt.pipeline!, root = pipelineRoot(attempt), inputs: Record<string, RetainedInput> = {};
55
+ if (attempt.stage === "evaluator") {
56
+ for (const parent of pipeline.completed) inputs[parent.name] = { ref: parent.ref };
57
+ } else {
58
+ const stage = pipeline.definition.candidate.stages[pipeline.index]!;
59
+ for (const [name, input] of Object.entries(stage.inputs)) {
60
+ if ("task" in input) inputs[name] = input;
61
+ else {
62
+ const parent = pipeline.completed.find(value => value.name === input.stage);
63
+ if (!parent) throw new Error(`pipeline ${stage.name}.${name}: parent seal unavailable; reconcile without rerunning uncertain work`);
64
+ inputs[name] = { ref: parent.ref, output: input.output };
65
+ }
66
+ }
67
+ }
68
+ if (!pipeline.codeSnapshotHash) throw new Error("pipeline: frozen code snapshot receipt missing; reconcile without launching");
69
+ const result = await retainedOperation(attempt.executor, { op: "materialize", studyId: attempt.studyId, attemptId: attempt.id,
70
+ stage: attempt.stage === "evaluator" ? "evaluator" : pipeline.definition.candidate.stages[pipeline.index]!.name,
71
+ expectedTaskTreeHash: pipeline.taskTreeHash, codeRoot: attempt.paths.snapshot, expectedCodeHash: pipeline.codeSnapshotHash, target: attempt.stage === "evaluator" ? posix.join(root, "candidate") : pipelineInputRoot(attempt)!, taskRoot: posix.join(root, "task"), inputs }, ctx.runner ?? spawnRunner);
72
+ return { inputHashes: result.inputHashes ?? {}, materializationMs: performance.now() - started };
73
+ }
74
+ export function stageRetainedIdentity(attempt: Attempt) {
75
+ const stage = attempt.pipeline!.definition.candidate.stages[attempt.pipeline!.index]!;
76
+ return { definitionHash: sha256(canonical(stage)), inputHashes: attempt.pipeline!.inputHashes, codeTree: attempt.treeId, image: stage.image,
77
+ argvHash: sha256(canonical(stage.command)), envHash: sha256(canonical(stage.env ?? {})), seed: attempt.seed, producerVersion: version };
78
+ }
79
+ export async function sealPipeline(attempt: Attempt, ctx: AttemptContext): Promise<RetainedRef> {
80
+ const pipeline = attempt.pipeline!, stage = pipeline.definition.candidate.stages[pipeline.index]!, record = attempt.stages.candidate!;
81
+ if (!record.containerId || !record.endedAt || record.exitCode !== 0) throw new Error(`pipeline ${stage.name}: observed successful termination required before sealing`);
82
+ const metadataLimit = OUTPUT_METADATA_BYTES - Buffer.byteLength(JSON.stringify(attempt.outputs, null, 2)) - (pipeline.reusedSidecarBytes ?? 0);
83
+ if (metadataLimit < 0) throw new EvidenceError("artifact-limit", "pipeline: output metadata exhausts the shared sidecar budget");
84
+ const result = await retainedOperation(attempt.executor, { op: "seal", studyId: attempt.studyId, attemptId: attempt.id, stage: stage.name,
85
+ source: attempt.paths.output, outputs: stage.outputs, metadataLimit, observed: { containerId: record.containerId, endedAt: record.endedAt, exitCode: 0 },
86
+ ...(attempt.reuse?.stages[stage.name]?.key ? { reuseKey: attempt.reuse.stages[stage.name]!.key! } : {}),
87
+ identity: stageRetainedIdentity(attempt) }, ctx.runner ?? spawnRunner);
88
+ if (!result.manifest || result.manifest.files.some(file => !attempt.outputs.some(observed => observed.path === posix.join(attempt.paths.output, file.path) && observed.sha256 === file.sha256 && observed.bytes === file.bytes))) throw new Error(`pipeline ${stage.name}: retained bytes differ from observed output evidence`);
89
+ pipeline.sidecarBytes = (result.sidecarBytes ?? 0) + (pipeline.reusedSidecarBytes ?? 0);
90
+ if (!result.sha256) throw new Error(`pipeline ${stage.name}: missing manifest digest; reconcile the terminated stage`);
91
+ return { attemptId: attempt.id, stage: stage.name, sha256: result.sha256 };
92
+ }