@staix/agent-research 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +261 -24
  3. package/package.json +2 -2
  4. package/src/cli.ts +117 -10
  5. package/src/commands-table.ts +39 -8
  6. package/src/commands.ts +201 -34
  7. package/src/exp/artifacts.ts +20 -2
  8. package/src/exp/attempts.ts +505 -65
  9. package/src/exp/executor.ts +264 -17
  10. package/src/exp/final.ts +1 -1
  11. package/src/exp/logs.ts +25 -12
  12. package/src/exp/metrics.ts +8 -9
  13. package/src/exp/pipeline.ts +92 -0
  14. package/src/exp/protocol.ts +87 -20
  15. package/src/exp/retention-script.ts +649 -0
  16. package/src/exp/retention.ts +70 -0
  17. package/src/exp/reuse-admission.ts +65 -0
  18. package/src/exp/reuse-contract.ts +48 -0
  19. package/src/exp/reuse-runtime.ts +91 -0
  20. package/src/exp/reuse.ts +87 -0
  21. package/src/exp/selection.ts +1 -1
  22. package/src/exp/snapshot.ts +30 -10
  23. package/src/exp/stages.ts +117 -0
  24. package/src/harness/experience-source.ts +34 -0
  25. package/src/harness/experience.ts +206 -0
  26. package/src/harness/hub-guidance.ts +140 -0
  27. package/src/harness/hub-reference.ts +18 -0
  28. package/src/harness/lesson-candidates.ts +162 -0
  29. package/src/harness/limits.ts +2 -0
  30. package/src/harness/privacy.ts +4 -0
  31. package/src/harness/receipts.ts +84 -0
  32. package/src/harness/rounds.ts +198 -0
  33. package/src/harness/transitions.ts +152 -0
  34. package/src/lit/candidates.ts +13 -5
  35. package/src/lit/cards.ts +55 -4
  36. package/src/lit/flow.ts +82 -0
  37. package/src/lit/queries.ts +62 -0
  38. package/src/manifest.ts +13 -6
  39. package/src/mcp-tools.ts +123 -25
  40. package/src/mcp.ts +4 -0
  41. package/src/memory/amem-show.ts +135 -0
  42. package/src/memory/amem.ts +3 -0
  43. package/src/memory/archive.ts +17 -8
  44. package/src/memory/evidence-local.ts +77 -0
  45. package/src/memory/evidence.ts +39 -0
  46. package/src/memory/lessons.ts +4 -2
  47. package/src/memory/skill-check.ts +56 -0
  48. package/src/memory/skill-format.ts +77 -0
  49. package/src/memory/skills.ts +72 -26
  50. package/src/memory/source-budget.ts +11 -0
  51. package/src/memory/vault-cards.ts +226 -0
  52. package/src/paper/build.ts +16 -7
  53. package/src/paper/check.ts +37 -10
  54. package/src/paper/headings.ts +39 -0
  55. package/src/paper/hygiene.ts +153 -0
  56. package/src/paper/placeholders.ts +16 -1
  57. package/src/paper/plan.ts +170 -0
  58. package/src/paper/point-evidence.ts +63 -0
  59. package/src/paper/points.ts +83 -0
  60. package/src/paper/review.ts +102 -9
  61. package/src/paper/scopes.ts +51 -0
  62. package/src/plan/definition.ts +5 -1
  63. package/src/plan/hub.ts +6 -0
  64. package/src/plan/state.ts +5 -0
  65. package/src/playbook.ts +35 -20
  66. package/src/privacy.ts +9 -0
  67. package/src/provenance.ts +679 -0
  68. package/src/scope.ts +24 -3
  69. package/src/study-export.ts +55 -27
  70. package/src/study.ts +54 -14
  71. package/src/ui/panel.css +4 -0
  72. package/src/ui/panel.js +263 -6
  73. package/src/ui/plugin.ts +68 -10
@@ -1,10 +1,11 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
3
  import { join, posix } from "node:path";
4
- import { commit, openStudy, plain, readJsonFile, requireExperiment, type Actor } from "../study.ts";
5
- import { readProtocol, validateProtocol, type Protocol } from "./protocol.ts";
4
+ import { commit, openStudy, plain, readJsonFile, requireExperiment, sha256, type Actor } from "../study.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;
@@ -13,6 +14,8 @@ export interface ProcessRequest {
13
14
  export interface ProcessResult { exitCode: number; stdout: string; stderr: string; timedOut?: boolean; truncated?: boolean }
14
15
  export type ProcessRunner = (request: ProcessRequest) => Promise<ProcessResult>;
15
16
  export const EXECUTOR_BYTES = 8192, PROCESS_OUTPUT_BYTES = 65_536;
17
+ // Domain tag keeps a container-name digest from ever being confused with another ares hash.
18
+ const CONTAINER_NAME_DOMAIN = "ares-container-name-v1";
16
19
 
17
20
  /** Opt-in context for native CLI attribution and config discovery; no API credentials. */
18
21
  export const PROCESS_CONTEXT_ENV_KEYS = ["AGENTHUB_PEER_ID", "CLAUDECODE", "CLAUDE_CODE_SESSION_ID", "CODEX_THREAD_ID", "PI_SESSION_ID",
@@ -92,17 +95,42 @@ function failed(executor: Executor, step: string): Error {
92
95
  }
93
96
  function directory(value: unknown, field: string): string {
94
97
  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);
98
+ return canonicalExecutorPath(value);
99
+ }
100
+ 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}$/;
101
+ 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`); }
102
+ function gpuSelector(raw: unknown): string {
103
+ if (typeof raw === "number" && Number.isSafeInteger(raw) && raw >= 0) return String(raw);
104
+ if (typeof raw === "string" && /^(?:0|[1-9][0-9]*)$/.test(raw) && Number.isSafeInteger(Number(raw))) return raw;
105
+ if (typeof raw === "string" && GPU_UUID.test(raw)) return "GPU-" + raw.slice(4).toLowerCase();
106
+ return gpuConfigurationError("devices");
107
+ }
108
+ export function validateExecutorGpu(raw: unknown): ExecutorGpu {
109
+ if (!plain(raw) || Object.keys(raw).some(key => !["devices", "minFreeMemoryMb", "maxLoadRatio"].includes(key))) gpuConfigurationError("configuration");
110
+ if (!Array.isArray(raw.devices) || raw.devices.length < 1 || raw.devices.length > 64) gpuConfigurationError("devices");
111
+ const devices = raw.devices.map(gpuSelector);
112
+ if (new Set(devices).size !== devices.length) gpuConfigurationError("devices");
113
+ if (!Number.isSafeInteger(raw.minFreeMemoryMb) || Number(raw.minFreeMemoryMb) < 0 || Number(raw.minFreeMemoryMb) > 2_147_483_647) gpuConfigurationError("minFreeMemoryMb");
114
+ if (typeof raw.maxLoadRatio !== "number" || !Number.isFinite(raw.maxLoadRatio) || raw.maxLoadRatio <= 0 || raw.maxLoadRatio > 1_000_000) gpuConfigurationError("maxLoadRatio");
115
+ return { devices, minFreeMemoryMb: raw.minFreeMemoryMb as number, maxLoadRatio: raw.maxLoadRatio };
116
+ }
117
+ /** Frozen assignments and explicit Docker device arguments contain unique UUIDs only. */
118
+ export function validateGpuDevices(raw: unknown, count: number): string[] {
119
+ 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");
120
+ const devices = (raw as string[]).map(id => "GPU-" + id.slice(4).toLowerCase());
121
+ if (new Set(devices).size !== devices.length) throw new Error("GPU devices: duplicate frozen assignment; restore distinct GPU UUIDs before retrying the attempt");
122
+ return devices;
96
123
  }
97
124
  export function validateExecutor(raw: unknown): Executor {
98
125
  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`);
126
+ const extra = Object.keys(raw).find(key => !["v", "kind", "host", "workdir", "gpu", "retentionCapBytes"].includes(key));
127
+ if (extra !== undefined) throw new Error(`executor: unknown field ${extra}; use only v, kind, host, workdir and optional gpu`);
101
128
  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
129
  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
130
  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
131
  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") };
132
+ 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");
133
+ 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
134
  }
107
135
  export function readExecutor(dir: string): Executor | undefined {
108
136
  const file = join(dir, "executor.json");
@@ -116,6 +144,14 @@ export function setExecutor(dir: string, raw: unknown, actor: Actor): Executor {
116
144
  return executor;
117
145
  }
118
146
 
147
+ /**
148
+ * The one tar-create rule for archives ares reads or extracts elsewhere: content only. macOS bsdtar otherwise adds
149
+ * extended-attribute PAX records and AppleDouble `._*` members, which a Linux GNU tar extracts as regular files.
150
+ * COPYFILE_DISABLE suppresses AppleDouble members and --no-xattrs the attribute records. Used as a `sh -c` prefix
151
+ * because executor children get a minimal environment that would drop COPYFILE_DISABLE.
152
+ * ponytail: requires GNU tar >= 1.27 or bsdtar with --no-xattrs; unsupported tar (e.g. BusyBox) fails closed.
153
+ */
154
+ export const PORTABLE_TAR_CREATE = "COPYFILE_DISABLE=1 tar --no-xattrs";
119
155
  /** SSH concatenates its remote command argv into a shell command, so quote every unsafe byte. */
120
156
  export function shellQuote(value: string): string {
121
157
  return /^[A-Za-z0-9_./:@=+-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
@@ -125,6 +161,166 @@ export async function runOnExecutor(executorArg: Executor, command: string, args
125
161
  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
162
  catch { throw failed(executor, "process start"); }
127
163
  }
164
+ export class InputVerificationError extends Error {}
165
+ export class InputConfigurationError extends InputVerificationError {
166
+ constructor(message: string) { super(message); this.name = "InputConfigurationError"; }
167
+ }
168
+ export interface GpuDeferred { status: "deferred"; reason: "devices" | "load" | "probe"; message: string; exitCode: 75 }
169
+ export type GpuAdmission = { status: "admitted"; devices: string[] } | GpuDeferred;
170
+ export class GpuAdmissionDeferred extends Error {
171
+ constructor(readonly result: GpuDeferred) { super(result.message); this.name = "GpuAdmissionDeferred"; }
172
+ }
173
+ export const GPU_PROBE_TIMEOUT_MS = 10_000, GPU_PROBE_OUTPUT_BYTES = 65_536, GPU_INVENTORY_LIMIT = 256;
174
+ export const GPU_ADMISSION_SCRIPT = `set -eu
175
+ printf 'ARES_GPU_INVENTORY\n'
176
+ nvidia-smi --query-gpu=index,uuid,memory.free --format=csv,noheader,nounits
177
+ printf 'ARES_GPU_LOAD\n'
178
+ cat /proc/loadavg
179
+ printf 'ARES_GPU_CPUS\n'
180
+ if command -v nproc >/dev/null 2>&1; then nproc; else getconf _NPROCESSORS_ONLN; fi
181
+ printf 'ARES_GPU_END\n'
182
+ `;
183
+ function gpuDeferred(reason: GpuDeferred["reason"]): GpuDeferred {
184
+ 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";
185
+ return { status: "deferred", reason, message, exitCode: 75 };
186
+ }
187
+ interface GpuInventoryRow { index: string; uuid: string; memory: number }
188
+ function gpuProbe(stdout: string): { inventory: GpuInventoryRow[]; loadRatio: number } {
189
+ const lines = stdout.split(/\r?\n/); if (lines.at(-1) === "") lines.pop();
190
+ const load = lines.indexOf("ARES_GPU_LOAD"), cpus = lines.indexOf("ARES_GPU_CPUS");
191
+ 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");
192
+ const indexes = new Set<string>(), uuids = new Set<string>(), inventory: GpuInventoryRow[] = [];
193
+ for (const line of lines.slice(1, load)) {
194
+ const fields = line.split(",").map(field => field.trim());
195
+ 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");
196
+ const index = fields[0]!, uuid = "GPU-" + fields[1]!.slice(4).toLowerCase();
197
+ if (indexes.has(index) || uuids.has(uuid)) throw new Error("duplicate GPU identity");
198
+ indexes.add(index); uuids.add(uuid); inventory.push({ index, uuid, memory: Number(fields[2]) });
199
+ }
200
+ const parts = lines[load + 1]!.split(/ +/), decimal = /^[0-9]+(?:\.[0-9]+)?$/;
201
+ 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");
202
+ const [active, total] = parts[3]!.split("/").map(Number);
203
+ if (![active, total, Number(parts[4])].every(Number.isSafeInteger) || total! < 1 || active! > total!) throw new Error("load identity");
204
+ const cpu = lines[cpus + 1]!;
205
+ if (!/^[1-9][0-9]*$/.test(cpu) || !Number.isSafeInteger(Number(cpu))) throw new Error("CPU telemetry");
206
+ return { inventory, loadRatio: Number(parts[0]) / Number(cpu) };
207
+ }
208
+ /** One read-only probe; admission never sleeps, retries or reserves a physical GPU. */
209
+ export async function probeGpuAdmission(executorArg: Executor, count: number, runner: ProcessRunner = spawnRunner): Promise<GpuAdmission> {
210
+ const executor = validateExecutor(executorArg);
211
+ 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");
212
+ if (!executor.gpu || count === 0) return { status: "admitted", devices: [] };
213
+ let parsed: ReturnType<typeof gpuProbe>;
214
+ try {
215
+ const result = await runOnExecutor(executor, "sh", ["-c", GPU_ADMISSION_SCRIPT], runner, { timeoutMs: GPU_PROBE_TIMEOUT_MS, maxOutputBytes: GPU_PROBE_OUTPUT_BYTES });
216
+ if (result.exitCode !== 0 || result.timedOut || result.truncated || Buffer.byteLength(result.stdout) > GPU_PROBE_OUTPUT_BYTES) return gpuDeferred("probe");
217
+ parsed = gpuProbe(result.stdout);
218
+ } catch { return gpuDeferred("probe"); }
219
+ if (parsed.loadRatio > executor.gpu.maxLoadRatio) return gpuDeferred("load");
220
+ const devices: string[] = [];
221
+ for (const selector of executor.gpu.devices) {
222
+ const gpu = parsed.inventory.find(gpu => gpu.index === String(selector) || gpu.uuid === selector);
223
+ if (!gpu || gpu.memory < executor.gpu.minFreeMemoryMb || devices.includes(gpu.uuid)) continue;
224
+ devices.push(gpu.uuid); if (devices.length === count) return { status: "admitted", devices };
225
+ }
226
+ return gpuDeferred("devices");
227
+ }
228
+
229
+ export interface InputManifest { sha256: string; files: number; bytes: number }
230
+ export const INPUT_MANIFEST_FILES = 100_000, INPUT_MANIFEST_TIMEOUT_MS = 300_000, INPUT_MANIFEST_OUTPUT_BYTES = 4096;
231
+ // ponytail: ceiling 100,000 files/directories, depth 64 and 5 minutes; bytes stream in 1 MiB chunks, never into the study.
232
+ export const INPUT_MANIFEST_SCRIPT = String.raw`import os,sys,stat,hashlib,json
233
+ MAX=100000
234
+ records=[]
235
+ entries=0
236
+ directories=0
237
+ total=0
238
+ def identity(s):
239
+ return (s.st_dev,s.st_ino,s.st_size,s.st_mtime_ns,s.st_ctime_ns)
240
+ def walk(fd,prefix,depth):
241
+ global entries,directories,total
242
+ if depth>64: raise ValueError()
243
+ directories+=1
244
+ if directories>MAX: raise ValueError()
245
+ before=os.fstat(fd)
246
+ with os.scandir(fd) as stream:
247
+ for item in stream:
248
+ entries+=1
249
+ if entries>2*MAX or item.name in ('.','..'): raise ValueError()
250
+ name=prefix+'/'+item.name if prefix else item.name
251
+ if len(name.encode('utf-8'))>4096: raise ValueError()
252
+ info=os.stat(item.name,dir_fd=fd,follow_symlinks=False)
253
+ if stat.S_ISDIR(info.st_mode):
254
+ child=os.open(item.name,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW|os.O_NONBLOCK,dir_fd=fd)
255
+ try:
256
+ if identity(os.fstat(child))!=identity(info): raise ValueError()
257
+ walk(child,name,depth+1)
258
+ finally: os.close(child)
259
+ elif stat.S_ISREG(info.st_mode):
260
+ if len(records)>=MAX or info.st_size>9007199254740991-total: raise ValueError()
261
+ child=os.open(item.name,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK,dir_fd=fd)
262
+ try:
263
+ opened=os.fstat(child)
264
+ if not stat.S_ISREG(opened.st_mode) or identity(opened)!=identity(info): raise ValueError()
265
+ digest=hashlib.sha256()
266
+ size=0
267
+ while True:
268
+ chunk=os.read(child,1048576)
269
+ if not chunk: break
270
+ size+=len(chunk)
271
+ if size>info.st_size: raise ValueError()
272
+ digest.update(chunk)
273
+ if size!=info.st_size or identity(os.fstat(child))!=identity(opened): raise ValueError()
274
+ finally: os.close(child)
275
+ total+=size
276
+ records.append((name,size,digest.hexdigest()))
277
+ else: raise ValueError()
278
+ if identity(os.fstat(fd))!=identity(before): raise ValueError()
279
+ try:
280
+ root=sys.argv[1]
281
+ if not os.path.isabs(root): raise ValueError()
282
+ fd=os.open('/',os.O_RDONLY|os.O_DIRECTORY)
283
+ try:
284
+ for part in root.split('/'):
285
+ if not part: continue
286
+ if part in ('.','..'): raise ValueError()
287
+ child=os.open(part,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW|os.O_NONBLOCK,dir_fd=fd)
288
+ os.close(fd)
289
+ fd=child
290
+ walk(fd,'',0)
291
+ finally: os.close(fd)
292
+ digest=hashlib.sha256()
293
+ for row in sorted(records,key=lambda row:row[0].encode('utf-8')):
294
+ digest.update((json.dumps(row,ensure_ascii=False,separators=(',',':'))+'\n').encode('utf-8'))
295
+ print(json.dumps({'sha256':digest.hexdigest(),'files':len(records),'bytes':total},separators=(',',':')))
296
+ except Exception:
297
+ sys.stderr.write('input manifest refused\n')
298
+ sys.exit(1)
299
+ `;
300
+ /** Host-local streaming only: stdout is bounded metadata, never file names, contents or host paths. */
301
+ export async function hashExecutorInput(executorArg: Executor, path: string, runner: ProcessRunner = spawnRunner): Promise<InputManifest> {
302
+ const executor = validateExecutor(executorArg), source = directory(path, "executor input path");
303
+ 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>");
304
+ let result: ProcessResult;
305
+ try {result = await runOnExecutor(executor, "python3", ["-I", "-S", "-c", INPUT_MANIFEST_SCRIPT, source], runner, {timeoutMs: INPUT_MANIFEST_TIMEOUT_MS, maxOutputBytes: INPUT_MANIFEST_OUTPUT_BYTES});}
306
+ catch {throw refuse();}
307
+ if (result.exitCode !== 0 || result.timedOut || result.truncated || Buffer.byteLength(result.stdout) > INPUT_MANIFEST_OUTPUT_BYTES) throw refuse();
308
+ let raw: unknown; try {raw = JSON.parse(result.stdout);} catch {throw refuse();}
309
+ 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();
310
+ return {sha256: raw.sha256, files: raw.files as number, bytes: raw.bytes as number};
311
+ }
312
+ /** Verify every declared input without persisting its host locator or manifest rows. */
313
+ export async function verifyExecutorInputs(executor: Executor, protocol: Protocol, runner: ProcessRunner = spawnRunner): Promise<Record<string, string>> {
314
+ const inputs = validateProtocol(protocol).inputs ?? {}, verified: [string, string][] = [];
315
+ for (const [name, input] of Object.entries(inputs)) {
316
+ let manifest: InputManifest;
317
+ try { manifest = await hashExecutorInput(executor, input.path!, runner); }
318
+ 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`); }
319
+ 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`);
320
+ verified.push([name, manifest.sha256]);
321
+ }
322
+ return Object.fromEntries(verified);
323
+ }
128
324
  async function step(executor: Executor, name: string, command: string, args: string[], runner: ProcessRunner, options: Omit<ProcessRequest, "command" | "args"> = {}): Promise<ProcessResult> {
129
325
  try {
130
326
  const result = await runOnExecutor(executor, command, args, runner, options);
@@ -132,16 +328,22 @@ async function step(executor: Executor, name: string, command: string, args: str
132
328
  return result;
133
329
  } catch { throw failed(executor, name); }
134
330
  }
135
- export interface ExecutorCheck { executor: Executor; serverVersion: string; user: string; images: { image: string; available: true }[]; pull: "missing" }
331
+ export interface ExecutorCheck { inputRuntime?: "python3"; executor: Executor; serverVersion: string; user: string; images: { image: string; available: true }[]; pull: "missing" }
136
332
  export async function checkExecutor(dir: string, runner: ProcessRunner = spawnRunner): Promise<ExecutorCheck> {
137
333
  requireExperiment(openStudy(dir).study);
138
334
  const executor = readExecutor(dir), protocol = readProtocol(dir);
139
335
  if (!executor) throw new Error("executor: not configured; run ares executor set <dir> --kind local|ssh [--host ALIAS] --workdir PATH");
140
336
  if (!protocol) throw new Error("protocol: missing; run ares protocol <dir> --file PATH before executor check");
337
+ if (protocol.v === 2) {
338
+ const { executionView } = await import("./pipeline.ts");
339
+ for (let index = 1; index < protocol.candidate.stages.length; index++) await checkExecutorInputs(executor, executionView(protocol, index), runner);
340
+ return checkExecutorInputs(executor, executionView(protocol), runner);
341
+ }
141
342
  return checkExecutorInputs(executor, protocol, runner);
142
343
  }
143
344
  /** Check a frozen attempt's configuration rather than mutable study files. */
144
345
  export async function checkExecutorInputs(executor: Executor, protocol: Protocol, runner: ProcessRunner = spawnRunner): Promise<ExecutorCheck> {
346
+ 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
347
  const version = (await step(executor, "Docker server version", "docker", ["version", "--format", "{{.Server.Version}}"], runner)).stdout.trim();
146
348
  if (!/^[0-9]+\.[0-9]+(?:\.[0-9]+)?[A-Za-z0-9.+_-]*$/.test(version) || version.length > 128) throw failed(executor, "Docker server version");
147
349
  const uid = (await step(executor, "host uid", "id", ["-u"], runner)).stdout.trim();
@@ -156,19 +358,48 @@ export async function checkExecutorInputs(executor: Executor, protocol: Protocol
156
358
  if (present.exitCode !== 0) await step(executor, "image pull", "docker", ["pull", image], runner, { timeoutMs: 300_000 });
157
359
  images.push({ image, available: true });
158
360
  }
159
- return { executor, serverVersion: version, user: `${uid}:${gid}`, images, pull: "missing" };
361
+ return { ...(Object.keys(protocol.inputs ?? {}).length ? { inputRuntime: "python3" as const } : {}), executor, serverVersion: version, user: `${uid}:${gid}`, images, pull: "missing" };
160
362
  }
161
363
 
364
+ export function executionPathsOverlap(left: string, right: string): boolean {
365
+ const a = canonicalExecutorPath(left), b = canonicalExecutorPath(right);
366
+ return a === b || a.startsWith(b === "/" ? b : `${b}/`) || b.startsWith(a === "/" ? a : `${a}/`);
367
+ }
162
368
  export type Stage = "candidate" | "evaluator";
163
369
  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 }
165
- export function containerName(attemptId: string, stage: Stage): string {
370
+ export interface ContainerOptions { protocol: Protocol; stage: Stage; studyId: string; attemptId: string; user: string; paths: ContainerPaths; seed?: number; gpuDevices?: string[]; name?: string; pipeline?: { name: string; inputRoot: string; seed: boolean } }
371
+ export function containerName(studyId: string, attemptId: string, stage: Stage): string {
166
372
  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
- return `ares-${attemptId}-${stage}`;
373
+ if (!/^[A-Za-z0-9_-]{1,80}$/.test(studyId)) throw new Error("container identity: invalid study id; use the id from study.json");
374
+ // An attempt id is study-local, so the name must carry the study too or two studies collide on one executor host.
375
+ return `ares-${sha256(`${CONTAINER_NAME_DOMAIN}\0${studyId}\0${attemptId}`).slice(0, 16)}-${stage}`;
376
+ }
377
+ /** The pipeline stage suffix is part of the launched name; one place keeps the argv and the attempt record identical. */
378
+ export function stageContainerName(studyId: string, attemptId: string, stage: Stage, pipelineStage?: string): string {
379
+ const name = containerName(studyId, attemptId, stage);
380
+ if (pipelineStage === undefined) return name;
381
+ if (stage !== "candidate" || !/^[a-z][a-z0-9_-]{0,31}$/.test(pipelineStage)) throw new Error("pipeline container: invalid stage name");
382
+ return `${name}-${pipelineStage}`;
383
+ }
384
+ /** A stage that was already recorded keeps its own launched name, pipeline suffix included. */
385
+ function recordedContainerName(name: string): string {
386
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(name)) throw new Error("container identity: invalid recorded name; use the name stored on the attempt stage");
387
+ return name;
388
+ }
389
+ /** Pure preflight for host input isolation; no hashing, transport or attempt side effects. */
390
+ export function validateContainerInputSources(protocol: Protocol, pathsArg: ContainerPaths): void {
391
+ const p = validateProtocol(protocol);
392
+ const paths = Object.fromEntries(Object.entries(pathsArg).map(([key, value]) => [key, directory(value, `container.paths.${key}`)])) as unknown as ContainerPaths;
393
+ const sources = [paths.snapshot, paths.output, paths.evaluator, paths.result], inputs = Object.values(p.inputs ?? {});
394
+ 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");
395
+ for (let a = 0; a < inputs.length; a++) for (let b = a + 1; b < inputs.length; b++) {
396
+ const x = inputs[a]!, y = inputs[b]!;
397
+ 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");
398
+ }
168
399
  }
169
400
  /** Mounts are fixed by stage, never supplied as free-form Docker options. */
170
401
  export function buildContainerArgs(options: ContainerOptions): string[] {
171
- const p = validateProtocol(options.protocol), name = containerName(options.attemptId, options.stage);
402
+ const p = validateProtocol(options.protocol), name = options.name === undefined ? stageContainerName(options.studyId, options.attemptId, options.stage, options.pipeline?.name) : recordedContainerName(options.name);
172
403
  const seed = options.seed === undefined ? p.seeds[0]! : options.seed;
173
404
  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
405
  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 +411,16 @@ export function buildContainerArgs(options: ContainerOptions): string[] {
180
411
  const x = sources[a]!, y = sources[b]!;
181
412
  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
413
  }
414
+ validateContainerInputSources(p, paths);
415
+ const inputs = Object.values(p.inputs ?? {});
183
416
  const argv = ["run", "--detach", "--pull", "missing", "--name", name, "--label", `ares.study=${options.studyId}`, "--label", `ares.attempt=${options.attemptId}`, "--label", `ares.stage=${options.stage}`,
184
417
  "--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));
418
+ "--cpus", String(p.limits.cpus), "--memory", `${p.limits.memoryMb}m`, "--pids-limit", String(p.limits.pidsLimit)];
419
+ if (!options.pipeline || options.pipeline.seed) argv.push("--env", `ARES_SEED=${seed}`);
420
+ if (options.gpuDevices !== undefined) {
421
+ const devices = validateGpuDevices(options.gpuDevices, p.limits.gpus);
422
+ if (devices.length) argv.push("--gpus", `"device=${devices.join(",")}"`);
423
+ } else if (p.limits.gpus > 0) argv.push("--gpus", String(p.limits.gpus));
187
424
  const mount = (source: string, target: string, readonly: boolean) => argv.push("--mount", `type=bind,src=${source},dst=${target}${readonly ? ",readonly" : ""}`);
188
425
  if (options.stage === "candidate") {
189
426
  mount(paths.snapshot, "/workspace", true); mount(paths.output, "/out", false);
@@ -193,13 +430,23 @@ export function buildContainerArgs(options: ContainerOptions): string[] {
193
430
  mount(paths.evaluator, "/eval", true); mount(paths.output, "/candidate", true); mount(paths.result, "/result", false);
194
431
  argv.push("--workdir", "/eval");
195
432
  }
433
+ if (options.pipeline) {
434
+ const source = directory(options.pipeline.inputRoot, "pipeline inputs");
435
+ if (sources.some(path => executionPathsOverlap(source, path))) throw new Error("pipeline inputs: source overlaps workspace mounts");
436
+ mount(source, "/in", true);
437
+ }
438
+ for (const input of inputs) {
439
+ const target = input.mount[options.stage];
440
+ if (target !== undefined) mount(input.path!, target, true);
441
+ }
196
442
  argv.push(p[options.stage].image, ...p[options.stage].command);
197
443
  return argv;
198
444
  }
199
445
 
200
446
  /** Launch on the executor host; stdio is detached so SSH returns immediately. T3 reconciles deadlines as a backstop. */
201
- export async function startWatchdog(executor: Executor, attemptId: string, stage: Stage, wallSeconds: number, runner: ProcessRunner = spawnRunner, containerId?: string): Promise<void> {
202
- const name = containerName(attemptId, stage);
447
+ export async function startWatchdog(executor: Executor, name: string, wallSeconds: number, runner: ProcessRunner = spawnRunner, containerId?: string): Promise<void> {
448
+ // The caller passes the name the container was launched with, which is the recorded one for older attempts.
449
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(name)) throw new Error("watchdog container name: invalid; pass the launched container name");
203
450
  if (containerId !== undefined && !/^[a-f0-9]{64}$/.test(containerId)) throw new Error("watchdog container id: invalid; use the full id returned by the verified container start");
204
451
  if (!Number.isSafeInteger(wallSeconds) || wallSeconds < 1 || wallSeconds > 604_800) throw new Error("watchdog deadline: invalid wallSeconds; use the validated protocol limit (1..604800 seconds)");
205
452
  const script = `nohup sh -c ${shellQuote(`sleep ${wallSeconds}; docker kill ${containerId ?? name}`)} </dev/null >/dev/null 2>&1 &`;
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 {
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { posix } from "node:path";
3
3
  import { plain } from "../study.ts";
4
- import { runOnExecutor, shellQuote, type ProcessRunner, type Stage } from "./executor.ts";
4
+ import { PORTABLE_TAR_CREATE, runOnExecutor, shellQuote, type ProcessRunner, type Stage } from "./executor.ts";
5
5
  import { ARTIFACT_BYTES, ARTIFACT_FILES, ArtifactError, readArtifactArchive } from "./artifacts.ts";
6
6
  import type { Attempt, Evaluation } from "./attempts.ts";
7
7
  import type { Protocol } from "./protocol.ts";
@@ -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=$!`,
@@ -103,10 +104,8 @@ export async function collectStageEvidence(attempt: Attempt, stage: Stage, runne
103
104
  'if test "$status" -ne 0; then if test "$outcut" = true || test "$errcut" = true; then outcut=true; errcut=true; else exit "$status"; fi; fi',
104
105
  'printf \'{"stdout":%s,"stderr":%s}\\n\' "$outcut" "$errcut" > "$statetmp"',
105
106
  'mv "$outtmp" "$out"; mv "$errtmp" "$err"; mv "$statetmp" "$state"', 'fi',
106
- // Archive content only: BSD tar otherwise emits binary xattr PAX and AppleDouble entries.
107
- // ponytail: requires GNU tar >= 1.27 or bsdtar with --no-xattrs; unsupported tar
108
- // (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)}`,
107
+ // Archive content only; see PORTABLE_TAR_CREATE for the shared tar portability rule and its ceiling.
108
+ `${PORTABLE_TAR_CREATE} -C ${shellQuote(root)} -cf - ${shellQuote(`logs/${stageLabel}.stdout.log`)} ${shellQuote(`logs/${stageLabel}.stderr.log`)} ${shellQuote(statePath)}`,
110
109
  ].join("\n");
111
110
  let logArchive;
112
111
  try { logArchive = await readArtifactArchive(attempt.executor, "sh", ["-c", script], runner, { capture: statePath, captureBytes: 1024, maxFiles: 3, maxBytes: LOG_COPY_BYTES * 2 + 1024 }); }
@@ -116,7 +115,7 @@ export async function collectStageEvidence(attempt: Attempt, stage: Stage, runne
116
115
  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
116
  const cuts = truncated as { stdout: boolean; stderr: boolean };
118
117
  const log = (kind: "stdout" | "stderr"): LogEvidence => {
119
- const file = logArchive.files.find(item => item.path === `logs/${stage}.${kind}.log`);
118
+ const file = logArchive.files.find(item => item.path === `logs/${stageLabel}.${kind}.log`);
120
119
  if (!file) throw new EvidenceError("missing-logs", "stage evidence: a stdout/stderr copy is missing; inspect the executor log directory and retry collection");
121
120
  return { path: posix.join(root, file.path), sha256: file.sha256, bytes: file.bytes, truncated: cuts[kind] || file.bytes >= LOG_COPY_BYTES };
122
121
  };
@@ -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
+ }