@staix/agent-research 0.3.0 → 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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,28 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## [0.3.1] - 2026-11-10
6
+
7
+ Finish or reconcile running attempts before downgrading to 0.3.0.
8
+
9
+ - Study-scoped executor container names (#149, product fix): a container name now derives from the study id together with the attempt id, so two studies that repeat one attempt identity on the same executor no longer collide and end `unknown` with `container isolation verification failed`. Each stage record stores the name it launched with; a record written before this change carries none and keeps resolving `ares-<attemptId>-<stage>[-<pipelineStage>]` for inspect, reconcile and absence confirmation. Isolation verification still refuses a foreign or leftover container that carries the new name, and the watchdog, cleanup and adoption paths use the recorded name rather than recomputing one. No record version changes and existing attempts stay readable.
10
+
11
+ - Reuse request warning (#150, product fix): eligible requests outside a matching investigation run still run fresh and return additive, non-persisted warnings with code `outside-investigation`, cause and nextStep. CLI/MCP result shapes are otherwise unchanged; no new command or flag is added.
12
+
13
+ - Task snapshot archive (#148): `ares attempt run` now creates the task archive with the shared content-only tar rule (`COPYFILE_DISABLE=1 tar --no-xattrs`, also used for stage logs) and checks every streamed member against the staged task files. An AppleDouble `._*` member or any member that differs from the staged files is refused by name, so a macOS controller no longer ships extended-attribute metadata to a Linux executor. The frozen task tree hash is unchanged and pinned by a test.
14
+
15
+ - Reuse rematerialization r2 preparation (#63 T3): export existing source/fault helpers without changing their implementations, add an arm-neutral fresh/eligible fixture runner and a separate create-once superseding setup receipt. Per-case stage hashes and fault states must equal the original amendment; all frozen inputs, labels, v1/v2 seals and the original Reuse receipt stay unchanged. Phase parent CPU, subprocess unknowns and wall clocks stay distinct. This preparation step contains no measurement; the completed T3 runs are reported separately below. The r2 developer receipt names the original setup seal as superseded before use; invalid r2 receipts refuse instead of falling back. Earlier setup verification may report changed code and never rewrites history.
16
+
17
+ - Reuse admission (#64, product fix): a candidate stage is no longer reused from a source attempt that is not `succeeded`. A `cancelled` or `unknown` attempt that left its sealed stages intact used to produce a verified hit; it now misses as `ineligible-source` and the stage runs fresh. A valid digest alone never makes an interrupted or semantically stale source eligible, so the rule only narrows reuse: no stage is added, no stored byte or format changes, and a hit from a succeeded source is unaffected.
18
+
19
+ - Reuse source rematerialization amendment (#63 T3a): `integration-check` reports the Reuse arm as `integrated-rematerialized-source`. A deterministic, code-bound setup rebuilds each case's source stage outputs from that case's own frozen `source.workload` with the v1 workload arithmetic, at every declared seed, as the producer's own payload bytes, and a separate create-once receipt seals the setup. All ten cases that declare a source are rebuilt: four healthy and six rebuilt healthy and then given their own declared fault, so the fault suites reach the reuse path instead of being refused by the setup. Corruption changes a retained payload after the seal so the sealed manifest hash no longer matches; pruning disposes the rebuilt stages through the retention prune path; an interrupted source is recorded `cancelled` or `unknown` after its candidate stages were sealed. The admission check is a fake-runner test per fault and requires the reuse path itself to refuse all three stages with its own reason and admit none. The seal binds the setup modules including the fault-injection code, the corpus index, all twelve input hashes, the per-case workload and stage hashes, inherited thresholds/denominators and the immutable v1 parent; `freeze-reuse-rematerialization` and `verify-reuse-rematerialization` verify it and refuse drift. Evaluator labels are never read, so no expected file enters the seal. Outcomes stay `null` with zero trial executions, and the setup's own cost is recorded separately in the materialization dimensions while every other clock stays `unknown`.
20
+
21
+ - Supervision snapshot integration (#63 T2b): pin the closed exported snapshot with source-owned evaluated triples and evaluatedSuppressed. Independent producer-generated unit vectors replace hand-authored snapshots; frozen v1/v2 corpora, labels, receipts and baseline bytes stay unchanged. Absence scoring requires exact rule/task/revision coverage, with gaps and retention overflow remaining insufficient. Intent `none` requires all three rules; wrong/false proposal burden remains counted from presence, and zero helpful actions reports 0. No treatment trial or runtime hub/model/network call is added by this reader. Its unsealed fixture envelope requires evaluated and evaluatedSuppressed; earlier incomplete envelopes refuse with a restore-from-producer next step.
22
+
23
+ - Supervision corpus v2 amendment (#63 T2c-B): separate create-once freeze/verify receipt binds the approved v2 protocol/join method, inherited budgets/thresholds/denominators, all input/expected bytes and the immutable v1 parent. Integration-check keeps v1 unsupported and adds twelve format-covered v2 cases with null outcomes and zero runs. The intent join uses action/rule/task/current revision, never producer trigger strings; the 2026-11-10 ruling separates exclusive case outcomes from observed wrong/false proposal burden. Always-wrong proposals consume the false-proposal budget even when missing desired-rule coverage leaves the case insufficient. Absence scoring remains pending source-owned evaluated coverage; no evaluator, treatment, hub or model call is added.
24
+
25
+ - Execution evaluation (#63 T3/T4): preserve immutable paired Diagnose/Reuse and Supervision v2 shadow receipts and publish the evidence-bound disposition report and closeout. Diagnose is insufficient evidence, Reuse is restricted after failed performance gates, and Supervision is at most retained in shadow mode. Lineage remains read-only utility, eligible reuse stays off by default with explicit operator opt-in, and advisory mode remains off without separate authorization. Human timing and live/native/account benefits are not inferred from synthetic observations.
26
+
5
27
  ## [0.3.0] - 2026-11-10
6
28
 
7
29
  N-1 compatibility for 0.3.0 is against **0.2.1**, the latest published patch of the 0.2 minor line. The installed-package `bun scripts/n1-check.ts` check passed on the prepared 0.3.0 candidate; the existing networked `n1` CI job repeats it and remains required by `ci-ok`.
package/README.md CHANGED
@@ -190,8 +190,12 @@ Before admission and when preparing a stage launch, ares verifies input manifest
190
190
 
191
191
  Only the evaluator's `/result/metrics.json` supplies metrics: at most 64 KiB, exactly the declared names with finite numeric values, for example `{"score": 7}`. Units and directions come from the protocol. Missing, malformed or undeclared metrics fail at the evaluator stage; candidate-printed scores never become metrics.
192
192
 
193
+ Task snapshot archives use the shared content-only tar rule (`COPYFILE_DISABLE=1 tar --no-xattrs`) and check streamed members against the staged task files. AppleDouble `._*` or unexpected/mismatched members are refused by name; frozen task tree hashes and receipt formats are unchanged. Offline archive checks do not establish native Docker isolation.
194
+
193
195
  Without `--detach`, `attempt run` reconciles until finished. Detached runs and MCP `ares_attempt_run` return while running; call `attempt reconcile` again to advance stages and collect results. States progress from running candidate to running evaluator, then succeeded, failed, cancelled or unknown. A gone container without an exit record becomes unknown (`lost`); reconcile never creates a new attempt. One attempt may be active per study. A host watchdog enforces each stage's wall-clock limit.
194
196
 
197
+ New stage records store a container name derived from the study and attempt identities; two studies with the same attempt identity no longer share a container name. Inspection, reconciliation, cleanup and watchdogs use the recorded name. Older stage records without it keep their legacy name. Finish or reconcile running attempts before downgrading to 0.3.0, whose reader recomputes the legacy name.
198
+
195
199
  The same protocol hash, commit/tree, seed and run return the same attempt. Use `--retry <id>` for a linked new attempt; a different commit or seed is a new attempt, not a reproduction. Every status counts toward study budgets (attempt count, wall hours, GPU hours). `attempt list` returns summaries and whole-study totals for every status regardless of filters or page; default page size 50, maximum 200, with `--offset` for later pages. `attempt show` returns the full record.
196
200
 
197
201
  Raw outputs and logs stay in the private executor attempt directory. The study holds output paths, sha256 and byte counts (regular files only, at most 500 files and 256 MiB total), plus each log stream's path, hash, bytes and truncation flag. Each stdout/stderr copy is capped at 16 MiB; excess log volume does not fail an attempt. `attempt logs` checks the recorded copies and prints tails without changing the study; `--tail` accepts 0..65536 bytes per stream (default 16384), and omitted stage/stream filters return all recorded streams, including completed v2 candidates. Use `--candidate-stage NAME` (MCP `candidateStage`) to select one named current or completed candidate. Combined returned tails are capped at 256 KiB: defaults shrink across many streams, while an oversized explicit tail requires a narrower selection or smaller value. No log content is persisted in the study.
@@ -234,7 +238,7 @@ ares attempt run experiment --repo ./candidate --commit FULL_SHA --run investiga
234
238
  ares attempt run experiment --repo ./candidate --commit FULL_SHA --run investigate --reuse eligible --force-fresh --retry SOURCE_ID --detach
235
239
  ```
236
240
 
237
- The run must match the current selection rule. MCP `ares_attempt_run` accepts equivalent `reuse: off|eligible` and `forceFresh` fields. Plan `attempt.run` steps forward the corresponding `reuse` and `force-fresh` arguments admitted by the shared command table. Re-delivery with the same controls returns the existing running or terminal attempt, including force-fresh requests. Changing reuse/force-fresh controls on an existing identity is refused with its recorded controls and an explicit retry hint. Off-mode artifacts are not indexed retroactively. Evaluators, ablation, final and posthoc always execute fresh. Missing/pruned/corrupt/unsupported sources are reasoned misses with ordinary budget checks. GPU ABI reuse is currently unsupported and falls back to fresh execution.
241
+ Eligible reuse requires the run to match the current selection rule. Outside a matching investigation run, the request still executes fresh and its CLI/MCP result adds `warnings[{code:"outside-investigation", cause, nextStep}]`, naming the cause and advising a matching selection run or dropping `--reuse`; the warning is not persisted. MCP `ares_attempt_run` accepts equivalent `reuse: off|eligible` and `forceFresh` fields. Plan `attempt.run` steps forward the corresponding `reuse` and `force-fresh` arguments admitted by the shared command table. Re-delivery with the same controls returns the existing running or terminal attempt, including force-fresh requests. Changing reuse/force-fresh controls on an existing identity is refused with its recorded controls and an explicit retry hint. Off-mode artifacts are not indexed retroactively. Evaluators, ablation, final and posthoc always execute fresh. Only a `succeeded` source attempt can supply a reuse hit; a cancelled or unknown source is an `ineligible-source` miss even if its stage bytes remain intact. Missing/pruned/corrupt/unsupported sources are reasoned misses with ordinary budget checks. GPU ABI reuse is currently unsupported and falls back to fresh execution.
238
242
 
239
243
  Keys bind the study and frozen selection/reserved-seed population, protocol comparison domain, complete selected stage, full code tree and snapshot digest, exact declared input hashes, seed, producer version/source/runtime and observed executor/platform ABI. A changed code tree therefore misses even if only a downstream stage changed. Unavailable platform facts give a reasoned miss; caller assertions cannot supply them.
240
244
 
@@ -606,11 +610,13 @@ Read local execution references and their recorded relationships with `ares line
606
610
 
607
611
  MCP exposes the same reads as `ares_lineage_show({study, root?, cursor?})` and `ares_lineage_compare({study, attempts?, candidates?})`. An MCP root is a local `ExecutionReferenceV1` with `v: 1`, `tool: "ares"`, `projectKey`, `kind`, native `id`, and optional `revision`/`sha256`. Both tools are read-only and closed-world. Reads do not acquire study locks, repair files, read executor output bodies, contact a hub or executor, or start network requests. Source receipts can remain historical or unavailable; an artifact digest is not proof that its bytes are retained. Synthetic fixture checks establish surface parity only, with no measured diagnosis or usability benefit claimed.
608
612
 
609
- ## Evaluation fixtures and pending trials
613
+ ## Evaluation fixtures and treatment evidence
610
614
 
611
615
  The repository preregisters synthetic Diagnose, Reuse and Supervision comparisons and preserves the frozen corpus, thresholds and T2a baseline receipts. These developer scripts are separate from product study results. The read-only `bun scripts/execution-eval.ts integration-check` verifies the seal and committed code binding and reports all 36 frozen cases; it launches no treatment arm, writes no receipt and reports zero treatment observations.
612
616
 
613
- Diagnose has a read-only adapter to the actual lineage/comparison readers. Reuse uses the attempt/retention/fresh-evaluator path through a synthetic container seam, but the frozen cached strings cannot establish numeric producer manifests, so those cases stay fresh fallback. A separate non-frozen fixture proves byte-exact producer hits, without becoming a treatment observation. Supervision has a record consumer pinned to agent-hub#1221 at `bc6f46b077dd3a255debaee8152fa17f1f13b79c`; all 12 frozen task-state inputs are unsupported T1 rule facts. Coverage stays 0 supported / 12 unsupported, helpful/false/missed remain `null`, and person decisions stay 0. No hub rule evaluator or live hub is called. Corpus amendments and T3 launch authorization remain separate from this released v1 integration. See [the integration boundaries and pending trials](docs/verification/execution-eval-treatment-integration.md).
617
+ Diagnose has a read-only adapter to the actual lineage/comparison readers. The separate Reuse r2 amendment rematerializes sources from frozen source workloads with setup costs recorded separately; it supersedes the original opaque-byte source setup without changing the v1 corpus or seal. Supervision consumes the producer-owned snapshot pinned to agent-hub#1221 at `a470ebbd5d809e421c6fc82fab8a69434c1b2e08`. The original v1 Supervision inputs remain unsupported; a separately sealed v2 corpus supplies twelve T1-fact inputs and intent labels. Check-only integration and freeze/verify modes launch no treatment trial and create no product result authority. The v2 intent join counts present wrong/false proposals independently of absent-action coverage; the current snapshot cannot establish correct non-triggers.
618
+
619
+ Authorized CPU-only synthetic T3 trials are now recorded in the [measured treatment report](docs/verification/execution-eval-t3-report.md), with fresh controls for Diagnose and Reuse, immutable receipts and full denominators. Diagnose remains insufficient evidence: parity is by construction and human time-to-find is unmeasured. Reuse is restricted rather than adopted because the eligible-compute and no-hit-overhead gates fail. Supervision is at most retained in shadow mode, insufficient for adoption; arms A and C were not executed, and the twelve changed-deliverable misses remain unrelabeled. These are harness-observed fixture results, not native isolation, human benefit or live-board evidence. The [T4 closeout](docs/verification/execution-eval-t4-status.md) records evidence hashes, defaults and remaining live-evidence gaps: lineage remains read-only utility, eligible reuse stays off by default with explicit operator opt-in and no performance/cost claim, and advisory mode remains off without separate authorization. The sealed v1/v2 corpora and r2 receipt remain unchanged.
614
620
 
615
621
  The separate [guidance-improvement preregistration](docs/verification/harness-eval-protocol.md) includes deterministic prerecorded controls through `scripts/harness-eval.ts`. Controls, fixture conformance and metadata decoding do not establish real model behavior, transfer, native isolation or measured cost benefit. Treatment trials and native/account/model proof still need their own authorization and evidence.
616
622
 
@@ -886,7 +892,7 @@ The tag workflow first waits up to 30 minutes for the exact commit's main-push `
886
892
 
887
893
  Publication runs only when `NPM_PUBLISH_ENABLED` is `true` and a reviewer approves `npm-production`. It uses Node 24 and npm 11.5.1 or newer with [npm OIDC trusted publishing](https://docs.npmjs.com/trusted-publishers), without an npm token. The owner manages trusted-publisher settings, environment approval and branch protection requiring `ci-ok`; the scripts do not change those settings.
888
894
 
889
- N-1 compatibility is stated per minor release in CHANGELOG.md, separately for CLI, MCP tools and study/ledger formats. For 0.3.0, N-1 is 0.2.1: all 60 published commands/usages and 55 MCP tool names/readOnly values are retained (90 commands and 85 tools total). The installed-package check verifies unchanged reads of 0.2.1 survey/experiment studies and ledgers, and preserves a no-input protocol's hash, design binding and approved gate; 0.2.1 can also read a newly written study v2 unchanged. Its old readers refuse protocol v2, attempt v2/v3, skill-proposal v2 and paper-evidence v2, plus new fields in closed protocol/executor/scope/plan-step schemas. It has no reader for paper-plan v1/v2, harness/experience/lesson namespaces or study.toml, so ignored files do not provide routing, points or other newer checks. Use 0.3.0 for those feature semantics; supporting an old format does not promise identical readiness or safe downgrade. See the dated CHANGELOG block for the refusal/ignore distinctions. The networked n1 CI job (bun scripts/n1-check.ts), required by ci-ok, resolves the latest published patch of the previous minor line (0.2.x for every 0.3 release); it checks the stated manifest and representative read paths, not every new feature.
895
+ N-1 compatibility is stated per minor release in CHANGELOG.md, separately for CLI, MCP tools and study/ledger formats. For the 0.3 minor line, N-1 remains 0.2.1: all 60 published commands/usages and 55 MCP tool names/readOnly values are retained (90 commands and 85 tools total). The installed-package check verifies unchanged reads of 0.2.1 survey/experiment studies and ledgers, and preserves a no-input protocol's hash, design binding and approved gate; 0.2.1 can also read a newly written study v2 unchanged. Its old readers refuse protocol v2, attempt v2/v3, skill-proposal v2 and paper-evidence v2, plus new fields in closed protocol/executor/scope/plan-step schemas. It has no reader for paper-plan v1/v2, harness/experience/lesson namespaces or study.toml, so ignored files do not provide routing, points or other newer checks. Use 0.3.0 for those feature semantics; supporting an old format does not promise identical readiness or safe downgrade. See the dated CHANGELOG block for the refusal/ignore distinctions. The networked n1 CI job (bun scripts/n1-check.ts), required by ci-ok, resolves the latest published patch of the previous minor line (0.2.x for every 0.3 release); it checks the stated manifest and representative read paths, not every new feature. It does not create populated attempt records, so this check alone does not verify the optional stage containerName field against 0.2.1 or safe reconciliation after a downgrade.
890
896
 
891
897
  ## Development
892
898
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-research",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Research engine for the agent family: literature with verified references, study ledger and gates (ares)",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/commands.ts CHANGED
@@ -21,7 +21,8 @@ import { addAblation, showAblate, closeAblate } from "./exp/ablate.ts";
21
21
  import { setFinalSeeds, finalGateBinding, requireFinalInputs, closeFinal, showPosthoc } from "./exp/final.ts";
22
22
  import { addIdea, decideIdea } from "./exp/ideas.ts";
23
23
  import { showInvestigation, closeInvestigation } from "./exp/investigate.ts";
24
- import { setSelection } from "./exp/selection.ts";
24
+ import { isInvestigationRun } from "./exp/reuse-runtime.ts";
25
+ import { readSelection, setSelection } from "./exp/selection.ts";
25
26
  import { createHubClient } from "./plan/hub.ts";
26
27
  import { runPlan, type ControllerRuntime, type Observation, type StepNode } from "./plan/controller.ts";
27
28
  import { resolveSnapshot } from "./exp/snapshot.ts";
@@ -44,7 +45,7 @@ import { assignCitekeys, renderBib } from "./lit/bibtex.ts";
44
45
  import { checkCitations } from "./lit/cite.ts";
45
46
  import { cardPath, validateCard } from "./lit/cards.ts";
46
47
  import { createVaultClient, exportCards, importCards, listCards, previewCardExport } from "./memory/vault-cards.ts";
47
- import { designBinding, protocolHash, readDesign, setProtocol } from "./exp/protocol.ts";
48
+ import { designBinding, protocolHash, readDesign, readProtocol, setProtocol } from "./exp/protocol.ts";
48
49
  import { requireExperiment } from "./study.ts";
49
50
  import { checkExecutor, setExecutor, readExecutor, hashExecutorInput, type InputManifest } from "./exp/executor.ts";
50
51
  import { cancelAttempt, listAttempts, listAttemptSummaries, reconcileAttempts, runAttempt, showAttempt, type AttemptContext, type AttemptListOptions, type AttemptOptions } from "./exp/attempts.ts";
@@ -194,8 +195,14 @@ export const harnessImport = (dir: string, round: string, raw: unknown, ctx: Ctx
194
195
  export async function attemptRun(dir: string, options: AttemptOptions, ctx: Ctx) {
195
196
  if (options.reuse !== undefined && options.reuse !== "off" && options.reuse !== "eligible") throw new Error("attempt reuse: off or eligible required; select --reuse off|eligible (MCP reuse) and retry");
196
197
  if (options.forceFresh !== undefined && typeof options.forceFresh !== "boolean") throw new Error("attempt forceFresh: boolean required; set forceFresh to true/false or use --force-fresh, then retry");
197
- try { return await runAttempt(dir, options, ctx); }
198
- catch (error) { if (error instanceof GpuAdmissionDeferred) return error.result; throw error; }
198
+ const protocol = options.reuse === "eligible" ? readProtocol(dir) : undefined;
199
+ const selection = protocol ? readSelection(dir, protocol) : undefined;
200
+ const warnings = options.reuse === "eligible" && !isInvestigationRun(options.run ?? "main", selection)
201
+ ? [{ code: "outside-investigation", cause: "not an investigation run", nextStep: "declare the selection run, or drop --reuse" }] : undefined;
202
+ let result;
203
+ try { result = await runAttempt(dir, options, ctx); }
204
+ catch (error) { if (error instanceof GpuAdmissionDeferred) result = error.result; else throw error; }
205
+ return warnings ? { ...result, warnings } : result;
199
206
  }
200
207
  export const attemptList = (dir: string, options: AttemptListOptions = {}) => listAttemptSummaries(dir, options);
201
208
  export const attemptShow = (dir: string, id: string) => {
@@ -4,6 +4,8 @@ import { runOnExecutor, type Executor, type ProcessRunner } from "./executor.ts"
4
4
  export const ARTIFACT_FILES = 500, ARTIFACT_BYTES = 256 * 1024 * 1024;
5
5
  export const ARTIFACT_CAPTURE_BYTES = 65_536;
6
6
  export const ARTIFACT_HEADERS = 2048, ARTIFACT_METADATA_BYTES = 65_536;
7
+ /** One entry header plus at most a GNU long-name (`L`) and a PAX (`x`) header, plus one shared global (`g`) slack. */
8
+ const TAR_HEADERS_PER_ENTRY = 4;
7
9
  export const ARTIFACT_WIRE_BYTES = ARTIFACT_BYTES + 16 * 1024 * 1024;
8
10
  export type ArtifactErrorCode = "invalid-artifact" | "artifact-limit" | "artifact-read";
9
11
  export class ArtifactError extends Error {
@@ -93,7 +95,7 @@ class TarArtifacts {
93
95
  private pendingMetadata = false;
94
96
  private longName?: string;
95
97
  private seen = new Map<string, "file" | "directory">();
96
- constructor(private capture: string | undefined, private captureBytes: number, private maxBytes: number, private maxFiles: number) {}
98
+ constructor(private capture: string | undefined, private captureBytes: number, private maxBytes: number, private maxFiles: number, private maxHeaders = ARTIFACT_HEADERS) {}
97
99
  push(chunk: Uint8Array): void {
98
100
  if (!(chunk instanceof Uint8Array)) return invalid("non-binary archive stream");
99
101
  this.wireBytes += chunk.byteLength;
@@ -126,7 +128,7 @@ class TarArtifacts {
126
128
  const header = this.header;
127
129
  if (header.every(byte => byte === 0)) { if (++this.zeros === 2) this.ended = true; return; }
128
130
  if (this.zeros) return invalid("entry after an incomplete tar end marker");
129
- if (++this.headers > ARTIFACT_HEADERS) return limit(`archive exceeds ${ARTIFACT_HEADERS} headers`);
131
+ if (++this.headers > this.maxHeaders) return limit(`archive exceeds ${this.maxHeaders} headers`);
130
132
  const expected = octal(header.subarray(148, 156));
131
133
  let checksum = 0;
132
134
  for (let i = 0; i < 512; i++) checksum += i >= 148 && i < 156 ? 32 : header[i]!;
@@ -206,6 +208,22 @@ class TarArtifacts {
206
208
  }
207
209
  }
208
210
 
211
+ /**
212
+ * Streaming member scan for an archive the caller transfers elsewhere: the same header, PAX and path validation as
213
+ * artifact reads, exposing each regular member's path and digest when the archive ends. The caller sizes the header
214
+ * budget from its own entry limits (each file or directory: its header plus GNU long-name or PAX headers). Metadata
215
+ * stays bounded per record by ARTIFACT_METADATA_BYTES, which already exceeds the 4096-byte path limit.
216
+ */
217
+ export class TarMemberScan {
218
+ private readonly parser: TarArtifacts;
219
+ constructor(maxBytes: number, maxFiles: number, maxEntries: number) {
220
+ const entries = bound(maxEntries, 1_000_000, "maxEntries");
221
+ this.parser = new TarArtifacts(undefined, 0, bound(maxBytes, ARTIFACT_BYTES, "maxBytes"), bound(maxFiles, ARTIFACT_FILES, "maxFiles"), Math.max(ARTIFACT_HEADERS, entries * TAR_HEADERS_PER_ENTRY));
222
+ }
223
+ push(chunk: Uint8Array): void { this.parser.push(chunk); }
224
+ finish(): ArtifactFile[] { return this.parser.finish().files; }
225
+ }
226
+
209
227
  /** Hash regular artifacts, retaining no payload except an explicitly selected bounded capture. */
210
228
  export async function readArtifactArchive(executor: Executor, command: string, args: string[], runner: ProcessRunner, options: ArtifactArchiveOptions = {}): Promise<ArtifactArchive> {
211
229
  const capture = options.capture === undefined ? undefined : relative(options.capture), captureBytes = bound(options.captureBytes ?? ARTIFACT_CAPTURE_BYTES, ARTIFACT_CAPTURE_BYTES, "captureBytes");
@@ -12,12 +12,12 @@ import { randomUUID } from "node:crypto";
12
12
  import { AsyncLocalStorage } from "node:async_hooks";
13
13
  import { boundedText, commit, openStudy, plain, readJsonFile, readTextBounded, requireExperiment, requireGate, sha256, withLock, StudyLockBusyError, type Actor, type PendingEvent } from "../study.ts";
14
14
  import { canonical, designBinding, sameProtocolInputs, frozenProtocol, validateStoredProtocol, protocolHash, readProtocol, readDesign, type Protocol } from "./protocol.ts";
15
- import { buildContainerArgs, probeGpuAdmission, GpuAdmissionDeferred, validateGpuDevices, validateContainerInputSources, executionPathsOverlap, verifyExecutorInputs, InputVerificationError, checkExecutorInputs, containerName, readExecutor, runOnExecutor, shellQuote, spawnRunner, startWatchdog, type ContainerPaths, type Executor, type ProcessRunner, type Stage } from "./executor.ts";
15
+ import { buildContainerArgs, probeGpuAdmission, GpuAdmissionDeferred, validateGpuDevices, validateContainerInputSources, executionPathsOverlap, verifyExecutorInputs, InputVerificationError, checkExecutorInputs, stageContainerName, readExecutor, runOnExecutor, shellQuote, spawnRunner, startWatchdog, type ContainerPaths, type Executor, type ProcessRunner, type Stage } from "./executor.ts";
16
16
  import { resolveSnapshot, transferSnapshot, transferTask } from "./snapshot.ts";
17
17
  import { collectEvaluation as defaultEvaluationCollector, collectStageEvidence as defaultStageCollector, EvidenceError, MetricsError, OUTPUT_METADATA_BYTES, outputBudget, type StageEvidence } from "./metrics.ts";
18
18
 
19
19
  export type AttemptStatus = "running" | "succeeded" | "failed" | "cancelled" | "unknown";
20
- export interface AttemptStage { image: string; argv: string[]; mounts: { target: string; readOnly: boolean }[]; network: "none"; limits: Protocol["limits"]; user: string; containerId?: string; startedAt: string; endedAt?: string; exitCode?: number; evidence?: StageEvidence; evidenceError?: { reason: string; message: string }; launchPending?: true }
20
+ export interface AttemptStage { image: string; argv: string[]; mounts: { target: string; readOnly: boolean }[]; network: "none"; limits: Protocol["limits"]; user: string; containerName?: string; containerId?: string; startedAt: string; endedAt?: string; exitCode?: number; evidence?: StageEvidence; evidenceError?: { reason: string; message: string }; launchPending?: true }
21
21
  export interface Evaluation { metrics: { name: string; unit: string; value: number; provenance: "ares-observed" }[]; outputs: { path: string; sha256: string; bytes: number }[] }
22
22
  export interface Attempt {
23
23
  v: 1 | 2 | 3; pipeline?: PipelineState; reuse?: AttemptReuseState; freshRequest?: { reuse: "off" | "eligible"; forceFresh: boolean }; id: string; studyId: string; run: string; protocolHash: string; sealBinding: string; commit: string; treeId: string; snapshotSha256?: string; seed: number; label: string; retryOf?: string;
@@ -275,7 +275,7 @@ function executionProtocol(dir: string, attempt: Attempt): Protocol {
275
275
  return { ...attempt.protocol, inputs: current.inputs };
276
276
  }
277
277
  function stageRecord(attempt: Attempt, stage: Stage, user: string, ctx: AttemptContext): AttemptStage {
278
- return { image: attempt.protocol[stage].image, argv: attempt.protocol[stage].command, mounts: [...(stage === "candidate" ? [{ target: "/workspace", readOnly: true }, { target: "/out", readOnly: false }] : [{ target: "/eval", readOnly: true }, { target: "/candidate", readOnly: true }, { target: "/result", readOnly: false }]), ...(pipelineInputRoot(attempt) ? [{ target: "/in", readOnly: true }] : []), ...Object.values(attempt.protocol.inputs ?? {}).flatMap(input => input.mount[stage] ? [{ target: input.mount[stage]!, readOnly: true }] : [])], network: "none", limits: attempt.protocol.limits, user, startedAt: at(ctx) };
278
+ return { image: attempt.protocol[stage].image, argv: attempt.protocol[stage].command, mounts: [...(stage === "candidate" ? [{ target: "/workspace", readOnly: true }, { target: "/out", readOnly: false }] : [{ target: "/eval", readOnly: true }, { target: "/candidate", readOnly: true }, { target: "/result", readOnly: false }]), ...(pipelineInputRoot(attempt) ? [{ target: "/in", readOnly: true }] : []), ...Object.values(attempt.protocol.inputs ?? {}).flatMap(input => input.mount[stage] ? [{ target: input.mount[stage]!, readOnly: true }] : [])], network: "none", limits: attempt.protocol.limits, user, containerName: stageContainerName(attempt.studyId, attempt.id, stage, attempt.pipeline && stage === "candidate" ? attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name : undefined), startedAt: at(ctx) };
279
279
  }
280
280
 
281
281
  /** Validate observed container settings before describing its sealing as ares-observed. */
@@ -348,10 +348,14 @@ async function recordVerifiedStage(dir: string, attempt: Attempt, state: Observe
348
348
  return event;
349
349
  }, approvals);
350
350
  }
351
- function attemptContainerName(attempt: Attempt): string {
352
- const base = containerName(attempt.id, attempt.stage);
351
+ function legacyContainerName(attempt: Attempt): string {
352
+ // Records written before study-scoped names carry no launched name; keep resolving the one they used.
353
+ const base = `ares-${attempt.id}-${attempt.stage}`;
353
354
  return attempt.pipeline && attempt.stage === "candidate" ? `${base}-${attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name}` : base;
354
355
  }
356
+ function attemptContainerName(attempt: Attempt): string {
357
+ return attempt.stages[attempt.stage]?.containerName ?? legacyContainerName(attempt);
358
+ }
355
359
  async function inspect(dir: string, attempt: Attempt, ctx: AttemptContext, ownershipOnly = false) {
356
360
  const protocol = ownershipOnly ? attempt.protocol : executionProtocol(dir, attempt);
357
361
  let result;
@@ -504,7 +508,8 @@ async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptC
504
508
  if (decision.outcome === "reused") return attempt;
505
509
  }
506
510
  // Keep configuration refusals outside the uncertain container-start catch.
507
- args = buildContainerArgs({ protocol, stage: attempt.stage, studyId: openStudy(dir).study.id, attemptId: attempt.id, seed: attempt.seed, user, paths: attempt.paths, ...(attempt.gpuDevices ? { gpuDevices: attempt.gpuDevices } : {}), ...(attempt.pipeline && attempt.stage === "candidate" ? { pipeline: { name: attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name, inputRoot: pipelineInputRoot(attempt)!, seed: attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.seed } } : {}) });
511
+ // The record's own name is authoritative: a stage recorded before study-scoped names must start where inspect looks.
512
+ args = buildContainerArgs({ protocol, stage: attempt.stage, studyId: attempt.studyId, attemptId: attempt.id, name: attemptContainerName(attempt), seed: attempt.seed, user, paths: attempt.paths, ...(attempt.gpuDevices ? { gpuDevices: attempt.gpuDevices } : {}), ...(attempt.pipeline && attempt.stage === "candidate" ? { pipeline: { name: attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name, inputRoot: pipelineInputRoot(attempt)!, seed: attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.seed } } : {}) });
508
513
  if (attempt.reuse) attempt = await update(dir, attempt.id, recoveryCtx, current => {
509
514
  if (current.status !== "running" || current.stage !== attempt.stage || current.pipeline?.index !== attempt.pipeline?.index || current.launching?.token !== attempt.launching?.token) throw new InputVerificationError("reuse: container launch ownership changed; run ares attempt reconcile <dir> after the active control operation finishes before retrying");
510
515
  requireCopilotAccept(dir, "hypotheses");
@@ -530,7 +535,7 @@ async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptC
530
535
  if (!/^[a-f0-9]{64}$/.test(cid)) throw hostError(attempt, "container start");
531
536
  startedId = cid;
532
537
  attempt.stages[attempt.stage]!.containerId = cid;
533
- await startWatchdog(attempt.executor, attempt.id, attempt.stage, remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, cid);
538
+ await startWatchdog(attempt.executor, attemptContainerName(attempt), remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, cid);
534
539
  const state = await inspect(dir, attempt, ctx); if (!state) throw hostError(attempt, "container start verification");
535
540
  return recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.started");
536
541
  } catch {
@@ -539,7 +544,7 @@ async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptC
539
544
  // A lost response is not proof that Docker rejected the start. Adopt only a verified owned container.
540
545
  const state = await inspect(dir, attempt, ctx);
541
546
  if (state) {
542
- if (state.running) await startWatchdog(attempt.executor, attempt.id, attempt.stage, remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, state.id);
547
+ if (state.running) await startWatchdog(attempt.executor, attemptContainerName(attempt), remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, state.id);
543
548
  return recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.recovered");
544
549
  }
545
550
  } catch {
@@ -1,7 +1,7 @@
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";
4
+ import { commit, openStudy, plain, readJsonFile, requireExperiment, sha256, type Actor } from "../study.ts";
5
5
  import { readProtocol, canonicalExecutorPath, validateProtocol, type Protocol } from "./protocol.ts";
6
6
 
7
7
  export interface ExecutorGpu { devices: (number | string)[]; minFreeMemoryMb: number; maxLoadRatio: number }
@@ -14,6 +14,8 @@ export interface ProcessRequest {
14
14
  export interface ProcessResult { exitCode: number; stdout: string; stderr: string; timedOut?: boolean; truncated?: boolean }
15
15
  export type ProcessRunner = (request: ProcessRequest) => Promise<ProcessResult>;
16
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";
17
19
 
18
20
  /** Opt-in context for native CLI attribution and config discovery; no API credentials. */
19
21
  export const PROCESS_CONTEXT_ENV_KEYS = ["AGENTHUB_PEER_ID", "CLAUDECODE", "CLAUDE_CODE_SESSION_ID", "CODEX_THREAD_ID", "PI_SESSION_ID",
@@ -142,6 +144,14 @@ export function setExecutor(dir: string, raw: unknown, actor: Actor): Executor {
142
144
  return executor;
143
145
  }
144
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";
145
155
  /** SSH concatenates its remote command argv into a shell command, so quote every unsafe byte. */
146
156
  export function shellQuote(value: string): string {
147
157
  return /^[A-Za-z0-9_./:@=+-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
@@ -357,10 +367,24 @@ export function executionPathsOverlap(left: string, right: string): boolean {
357
367
  }
358
368
  export type Stage = "candidate" | "evaluator";
359
369
  export interface ContainerPaths { snapshot: string; output: string; evaluator: string; result: string }
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 } }
361
- 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 {
362
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");
363
- 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;
364
388
  }
365
389
  /** Pure preflight for host input isolation; no hashing, transport or attempt side effects. */
366
390
  export function validateContainerInputSources(protocol: Protocol, pathsArg: ContainerPaths): void {
@@ -375,8 +399,7 @@ export function validateContainerInputSources(protocol: Protocol, pathsArg: Cont
375
399
  }
376
400
  /** Mounts are fixed by stage, never supplied as free-form Docker options. */
377
401
  export function buildContainerArgs(options: ContainerOptions): string[] {
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");
402
+ const p = validateProtocol(options.protocol), name = options.name === undefined ? stageContainerName(options.studyId, options.attemptId, options.stage, options.pipeline?.name) : recordedContainerName(options.name);
380
403
  const seed = options.seed === undefined ? p.seeds[0]! : options.seed;
381
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");
382
405
  if (!/^[A-Za-z0-9_-]{1,80}$/.test(options.studyId)) throw new Error("study id: invalid label; use the id from study.json");
@@ -421,8 +444,9 @@ export function buildContainerArgs(options: ContainerOptions): string[] {
421
444
  }
422
445
 
423
446
  /** Launch on the executor host; stdio is detached so SSH returns immediately. T3 reconciles deadlines as a backstop. */
424
- export async function startWatchdog(executor: Executor, attemptId: string, stage: Stage, wallSeconds: number, runner: ProcessRunner = spawnRunner, containerId?: string): Promise<void> {
425
- 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");
426
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");
427
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)");
428
452
  const script = `nohup sh -c ${shellQuote(`sleep ${wallSeconds}; docker kill ${containerId ?? name}`)} </dev/null >/dev/null 2>&1 &`;
@@ -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";
@@ -104,10 +104,8 @@ export async function collectStageEvidence(attempt: Attempt, stage: Stage, runne
104
104
  'if test "$status" -ne 0; then if test "$outcut" = true || test "$errcut" = true; then outcut=true; errcut=true; else exit "$status"; fi; fi',
105
105
  'printf \'{"stdout":%s,"stderr":%s}\\n\' "$outcut" "$errcut" > "$statetmp"',
106
106
  'mv "$outtmp" "$out"; mv "$errtmp" "$err"; mv "$statetmp" "$state"', 'fi',
107
- // Archive content only: BSD tar otherwise emits binary xattr PAX and AppleDouble entries.
108
- // ponytail: requires GNU tar >= 1.27 or bsdtar with --no-xattrs; unsupported tar
109
- // (e.g. BusyBox) fails closed with the generic stage-log collection error, never a metadata fallback.
110
- `COPYFILE_DISABLE=1 tar --no-xattrs -C ${shellQuote(root)} -cf - ${shellQuote(`logs/${stageLabel}.stdout.log`)} ${shellQuote(`logs/${stageLabel}.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)}`,
111
109
  ].join("\n");
112
110
  let logArchive;
113
111
  try { logArchive = await readArtifactArchive(attempt.executor, "sh", ["-c", script], runner, { capture: statePath, captureBytes: 1024, maxFiles: 3, maxBytes: LOG_COPY_BYTES * 2 + 1024 }); }
@@ -23,7 +23,7 @@ export function validateProtocolDefinition(raw: unknown): ProtocolDefinition {
23
23
  return validateProtocol(raw);
24
24
  }
25
25
  export const METRIC_LIMIT = 100;
26
- export const PROTOCOL_BYTES = 65_536, TASK_FILES = 500, TASK_BYTES = 64 * 1024 * 1024;
26
+ export const PROTOCOL_BYTES = 65_536, TASK_FILES = 500, TASK_BYTES = 64 * 1024 * 1024, TASK_DIRECTORIES = 1000;
27
27
  export const LIMIT_BOUNDS = { cpus: [0.1, 256], memoryMb: [16, 1_048_576], pidsLimit: [1, 65_536], wallSeconds: [1, 604_800], gpus: [0, 64] } as const;
28
28
  function object(raw: unknown, keys: string[], what: string): Record<string, unknown> {
29
29
  if (!plain(raw)) throw new Error(`${what}: object required; set ${what} to a JSON object`);
@@ -172,7 +172,7 @@ export function taskTreeHash(dir: string): string {
172
172
  if (stat.isSymbolicLink()) throw new Error(`${label}: symlink refused; replace it with a regular file or directory inside task/`);
173
173
  if (!relative && !stat.isDirectory()) throw new Error("task/: directory required; replace task with a directory containing task.md and evaluator/");
174
174
  if (stat.isDirectory()) {
175
- if (depth > 64 || ++directories > 1000) throw new Error(`${label}: too many directories or nesting too deep; reduce task/ to at most 1000 directories and 64 levels`);
175
+ if (depth > 64 || ++directories > TASK_DIRECTORIES) throw new Error(`${label}: too many directories or nesting too deep; reduce task/ to at most 1000 directories and 64 levels`);
176
176
  const directory = opendirSync(path);
177
177
  try {
178
178
  for (let entry = directory.readSync(); entry; entry = directory.readSync()) walk(relative ? `${relative}/${entry.name}` : entry.name, depth + 1);
@@ -44,7 +44,9 @@ export async function prepareStageReuse(dir: string, attempt: Attempt, ctx: Atte
44
44
  let original: Attempt, record: AttemptStage | undefined;
45
45
  try {
46
46
  original = sourceAttempt(result.ref.attemptId);
47
- if (original.status === "running" || original.studyId !== attempt.studyId || !original.pipeline || original.treeId !== attempt.treeId || original.seed !== attempt.seed || original.pipeline.codeSnapshotHash !== pipeline.codeSnapshotHash || original.reuse?.stages[stage.name]?.outcome !== "fresh" || original.reuse.stages[stage.name]?.key !== key || canonical(original.executor) !== canonical(attempt.executor) || !original.sealing.candidateHasNoEvaluator || canonical(original.reuse?.stages[stage.name]?.context) !== canonical(facts)) return fresh("ineligible-source", key);
47
+ // A valid done-but-not-succeeded receipt never makes a source eligible: a cancelled or unknown attempt's stages may
48
+ // be partial, so only a succeeded source is admitted, never merely a non-running one.
49
+ if (original.status !== "succeeded" || original.studyId !== attempt.studyId || !original.pipeline || original.treeId !== attempt.treeId || original.seed !== attempt.seed || original.pipeline.codeSnapshotHash !== pipeline.codeSnapshotHash || original.reuse?.stages[stage.name]?.outcome !== "fresh" || original.reuse.stages[stage.name]?.key !== key || canonical(original.executor) !== canonical(attempt.executor) || !original.sealing.candidateHasNoEvaluator || canonical(original.reuse?.stages[stage.name]?.context) !== canonical(facts)) return fresh("ineligible-source", key);
48
50
  const completed = original.pipeline.completed.find(parent => parent.name === stage.name && canonical(parent.ref) === canonical(result.ref) && !parent.reuse);
49
51
  record = completed?.record;
50
52
  if (!record && original.stage === "candidate" && original.pipeline.definition.candidate.stages[original.pipeline.index]?.name === stage.name) record = original.stages.candidate;
@@ -50,6 +50,10 @@ function producerSemantics(): string | undefined {
50
50
  const sources = PRODUCER_SOURCES.map(name => [name, sha256(readBytesBounded(fileURLToPath(new URL(`./${name}`, import.meta.url)), PRODUCER_SOURCE_BYTES))]);
51
51
  return `ares-stage-v2/reuse-1:${sha256(canonical({ bun, sources }))}`;
52
52
  }
53
+ export function isInvestigationRun(run: string, selection: { run: string } | undefined): boolean {
54
+ return selection?.run === run && !["ablate", "final", "posthoc"].includes(run);
55
+ }
56
+
53
57
  /** Read-only, source-owned facts. Caller still owns current design/policy/budget fencing at admission. */
54
58
  export async function reuseSourceFacts(dir: string, attempt: Attempt, ctx: AttemptContext): Promise<StageReuseSourceFactsResult> {
55
59
  const protocol = attempt.pipeline?.definition ?? attempt.protocol;
@@ -59,7 +63,7 @@ export async function reuseSourceFacts(dir: string, attempt: Attempt, ctx: Attem
59
63
  if (study.mode !== "experiment" || study.id !== attempt.studyId) return { reason: "unsupported-study" };
60
64
  before = population(dir, protocol);
61
65
  } catch { return { reason: "population-unavailable" }; }
62
- if (attempt.stage !== "candidate" || !before.selection || before.selection.run !== attempt.run || ["ablate", "final", "posthoc"].includes(attempt.run)) return { reason: "outside-investigation" };
66
+ if (attempt.stage !== "candidate" || !isInvestigationRun(attempt.run, before.selection)) return { reason: "outside-investigation" };
63
67
  if (protocol.limits.gpus > 0) return { reason: "unsupported-gpu-abi" };
64
68
  if (!identity(process.versions.bun)) return { reason: "producer-runtime-unavailable" };
65
69
  let semantics: string | undefined;
@@ -2,8 +2,9 @@ import { createHash } from "node:crypto";
2
2
  import { lstatSync, mkdirSync, mkdtempSync, opendirSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { dirname, join, posix } from "node:path";
5
- import { runOnExecutor, spawnRunner, validateExecutor, type Executor, type ProcessResult, type ProcessRunner } from "./executor.ts";
6
- import { TASK_BYTES, TASK_FILES } from "./protocol.ts";
5
+ import { PORTABLE_TAR_CREATE, runOnExecutor, shellQuote, spawnRunner, validateExecutor, type Executor, type ProcessResult, type ProcessRunner } from "./executor.ts";
6
+ import { TarMemberScan, type ArtifactFile } from "./artifacts.ts";
7
+ import { TASK_BYTES, TASK_DIRECTORIES, TASK_FILES } from "./protocol.ts";
7
8
  import { readBytesBounded, sha256 } from "../study.ts";
8
9
 
9
10
  export const SNAPSHOT_BYTES = 256 * 1024 * 1024;
@@ -80,7 +81,7 @@ export async function transferTask(taskDir: string, executor: Executor, destinat
80
81
  const source = relative ? join(taskDir, relative) : taskDir, label = relative ? `task/${relative}` : "task/", stat = lstatSync(source);
81
82
  if (stat.isSymbolicLink()) throw new Error(`${label}: symlink refused; replace it with regular task files before ares attempt run`);
82
83
  if (stat.isDirectory()) {
83
- if (++directories > 1000 || depth > 64) throw new Error(`${label}: task traversal limit exceeded; reduce task/ to 1000 directories and 64 levels`);
84
+ if (++directories > TASK_DIRECTORIES || depth > 64) throw new Error(`${label}: task traversal limit exceeded; reduce task/ to 1000 directories and 64 levels`);
84
85
  if (relative.startsWith("evaluator/")) mkdirSync(join(staging, relative), { recursive: true, mode: 0o700 });
85
86
  const directory = opendirSync(source);
86
87
  try { for (let entry = directory.readSync(); entry; entry = directory.readSync()) capture(relative ? `${relative}/${entry.name}` : entry.name, depth + 1); }
@@ -101,29 +102,46 @@ export async function transferTask(taskDir: string, executor: Executor, destinat
101
102
  capture("", 0);
102
103
  const treeHash = sha256(JSON.stringify(entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
103
104
  if (expectedTreeHash !== undefined && treeHash !== expectedTreeHash) throw new Error("task/: content changed since approval; set the protocol, approve design again, and retry ares attempt run");
104
- // Bounded tar headers and long-path metadata supplement the 64 MiB task payload cap.
105
- const transferred = await transferArchive("task", { command: "tar", args: ["-C", staging, "-cf", "-", includeCandidate ? "." : "evaluator"] }, TASK_BYTES + 16 * 1024 * 1024, executor, destination, runner);
105
+ // Bounded tar headers and long-path metadata supplement the 64 MiB task payload cap. The archive is created with the
106
+ // shared content-only tar rule, and its members are checked against the staged files while it streams.
107
+ const staged = new Map((includeCandidate ? entries : entries.filter(([path]) => path.startsWith("evaluator/"))).map(([path, digest]) => [path, digest]));
108
+ const transferred = await transferArchive("task", { command: "sh", args: ["-c", `${PORTABLE_TAR_CREATE} -C ${shellQuote(staging)} -cf - ${includeCandidate ? "." : "evaluator"}`] }, TASK_BYTES + 16 * 1024 * 1024, executor, destination, runner, staged);
106
109
  return { ...transferred, treeHash };
107
110
  } catch (error) {
108
- if (error instanceof Error && (error.message.startsWith("task/") || error.message.startsWith("executor "))) throw error;
111
+ if (error instanceof Error && (error.message.startsWith("task/") || error.message.startsWith("task archive:") || error.message.startsWith("executor "))) throw error;
109
112
  throw new Error("task archive capture failed; restore readable task/evaluator files, then retry ares attempt run");
110
113
  } finally { rmSync(staging, { recursive: true, force: true }); }
111
114
  }
112
115
 
113
- async function transferArchive(kind: "snapshot" | "task", source: { command: string; args: string[] }, limit: number, executorArg: Executor, destination: string, runner: ProcessRunner): Promise<{ sha256: string; bytes: number }> {
116
+ /** Checks a task archive's members against the staged files: refuses AppleDouble `._*` members and any other drift by name. */
117
+ function memberCheck(files: ArtifactFile[], staged: Map<string, string>): void {
118
+ const metadata = files.find(file => file.path.split("/").some(part => part.startsWith("._")) && !staged.has(file.path));
119
+ if (metadata) throw new Error(`task archive: AppleDouble/extended-attribute metadata member ${metadata.path.slice(0, 200)} refused; the archive must carry task content only (tar --no-xattrs with COPYFILE_DISABLE=1, GNU tar >= 1.27 or bsdtar), then retry ares attempt run`);
120
+ const extra = files.find(file => staged.get(file.path) !== file.sha256);
121
+ if (extra || files.length !== staged.size) throw new Error(`task archive: member ${(extra?.path ?? "set").slice(0, 200)} differs from the staged task files; check the controller tar (GNU tar >= 1.27 or bsdtar) and retry ares attempt run`);
122
+ }
123
+
124
+ async function transferArchive(kind: "snapshot" | "task", source: { command: string; args: string[] }, limit: number, executorArg: Executor, destination: string, runner: ProcessRunner, staged?: Map<string, string>): Promise<{ sha256: string; bytes: number }> {
114
125
  const executor = validateExecutor(executorArg);
115
126
  if (!destination.startsWith("/") || destination.length > 4096 || /[\0\r\n,"]/.test(destination) || posix.normalize(destination) === "/") throw new Error("snapshot destination: invalid directory; use a private absolute non-root directory without NUL, newlines, commas or double quotes");
116
127
  const stream = new ArchiveChannel(), controller = new AbortController(), hash = createHash("sha256");
117
- let bytes = 0, oversized = false, failedSide: "archive" | "extract" | undefined;
128
+ const scan = staged ? new TarMemberScan(TASK_BYTES, TASK_FILES, TASK_FILES + TASK_DIRECTORIES) : undefined;
129
+ let bytes = 0, oversized = false, failedSide: "archive" | "extract" | undefined, refused: Error | undefined;
118
130
  const archive = (async () => {
119
131
  try {
120
132
  const result = await runner({ ...source, signal: controller.signal, timeoutMs: 300_000,
121
133
  stdoutSink: async chunk => {
122
134
  if (bytes + chunk.byteLength > limit) { oversized = true; throw new Error("archive size limit"); }
123
135
  bytes += chunk.byteLength; hash.update(chunk);
136
+ try { scan?.push(chunk); } catch { refused ??= new Error("task archive: malformed or unsupported tar stream refused; check the controller tar (GNU tar >= 1.27 or bsdtar) and retry ares attempt run"); throw refused; }
124
137
  await stream.write(chunk);
125
138
  } });
126
139
  if (!passed(result)) throw gitFailure("archive");
140
+ if (scan && staged) {
141
+ let files: ArtifactFile[];
142
+ try { files = scan.finish(); } catch { refused ??= new Error("task archive: truncated tar stream refused; retry ares attempt run"); throw refused; }
143
+ try { memberCheck(files, staged); } catch (error) { refused ??= error as Error; throw refused; }
144
+ }
127
145
  stream.end();
128
146
  } catch (error) { failedSide ??= "archive"; stream.end(error as Error); throw error; }
129
147
  })();
@@ -141,6 +159,8 @@ async function transferArchive(kind: "snapshot" | "task", source: { command: str
141
159
  controller.abort(); stream.end(new Error("archive transfer cancelled"));
142
160
  await Promise.allSettled([archive, extract]);
143
161
  if (oversized) throw new Error(`${kind} archive: larger than ${limit} bytes; reduce the ${kind === "snapshot" ? "committed snapshot" : "task evaluator"} before ares attempt run`);
162
+ // A refused member is named even though extraction may have begun; the attempt fails and nothing is marked verified.
163
+ if (refused) throw refused;
144
164
  if (failedSide === "archive") throw kind === "snapshot" ? gitFailure("archive") : new Error("task archive failed; restore readable task/evaluator files, then retry ares attempt run");
145
165
  throw new Error(`executor ${executor.kind === "ssh" ? executor.host : "local"}: snapshot extraction failed; check the private destination directory and tar on the executor host, then retry ares attempt run`);
146
166
  }
package/src/playbook.ts CHANGED
@@ -49,9 +49,9 @@ ares lessons <dir> --for "prepare reproducible experiments"
49
49
  1. Use the initialized experiment study (--mode experiment at init). Survey studies refuse experiment commands; study mode is fixed at init.
50
50
  2. Write task/task.md and task/evaluator/ entrypoint/data, optionally task/rubric.md. Use regular files only, at most 500 files and 64 MiB; symlinks are refused.
51
51
  3. Set design/protocol.json: ares protocol <dir> --file protocol.json. For v1, declare digest-pinned candidate/evaluator images, argv arrays, metrics (name/unit/max|min), seeds, limits, network "none" and budgets. For v2, candidate.stages declares 1..16 stages in serial order with unique names, image/command, boolean seed, code:"snapshot", needs, named inputs and outputs. Each needs edge and {stage,output} input must name an earlier stage and its declared output; a task input uses {task:"relative/path"} outside evaluator/, and output ports name disjoint relative paths. V2 does not accept the v1 top-level inputs field. Dependencies belong in images. ARES_SEED is reserved and supplied from the selected seed (to v2 candidate stages only when seed:true, and to the evaluator); never put secret-like keys in candidate.env.
52
- 4. Configure the executor: ares executor set <dir> --kind ssh --host ALIAS --workdir /private/owned/path, or --kind local with an explicit private workdir. Create that host directory owned by the executor user with mode 0700. Run ares executor check <dir> to check Docker, images and non-root uid:gid; it may pull missing images. For pre-staged large/private inputs, run ares executor inputs hash <dir> /absolute/input, for protocol v1 declare names/hashes/read-only /in/ stage mounts in protocol.inputs and keep the directories stable. Python3 is required for declared v1 inputs and protocol v2 stages. By default, v2 candidate stages execute fresh: frozen code at /workspace, named read-only inputs at /in/<port>, fresh /out, then a separate evaluator with all sealed stage trees under /candidate/<stage>. Every parent manifest and byte tree is verified before consumption; each stage gets a fresh read-only input copy, and publication follows observed successful termination plus bounded verification. Outputs are cumulative across candidates and evaluator: 500 files, 256 MiB payload, 256 KiB metadata including retained sidecars, and a 1 MiB attempt record. Wall/compute accounting sums stages and never multiplies the attempt allowance. For shared Linux NVIDIA hosts, optionally set --gpu-devices IDS --gpu-min-free-memory-mb MB --gpu-max-load-ratio RATIO together. GPU attempts then get one read-only admission probe; devices/load/probe deferrals return status deferred and exit 75 with no Attempt or budget use. Never queue or automatically retry a deferral; try again explicitly after the named condition improves. A deferred plan node has reason deferred:devices|load|probe with no attempt id; recover with ares plan control <dir> retry <node> --command-id ID --expected-revision N. The chosen UUIDs are frozen across all candidate stages and the evaluator; this advisory check is not a reservation. Without GPU settings, execution is unchanged. The staged path and all ancestors must be symlink-free; on macOS use /private/tmp rather than /tmp. No input download or copy into the study occurs; evaluator-only inputs stay hidden from the candidate. Hash/mount edits reopen design approval, locator-only edits do not. Manifest hashing runs outside the launch claim/control transaction; the short launch claim rechecks frozen input identities before container start.
52
+ 4. Configure the executor: ares executor set <dir> --kind ssh --host ALIAS --workdir /private/owned/path, or --kind local with an explicit private workdir. Create that host directory owned by the executor user with mode 0700. Run ares executor check <dir> to check Docker, images and non-root uid:gid; it may pull missing images. For pre-staged large/private inputs, run ares executor inputs hash <dir> /absolute/input, for protocol v1 declare names/hashes/read-only /in/ stage mounts in protocol.inputs and keep the directories stable. Python3 is required for declared v1 inputs and protocol v2 stages. By default, v2 candidate stages execute fresh: frozen code at /workspace, named read-only inputs at /in/<port>, fresh /out, then a separate evaluator with all sealed stage trees under /candidate/<stage>. Every parent manifest and byte tree is verified before consumption; each stage gets a fresh read-only input copy, and publication follows observed successful termination plus bounded verification. Outputs are cumulative across candidates and evaluator: 500 files, 256 MiB payload, 256 KiB metadata including retained sidecars, and a 1 MiB attempt record. Wall/compute accounting sums stages and never multiplies the attempt allowance. For shared Linux NVIDIA hosts, optionally set --gpu-devices IDS --gpu-min-free-memory-mb MB --gpu-max-load-ratio RATIO together. GPU attempts then get one read-only admission probe; devices/load/probe deferrals return status deferred and exit 75 with no Attempt or budget use. Never queue or automatically retry a deferral; try again explicitly after the named condition improves. A deferred plan node has reason deferred:devices|load|probe with no attempt id; recover with ares plan control <dir> retry <node> --command-id ID --expected-revision N. The chosen UUIDs are frozen across all candidate stages and the evaluator; this advisory check is not a reservation. Without GPU settings, execution is unchanged. New attempt stages store their study-scoped container name for inspection, reconciliation and watchdogs; old stages without it retain their legacy name. Finish or reconcile running attempts before downgrading to 0.3.0. Task archives use the shared content-only tar rule and refuse AppleDouble or unexpected/mismatched streamed members without changing the frozen tree hash. The staged path and all ancestors must be symlink-free; on macOS use /private/tmp rather than /tmp. No input download or copy into the study occurs; evaluator-only inputs stay hidden from the candidate. Hash/mount edits reopen design approval, locator-only edits do not. Manifest hashing runs outside the launch claim/control transaction; the short launch claim rechecks frozen input identities before container start.
53
53
  For retention, inspect with ares retention inspect <dir> [--offset N] [--limit N]; page through released-history shards as needed; capacity includes active reservations (default 1 GiB, optional executor --retention-cap-bytes). Prune explicit {attemptId,stage,sha256} refs with ares retention prune <dir> --file refs.json, then --confirm FINGERPRINT. Preview needs no design approval; confirm requires the current design gate and unchanged fingerprint. Active producers/consumers refuse; tombstones remain. Source pruning does not erase an already recorded reuse lineage: show/lineage/export project disposed only from an exact prune ledger witness, otherwise unknown, never invented available. A failed terminal release is reconciled with ares attempt reconcile only after no owned live container is confirmed. Transient seal/transport contention may keep a stopped stage and its reservation for the next reconcile; permanent integrity/limit failures terminate with their cause. An unobserved stop keeps the reservation held. Never rerun uncertain work.
54
- For optional deterministic artifact reuse, declare stages[].reuse as {v:1,kind:"pure-artifact",inputs:"declared-only",externalState:"none",writableState:"fresh-output-only",modelOutputs:"forbidden",determinism:"byte-exact",toolchain:{description,documentationSha256}}, then review the actual toolchain and approve the current design. Run --reuse eligible only on the selected investigation run; off is default. The key binds this study, frozen selection/reserved-seed population, complete code tree/snapshot, exact declared input hashes, stage/toolchain, seed, runtime and platform ABI. Sources must be actual earlier fresh executions admitted under eligible controls; ordinary fresh/off attempts do not populate the reuse key. Missing/pruned/corrupt/unsupported sources stay fresh under ordinary budgets. GPU ABI reuse is unsupported. Use --force-fresh with an explicit --retry ID to recompute an existing identity. Evaluator/ablate/final/posthoc always stay fresh. Source manifests/bytes are reverified and pinned before a hit is admitted; downstream work still uses fresh read-only input copies. Source receipts and original compute remain distinct from current verification/materialization overhead. Reused computation and retries do not create independent samples; the fresh evaluator count is separate and its metrics are never reused or overwritten. Unknown costs are not zero or savings. The measured benefit pilot and native container proof remain separate from fixture-equivalence checks.
54
+ For optional deterministic artifact reuse, declare stages[].reuse as {v:1,kind:"pure-artifact",inputs:"declared-only",externalState:"none",writableState:"fresh-output-only",modelOutputs:"forbidden",determinism:"byte-exact",toolchain:{description,documentationSha256}}, then review the actual toolchain and approve the current design. Run --reuse eligible only on the selected investigation run; off is default. Outside a matching investigation run the request still runs fresh and its result carries warnings[{code:"outside-investigation", cause, nextStep}]; this additive warning is not persisted. The key binds this study, frozen selection/reserved-seed population, complete code tree/snapshot, exact declared input hashes, stage/toolchain, seed, runtime and platform ABI. Sources must be actual earlier fresh executions from succeeded attempts admitted under eligible controls; cancelled or unknown sources miss as ineligible-source even with retained stage bytes; ordinary fresh/off attempts do not populate the reuse key. Missing/pruned/corrupt/unsupported sources stay fresh under ordinary budgets. GPU ABI reuse is unsupported. Use --force-fresh with an explicit --retry ID to recompute an existing identity. Evaluator/ablate/final/posthoc always stay fresh. Source manifests/bytes are reverified and pinned before a hit is admitted; downstream work still uses fresh read-only input copies. Source receipts and original compute remain distinct from current verification/materialization overhead. Reused computation and retries do not create independent samples; the fresh evaluator count is separate and its metrics are never reused or overwritten. Unknown costs are not zero or savings. The T3 report (docs/verification/execution-eval-t3-report.md) records harness-observed synthetic trials: Diagnose is insufficient, Reuse is restricted after failed performance gates, and Supervision is at most retained in shadow mode. The T4 closeout (docs/verification/execution-eval-t4-status.md) records defaults and live-evidence gaps. These observations grant no adoption, human-benefit or native-container authority; reuse remains off by default and advisory mode stays unauthorized.
55
55
  5. In gates mode approve the sealed inputs: ares gate approve <dir> design. The seal binds the task tree and, for v1 without inputs, exact protocol bytes. With v1 inputs it binds the canonical path-free protocol identity: names, hashes and stage mounts, not executor locators. V2 binds the canonical full stage protocol including its budget and reuse contracts; its comparable protocol hash excludes only budget. Sealed identity edits reopen approval; a same-identity locator relocation does not. A budget-only edit still reopens design approval while preserving comparable attempt protocol identity.
56
56
  6. Run a frozen baseline: ares attempt run <dir> --repo /absolute/repo --commit <full-40-hex-SHA> --seed <declared-seed> --run main --label baseline --detach. Run a variant with a different frozen commit or declared seed and --label variant. The same request returns the existing attempt; --retry <id> creates a linked attempt. A different seed or commit is a new attempt, not a reproduction. MCP attempt_run is always detached.
57
57
  7. Run ares attempt reconcile <dir> to advance recorded containers, then inspect ares attempt show <dir> <id> for the full record. ares attempt list <dir> returns summaries, default 50 per page; use --limit N (at most 200) and --offset N. Reconcile again while a stage runs. Totals include failed, cancelled and unknown attempts over the whole study regardless of filters or page, all of which count against budgets. Use ares attempt cancel <dir> <id> --reason "..." to stop a stage. Lost containers become unknown; reconciliation never creates a new attempt.